gcc/
[official-gcc.git] / gcc / tree-eh.c
blobedd43e6a7fdc4426c2f81acc917a3b20f2fe5c19
1 /* Exception handling semantics and decomposition for trees.
2 Copyright (C) 2003-2015 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 "tm.h"
24 #include "alias.h"
25 #include "symtab.h"
26 #include "tree.h"
27 #include "fold-const.h"
28 #include "hard-reg-set.h"
29 #include "function.h"
30 #include "rtl.h"
31 #include "flags.h"
32 #include "insn-config.h"
33 #include "expmed.h"
34 #include "dojump.h"
35 #include "explow.h"
36 #include "calls.h"
37 #include "emit-rtl.h"
38 #include "varasm.h"
39 #include "stmt.h"
40 #include "expr.h"
41 #include "except.h"
42 #include "predict.h"
43 #include "dominance.h"
44 #include "cfg.h"
45 #include "cfganal.h"
46 #include "cfgcleanup.h"
47 #include "basic-block.h"
48 #include "tree-ssa-alias.h"
49 #include "internal-fn.h"
50 #include "tree-eh.h"
51 #include "gimple-expr.h"
52 #include "gimple.h"
53 #include "gimple-iterator.h"
54 #include "gimple-ssa.h"
55 #include "plugin-api.h"
56 #include "ipa-ref.h"
57 #include "cgraph.h"
58 #include "tree-cfg.h"
59 #include "tree-phinodes.h"
60 #include "ssa-iterators.h"
61 #include "stringpool.h"
62 #include "tree-ssanames.h"
63 #include "tree-into-ssa.h"
64 #include "tree-ssa.h"
65 #include "tree-inline.h"
66 #include "tree-pass.h"
67 #include "langhooks.h"
68 #include "diagnostic-core.h"
69 #include "target.h"
70 #include "cfgloop.h"
71 #include "gimple-low.h"
73 /* In some instances a tree and a gimple need to be stored in a same table,
74 i.e. in hash tables. This is a structure to do this. */
75 typedef union {tree *tp; tree t; gimple g;} treemple;
77 /* Misc functions used in this file. */
79 /* Remember and lookup EH landing pad data for arbitrary statements.
80 Really this means any statement that could_throw_p. We could
81 stuff this information into the stmt_ann data structure, but:
83 (1) We absolutely rely on this information being kept until
84 we get to rtl. Once we're done with lowering here, if we lose
85 the information there's no way to recover it!
87 (2) There are many more statements that *cannot* throw as
88 compared to those that can. We should be saving some amount
89 of space by only allocating memory for those that can throw. */
91 /* Add statement T in function IFUN to landing pad NUM. */
93 static void
94 add_stmt_to_eh_lp_fn (struct function *ifun, gimple t, int num)
96 gcc_assert (num != 0);
98 if (!get_eh_throw_stmt_table (ifun))
99 set_eh_throw_stmt_table (ifun, hash_map<gimple, int>::create_ggc (31));
101 gcc_assert (!get_eh_throw_stmt_table (ifun)->put (t, num));
104 /* Add statement T in the current function (cfun) to EH landing pad NUM. */
106 void
107 add_stmt_to_eh_lp (gimple t, int num)
109 add_stmt_to_eh_lp_fn (cfun, t, num);
112 /* Add statement T to the single EH landing pad in REGION. */
114 static void
115 record_stmt_eh_region (eh_region region, gimple t)
117 if (region == NULL)
118 return;
119 if (region->type == ERT_MUST_NOT_THROW)
120 add_stmt_to_eh_lp_fn (cfun, t, -region->index);
121 else
123 eh_landing_pad lp = region->landing_pads;
124 if (lp == NULL)
125 lp = gen_eh_landing_pad (region);
126 else
127 gcc_assert (lp->next_lp == NULL);
128 add_stmt_to_eh_lp_fn (cfun, t, lp->index);
133 /* Remove statement T in function IFUN from its EH landing pad. */
135 bool
136 remove_stmt_from_eh_lp_fn (struct function *ifun, gimple t)
138 if (!get_eh_throw_stmt_table (ifun))
139 return false;
141 if (!get_eh_throw_stmt_table (ifun)->get (t))
142 return false;
144 get_eh_throw_stmt_table (ifun)->remove (t);
145 return true;
149 /* Remove statement T in the current function (cfun) from its
150 EH landing pad. */
152 bool
153 remove_stmt_from_eh_lp (gimple t)
155 return remove_stmt_from_eh_lp_fn (cfun, t);
158 /* Determine if statement T is inside an EH region in function IFUN.
159 Positive numbers indicate a landing pad index; negative numbers
160 indicate a MUST_NOT_THROW region index; zero indicates that the
161 statement is not recorded in the region table. */
164 lookup_stmt_eh_lp_fn (struct function *ifun, gimple t)
166 if (ifun->eh->throw_stmt_table == NULL)
167 return 0;
169 int *lp_nr = ifun->eh->throw_stmt_table->get (t);
170 return lp_nr ? *lp_nr : 0;
173 /* Likewise, but always use the current function. */
176 lookup_stmt_eh_lp (gimple t)
178 /* We can get called from initialized data when -fnon-call-exceptions
179 is on; prevent crash. */
180 if (!cfun)
181 return 0;
182 return lookup_stmt_eh_lp_fn (cfun, t);
185 /* First pass of EH node decomposition. Build up a tree of GIMPLE_TRY_FINALLY
186 nodes and LABEL_DECL nodes. We will use this during the second phase to
187 determine if a goto leaves the body of a TRY_FINALLY_EXPR node. */
189 struct finally_tree_node
191 /* When storing a GIMPLE_TRY, we have to record a gimple. However
192 when deciding whether a GOTO to a certain LABEL_DECL (which is a
193 tree) leaves the TRY block, its necessary to record a tree in
194 this field. Thus a treemple is used. */
195 treemple child;
196 gtry *parent;
199 /* Hashtable helpers. */
201 struct finally_tree_hasher : free_ptr_hash <finally_tree_node>
203 static inline hashval_t hash (const finally_tree_node *);
204 static inline bool equal (const finally_tree_node *,
205 const finally_tree_node *);
208 inline hashval_t
209 finally_tree_hasher::hash (const finally_tree_node *v)
211 return (intptr_t)v->child.t >> 4;
214 inline bool
215 finally_tree_hasher::equal (const finally_tree_node *v,
216 const finally_tree_node *c)
218 return v->child.t == c->child.t;
221 /* Note that this table is *not* marked GTY. It is short-lived. */
222 static hash_table<finally_tree_hasher> *finally_tree;
224 static void
225 record_in_finally_tree (treemple child, gtry *parent)
227 struct finally_tree_node *n;
228 finally_tree_node **slot;
230 n = XNEW (struct finally_tree_node);
231 n->child = child;
232 n->parent = parent;
234 slot = finally_tree->find_slot (n, INSERT);
235 gcc_assert (!*slot);
236 *slot = n;
239 static void
240 collect_finally_tree (gimple stmt, gtry *region);
242 /* Go through the gimple sequence. Works with collect_finally_tree to
243 record all GIMPLE_LABEL and GIMPLE_TRY statements. */
245 static void
246 collect_finally_tree_1 (gimple_seq seq, gtry *region)
248 gimple_stmt_iterator gsi;
250 for (gsi = gsi_start (seq); !gsi_end_p (gsi); gsi_next (&gsi))
251 collect_finally_tree (gsi_stmt (gsi), region);
254 static void
255 collect_finally_tree (gimple stmt, gtry *region)
257 treemple temp;
259 switch (gimple_code (stmt))
261 case GIMPLE_LABEL:
262 temp.t = gimple_label_label (as_a <glabel *> (stmt));
263 record_in_finally_tree (temp, region);
264 break;
266 case GIMPLE_TRY:
267 if (gimple_try_kind (stmt) == GIMPLE_TRY_FINALLY)
269 temp.g = stmt;
270 record_in_finally_tree (temp, region);
271 collect_finally_tree_1 (gimple_try_eval (stmt),
272 as_a <gtry *> (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 (
284 as_a <gcatch *> (stmt)),
285 region);
286 break;
288 case GIMPLE_EH_FILTER:
289 collect_finally_tree_1 (gimple_eh_filter_failure (stmt), region);
290 break;
292 case GIMPLE_EH_ELSE:
294 geh_else *eh_else_stmt = as_a <geh_else *> (stmt);
295 collect_finally_tree_1 (gimple_eh_else_n_body (eh_else_stmt), region);
296 collect_finally_tree_1 (gimple_eh_else_e_body (eh_else_stmt), region);
298 break;
300 default:
301 /* A type, a decl, or some kind of statement that we're not
302 interested in. Don't walk them. */
303 break;
308 /* Use the finally tree to determine if a jump from START to TARGET
309 would leave the try_finally node that START lives in. */
311 static bool
312 outside_finally_tree (treemple start, gimple target)
314 struct finally_tree_node n, *p;
318 n.child = start;
319 p = finally_tree->find (&n);
320 if (!p)
321 return true;
322 start.g = p->parent;
324 while (start.g != target);
326 return false;
329 /* Second pass of EH node decomposition. Actually transform the GIMPLE_TRY
330 nodes into a set of gotos, magic labels, and eh regions.
331 The eh region creation is straight-forward, but frobbing all the gotos
332 and such into shape isn't. */
334 /* The sequence into which we record all EH stuff. This will be
335 placed at the end of the function when we're all done. */
336 static gimple_seq eh_seq;
338 /* Record whether an EH region contains something that can throw,
339 indexed by EH region number. */
340 static bitmap eh_region_may_contain_throw_map;
342 /* The GOTO_QUEUE is is an array of GIMPLE_GOTO and GIMPLE_RETURN
343 statements that are seen to escape this GIMPLE_TRY_FINALLY node.
344 The idea is to record a gimple statement for everything except for
345 the conditionals, which get their labels recorded. Since labels are
346 of type 'tree', we need this node to store both gimple and tree
347 objects. REPL_STMT is the sequence used to replace the goto/return
348 statement. CONT_STMT is used to store the statement that allows
349 the return/goto to jump to the original destination. */
351 struct goto_queue_node
353 treemple stmt;
354 location_t location;
355 gimple_seq repl_stmt;
356 gimple cont_stmt;
357 int index;
358 /* This is used when index >= 0 to indicate that stmt is a label (as
359 opposed to a goto stmt). */
360 int is_label;
363 /* State of the world while lowering. */
365 struct leh_state
367 /* What's "current" while constructing the eh region tree. These
368 correspond to variables of the same name in cfun->eh, which we
369 don't have easy access to. */
370 eh_region cur_region;
372 /* What's "current" for the purposes of __builtin_eh_pointer. For
373 a CATCH, this is the associated TRY. For an EH_FILTER, this is
374 the associated ALLOWED_EXCEPTIONS, etc. */
375 eh_region ehp_region;
377 /* Processing of TRY_FINALLY requires a bit more state. This is
378 split out into a separate structure so that we don't have to
379 copy so much when processing other nodes. */
380 struct leh_tf_state *tf;
383 struct leh_tf_state
385 /* Pointer to the GIMPLE_TRY_FINALLY node under discussion. The
386 try_finally_expr is the original GIMPLE_TRY_FINALLY. We need to retain
387 this so that outside_finally_tree can reliably reference the tree used
388 in the collect_finally_tree data structures. */
389 gtry *try_finally_expr;
390 gtry *top_p;
392 /* While lowering a top_p usually it is expanded into multiple statements,
393 thus we need the following field to store them. */
394 gimple_seq top_p_seq;
396 /* The state outside this try_finally node. */
397 struct leh_state *outer;
399 /* The exception region created for it. */
400 eh_region region;
402 /* The goto queue. */
403 struct goto_queue_node *goto_queue;
404 size_t goto_queue_size;
405 size_t goto_queue_active;
407 /* Pointer map to help in searching goto_queue when it is large. */
408 hash_map<gimple, goto_queue_node *> *goto_queue_map;
410 /* The set of unique labels seen as entries in the goto queue. */
411 vec<tree> dest_array;
413 /* A label to be added at the end of the completed transformed
414 sequence. It will be set if may_fallthru was true *at one time*,
415 though subsequent transformations may have cleared that flag. */
416 tree fallthru_label;
418 /* True if it is possible to fall out the bottom of the try block.
419 Cleared if the fallthru is converted to a goto. */
420 bool may_fallthru;
422 /* True if any entry in goto_queue is a GIMPLE_RETURN. */
423 bool may_return;
425 /* True if the finally block can receive an exception edge.
426 Cleared if the exception case is handled by code duplication. */
427 bool may_throw;
430 static gimple_seq lower_eh_must_not_throw (struct leh_state *, gtry *);
432 /* Search for STMT in the goto queue. Return the replacement,
433 or null if the statement isn't in the queue. */
435 #define LARGE_GOTO_QUEUE 20
437 static void lower_eh_constructs_1 (struct leh_state *state, gimple_seq *seq);
439 static gimple_seq
440 find_goto_replacement (struct leh_tf_state *tf, treemple stmt)
442 unsigned int i;
444 if (tf->goto_queue_active < LARGE_GOTO_QUEUE)
446 for (i = 0; i < tf->goto_queue_active; i++)
447 if ( tf->goto_queue[i].stmt.g == stmt.g)
448 return tf->goto_queue[i].repl_stmt;
449 return NULL;
452 /* If we have a large number of entries in the goto_queue, create a
453 pointer map and use that for searching. */
455 if (!tf->goto_queue_map)
457 tf->goto_queue_map = new hash_map<gimple, goto_queue_node *>;
458 for (i = 0; i < tf->goto_queue_active; i++)
460 bool existed = tf->goto_queue_map->put (tf->goto_queue[i].stmt.g,
461 &tf->goto_queue[i]);
462 gcc_assert (!existed);
466 goto_queue_node **slot = tf->goto_queue_map->get (stmt.g);
467 if (slot != NULL)
468 return ((*slot)->repl_stmt);
470 return NULL;
473 /* A subroutine of replace_goto_queue_1. Handles the sub-clauses of a
474 lowered GIMPLE_COND. If, by chance, the replacement is a simple goto,
475 then we can just splat it in, otherwise we add the new stmts immediately
476 after the GIMPLE_COND and redirect. */
478 static void
479 replace_goto_queue_cond_clause (tree *tp, struct leh_tf_state *tf,
480 gimple_stmt_iterator *gsi)
482 tree label;
483 gimple_seq new_seq;
484 treemple temp;
485 location_t loc = gimple_location (gsi_stmt (*gsi));
487 temp.tp = tp;
488 new_seq = find_goto_replacement (tf, temp);
489 if (!new_seq)
490 return;
492 if (gimple_seq_singleton_p (new_seq)
493 && gimple_code (gimple_seq_first_stmt (new_seq)) == GIMPLE_GOTO)
495 *tp = gimple_goto_dest (gimple_seq_first_stmt (new_seq));
496 return;
499 label = create_artificial_label (loc);
500 /* Set the new label for the GIMPLE_COND */
501 *tp = label;
503 gsi_insert_after (gsi, gimple_build_label (label), GSI_CONTINUE_LINKING);
504 gsi_insert_seq_after (gsi, gimple_seq_copy (new_seq), GSI_CONTINUE_LINKING);
507 /* The real work of replace_goto_queue. Returns with TSI updated to
508 point to the next statement. */
510 static void replace_goto_queue_stmt_list (gimple_seq *, struct leh_tf_state *);
512 static void
513 replace_goto_queue_1 (gimple stmt, struct leh_tf_state *tf,
514 gimple_stmt_iterator *gsi)
516 gimple_seq seq;
517 treemple temp;
518 temp.g = NULL;
520 switch (gimple_code (stmt))
522 case GIMPLE_GOTO:
523 case GIMPLE_RETURN:
524 temp.g = stmt;
525 seq = find_goto_replacement (tf, temp);
526 if (seq)
528 gsi_insert_seq_before (gsi, gimple_seq_copy (seq), GSI_SAME_STMT);
529 gsi_remove (gsi, false);
530 return;
532 break;
534 case GIMPLE_COND:
535 replace_goto_queue_cond_clause (gimple_op_ptr (stmt, 2), tf, gsi);
536 replace_goto_queue_cond_clause (gimple_op_ptr (stmt, 3), tf, gsi);
537 break;
539 case GIMPLE_TRY:
540 replace_goto_queue_stmt_list (gimple_try_eval_ptr (stmt), tf);
541 replace_goto_queue_stmt_list (gimple_try_cleanup_ptr (stmt), tf);
542 break;
543 case GIMPLE_CATCH:
544 replace_goto_queue_stmt_list (gimple_catch_handler_ptr (
545 as_a <gcatch *> (stmt)),
546 tf);
547 break;
548 case GIMPLE_EH_FILTER:
549 replace_goto_queue_stmt_list (gimple_eh_filter_failure_ptr (stmt), tf);
550 break;
551 case GIMPLE_EH_ELSE:
553 geh_else *eh_else_stmt = as_a <geh_else *> (stmt);
554 replace_goto_queue_stmt_list (gimple_eh_else_n_body_ptr (eh_else_stmt),
555 tf);
556 replace_goto_queue_stmt_list (gimple_eh_else_e_body_ptr (eh_else_stmt),
557 tf);
559 break;
561 default:
562 /* These won't have gotos in them. */
563 break;
566 gsi_next (gsi);
569 /* A subroutine of replace_goto_queue. Handles GIMPLE_SEQ. */
571 static void
572 replace_goto_queue_stmt_list (gimple_seq *seq, struct leh_tf_state *tf)
574 gimple_stmt_iterator gsi = gsi_start (*seq);
576 while (!gsi_end_p (gsi))
577 replace_goto_queue_1 (gsi_stmt (gsi), tf, &gsi);
580 /* Replace all goto queue members. */
582 static void
583 replace_goto_queue (struct leh_tf_state *tf)
585 if (tf->goto_queue_active == 0)
586 return;
587 replace_goto_queue_stmt_list (&tf->top_p_seq, tf);
588 replace_goto_queue_stmt_list (&eh_seq, tf);
591 /* Add a new record to the goto queue contained in TF. NEW_STMT is the
592 data to be added, IS_LABEL indicates whether NEW_STMT is a label or
593 a gimple return. */
595 static void
596 record_in_goto_queue (struct leh_tf_state *tf,
597 treemple new_stmt,
598 int index,
599 bool is_label,
600 location_t location)
602 size_t active, size;
603 struct goto_queue_node *q;
605 gcc_assert (!tf->goto_queue_map);
607 active = tf->goto_queue_active;
608 size = tf->goto_queue_size;
609 if (active >= size)
611 size = (size ? size * 2 : 32);
612 tf->goto_queue_size = size;
613 tf->goto_queue
614 = XRESIZEVEC (struct goto_queue_node, tf->goto_queue, size);
617 q = &tf->goto_queue[active];
618 tf->goto_queue_active = active + 1;
620 memset (q, 0, sizeof (*q));
621 q->stmt = new_stmt;
622 q->index = index;
623 q->location = location;
624 q->is_label = is_label;
627 /* Record the LABEL label in the goto queue contained in TF.
628 TF is not null. */
630 static void
631 record_in_goto_queue_label (struct leh_tf_state *tf, treemple stmt, tree label,
632 location_t location)
634 int index;
635 treemple temp, new_stmt;
637 if (!label)
638 return;
640 /* Computed and non-local gotos do not get processed. Given
641 their nature we can neither tell whether we've escaped the
642 finally block nor redirect them if we knew. */
643 if (TREE_CODE (label) != LABEL_DECL)
644 return;
646 /* No need to record gotos that don't leave the try block. */
647 temp.t = label;
648 if (!outside_finally_tree (temp, tf->try_finally_expr))
649 return;
651 if (! tf->dest_array.exists ())
653 tf->dest_array.create (10);
654 tf->dest_array.quick_push (label);
655 index = 0;
657 else
659 int n = tf->dest_array.length ();
660 for (index = 0; index < n; ++index)
661 if (tf->dest_array[index] == label)
662 break;
663 if (index == n)
664 tf->dest_array.safe_push (label);
667 /* In the case of a GOTO we want to record the destination label,
668 since with a GIMPLE_COND we have an easy access to the then/else
669 labels. */
670 new_stmt = stmt;
671 record_in_goto_queue (tf, new_stmt, index, true, location);
674 /* For any GIMPLE_GOTO or GIMPLE_RETURN, decide whether it leaves a try_finally
675 node, and if so record that fact in the goto queue associated with that
676 try_finally node. */
678 static void
679 maybe_record_in_goto_queue (struct leh_state *state, gimple stmt)
681 struct leh_tf_state *tf = state->tf;
682 treemple new_stmt;
684 if (!tf)
685 return;
687 switch (gimple_code (stmt))
689 case GIMPLE_COND:
691 gcond *cond_stmt = as_a <gcond *> (stmt);
692 new_stmt.tp = gimple_op_ptr (cond_stmt, 2);
693 record_in_goto_queue_label (tf, new_stmt,
694 gimple_cond_true_label (cond_stmt),
695 EXPR_LOCATION (*new_stmt.tp));
696 new_stmt.tp = gimple_op_ptr (cond_stmt, 3);
697 record_in_goto_queue_label (tf, new_stmt,
698 gimple_cond_false_label (cond_stmt),
699 EXPR_LOCATION (*new_stmt.tp));
701 break;
702 case GIMPLE_GOTO:
703 new_stmt.g = stmt;
704 record_in_goto_queue_label (tf, new_stmt, gimple_goto_dest (stmt),
705 gimple_location (stmt));
706 break;
708 case GIMPLE_RETURN:
709 tf->may_return = true;
710 new_stmt.g = stmt;
711 record_in_goto_queue (tf, new_stmt, -1, false, gimple_location (stmt));
712 break;
714 default:
715 gcc_unreachable ();
720 #ifdef ENABLE_CHECKING
721 /* We do not process GIMPLE_SWITCHes for now. As long as the original source
722 was in fact structured, and we've not yet done jump threading, then none
723 of the labels will leave outer GIMPLE_TRY_FINALLY nodes. Verify this. */
725 static void
726 verify_norecord_switch_expr (struct leh_state *state,
727 gswitch *switch_expr)
729 struct leh_tf_state *tf = state->tf;
730 size_t i, n;
732 if (!tf)
733 return;
735 n = gimple_switch_num_labels (switch_expr);
737 for (i = 0; i < n; ++i)
739 treemple temp;
740 tree lab = CASE_LABEL (gimple_switch_label (switch_expr, i));
741 temp.t = lab;
742 gcc_assert (!outside_finally_tree (temp, tf->try_finally_expr));
745 #else
746 #define verify_norecord_switch_expr(state, switch_expr)
747 #endif
749 /* Redirect a RETURN_EXPR pointed to by Q to FINLAB. If MOD is
750 non-null, insert it before the new branch. */
752 static void
753 do_return_redirection (struct goto_queue_node *q, tree finlab, gimple_seq mod)
755 gimple x;
757 /* In the case of a return, the queue node must be a gimple statement. */
758 gcc_assert (!q->is_label);
760 /* Note that the return value may have already been computed, e.g.,
762 int x;
763 int foo (void)
765 x = 0;
766 try {
767 return x;
768 } finally {
769 x++;
773 should return 0, not 1. We don't have to do anything to make
774 this happens because the return value has been placed in the
775 RESULT_DECL already. */
777 q->cont_stmt = q->stmt.g;
779 if (mod)
780 gimple_seq_add_seq (&q->repl_stmt, mod);
782 x = gimple_build_goto (finlab);
783 gimple_set_location (x, q->location);
784 gimple_seq_add_stmt (&q->repl_stmt, x);
787 /* Similar, but easier, for GIMPLE_GOTO. */
789 static void
790 do_goto_redirection (struct goto_queue_node *q, tree finlab, gimple_seq mod,
791 struct leh_tf_state *tf)
793 ggoto *x;
795 gcc_assert (q->is_label);
797 q->cont_stmt = gimple_build_goto (tf->dest_array[q->index]);
799 if (mod)
800 gimple_seq_add_seq (&q->repl_stmt, mod);
802 x = gimple_build_goto (finlab);
803 gimple_set_location (x, q->location);
804 gimple_seq_add_stmt (&q->repl_stmt, x);
807 /* Emit a standard landing pad sequence into SEQ for REGION. */
809 static void
810 emit_post_landing_pad (gimple_seq *seq, eh_region region)
812 eh_landing_pad lp = region->landing_pads;
813 glabel *x;
815 if (lp == NULL)
816 lp = gen_eh_landing_pad (region);
818 lp->post_landing_pad = create_artificial_label (UNKNOWN_LOCATION);
819 EH_LANDING_PAD_NR (lp->post_landing_pad) = lp->index;
821 x = gimple_build_label (lp->post_landing_pad);
822 gimple_seq_add_stmt (seq, x);
825 /* Emit a RESX statement into SEQ for REGION. */
827 static void
828 emit_resx (gimple_seq *seq, eh_region region)
830 gresx *x = gimple_build_resx (region->index);
831 gimple_seq_add_stmt (seq, x);
832 if (region->outer)
833 record_stmt_eh_region (region->outer, x);
836 /* Emit an EH_DISPATCH statement into SEQ for REGION. */
838 static void
839 emit_eh_dispatch (gimple_seq *seq, eh_region region)
841 geh_dispatch *x = gimple_build_eh_dispatch (region->index);
842 gimple_seq_add_stmt (seq, x);
845 /* Note that the current EH region may contain a throw, or a
846 call to a function which itself may contain a throw. */
848 static void
849 note_eh_region_may_contain_throw (eh_region region)
851 while (bitmap_set_bit (eh_region_may_contain_throw_map, region->index))
853 if (region->type == ERT_MUST_NOT_THROW)
854 break;
855 region = region->outer;
856 if (region == NULL)
857 break;
861 /* Check if REGION has been marked as containing a throw. If REGION is
862 NULL, this predicate is false. */
864 static inline bool
865 eh_region_may_contain_throw (eh_region r)
867 return r && bitmap_bit_p (eh_region_may_contain_throw_map, r->index);
870 /* We want to transform
871 try { body; } catch { stuff; }
873 normal_sequence:
874 body;
875 over:
876 eh_sequence:
877 landing_pad:
878 stuff;
879 goto over;
881 TP is a GIMPLE_TRY node. REGION is the region whose post_landing_pad
882 should be placed before the second operand, or NULL. OVER is
883 an existing label that should be put at the exit, or NULL. */
885 static gimple_seq
886 frob_into_branch_around (gtry *tp, eh_region region, tree over)
888 gimple x;
889 gimple_seq cleanup, result;
890 location_t loc = gimple_location (tp);
892 cleanup = gimple_try_cleanup (tp);
893 result = gimple_try_eval (tp);
895 if (region)
896 emit_post_landing_pad (&eh_seq, region);
898 if (gimple_seq_may_fallthru (cleanup))
900 if (!over)
901 over = create_artificial_label (loc);
902 x = gimple_build_goto (over);
903 gimple_set_location (x, loc);
904 gimple_seq_add_stmt (&cleanup, x);
906 gimple_seq_add_seq (&eh_seq, cleanup);
908 if (over)
910 x = gimple_build_label (over);
911 gimple_seq_add_stmt (&result, x);
913 return result;
916 /* A subroutine of lower_try_finally. Duplicate the tree rooted at T.
917 Make sure to record all new labels found. */
919 static gimple_seq
920 lower_try_finally_dup_block (gimple_seq seq, struct leh_state *outer_state,
921 location_t loc)
923 gtry *region = NULL;
924 gimple_seq new_seq;
925 gimple_stmt_iterator gsi;
927 new_seq = copy_gimple_seq_and_replace_locals (seq);
929 for (gsi = gsi_start (new_seq); !gsi_end_p (gsi); gsi_next (&gsi))
931 gimple stmt = gsi_stmt (gsi);
932 if (LOCATION_LOCUS (gimple_location (stmt)) == UNKNOWN_LOCATION)
934 tree block = gimple_block (stmt);
935 gimple_set_location (stmt, loc);
936 gimple_set_block (stmt, block);
940 if (outer_state->tf)
941 region = outer_state->tf->try_finally_expr;
942 collect_finally_tree_1 (new_seq, region);
944 return new_seq;
947 /* A subroutine of lower_try_finally. Create a fallthru label for
948 the given try_finally state. The only tricky bit here is that
949 we have to make sure to record the label in our outer context. */
951 static tree
952 lower_try_finally_fallthru_label (struct leh_tf_state *tf)
954 tree label = tf->fallthru_label;
955 treemple temp;
957 if (!label)
959 label = create_artificial_label (gimple_location (tf->try_finally_expr));
960 tf->fallthru_label = label;
961 if (tf->outer->tf)
963 temp.t = label;
964 record_in_finally_tree (temp, tf->outer->tf->try_finally_expr);
967 return label;
970 /* A subroutine of lower_try_finally. If FINALLY consits of a
971 GIMPLE_EH_ELSE node, return it. */
973 static inline geh_else *
974 get_eh_else (gimple_seq finally)
976 gimple x = gimple_seq_first_stmt (finally);
977 if (gimple_code (x) == GIMPLE_EH_ELSE)
979 gcc_assert (gimple_seq_singleton_p (finally));
980 return as_a <geh_else *> (x);
982 return NULL;
985 /* A subroutine of lower_try_finally. If the eh_protect_cleanup_actions
986 langhook returns non-null, then the language requires that the exception
987 path out of a try_finally be treated specially. To wit: the code within
988 the finally block may not itself throw an exception. We have two choices
989 here. First we can duplicate the finally block and wrap it in a
990 must_not_throw region. Second, we can generate code like
992 try {
993 finally_block;
994 } catch {
995 if (fintmp == eh_edge)
996 protect_cleanup_actions;
999 where "fintmp" is the temporary used in the switch statement generation
1000 alternative considered below. For the nonce, we always choose the first
1001 option.
1003 THIS_STATE may be null if this is a try-cleanup, not a try-finally. */
1005 static void
1006 honor_protect_cleanup_actions (struct leh_state *outer_state,
1007 struct leh_state *this_state,
1008 struct leh_tf_state *tf)
1010 tree protect_cleanup_actions;
1011 gimple_stmt_iterator gsi;
1012 bool finally_may_fallthru;
1013 gimple_seq finally;
1014 gimple x;
1015 geh_mnt *eh_mnt;
1016 gtry *try_stmt;
1017 geh_else *eh_else;
1019 /* First check for nothing to do. */
1020 if (lang_hooks.eh_protect_cleanup_actions == NULL)
1021 return;
1022 protect_cleanup_actions = lang_hooks.eh_protect_cleanup_actions ();
1023 if (protect_cleanup_actions == NULL)
1024 return;
1026 finally = gimple_try_cleanup (tf->top_p);
1027 eh_else = get_eh_else (finally);
1029 /* Duplicate the FINALLY block. Only need to do this for try-finally,
1030 and not for cleanups. If we've got an EH_ELSE, extract it now. */
1031 if (eh_else)
1033 finally = gimple_eh_else_e_body (eh_else);
1034 gimple_try_set_cleanup (tf->top_p, gimple_eh_else_n_body (eh_else));
1036 else if (this_state)
1037 finally = lower_try_finally_dup_block (finally, outer_state,
1038 gimple_location (tf->try_finally_expr));
1039 finally_may_fallthru = gimple_seq_may_fallthru (finally);
1041 /* If this cleanup consists of a TRY_CATCH_EXPR with TRY_CATCH_IS_CLEANUP
1042 set, the handler of the TRY_CATCH_EXPR is another cleanup which ought
1043 to be in an enclosing scope, but needs to be implemented at this level
1044 to avoid a nesting violation (see wrap_temporary_cleanups in
1045 cp/decl.c). Since it's logically at an outer level, we should call
1046 terminate before we get to it, so strip it away before adding the
1047 MUST_NOT_THROW filter. */
1048 gsi = gsi_start (finally);
1049 x = gsi_stmt (gsi);
1050 if (gimple_code (x) == GIMPLE_TRY
1051 && gimple_try_kind (x) == GIMPLE_TRY_CATCH
1052 && gimple_try_catch_is_cleanup (x))
1054 gsi_insert_seq_before (&gsi, gimple_try_eval (x), GSI_SAME_STMT);
1055 gsi_remove (&gsi, false);
1058 /* Wrap the block with protect_cleanup_actions as the action. */
1059 eh_mnt = gimple_build_eh_must_not_throw (protect_cleanup_actions);
1060 try_stmt = gimple_build_try (finally, gimple_seq_alloc_with_stmt (eh_mnt),
1061 GIMPLE_TRY_CATCH);
1062 finally = lower_eh_must_not_throw (outer_state, try_stmt);
1064 /* Drop all of this into the exception sequence. */
1065 emit_post_landing_pad (&eh_seq, tf->region);
1066 gimple_seq_add_seq (&eh_seq, finally);
1067 if (finally_may_fallthru)
1068 emit_resx (&eh_seq, tf->region);
1070 /* Having now been handled, EH isn't to be considered with
1071 the rest of the outgoing edges. */
1072 tf->may_throw = false;
1075 /* A subroutine of lower_try_finally. We have determined that there is
1076 no fallthru edge out of the finally block. This means that there is
1077 no outgoing edge corresponding to any incoming edge. Restructure the
1078 try_finally node for this special case. */
1080 static void
1081 lower_try_finally_nofallthru (struct leh_state *state,
1082 struct leh_tf_state *tf)
1084 tree lab;
1085 gimple x;
1086 geh_else *eh_else;
1087 gimple_seq finally;
1088 struct goto_queue_node *q, *qe;
1090 lab = create_artificial_label (gimple_location (tf->try_finally_expr));
1092 /* We expect that tf->top_p is a GIMPLE_TRY. */
1093 finally = gimple_try_cleanup (tf->top_p);
1094 tf->top_p_seq = gimple_try_eval (tf->top_p);
1096 x = gimple_build_label (lab);
1097 gimple_seq_add_stmt (&tf->top_p_seq, x);
1099 q = tf->goto_queue;
1100 qe = q + tf->goto_queue_active;
1101 for (; q < qe; ++q)
1102 if (q->index < 0)
1103 do_return_redirection (q, lab, NULL);
1104 else
1105 do_goto_redirection (q, lab, NULL, tf);
1107 replace_goto_queue (tf);
1109 /* Emit the finally block into the stream. Lower EH_ELSE at this time. */
1110 eh_else = get_eh_else (finally);
1111 if (eh_else)
1113 finally = gimple_eh_else_n_body (eh_else);
1114 lower_eh_constructs_1 (state, &finally);
1115 gimple_seq_add_seq (&tf->top_p_seq, finally);
1117 if (tf->may_throw)
1119 finally = gimple_eh_else_e_body (eh_else);
1120 lower_eh_constructs_1 (state, &finally);
1122 emit_post_landing_pad (&eh_seq, tf->region);
1123 gimple_seq_add_seq (&eh_seq, finally);
1126 else
1128 lower_eh_constructs_1 (state, &finally);
1129 gimple_seq_add_seq (&tf->top_p_seq, finally);
1131 if (tf->may_throw)
1133 emit_post_landing_pad (&eh_seq, tf->region);
1135 x = gimple_build_goto (lab);
1136 gimple_set_location (x, gimple_location (tf->try_finally_expr));
1137 gimple_seq_add_stmt (&eh_seq, x);
1142 /* A subroutine of lower_try_finally. We have determined that there is
1143 exactly one destination of the finally block. Restructure the
1144 try_finally node for this special case. */
1146 static void
1147 lower_try_finally_onedest (struct leh_state *state, struct leh_tf_state *tf)
1149 struct goto_queue_node *q, *qe;
1150 geh_else *eh_else;
1151 glabel *label_stmt;
1152 gimple x;
1153 gimple_seq finally;
1154 gimple_stmt_iterator gsi;
1155 tree finally_label;
1156 location_t loc = gimple_location (tf->try_finally_expr);
1158 finally = gimple_try_cleanup (tf->top_p);
1159 tf->top_p_seq = gimple_try_eval (tf->top_p);
1161 /* Since there's only one destination, and the destination edge can only
1162 either be EH or non-EH, that implies that all of our incoming edges
1163 are of the same type. Therefore we can lower EH_ELSE immediately. */
1164 eh_else = get_eh_else (finally);
1165 if (eh_else)
1167 if (tf->may_throw)
1168 finally = gimple_eh_else_e_body (eh_else);
1169 else
1170 finally = gimple_eh_else_n_body (eh_else);
1173 lower_eh_constructs_1 (state, &finally);
1175 for (gsi = gsi_start (finally); !gsi_end_p (gsi); gsi_next (&gsi))
1177 gimple stmt = gsi_stmt (gsi);
1178 if (LOCATION_LOCUS (gimple_location (stmt)) == UNKNOWN_LOCATION)
1180 tree block = gimple_block (stmt);
1181 gimple_set_location (stmt, gimple_location (tf->try_finally_expr));
1182 gimple_set_block (stmt, block);
1186 if (tf->may_throw)
1188 /* Only reachable via the exception edge. Add the given label to
1189 the head of the FINALLY block. Append a RESX at the end. */
1190 emit_post_landing_pad (&eh_seq, tf->region);
1191 gimple_seq_add_seq (&eh_seq, finally);
1192 emit_resx (&eh_seq, tf->region);
1193 return;
1196 if (tf->may_fallthru)
1198 /* Only reachable via the fallthru edge. Do nothing but let
1199 the two blocks run together; we'll fall out the bottom. */
1200 gimple_seq_add_seq (&tf->top_p_seq, finally);
1201 return;
1204 finally_label = create_artificial_label (loc);
1205 label_stmt = gimple_build_label (finally_label);
1206 gimple_seq_add_stmt (&tf->top_p_seq, label_stmt);
1208 gimple_seq_add_seq (&tf->top_p_seq, finally);
1210 q = tf->goto_queue;
1211 qe = q + tf->goto_queue_active;
1213 if (tf->may_return)
1215 /* Reachable by return expressions only. Redirect them. */
1216 for (; q < qe; ++q)
1217 do_return_redirection (q, finally_label, NULL);
1218 replace_goto_queue (tf);
1220 else
1222 /* Reachable by goto expressions only. Redirect them. */
1223 for (; q < qe; ++q)
1224 do_goto_redirection (q, finally_label, NULL, tf);
1225 replace_goto_queue (tf);
1227 if (tf->dest_array[0] == tf->fallthru_label)
1229 /* Reachable by goto to fallthru label only. Redirect it
1230 to the new label (already created, sadly), and do not
1231 emit the final branch out, or the fallthru label. */
1232 tf->fallthru_label = NULL;
1233 return;
1237 /* Place the original return/goto to the original destination
1238 immediately after the finally block. */
1239 x = tf->goto_queue[0].cont_stmt;
1240 gimple_seq_add_stmt (&tf->top_p_seq, x);
1241 maybe_record_in_goto_queue (state, x);
1244 /* A subroutine of lower_try_finally. There are multiple edges incoming
1245 and outgoing from the finally block. Implement this by duplicating the
1246 finally block for every destination. */
1248 static void
1249 lower_try_finally_copy (struct leh_state *state, struct leh_tf_state *tf)
1251 gimple_seq finally;
1252 gimple_seq new_stmt;
1253 gimple_seq seq;
1254 gimple x;
1255 geh_else *eh_else;
1256 tree tmp;
1257 location_t tf_loc = gimple_location (tf->try_finally_expr);
1259 finally = gimple_try_cleanup (tf->top_p);
1261 /* Notice EH_ELSE, and simplify some of the remaining code
1262 by considering FINALLY to be the normal return path only. */
1263 eh_else = get_eh_else (finally);
1264 if (eh_else)
1265 finally = gimple_eh_else_n_body (eh_else);
1267 tf->top_p_seq = gimple_try_eval (tf->top_p);
1268 new_stmt = NULL;
1270 if (tf->may_fallthru)
1272 seq = lower_try_finally_dup_block (finally, state, tf_loc);
1273 lower_eh_constructs_1 (state, &seq);
1274 gimple_seq_add_seq (&new_stmt, seq);
1276 tmp = lower_try_finally_fallthru_label (tf);
1277 x = gimple_build_goto (tmp);
1278 gimple_set_location (x, tf_loc);
1279 gimple_seq_add_stmt (&new_stmt, x);
1282 if (tf->may_throw)
1284 /* We don't need to copy the EH path of EH_ELSE,
1285 since it is only emitted once. */
1286 if (eh_else)
1287 seq = gimple_eh_else_e_body (eh_else);
1288 else
1289 seq = lower_try_finally_dup_block (finally, state, tf_loc);
1290 lower_eh_constructs_1 (state, &seq);
1292 emit_post_landing_pad (&eh_seq, tf->region);
1293 gimple_seq_add_seq (&eh_seq, seq);
1294 emit_resx (&eh_seq, tf->region);
1297 if (tf->goto_queue)
1299 struct goto_queue_node *q, *qe;
1300 int return_index, index;
1301 struct labels_s
1303 struct goto_queue_node *q;
1304 tree label;
1305 } *labels;
1307 return_index = tf->dest_array.length ();
1308 labels = XCNEWVEC (struct labels_s, return_index + 1);
1310 q = tf->goto_queue;
1311 qe = q + tf->goto_queue_active;
1312 for (; q < qe; q++)
1314 index = q->index < 0 ? return_index : q->index;
1316 if (!labels[index].q)
1317 labels[index].q = q;
1320 for (index = 0; index < return_index + 1; index++)
1322 tree lab;
1324 q = labels[index].q;
1325 if (! q)
1326 continue;
1328 lab = labels[index].label
1329 = create_artificial_label (tf_loc);
1331 if (index == return_index)
1332 do_return_redirection (q, lab, NULL);
1333 else
1334 do_goto_redirection (q, lab, NULL, tf);
1336 x = gimple_build_label (lab);
1337 gimple_seq_add_stmt (&new_stmt, x);
1339 seq = lower_try_finally_dup_block (finally, state, q->location);
1340 lower_eh_constructs_1 (state, &seq);
1341 gimple_seq_add_seq (&new_stmt, seq);
1343 gimple_seq_add_stmt (&new_stmt, q->cont_stmt);
1344 maybe_record_in_goto_queue (state, q->cont_stmt);
1347 for (q = tf->goto_queue; q < qe; q++)
1349 tree lab;
1351 index = q->index < 0 ? return_index : q->index;
1353 if (labels[index].q == q)
1354 continue;
1356 lab = labels[index].label;
1358 if (index == return_index)
1359 do_return_redirection (q, lab, NULL);
1360 else
1361 do_goto_redirection (q, lab, NULL, tf);
1364 replace_goto_queue (tf);
1365 free (labels);
1368 /* Need to link new stmts after running replace_goto_queue due
1369 to not wanting to process the same goto stmts twice. */
1370 gimple_seq_add_seq (&tf->top_p_seq, new_stmt);
1373 /* A subroutine of lower_try_finally. There are multiple edges incoming
1374 and outgoing from the finally block. Implement this by instrumenting
1375 each incoming edge and creating a switch statement at the end of the
1376 finally block that branches to the appropriate destination. */
1378 static void
1379 lower_try_finally_switch (struct leh_state *state, struct leh_tf_state *tf)
1381 struct goto_queue_node *q, *qe;
1382 tree finally_tmp, finally_label;
1383 int return_index, eh_index, fallthru_index;
1384 int nlabels, ndests, j, last_case_index;
1385 tree last_case;
1386 vec<tree> case_label_vec;
1387 gimple_seq switch_body = NULL;
1388 gimple x;
1389 geh_else *eh_else;
1390 tree tmp;
1391 gimple switch_stmt;
1392 gimple_seq finally;
1393 hash_map<tree, gimple> *cont_map = NULL;
1394 /* The location of the TRY_FINALLY stmt. */
1395 location_t tf_loc = gimple_location (tf->try_finally_expr);
1396 /* The location of the finally block. */
1397 location_t finally_loc;
1399 finally = gimple_try_cleanup (tf->top_p);
1400 eh_else = get_eh_else (finally);
1402 /* Mash the TRY block to the head of the chain. */
1403 tf->top_p_seq = gimple_try_eval (tf->top_p);
1405 /* The location of the finally is either the last stmt in the finally
1406 block or the location of the TRY_FINALLY itself. */
1407 x = gimple_seq_last_stmt (finally);
1408 finally_loc = x ? gimple_location (x) : tf_loc;
1410 /* Prepare for switch statement generation. */
1411 nlabels = tf->dest_array.length ();
1412 return_index = nlabels;
1413 eh_index = return_index + tf->may_return;
1414 fallthru_index = eh_index + (tf->may_throw && !eh_else);
1415 ndests = fallthru_index + tf->may_fallthru;
1417 finally_tmp = create_tmp_var (integer_type_node, "finally_tmp");
1418 finally_label = create_artificial_label (finally_loc);
1420 /* We use vec::quick_push on case_label_vec throughout this function,
1421 since we know the size in advance and allocate precisely as muce
1422 space as needed. */
1423 case_label_vec.create (ndests);
1424 last_case = NULL;
1425 last_case_index = 0;
1427 /* Begin inserting code for getting to the finally block. Things
1428 are done in this order to correspond to the sequence the code is
1429 laid out. */
1431 if (tf->may_fallthru)
1433 x = gimple_build_assign (finally_tmp,
1434 build_int_cst (integer_type_node,
1435 fallthru_index));
1436 gimple_seq_add_stmt (&tf->top_p_seq, x);
1438 tmp = build_int_cst (integer_type_node, fallthru_index);
1439 last_case = build_case_label (tmp, NULL,
1440 create_artificial_label (tf_loc));
1441 case_label_vec.quick_push (last_case);
1442 last_case_index++;
1444 x = gimple_build_label (CASE_LABEL (last_case));
1445 gimple_seq_add_stmt (&switch_body, x);
1447 tmp = lower_try_finally_fallthru_label (tf);
1448 x = gimple_build_goto (tmp);
1449 gimple_set_location (x, tf_loc);
1450 gimple_seq_add_stmt (&switch_body, x);
1453 /* For EH_ELSE, emit the exception path (plus resx) now, then
1454 subsequently we only need consider the normal path. */
1455 if (eh_else)
1457 if (tf->may_throw)
1459 finally = gimple_eh_else_e_body (eh_else);
1460 lower_eh_constructs_1 (state, &finally);
1462 emit_post_landing_pad (&eh_seq, tf->region);
1463 gimple_seq_add_seq (&eh_seq, finally);
1464 emit_resx (&eh_seq, tf->region);
1467 finally = gimple_eh_else_n_body (eh_else);
1469 else if (tf->may_throw)
1471 emit_post_landing_pad (&eh_seq, tf->region);
1473 x = gimple_build_assign (finally_tmp,
1474 build_int_cst (integer_type_node, eh_index));
1475 gimple_seq_add_stmt (&eh_seq, x);
1477 x = gimple_build_goto (finally_label);
1478 gimple_set_location (x, tf_loc);
1479 gimple_seq_add_stmt (&eh_seq, x);
1481 tmp = build_int_cst (integer_type_node, eh_index);
1482 last_case = build_case_label (tmp, NULL,
1483 create_artificial_label (tf_loc));
1484 case_label_vec.quick_push (last_case);
1485 last_case_index++;
1487 x = gimple_build_label (CASE_LABEL (last_case));
1488 gimple_seq_add_stmt (&eh_seq, x);
1489 emit_resx (&eh_seq, tf->region);
1492 x = gimple_build_label (finally_label);
1493 gimple_seq_add_stmt (&tf->top_p_seq, x);
1495 lower_eh_constructs_1 (state, &finally);
1496 gimple_seq_add_seq (&tf->top_p_seq, finally);
1498 /* Redirect each incoming goto edge. */
1499 q = tf->goto_queue;
1500 qe = q + tf->goto_queue_active;
1501 j = last_case_index + tf->may_return;
1502 /* Prepare the assignments to finally_tmp that are executed upon the
1503 entrance through a particular edge. */
1504 for (; q < qe; ++q)
1506 gimple_seq mod = NULL;
1507 int switch_id;
1508 unsigned int case_index;
1510 if (q->index < 0)
1512 x = gimple_build_assign (finally_tmp,
1513 build_int_cst (integer_type_node,
1514 return_index));
1515 gimple_seq_add_stmt (&mod, x);
1516 do_return_redirection (q, finally_label, mod);
1517 switch_id = return_index;
1519 else
1521 x = gimple_build_assign (finally_tmp,
1522 build_int_cst (integer_type_node, q->index));
1523 gimple_seq_add_stmt (&mod, x);
1524 do_goto_redirection (q, finally_label, mod, tf);
1525 switch_id = q->index;
1528 case_index = j + q->index;
1529 if (case_label_vec.length () <= case_index || !case_label_vec[case_index])
1531 tree case_lab;
1532 tmp = build_int_cst (integer_type_node, switch_id);
1533 case_lab = build_case_label (tmp, NULL,
1534 create_artificial_label (tf_loc));
1535 /* We store the cont_stmt in the pointer map, so that we can recover
1536 it in the loop below. */
1537 if (!cont_map)
1538 cont_map = new hash_map<tree, gimple>;
1539 cont_map->put (case_lab, q->cont_stmt);
1540 case_label_vec.quick_push (case_lab);
1543 for (j = last_case_index; j < last_case_index + nlabels; j++)
1545 gimple cont_stmt;
1547 last_case = case_label_vec[j];
1549 gcc_assert (last_case);
1550 gcc_assert (cont_map);
1552 cont_stmt = *cont_map->get (last_case);
1554 x = gimple_build_label (CASE_LABEL (last_case));
1555 gimple_seq_add_stmt (&switch_body, x);
1556 gimple_seq_add_stmt (&switch_body, cont_stmt);
1557 maybe_record_in_goto_queue (state, cont_stmt);
1559 if (cont_map)
1560 delete cont_map;
1562 replace_goto_queue (tf);
1564 /* Make sure that the last case is the default label, as one is required.
1565 Then sort the labels, which is also required in GIMPLE. */
1566 CASE_LOW (last_case) = NULL;
1567 tree tem = case_label_vec.pop ();
1568 gcc_assert (tem == last_case);
1569 sort_case_labels (case_label_vec);
1571 /* Build the switch statement, setting last_case to be the default
1572 label. */
1573 switch_stmt = gimple_build_switch (finally_tmp, last_case,
1574 case_label_vec);
1575 gimple_set_location (switch_stmt, finally_loc);
1577 /* Need to link SWITCH_STMT after running replace_goto_queue
1578 due to not wanting to process the same goto stmts twice. */
1579 gimple_seq_add_stmt (&tf->top_p_seq, switch_stmt);
1580 gimple_seq_add_seq (&tf->top_p_seq, switch_body);
1583 /* Decide whether or not we are going to duplicate the finally block.
1584 There are several considerations.
1586 First, if this is Java, then the finally block contains code
1587 written by the user. It has line numbers associated with it,
1588 so duplicating the block means it's difficult to set a breakpoint.
1589 Since controlling code generation via -g is verboten, we simply
1590 never duplicate code without optimization.
1592 Second, we'd like to prevent egregious code growth. One way to
1593 do this is to estimate the size of the finally block, multiply
1594 that by the number of copies we'd need to make, and compare against
1595 the estimate of the size of the switch machinery we'd have to add. */
1597 static bool
1598 decide_copy_try_finally (int ndests, bool may_throw, gimple_seq finally)
1600 int f_estimate, sw_estimate;
1601 geh_else *eh_else;
1603 /* If there's an EH_ELSE involved, the exception path is separate
1604 and really doesn't come into play for this computation. */
1605 eh_else = get_eh_else (finally);
1606 if (eh_else)
1608 ndests -= may_throw;
1609 finally = gimple_eh_else_n_body (eh_else);
1612 if (!optimize)
1614 gimple_stmt_iterator gsi;
1616 if (ndests == 1)
1617 return true;
1619 for (gsi = gsi_start (finally); !gsi_end_p (gsi); gsi_next (&gsi))
1621 gimple stmt = gsi_stmt (gsi);
1622 if (!is_gimple_debug (stmt) && !gimple_clobber_p (stmt))
1623 return false;
1625 return true;
1628 /* Finally estimate N times, plus N gotos. */
1629 f_estimate = count_insns_seq (finally, &eni_size_weights);
1630 f_estimate = (f_estimate + 1) * ndests;
1632 /* Switch statement (cost 10), N variable assignments, N gotos. */
1633 sw_estimate = 10 + 2 * ndests;
1635 /* Optimize for size clearly wants our best guess. */
1636 if (optimize_function_for_size_p (cfun))
1637 return f_estimate < sw_estimate;
1639 /* ??? These numbers are completely made up so far. */
1640 if (optimize > 1)
1641 return f_estimate < 100 || f_estimate < sw_estimate * 2;
1642 else
1643 return f_estimate < 40 || f_estimate * 2 < sw_estimate * 3;
1646 /* REG is the enclosing region for a possible cleanup region, or the region
1647 itself. Returns TRUE if such a region would be unreachable.
1649 Cleanup regions within a must-not-throw region aren't actually reachable
1650 even if there are throwing stmts within them, because the personality
1651 routine will call terminate before unwinding. */
1653 static bool
1654 cleanup_is_dead_in (eh_region reg)
1656 while (reg && reg->type == ERT_CLEANUP)
1657 reg = reg->outer;
1658 return (reg && reg->type == ERT_MUST_NOT_THROW);
1661 /* A subroutine of lower_eh_constructs_1. Lower a GIMPLE_TRY_FINALLY nodes
1662 to a sequence of labels and blocks, plus the exception region trees
1663 that record all the magic. This is complicated by the need to
1664 arrange for the FINALLY block to be executed on all exits. */
1666 static gimple_seq
1667 lower_try_finally (struct leh_state *state, gtry *tp)
1669 struct leh_tf_state this_tf;
1670 struct leh_state this_state;
1671 int ndests;
1672 gimple_seq old_eh_seq;
1674 /* Process the try block. */
1676 memset (&this_tf, 0, sizeof (this_tf));
1677 this_tf.try_finally_expr = tp;
1678 this_tf.top_p = tp;
1679 this_tf.outer = state;
1680 if (using_eh_for_cleanups_p () && !cleanup_is_dead_in (state->cur_region))
1682 this_tf.region = gen_eh_region_cleanup (state->cur_region);
1683 this_state.cur_region = this_tf.region;
1685 else
1687 this_tf.region = NULL;
1688 this_state.cur_region = state->cur_region;
1691 this_state.ehp_region = state->ehp_region;
1692 this_state.tf = &this_tf;
1694 old_eh_seq = eh_seq;
1695 eh_seq = NULL;
1697 lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1699 /* Determine if the try block is escaped through the bottom. */
1700 this_tf.may_fallthru = gimple_seq_may_fallthru (gimple_try_eval (tp));
1702 /* Determine if any exceptions are possible within the try block. */
1703 if (this_tf.region)
1704 this_tf.may_throw = eh_region_may_contain_throw (this_tf.region);
1705 if (this_tf.may_throw)
1706 honor_protect_cleanup_actions (state, &this_state, &this_tf);
1708 /* Determine how many edges (still) reach the finally block. Or rather,
1709 how many destinations are reached by the finally block. Use this to
1710 determine how we process the finally block itself. */
1712 ndests = this_tf.dest_array.length ();
1713 ndests += this_tf.may_fallthru;
1714 ndests += this_tf.may_return;
1715 ndests += this_tf.may_throw;
1717 /* If the FINALLY block is not reachable, dike it out. */
1718 if (ndests == 0)
1720 gimple_seq_add_seq (&this_tf.top_p_seq, gimple_try_eval (tp));
1721 gimple_try_set_cleanup (tp, NULL);
1723 /* If the finally block doesn't fall through, then any destination
1724 we might try to impose there isn't reached either. There may be
1725 some minor amount of cleanup and redirection still needed. */
1726 else if (!gimple_seq_may_fallthru (gimple_try_cleanup (tp)))
1727 lower_try_finally_nofallthru (state, &this_tf);
1729 /* We can easily special-case redirection to a single destination. */
1730 else if (ndests == 1)
1731 lower_try_finally_onedest (state, &this_tf);
1732 else if (decide_copy_try_finally (ndests, this_tf.may_throw,
1733 gimple_try_cleanup (tp)))
1734 lower_try_finally_copy (state, &this_tf);
1735 else
1736 lower_try_finally_switch (state, &this_tf);
1738 /* If someone requested we add a label at the end of the transformed
1739 block, do so. */
1740 if (this_tf.fallthru_label)
1742 /* This must be reached only if ndests == 0. */
1743 gimple x = gimple_build_label (this_tf.fallthru_label);
1744 gimple_seq_add_stmt (&this_tf.top_p_seq, x);
1747 this_tf.dest_array.release ();
1748 free (this_tf.goto_queue);
1749 if (this_tf.goto_queue_map)
1750 delete this_tf.goto_queue_map;
1752 /* If there was an old (aka outer) eh_seq, append the current eh_seq.
1753 If there was no old eh_seq, then the append is trivially already done. */
1754 if (old_eh_seq)
1756 if (eh_seq == NULL)
1757 eh_seq = old_eh_seq;
1758 else
1760 gimple_seq new_eh_seq = eh_seq;
1761 eh_seq = old_eh_seq;
1762 gimple_seq_add_seq (&eh_seq, new_eh_seq);
1766 return this_tf.top_p_seq;
1769 /* A subroutine of lower_eh_constructs_1. Lower a GIMPLE_TRY_CATCH with a
1770 list of GIMPLE_CATCH to a sequence of labels and blocks, plus the
1771 exception region trees that records all the magic. */
1773 static gimple_seq
1774 lower_catch (struct leh_state *state, gtry *tp)
1776 eh_region try_region = NULL;
1777 struct leh_state this_state = *state;
1778 gimple_stmt_iterator gsi;
1779 tree out_label;
1780 gimple_seq new_seq, cleanup;
1781 gimple x;
1782 location_t try_catch_loc = gimple_location (tp);
1784 if (flag_exceptions)
1786 try_region = gen_eh_region_try (state->cur_region);
1787 this_state.cur_region = try_region;
1790 lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1792 if (!eh_region_may_contain_throw (try_region))
1793 return gimple_try_eval (tp);
1795 new_seq = NULL;
1796 emit_eh_dispatch (&new_seq, try_region);
1797 emit_resx (&new_seq, try_region);
1799 this_state.cur_region = state->cur_region;
1800 this_state.ehp_region = try_region;
1802 /* Add eh_seq from lowering EH in the cleanup sequence after the cleanup
1803 itself, so that e.g. for coverage purposes the nested cleanups don't
1804 appear before the cleanup body. See PR64634 for details. */
1805 gimple_seq old_eh_seq = eh_seq;
1806 eh_seq = NULL;
1808 out_label = NULL;
1809 cleanup = gimple_try_cleanup (tp);
1810 for (gsi = gsi_start (cleanup);
1811 !gsi_end_p (gsi);
1812 gsi_next (&gsi))
1814 eh_catch c;
1815 gcatch *catch_stmt;
1816 gimple_seq handler;
1818 catch_stmt = as_a <gcatch *> (gsi_stmt (gsi));
1819 c = gen_eh_region_catch (try_region, gimple_catch_types (catch_stmt));
1821 handler = gimple_catch_handler (catch_stmt);
1822 lower_eh_constructs_1 (&this_state, &handler);
1824 c->label = create_artificial_label (UNKNOWN_LOCATION);
1825 x = gimple_build_label (c->label);
1826 gimple_seq_add_stmt (&new_seq, x);
1828 gimple_seq_add_seq (&new_seq, handler);
1830 if (gimple_seq_may_fallthru (new_seq))
1832 if (!out_label)
1833 out_label = create_artificial_label (try_catch_loc);
1835 x = gimple_build_goto (out_label);
1836 gimple_seq_add_stmt (&new_seq, x);
1838 if (!c->type_list)
1839 break;
1842 gimple_try_set_cleanup (tp, new_seq);
1844 gimple_seq new_eh_seq = eh_seq;
1845 eh_seq = old_eh_seq;
1846 gimple_seq ret_seq = frob_into_branch_around (tp, try_region, out_label);
1847 gimple_seq_add_seq (&eh_seq, new_eh_seq);
1848 return ret_seq;
1851 /* A subroutine of lower_eh_constructs_1. Lower a GIMPLE_TRY with a
1852 GIMPLE_EH_FILTER to a sequence of labels and blocks, plus the exception
1853 region trees that record all the magic. */
1855 static gimple_seq
1856 lower_eh_filter (struct leh_state *state, gtry *tp)
1858 struct leh_state this_state = *state;
1859 eh_region this_region = NULL;
1860 gimple inner, x;
1861 gimple_seq new_seq;
1863 inner = gimple_seq_first_stmt (gimple_try_cleanup (tp));
1865 if (flag_exceptions)
1867 this_region = gen_eh_region_allowed (state->cur_region,
1868 gimple_eh_filter_types (inner));
1869 this_state.cur_region = this_region;
1872 lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1874 if (!eh_region_may_contain_throw (this_region))
1875 return gimple_try_eval (tp);
1877 new_seq = NULL;
1878 this_state.cur_region = state->cur_region;
1879 this_state.ehp_region = this_region;
1881 emit_eh_dispatch (&new_seq, this_region);
1882 emit_resx (&new_seq, this_region);
1884 this_region->u.allowed.label = create_artificial_label (UNKNOWN_LOCATION);
1885 x = gimple_build_label (this_region->u.allowed.label);
1886 gimple_seq_add_stmt (&new_seq, x);
1888 lower_eh_constructs_1 (&this_state, gimple_eh_filter_failure_ptr (inner));
1889 gimple_seq_add_seq (&new_seq, gimple_eh_filter_failure (inner));
1891 gimple_try_set_cleanup (tp, new_seq);
1893 return frob_into_branch_around (tp, this_region, NULL);
1896 /* A subroutine of lower_eh_constructs_1. Lower a GIMPLE_TRY with
1897 an GIMPLE_EH_MUST_NOT_THROW to a sequence of labels and blocks,
1898 plus the exception region trees that record all the magic. */
1900 static gimple_seq
1901 lower_eh_must_not_throw (struct leh_state *state, gtry *tp)
1903 struct leh_state this_state = *state;
1905 if (flag_exceptions)
1907 gimple inner = gimple_seq_first_stmt (gimple_try_cleanup (tp));
1908 eh_region this_region;
1910 this_region = gen_eh_region_must_not_throw (state->cur_region);
1911 this_region->u.must_not_throw.failure_decl
1912 = gimple_eh_must_not_throw_fndecl (
1913 as_a <geh_mnt *> (inner));
1914 this_region->u.must_not_throw.failure_loc
1915 = LOCATION_LOCUS (gimple_location (tp));
1917 /* In order to get mangling applied to this decl, we must mark it
1918 used now. Otherwise, pass_ipa_free_lang_data won't think it
1919 needs to happen. */
1920 TREE_USED (this_region->u.must_not_throw.failure_decl) = 1;
1922 this_state.cur_region = this_region;
1925 lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1927 return gimple_try_eval (tp);
1930 /* Implement a cleanup expression. This is similar to try-finally,
1931 except that we only execute the cleanup block for exception edges. */
1933 static gimple_seq
1934 lower_cleanup (struct leh_state *state, gtry *tp)
1936 struct leh_state this_state = *state;
1937 eh_region this_region = NULL;
1938 struct leh_tf_state fake_tf;
1939 gimple_seq result;
1940 bool cleanup_dead = cleanup_is_dead_in (state->cur_region);
1942 if (flag_exceptions && !cleanup_dead)
1944 this_region = gen_eh_region_cleanup (state->cur_region);
1945 this_state.cur_region = this_region;
1948 lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1950 if (cleanup_dead || !eh_region_may_contain_throw (this_region))
1951 return gimple_try_eval (tp);
1953 /* Build enough of a try-finally state so that we can reuse
1954 honor_protect_cleanup_actions. */
1955 memset (&fake_tf, 0, sizeof (fake_tf));
1956 fake_tf.top_p = fake_tf.try_finally_expr = tp;
1957 fake_tf.outer = state;
1958 fake_tf.region = this_region;
1959 fake_tf.may_fallthru = gimple_seq_may_fallthru (gimple_try_eval (tp));
1960 fake_tf.may_throw = true;
1962 honor_protect_cleanup_actions (state, NULL, &fake_tf);
1964 if (fake_tf.may_throw)
1966 /* In this case honor_protect_cleanup_actions had nothing to do,
1967 and we should process this normally. */
1968 lower_eh_constructs_1 (state, gimple_try_cleanup_ptr (tp));
1969 result = frob_into_branch_around (tp, this_region,
1970 fake_tf.fallthru_label);
1972 else
1974 /* In this case honor_protect_cleanup_actions did nearly all of
1975 the work. All we have left is to append the fallthru_label. */
1977 result = gimple_try_eval (tp);
1978 if (fake_tf.fallthru_label)
1980 gimple x = gimple_build_label (fake_tf.fallthru_label);
1981 gimple_seq_add_stmt (&result, x);
1984 return result;
1987 /* Main loop for lowering eh constructs. Also moves gsi to the next
1988 statement. */
1990 static void
1991 lower_eh_constructs_2 (struct leh_state *state, gimple_stmt_iterator *gsi)
1993 gimple_seq replace;
1994 gimple x;
1995 gimple stmt = gsi_stmt (*gsi);
1997 switch (gimple_code (stmt))
1999 case GIMPLE_CALL:
2001 tree fndecl = gimple_call_fndecl (stmt);
2002 tree rhs, lhs;
2004 if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
2005 switch (DECL_FUNCTION_CODE (fndecl))
2007 case BUILT_IN_EH_POINTER:
2008 /* The front end may have generated a call to
2009 __builtin_eh_pointer (0) within a catch region. Replace
2010 this zero argument with the current catch region number. */
2011 if (state->ehp_region)
2013 tree nr = build_int_cst (integer_type_node,
2014 state->ehp_region->index);
2015 gimple_call_set_arg (stmt, 0, nr);
2017 else
2019 /* The user has dome something silly. Remove it. */
2020 rhs = null_pointer_node;
2021 goto do_replace;
2023 break;
2025 case BUILT_IN_EH_FILTER:
2026 /* ??? This should never appear, but since it's a builtin it
2027 is accessible to abuse by users. Just remove it and
2028 replace the use with the arbitrary value zero. */
2029 rhs = build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), 0);
2030 do_replace:
2031 lhs = gimple_call_lhs (stmt);
2032 x = gimple_build_assign (lhs, rhs);
2033 gsi_insert_before (gsi, x, GSI_SAME_STMT);
2034 /* FALLTHRU */
2036 case BUILT_IN_EH_COPY_VALUES:
2037 /* Likewise this should not appear. Remove it. */
2038 gsi_remove (gsi, true);
2039 return;
2041 default:
2042 break;
2045 /* FALLTHRU */
2047 case GIMPLE_ASSIGN:
2048 /* If the stmt can throw use a new temporary for the assignment
2049 to a LHS. This makes sure the old value of the LHS is
2050 available on the EH edge. Only do so for statements that
2051 potentially fall through (no noreturn calls e.g.), otherwise
2052 this new assignment might create fake fallthru regions. */
2053 if (stmt_could_throw_p (stmt)
2054 && gimple_has_lhs (stmt)
2055 && gimple_stmt_may_fallthru (stmt)
2056 && !tree_could_throw_p (gimple_get_lhs (stmt))
2057 && is_gimple_reg_type (TREE_TYPE (gimple_get_lhs (stmt))))
2059 tree lhs = gimple_get_lhs (stmt);
2060 tree tmp = create_tmp_var (TREE_TYPE (lhs));
2061 gimple s = gimple_build_assign (lhs, tmp);
2062 gimple_set_location (s, gimple_location (stmt));
2063 gimple_set_block (s, gimple_block (stmt));
2064 gimple_set_lhs (stmt, tmp);
2065 if (TREE_CODE (TREE_TYPE (tmp)) == COMPLEX_TYPE
2066 || TREE_CODE (TREE_TYPE (tmp)) == VECTOR_TYPE)
2067 DECL_GIMPLE_REG_P (tmp) = 1;
2068 gsi_insert_after (gsi, s, GSI_SAME_STMT);
2070 /* Look for things that can throw exceptions, and record them. */
2071 if (state->cur_region && stmt_could_throw_p (stmt))
2073 record_stmt_eh_region (state->cur_region, stmt);
2074 note_eh_region_may_contain_throw (state->cur_region);
2076 break;
2078 case GIMPLE_COND:
2079 case GIMPLE_GOTO:
2080 case GIMPLE_RETURN:
2081 maybe_record_in_goto_queue (state, stmt);
2082 break;
2084 case GIMPLE_SWITCH:
2085 verify_norecord_switch_expr (state, as_a <gswitch *> (stmt));
2086 break;
2088 case GIMPLE_TRY:
2090 gtry *try_stmt = as_a <gtry *> (stmt);
2091 if (gimple_try_kind (try_stmt) == GIMPLE_TRY_FINALLY)
2092 replace = lower_try_finally (state, try_stmt);
2093 else
2095 x = gimple_seq_first_stmt (gimple_try_cleanup (try_stmt));
2096 if (!x)
2098 replace = gimple_try_eval (try_stmt);
2099 lower_eh_constructs_1 (state, &replace);
2101 else
2102 switch (gimple_code (x))
2104 case GIMPLE_CATCH:
2105 replace = lower_catch (state, try_stmt);
2106 break;
2107 case GIMPLE_EH_FILTER:
2108 replace = lower_eh_filter (state, try_stmt);
2109 break;
2110 case GIMPLE_EH_MUST_NOT_THROW:
2111 replace = lower_eh_must_not_throw (state, try_stmt);
2112 break;
2113 case GIMPLE_EH_ELSE:
2114 /* This code is only valid with GIMPLE_TRY_FINALLY. */
2115 gcc_unreachable ();
2116 default:
2117 replace = lower_cleanup (state, try_stmt);
2118 break;
2123 /* Remove the old stmt and insert the transformed sequence
2124 instead. */
2125 gsi_insert_seq_before (gsi, replace, GSI_SAME_STMT);
2126 gsi_remove (gsi, true);
2128 /* Return since we don't want gsi_next () */
2129 return;
2131 case GIMPLE_EH_ELSE:
2132 /* We should be eliminating this in lower_try_finally et al. */
2133 gcc_unreachable ();
2135 default:
2136 /* A type, a decl, or some kind of statement that we're not
2137 interested in. Don't walk them. */
2138 break;
2141 gsi_next (gsi);
2144 /* A helper to unwrap a gimple_seq and feed stmts to lower_eh_constructs_2. */
2146 static void
2147 lower_eh_constructs_1 (struct leh_state *state, gimple_seq *pseq)
2149 gimple_stmt_iterator gsi;
2150 for (gsi = gsi_start (*pseq); !gsi_end_p (gsi);)
2151 lower_eh_constructs_2 (state, &gsi);
2154 namespace {
2156 const pass_data pass_data_lower_eh =
2158 GIMPLE_PASS, /* type */
2159 "eh", /* name */
2160 OPTGROUP_NONE, /* optinfo_flags */
2161 TV_TREE_EH, /* tv_id */
2162 PROP_gimple_lcf, /* properties_required */
2163 PROP_gimple_leh, /* properties_provided */
2164 0, /* properties_destroyed */
2165 0, /* todo_flags_start */
2166 0, /* todo_flags_finish */
2169 class pass_lower_eh : public gimple_opt_pass
2171 public:
2172 pass_lower_eh (gcc::context *ctxt)
2173 : gimple_opt_pass (pass_data_lower_eh, ctxt)
2176 /* opt_pass methods: */
2177 virtual unsigned int execute (function *);
2179 }; // class pass_lower_eh
2181 unsigned int
2182 pass_lower_eh::execute (function *fun)
2184 struct leh_state null_state;
2185 gimple_seq bodyp;
2187 bodyp = gimple_body (current_function_decl);
2188 if (bodyp == NULL)
2189 return 0;
2191 finally_tree = new hash_table<finally_tree_hasher> (31);
2192 eh_region_may_contain_throw_map = BITMAP_ALLOC (NULL);
2193 memset (&null_state, 0, sizeof (null_state));
2195 collect_finally_tree_1 (bodyp, NULL);
2196 lower_eh_constructs_1 (&null_state, &bodyp);
2197 gimple_set_body (current_function_decl, bodyp);
2199 /* We assume there's a return statement, or something, at the end of
2200 the function, and thus ploping the EH sequence afterward won't
2201 change anything. */
2202 gcc_assert (!gimple_seq_may_fallthru (bodyp));
2203 gimple_seq_add_seq (&bodyp, eh_seq);
2205 /* We assume that since BODYP already existed, adding EH_SEQ to it
2206 didn't change its value, and we don't have to re-set the function. */
2207 gcc_assert (bodyp == gimple_body (current_function_decl));
2209 delete finally_tree;
2210 finally_tree = NULL;
2211 BITMAP_FREE (eh_region_may_contain_throw_map);
2212 eh_seq = NULL;
2214 /* If this function needs a language specific EH personality routine
2215 and the frontend didn't already set one do so now. */
2216 if (function_needs_eh_personality (fun) == eh_personality_lang
2217 && !DECL_FUNCTION_PERSONALITY (current_function_decl))
2218 DECL_FUNCTION_PERSONALITY (current_function_decl)
2219 = lang_hooks.eh_personality ();
2221 return 0;
2224 } // anon namespace
2226 gimple_opt_pass *
2227 make_pass_lower_eh (gcc::context *ctxt)
2229 return new pass_lower_eh (ctxt);
2232 /* Create the multiple edges from an EH_DISPATCH statement to all of
2233 the possible handlers for its EH region. Return true if there's
2234 no fallthru edge; false if there is. */
2236 bool
2237 make_eh_dispatch_edges (geh_dispatch *stmt)
2239 eh_region r;
2240 eh_catch c;
2241 basic_block src, dst;
2243 r = get_eh_region_from_number (gimple_eh_dispatch_region (stmt));
2244 src = gimple_bb (stmt);
2246 switch (r->type)
2248 case ERT_TRY:
2249 for (c = r->u.eh_try.first_catch; c ; c = c->next_catch)
2251 dst = label_to_block (c->label);
2252 make_edge (src, dst, 0);
2254 /* A catch-all handler doesn't have a fallthru. */
2255 if (c->type_list == NULL)
2256 return false;
2258 break;
2260 case ERT_ALLOWED_EXCEPTIONS:
2261 dst = label_to_block (r->u.allowed.label);
2262 make_edge (src, dst, 0);
2263 break;
2265 default:
2266 gcc_unreachable ();
2269 return true;
2272 /* Create the single EH edge from STMT to its nearest landing pad,
2273 if there is such a landing pad within the current function. */
2275 void
2276 make_eh_edges (gimple stmt)
2278 basic_block src, dst;
2279 eh_landing_pad lp;
2280 int lp_nr;
2282 lp_nr = lookup_stmt_eh_lp (stmt);
2283 if (lp_nr <= 0)
2284 return;
2286 lp = get_eh_landing_pad_from_number (lp_nr);
2287 gcc_assert (lp != NULL);
2289 src = gimple_bb (stmt);
2290 dst = label_to_block (lp->post_landing_pad);
2291 make_edge (src, dst, EDGE_EH);
2294 /* Do the work in redirecting EDGE_IN to NEW_BB within the EH region tree;
2295 do not actually perform the final edge redirection.
2297 CHANGE_REGION is true when we're being called from cleanup_empty_eh and
2298 we intend to change the destination EH region as well; this means
2299 EH_LANDING_PAD_NR must already be set on the destination block label.
2300 If false, we're being called from generic cfg manipulation code and we
2301 should preserve our place within the region tree. */
2303 static void
2304 redirect_eh_edge_1 (edge edge_in, basic_block new_bb, bool change_region)
2306 eh_landing_pad old_lp, new_lp;
2307 basic_block old_bb;
2308 gimple throw_stmt;
2309 int old_lp_nr, new_lp_nr;
2310 tree old_label, new_label;
2311 edge_iterator ei;
2312 edge e;
2314 old_bb = edge_in->dest;
2315 old_label = gimple_block_label (old_bb);
2316 old_lp_nr = EH_LANDING_PAD_NR (old_label);
2317 gcc_assert (old_lp_nr > 0);
2318 old_lp = get_eh_landing_pad_from_number (old_lp_nr);
2320 throw_stmt = last_stmt (edge_in->src);
2321 gcc_assert (lookup_stmt_eh_lp (throw_stmt) == old_lp_nr);
2323 new_label = gimple_block_label (new_bb);
2325 /* Look for an existing region that might be using NEW_BB already. */
2326 new_lp_nr = EH_LANDING_PAD_NR (new_label);
2327 if (new_lp_nr)
2329 new_lp = get_eh_landing_pad_from_number (new_lp_nr);
2330 gcc_assert (new_lp);
2332 /* Unless CHANGE_REGION is true, the new and old landing pad
2333 had better be associated with the same EH region. */
2334 gcc_assert (change_region || new_lp->region == old_lp->region);
2336 else
2338 new_lp = NULL;
2339 gcc_assert (!change_region);
2342 /* Notice when we redirect the last EH edge away from OLD_BB. */
2343 FOR_EACH_EDGE (e, ei, old_bb->preds)
2344 if (e != edge_in && (e->flags & EDGE_EH))
2345 break;
2347 if (new_lp)
2349 /* NEW_LP already exists. If there are still edges into OLD_LP,
2350 there's nothing to do with the EH tree. If there are no more
2351 edges into OLD_LP, then we want to remove OLD_LP as it is unused.
2352 If CHANGE_REGION is true, then our caller is expecting to remove
2353 the landing pad. */
2354 if (e == NULL && !change_region)
2355 remove_eh_landing_pad (old_lp);
2357 else
2359 /* No correct landing pad exists. If there are no more edges
2360 into OLD_LP, then we can simply re-use the existing landing pad.
2361 Otherwise, we have to create a new landing pad. */
2362 if (e == NULL)
2364 EH_LANDING_PAD_NR (old_lp->post_landing_pad) = 0;
2365 new_lp = old_lp;
2367 else
2368 new_lp = gen_eh_landing_pad (old_lp->region);
2369 new_lp->post_landing_pad = new_label;
2370 EH_LANDING_PAD_NR (new_label) = new_lp->index;
2373 /* Maybe move the throwing statement to the new region. */
2374 if (old_lp != new_lp)
2376 remove_stmt_from_eh_lp (throw_stmt);
2377 add_stmt_to_eh_lp (throw_stmt, new_lp->index);
2381 /* Redirect EH edge E to NEW_BB. */
2383 edge
2384 redirect_eh_edge (edge edge_in, basic_block new_bb)
2386 redirect_eh_edge_1 (edge_in, new_bb, false);
2387 return ssa_redirect_edge (edge_in, new_bb);
2390 /* This is a subroutine of gimple_redirect_edge_and_branch. Update the
2391 labels for redirecting a non-fallthru EH_DISPATCH edge E to NEW_BB.
2392 The actual edge update will happen in the caller. */
2394 void
2395 redirect_eh_dispatch_edge (geh_dispatch *stmt, edge e, basic_block new_bb)
2397 tree new_lab = gimple_block_label (new_bb);
2398 bool any_changed = false;
2399 basic_block old_bb;
2400 eh_region r;
2401 eh_catch c;
2403 r = get_eh_region_from_number (gimple_eh_dispatch_region (stmt));
2404 switch (r->type)
2406 case ERT_TRY:
2407 for (c = r->u.eh_try.first_catch; c ; c = c->next_catch)
2409 old_bb = label_to_block (c->label);
2410 if (old_bb == e->dest)
2412 c->label = new_lab;
2413 any_changed = true;
2416 break;
2418 case ERT_ALLOWED_EXCEPTIONS:
2419 old_bb = label_to_block (r->u.allowed.label);
2420 gcc_assert (old_bb == e->dest);
2421 r->u.allowed.label = new_lab;
2422 any_changed = true;
2423 break;
2425 default:
2426 gcc_unreachable ();
2429 gcc_assert (any_changed);
2432 /* Helper function for operation_could_trap_p and stmt_could_throw_p. */
2434 bool
2435 operation_could_trap_helper_p (enum tree_code op,
2436 bool fp_operation,
2437 bool honor_trapv,
2438 bool honor_nans,
2439 bool honor_snans,
2440 tree divisor,
2441 bool *handled)
2443 *handled = true;
2444 switch (op)
2446 case TRUNC_DIV_EXPR:
2447 case CEIL_DIV_EXPR:
2448 case FLOOR_DIV_EXPR:
2449 case ROUND_DIV_EXPR:
2450 case EXACT_DIV_EXPR:
2451 case CEIL_MOD_EXPR:
2452 case FLOOR_MOD_EXPR:
2453 case ROUND_MOD_EXPR:
2454 case TRUNC_MOD_EXPR:
2455 case RDIV_EXPR:
2456 if (honor_snans || honor_trapv)
2457 return true;
2458 if (fp_operation)
2459 return flag_trapping_math;
2460 if (!TREE_CONSTANT (divisor) || integer_zerop (divisor))
2461 return true;
2462 return false;
2464 case LT_EXPR:
2465 case LE_EXPR:
2466 case GT_EXPR:
2467 case GE_EXPR:
2468 case LTGT_EXPR:
2469 /* Some floating point comparisons may trap. */
2470 return honor_nans;
2472 case EQ_EXPR:
2473 case NE_EXPR:
2474 case UNORDERED_EXPR:
2475 case ORDERED_EXPR:
2476 case UNLT_EXPR:
2477 case UNLE_EXPR:
2478 case UNGT_EXPR:
2479 case UNGE_EXPR:
2480 case UNEQ_EXPR:
2481 return honor_snans;
2483 case NEGATE_EXPR:
2484 case ABS_EXPR:
2485 case CONJ_EXPR:
2486 /* These operations don't trap with floating point. */
2487 if (honor_trapv)
2488 return true;
2489 return false;
2491 case PLUS_EXPR:
2492 case MINUS_EXPR:
2493 case MULT_EXPR:
2494 /* Any floating arithmetic may trap. */
2495 if (fp_operation && flag_trapping_math)
2496 return true;
2497 if (honor_trapv)
2498 return true;
2499 return false;
2501 case COMPLEX_EXPR:
2502 case CONSTRUCTOR:
2503 /* Constructing an object cannot trap. */
2504 return false;
2506 default:
2507 /* Any floating arithmetic may trap. */
2508 if (fp_operation && flag_trapping_math)
2509 return true;
2511 *handled = false;
2512 return false;
2516 /* Return true if operation OP may trap. FP_OPERATION is true if OP is applied
2517 on floating-point values. HONOR_TRAPV is true if OP is applied on integer
2518 type operands that may trap. If OP is a division operator, DIVISOR contains
2519 the value of the divisor. */
2521 bool
2522 operation_could_trap_p (enum tree_code op, bool fp_operation, bool honor_trapv,
2523 tree divisor)
2525 bool honor_nans = (fp_operation && flag_trapping_math
2526 && !flag_finite_math_only);
2527 bool honor_snans = fp_operation && flag_signaling_nans != 0;
2528 bool handled;
2530 if (TREE_CODE_CLASS (op) != tcc_comparison
2531 && TREE_CODE_CLASS (op) != tcc_unary
2532 && TREE_CODE_CLASS (op) != tcc_binary)
2533 return false;
2535 return operation_could_trap_helper_p (op, fp_operation, honor_trapv,
2536 honor_nans, honor_snans, divisor,
2537 &handled);
2541 /* Returns true if it is possible to prove that the index of
2542 an array access REF (an ARRAY_REF expression) falls into the
2543 array bounds. */
2545 static bool
2546 in_array_bounds_p (tree ref)
2548 tree idx = TREE_OPERAND (ref, 1);
2549 tree min, max;
2551 if (TREE_CODE (idx) != INTEGER_CST)
2552 return false;
2554 min = array_ref_low_bound (ref);
2555 max = array_ref_up_bound (ref);
2556 if (!min
2557 || !max
2558 || TREE_CODE (min) != INTEGER_CST
2559 || TREE_CODE (max) != INTEGER_CST)
2560 return false;
2562 if (tree_int_cst_lt (idx, min)
2563 || tree_int_cst_lt (max, idx))
2564 return false;
2566 return true;
2569 /* Returns true if it is possible to prove that the range of
2570 an array access REF (an ARRAY_RANGE_REF expression) falls
2571 into the array bounds. */
2573 static bool
2574 range_in_array_bounds_p (tree ref)
2576 tree domain_type = TYPE_DOMAIN (TREE_TYPE (ref));
2577 tree range_min, range_max, min, max;
2579 range_min = TYPE_MIN_VALUE (domain_type);
2580 range_max = TYPE_MAX_VALUE (domain_type);
2581 if (!range_min
2582 || !range_max
2583 || TREE_CODE (range_min) != INTEGER_CST
2584 || TREE_CODE (range_max) != INTEGER_CST)
2585 return false;
2587 min = array_ref_low_bound (ref);
2588 max = array_ref_up_bound (ref);
2589 if (!min
2590 || !max
2591 || TREE_CODE (min) != INTEGER_CST
2592 || TREE_CODE (max) != INTEGER_CST)
2593 return false;
2595 if (tree_int_cst_lt (range_min, min)
2596 || tree_int_cst_lt (max, range_max))
2597 return false;
2599 return true;
2602 /* Return true if EXPR can trap, as in dereferencing an invalid pointer
2603 location or floating point arithmetic. C.f. the rtl version, may_trap_p.
2604 This routine expects only GIMPLE lhs or rhs input. */
2606 bool
2607 tree_could_trap_p (tree expr)
2609 enum tree_code code;
2610 bool fp_operation = false;
2611 bool honor_trapv = false;
2612 tree t, base, div = NULL_TREE;
2614 if (!expr)
2615 return false;
2617 code = TREE_CODE (expr);
2618 t = TREE_TYPE (expr);
2620 if (t)
2622 if (COMPARISON_CLASS_P (expr))
2623 fp_operation = FLOAT_TYPE_P (TREE_TYPE (TREE_OPERAND (expr, 0)));
2624 else
2625 fp_operation = FLOAT_TYPE_P (t);
2626 honor_trapv = INTEGRAL_TYPE_P (t) && TYPE_OVERFLOW_TRAPS (t);
2629 if (TREE_CODE_CLASS (code) == tcc_binary)
2630 div = TREE_OPERAND (expr, 1);
2631 if (operation_could_trap_p (code, fp_operation, honor_trapv, div))
2632 return true;
2634 restart:
2635 switch (code)
2637 case COMPONENT_REF:
2638 case REALPART_EXPR:
2639 case IMAGPART_EXPR:
2640 case BIT_FIELD_REF:
2641 case VIEW_CONVERT_EXPR:
2642 case WITH_SIZE_EXPR:
2643 expr = TREE_OPERAND (expr, 0);
2644 code = TREE_CODE (expr);
2645 goto restart;
2647 case ARRAY_RANGE_REF:
2648 base = TREE_OPERAND (expr, 0);
2649 if (tree_could_trap_p (base))
2650 return true;
2651 if (TREE_THIS_NOTRAP (expr))
2652 return false;
2653 return !range_in_array_bounds_p (expr);
2655 case ARRAY_REF:
2656 base = TREE_OPERAND (expr, 0);
2657 if (tree_could_trap_p (base))
2658 return true;
2659 if (TREE_THIS_NOTRAP (expr))
2660 return false;
2661 return !in_array_bounds_p (expr);
2663 case TARGET_MEM_REF:
2664 case MEM_REF:
2665 if (TREE_CODE (TREE_OPERAND (expr, 0)) == ADDR_EXPR
2666 && tree_could_trap_p (TREE_OPERAND (TREE_OPERAND (expr, 0), 0)))
2667 return true;
2668 if (TREE_THIS_NOTRAP (expr))
2669 return false;
2670 /* We cannot prove that the access is in-bounds when we have
2671 variable-index TARGET_MEM_REFs. */
2672 if (code == TARGET_MEM_REF
2673 && (TMR_INDEX (expr) || TMR_INDEX2 (expr)))
2674 return true;
2675 if (TREE_CODE (TREE_OPERAND (expr, 0)) == ADDR_EXPR)
2677 tree base = TREE_OPERAND (TREE_OPERAND (expr, 0), 0);
2678 offset_int off = mem_ref_offset (expr);
2679 if (wi::neg_p (off, SIGNED))
2680 return true;
2681 if (TREE_CODE (base) == STRING_CST)
2682 return wi::leu_p (TREE_STRING_LENGTH (base), off);
2683 else if (DECL_SIZE_UNIT (base) == NULL_TREE
2684 || TREE_CODE (DECL_SIZE_UNIT (base)) != INTEGER_CST
2685 || wi::leu_p (wi::to_offset (DECL_SIZE_UNIT (base)), off))
2686 return true;
2687 /* Now we are sure the first byte of the access is inside
2688 the object. */
2689 return false;
2691 return true;
2693 case INDIRECT_REF:
2694 return !TREE_THIS_NOTRAP (expr);
2696 case ASM_EXPR:
2697 return TREE_THIS_VOLATILE (expr);
2699 case CALL_EXPR:
2700 t = get_callee_fndecl (expr);
2701 /* Assume that calls to weak functions may trap. */
2702 if (!t || !DECL_P (t))
2703 return true;
2704 if (DECL_WEAK (t))
2705 return tree_could_trap_p (t);
2706 return false;
2708 case FUNCTION_DECL:
2709 /* Assume that accesses to weak functions may trap, unless we know
2710 they are certainly defined in current TU or in some other
2711 LTO partition. */
2712 if (DECL_WEAK (expr) && !DECL_COMDAT (expr) && DECL_EXTERNAL (expr))
2714 cgraph_node *node = cgraph_node::get (expr);
2715 if (node)
2716 node = node->function_symbol ();
2717 return !(node && node->in_other_partition);
2719 return false;
2721 case VAR_DECL:
2722 /* Assume that accesses to weak vars may trap, unless we know
2723 they are certainly defined in current TU or in some other
2724 LTO partition. */
2725 if (DECL_WEAK (expr) && !DECL_COMDAT (expr) && DECL_EXTERNAL (expr))
2727 varpool_node *node = varpool_node::get (expr);
2728 if (node)
2729 node = node->ultimate_alias_target ();
2730 return !(node && node->in_other_partition);
2732 return false;
2734 default:
2735 return false;
2740 /* Helper for stmt_could_throw_p. Return true if STMT (assumed to be a
2741 an assignment or a conditional) may throw. */
2743 static bool
2744 stmt_could_throw_1_p (gimple stmt)
2746 enum tree_code code = gimple_expr_code (stmt);
2747 bool honor_nans = false;
2748 bool honor_snans = false;
2749 bool fp_operation = false;
2750 bool honor_trapv = false;
2751 tree t;
2752 size_t i;
2753 bool handled, ret;
2755 if (TREE_CODE_CLASS (code) == tcc_comparison
2756 || TREE_CODE_CLASS (code) == tcc_unary
2757 || TREE_CODE_CLASS (code) == tcc_binary)
2759 if (is_gimple_assign (stmt)
2760 && TREE_CODE_CLASS (code) == tcc_comparison)
2761 t = TREE_TYPE (gimple_assign_rhs1 (stmt));
2762 else if (gimple_code (stmt) == GIMPLE_COND)
2763 t = TREE_TYPE (gimple_cond_lhs (stmt));
2764 else
2765 t = gimple_expr_type (stmt);
2766 fp_operation = FLOAT_TYPE_P (t);
2767 if (fp_operation)
2769 honor_nans = flag_trapping_math && !flag_finite_math_only;
2770 honor_snans = flag_signaling_nans != 0;
2772 else if (INTEGRAL_TYPE_P (t) && TYPE_OVERFLOW_TRAPS (t))
2773 honor_trapv = true;
2776 /* Check if the main expression may trap. */
2777 t = is_gimple_assign (stmt) ? gimple_assign_rhs2 (stmt) : NULL;
2778 ret = operation_could_trap_helper_p (code, fp_operation, honor_trapv,
2779 honor_nans, honor_snans, t,
2780 &handled);
2781 if (handled)
2782 return ret;
2784 /* If the expression does not trap, see if any of the individual operands may
2785 trap. */
2786 for (i = 0; i < gimple_num_ops (stmt); i++)
2787 if (tree_could_trap_p (gimple_op (stmt, i)))
2788 return true;
2790 return false;
2794 /* Return true if statement STMT could throw an exception. */
2796 bool
2797 stmt_could_throw_p (gimple stmt)
2799 if (!flag_exceptions)
2800 return false;
2802 /* The only statements that can throw an exception are assignments,
2803 conditionals, calls, resx, and asms. */
2804 switch (gimple_code (stmt))
2806 case GIMPLE_RESX:
2807 return true;
2809 case GIMPLE_CALL:
2810 return !gimple_call_nothrow_p (as_a <gcall *> (stmt));
2812 case GIMPLE_ASSIGN:
2813 case GIMPLE_COND:
2814 if (!cfun->can_throw_non_call_exceptions)
2815 return false;
2816 return stmt_could_throw_1_p (stmt);
2818 case GIMPLE_ASM:
2819 if (!cfun->can_throw_non_call_exceptions)
2820 return false;
2821 return gimple_asm_volatile_p (as_a <gasm *> (stmt));
2823 default:
2824 return false;
2829 /* Return true if expression T could throw an exception. */
2831 bool
2832 tree_could_throw_p (tree t)
2834 if (!flag_exceptions)
2835 return false;
2836 if (TREE_CODE (t) == MODIFY_EXPR)
2838 if (cfun->can_throw_non_call_exceptions
2839 && tree_could_trap_p (TREE_OPERAND (t, 0)))
2840 return true;
2841 t = TREE_OPERAND (t, 1);
2844 if (TREE_CODE (t) == WITH_SIZE_EXPR)
2845 t = TREE_OPERAND (t, 0);
2846 if (TREE_CODE (t) == CALL_EXPR)
2847 return (call_expr_flags (t) & ECF_NOTHROW) == 0;
2848 if (cfun->can_throw_non_call_exceptions)
2849 return tree_could_trap_p (t);
2850 return false;
2853 /* Return true if STMT can throw an exception that is not caught within
2854 the current function (CFUN). */
2856 bool
2857 stmt_can_throw_external (gimple stmt)
2859 int lp_nr;
2861 if (!stmt_could_throw_p (stmt))
2862 return false;
2864 lp_nr = lookup_stmt_eh_lp (stmt);
2865 return lp_nr == 0;
2868 /* Return true if STMT can throw an exception that is caught within
2869 the current function (CFUN). */
2871 bool
2872 stmt_can_throw_internal (gimple stmt)
2874 int lp_nr;
2876 if (!stmt_could_throw_p (stmt))
2877 return false;
2879 lp_nr = lookup_stmt_eh_lp (stmt);
2880 return lp_nr > 0;
2883 /* Given a statement STMT in IFUN, if STMT can no longer throw, then
2884 remove any entry it might have from the EH table. Return true if
2885 any change was made. */
2887 bool
2888 maybe_clean_eh_stmt_fn (struct function *ifun, gimple stmt)
2890 if (stmt_could_throw_p (stmt))
2891 return false;
2892 return remove_stmt_from_eh_lp_fn (ifun, stmt);
2895 /* Likewise, but always use the current function. */
2897 bool
2898 maybe_clean_eh_stmt (gimple stmt)
2900 return maybe_clean_eh_stmt_fn (cfun, stmt);
2903 /* Given a statement OLD_STMT and a new statement NEW_STMT that has replaced
2904 OLD_STMT in the function, remove OLD_STMT from the EH table and put NEW_STMT
2905 in the table if it should be in there. Return TRUE if a replacement was
2906 done that my require an EH edge purge. */
2908 bool
2909 maybe_clean_or_replace_eh_stmt (gimple old_stmt, gimple new_stmt)
2911 int lp_nr = lookup_stmt_eh_lp (old_stmt);
2913 if (lp_nr != 0)
2915 bool new_stmt_could_throw = stmt_could_throw_p (new_stmt);
2917 if (new_stmt == old_stmt && new_stmt_could_throw)
2918 return false;
2920 remove_stmt_from_eh_lp (old_stmt);
2921 if (new_stmt_could_throw)
2923 add_stmt_to_eh_lp (new_stmt, lp_nr);
2924 return false;
2926 else
2927 return true;
2930 return false;
2933 /* Given a statement OLD_STMT in OLD_FUN and a duplicate statement NEW_STMT
2934 in NEW_FUN, copy the EH table data from OLD_STMT to NEW_STMT. The MAP
2935 operand is the return value of duplicate_eh_regions. */
2937 bool
2938 maybe_duplicate_eh_stmt_fn (struct function *new_fun, gimple new_stmt,
2939 struct function *old_fun, gimple old_stmt,
2940 hash_map<void *, void *> *map,
2941 int default_lp_nr)
2943 int old_lp_nr, new_lp_nr;
2945 if (!stmt_could_throw_p (new_stmt))
2946 return false;
2948 old_lp_nr = lookup_stmt_eh_lp_fn (old_fun, old_stmt);
2949 if (old_lp_nr == 0)
2951 if (default_lp_nr == 0)
2952 return false;
2953 new_lp_nr = default_lp_nr;
2955 else if (old_lp_nr > 0)
2957 eh_landing_pad old_lp, new_lp;
2959 old_lp = (*old_fun->eh->lp_array)[old_lp_nr];
2960 new_lp = static_cast<eh_landing_pad> (*map->get (old_lp));
2961 new_lp_nr = new_lp->index;
2963 else
2965 eh_region old_r, new_r;
2967 old_r = (*old_fun->eh->region_array)[-old_lp_nr];
2968 new_r = static_cast<eh_region> (*map->get (old_r));
2969 new_lp_nr = -new_r->index;
2972 add_stmt_to_eh_lp_fn (new_fun, new_stmt, new_lp_nr);
2973 return true;
2976 /* Similar, but both OLD_STMT and NEW_STMT are within the current function,
2977 and thus no remapping is required. */
2979 bool
2980 maybe_duplicate_eh_stmt (gimple new_stmt, gimple old_stmt)
2982 int lp_nr;
2984 if (!stmt_could_throw_p (new_stmt))
2985 return false;
2987 lp_nr = lookup_stmt_eh_lp (old_stmt);
2988 if (lp_nr == 0)
2989 return false;
2991 add_stmt_to_eh_lp (new_stmt, lp_nr);
2992 return true;
2995 /* Returns TRUE if oneh and twoh are exception handlers (gimple_try_cleanup of
2996 GIMPLE_TRY) that are similar enough to be considered the same. Currently
2997 this only handles handlers consisting of a single call, as that's the
2998 important case for C++: a destructor call for a particular object showing
2999 up in multiple handlers. */
3001 static bool
3002 same_handler_p (gimple_seq oneh, gimple_seq twoh)
3004 gimple_stmt_iterator gsi;
3005 gimple ones, twos;
3006 unsigned int ai;
3008 gsi = gsi_start (oneh);
3009 if (!gsi_one_before_end_p (gsi))
3010 return false;
3011 ones = gsi_stmt (gsi);
3013 gsi = gsi_start (twoh);
3014 if (!gsi_one_before_end_p (gsi))
3015 return false;
3016 twos = gsi_stmt (gsi);
3018 if (!is_gimple_call (ones)
3019 || !is_gimple_call (twos)
3020 || gimple_call_lhs (ones)
3021 || gimple_call_lhs (twos)
3022 || gimple_call_chain (ones)
3023 || gimple_call_chain (twos)
3024 || !gimple_call_same_target_p (ones, twos)
3025 || gimple_call_num_args (ones) != gimple_call_num_args (twos))
3026 return false;
3028 for (ai = 0; ai < gimple_call_num_args (ones); ++ai)
3029 if (!operand_equal_p (gimple_call_arg (ones, ai),
3030 gimple_call_arg (twos, ai), 0))
3031 return false;
3033 return true;
3036 /* Optimize
3037 try { A() } finally { try { ~B() } catch { ~A() } }
3038 try { ... } finally { ~A() }
3039 into
3040 try { A() } catch { ~B() }
3041 try { ~B() ... } finally { ~A() }
3043 This occurs frequently in C++, where A is a local variable and B is a
3044 temporary used in the initializer for A. */
3046 static void
3047 optimize_double_finally (gtry *one, gtry *two)
3049 gimple oneh;
3050 gimple_stmt_iterator gsi;
3051 gimple_seq cleanup;
3053 cleanup = gimple_try_cleanup (one);
3054 gsi = gsi_start (cleanup);
3055 if (!gsi_one_before_end_p (gsi))
3056 return;
3058 oneh = gsi_stmt (gsi);
3059 if (gimple_code (oneh) != GIMPLE_TRY
3060 || gimple_try_kind (oneh) != GIMPLE_TRY_CATCH)
3061 return;
3063 if (same_handler_p (gimple_try_cleanup (oneh), gimple_try_cleanup (two)))
3065 gimple_seq seq = gimple_try_eval (oneh);
3067 gimple_try_set_cleanup (one, seq);
3068 gimple_try_set_kind (one, GIMPLE_TRY_CATCH);
3069 seq = copy_gimple_seq_and_replace_locals (seq);
3070 gimple_seq_add_seq (&seq, gimple_try_eval (two));
3071 gimple_try_set_eval (two, seq);
3075 /* Perform EH refactoring optimizations that are simpler to do when code
3076 flow has been lowered but EH structures haven't. */
3078 static void
3079 refactor_eh_r (gimple_seq seq)
3081 gimple_stmt_iterator gsi;
3082 gimple one, two;
3084 one = NULL;
3085 two = NULL;
3086 gsi = gsi_start (seq);
3087 while (1)
3089 one = two;
3090 if (gsi_end_p (gsi))
3091 two = NULL;
3092 else
3093 two = gsi_stmt (gsi);
3094 if (one && two)
3095 if (gtry *try_one = dyn_cast <gtry *> (one))
3096 if (gtry *try_two = dyn_cast <gtry *> (two))
3097 if (gimple_try_kind (try_one) == GIMPLE_TRY_FINALLY
3098 && gimple_try_kind (try_two) == GIMPLE_TRY_FINALLY)
3099 optimize_double_finally (try_one, try_two);
3100 if (one)
3101 switch (gimple_code (one))
3103 case GIMPLE_TRY:
3104 refactor_eh_r (gimple_try_eval (one));
3105 refactor_eh_r (gimple_try_cleanup (one));
3106 break;
3107 case GIMPLE_CATCH:
3108 refactor_eh_r (gimple_catch_handler (as_a <gcatch *> (one)));
3109 break;
3110 case GIMPLE_EH_FILTER:
3111 refactor_eh_r (gimple_eh_filter_failure (one));
3112 break;
3113 case GIMPLE_EH_ELSE:
3115 geh_else *eh_else_stmt = as_a <geh_else *> (one);
3116 refactor_eh_r (gimple_eh_else_n_body (eh_else_stmt));
3117 refactor_eh_r (gimple_eh_else_e_body (eh_else_stmt));
3119 break;
3120 default:
3121 break;
3123 if (two)
3124 gsi_next (&gsi);
3125 else
3126 break;
3130 namespace {
3132 const pass_data pass_data_refactor_eh =
3134 GIMPLE_PASS, /* type */
3135 "ehopt", /* name */
3136 OPTGROUP_NONE, /* optinfo_flags */
3137 TV_TREE_EH, /* tv_id */
3138 PROP_gimple_lcf, /* properties_required */
3139 0, /* properties_provided */
3140 0, /* properties_destroyed */
3141 0, /* todo_flags_start */
3142 0, /* todo_flags_finish */
3145 class pass_refactor_eh : public gimple_opt_pass
3147 public:
3148 pass_refactor_eh (gcc::context *ctxt)
3149 : gimple_opt_pass (pass_data_refactor_eh, ctxt)
3152 /* opt_pass methods: */
3153 virtual bool gate (function *) { return flag_exceptions != 0; }
3154 virtual unsigned int execute (function *)
3156 refactor_eh_r (gimple_body (current_function_decl));
3157 return 0;
3160 }; // class pass_refactor_eh
3162 } // anon namespace
3164 gimple_opt_pass *
3165 make_pass_refactor_eh (gcc::context *ctxt)
3167 return new pass_refactor_eh (ctxt);
3170 /* At the end of gimple optimization, we can lower RESX. */
3172 static bool
3173 lower_resx (basic_block bb, gresx *stmt,
3174 hash_map<eh_region, tree> *mnt_map)
3176 int lp_nr;
3177 eh_region src_r, dst_r;
3178 gimple_stmt_iterator gsi;
3179 gimple x;
3180 tree fn, src_nr;
3181 bool ret = false;
3183 lp_nr = lookup_stmt_eh_lp (stmt);
3184 if (lp_nr != 0)
3185 dst_r = get_eh_region_from_lp_number (lp_nr);
3186 else
3187 dst_r = NULL;
3189 src_r = get_eh_region_from_number (gimple_resx_region (stmt));
3190 gsi = gsi_last_bb (bb);
3192 if (src_r == NULL)
3194 /* We can wind up with no source region when pass_cleanup_eh shows
3195 that there are no entries into an eh region and deletes it, but
3196 then the block that contains the resx isn't removed. This can
3197 happen without optimization when the switch statement created by
3198 lower_try_finally_switch isn't simplified to remove the eh case.
3200 Resolve this by expanding the resx node to an abort. */
3202 fn = builtin_decl_implicit (BUILT_IN_TRAP);
3203 x = gimple_build_call (fn, 0);
3204 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3206 while (EDGE_COUNT (bb->succs) > 0)
3207 remove_edge (EDGE_SUCC (bb, 0));
3209 else if (dst_r)
3211 /* When we have a destination region, we resolve this by copying
3212 the excptr and filter values into place, and changing the edge
3213 to immediately after the landing pad. */
3214 edge e;
3216 if (lp_nr < 0)
3218 basic_block new_bb;
3219 tree lab;
3221 /* We are resuming into a MUST_NOT_CALL region. Expand a call to
3222 the failure decl into a new block, if needed. */
3223 gcc_assert (dst_r->type == ERT_MUST_NOT_THROW);
3225 tree *slot = mnt_map->get (dst_r);
3226 if (slot == NULL)
3228 gimple_stmt_iterator gsi2;
3230 new_bb = create_empty_bb (bb);
3231 add_bb_to_loop (new_bb, bb->loop_father);
3232 lab = gimple_block_label (new_bb);
3233 gsi2 = gsi_start_bb (new_bb);
3235 fn = dst_r->u.must_not_throw.failure_decl;
3236 x = gimple_build_call (fn, 0);
3237 gimple_set_location (x, dst_r->u.must_not_throw.failure_loc);
3238 gsi_insert_after (&gsi2, x, GSI_CONTINUE_LINKING);
3240 mnt_map->put (dst_r, lab);
3242 else
3244 lab = *slot;
3245 new_bb = label_to_block (lab);
3248 gcc_assert (EDGE_COUNT (bb->succs) == 0);
3249 e = make_edge (bb, new_bb, EDGE_FALLTHRU);
3250 e->count = bb->count;
3251 e->probability = REG_BR_PROB_BASE;
3253 else
3255 edge_iterator ei;
3256 tree dst_nr = build_int_cst (integer_type_node, dst_r->index);
3258 fn = builtin_decl_implicit (BUILT_IN_EH_COPY_VALUES);
3259 src_nr = build_int_cst (integer_type_node, src_r->index);
3260 x = gimple_build_call (fn, 2, dst_nr, src_nr);
3261 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3263 /* Update the flags for the outgoing edge. */
3264 e = single_succ_edge (bb);
3265 gcc_assert (e->flags & EDGE_EH);
3266 e->flags = (e->flags & ~EDGE_EH) | EDGE_FALLTHRU;
3268 /* If there are no more EH users of the landing pad, delete it. */
3269 FOR_EACH_EDGE (e, ei, e->dest->preds)
3270 if (e->flags & EDGE_EH)
3271 break;
3272 if (e == NULL)
3274 eh_landing_pad lp = get_eh_landing_pad_from_number (lp_nr);
3275 remove_eh_landing_pad (lp);
3279 ret = true;
3281 else
3283 tree var;
3285 /* When we don't have a destination region, this exception escapes
3286 up the call chain. We resolve this by generating a call to the
3287 _Unwind_Resume library function. */
3289 /* The ARM EABI redefines _Unwind_Resume as __cxa_end_cleanup
3290 with no arguments for C++ and Java. Check for that. */
3291 if (src_r->use_cxa_end_cleanup)
3293 fn = builtin_decl_implicit (BUILT_IN_CXA_END_CLEANUP);
3294 x = gimple_build_call (fn, 0);
3295 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3297 else
3299 fn = builtin_decl_implicit (BUILT_IN_EH_POINTER);
3300 src_nr = build_int_cst (integer_type_node, src_r->index);
3301 x = gimple_build_call (fn, 1, src_nr);
3302 var = create_tmp_var (ptr_type_node);
3303 var = make_ssa_name (var, x);
3304 gimple_call_set_lhs (x, var);
3305 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3307 fn = builtin_decl_implicit (BUILT_IN_UNWIND_RESUME);
3308 x = gimple_build_call (fn, 1, var);
3309 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3312 gcc_assert (EDGE_COUNT (bb->succs) == 0);
3315 gsi_remove (&gsi, true);
3317 return ret;
3320 namespace {
3322 const pass_data pass_data_lower_resx =
3324 GIMPLE_PASS, /* type */
3325 "resx", /* name */
3326 OPTGROUP_NONE, /* optinfo_flags */
3327 TV_TREE_EH, /* tv_id */
3328 PROP_gimple_lcf, /* properties_required */
3329 0, /* properties_provided */
3330 0, /* properties_destroyed */
3331 0, /* todo_flags_start */
3332 0, /* todo_flags_finish */
3335 class pass_lower_resx : public gimple_opt_pass
3337 public:
3338 pass_lower_resx (gcc::context *ctxt)
3339 : gimple_opt_pass (pass_data_lower_resx, ctxt)
3342 /* opt_pass methods: */
3343 virtual bool gate (function *) { return flag_exceptions != 0; }
3344 virtual unsigned int execute (function *);
3346 }; // class pass_lower_resx
3348 unsigned
3349 pass_lower_resx::execute (function *fun)
3351 basic_block bb;
3352 bool dominance_invalidated = false;
3353 bool any_rewritten = false;
3355 hash_map<eh_region, tree> mnt_map;
3357 FOR_EACH_BB_FN (bb, fun)
3359 gimple last = last_stmt (bb);
3360 if (last && is_gimple_resx (last))
3362 dominance_invalidated |=
3363 lower_resx (bb, as_a <gresx *> (last), &mnt_map);
3364 any_rewritten = true;
3368 if (dominance_invalidated)
3370 free_dominance_info (CDI_DOMINATORS);
3371 free_dominance_info (CDI_POST_DOMINATORS);
3374 return any_rewritten ? TODO_update_ssa_only_virtuals : 0;
3377 } // anon namespace
3379 gimple_opt_pass *
3380 make_pass_lower_resx (gcc::context *ctxt)
3382 return new pass_lower_resx (ctxt);
3385 /* Try to optimize var = {v} {CLOBBER} stmts followed just by
3386 external throw. */
3388 static void
3389 optimize_clobbers (basic_block bb)
3391 gimple_stmt_iterator gsi = gsi_last_bb (bb);
3392 bool any_clobbers = false;
3393 bool seen_stack_restore = false;
3394 edge_iterator ei;
3395 edge e;
3397 /* Only optimize anything if the bb contains at least one clobber,
3398 ends with resx (checked by caller), optionally contains some
3399 debug stmts or labels, or at most one __builtin_stack_restore
3400 call, and has an incoming EH edge. */
3401 for (gsi_prev (&gsi); !gsi_end_p (gsi); gsi_prev (&gsi))
3403 gimple stmt = gsi_stmt (gsi);
3404 if (is_gimple_debug (stmt))
3405 continue;
3406 if (gimple_clobber_p (stmt))
3408 any_clobbers = true;
3409 continue;
3411 if (!seen_stack_restore
3412 && gimple_call_builtin_p (stmt, BUILT_IN_STACK_RESTORE))
3414 seen_stack_restore = true;
3415 continue;
3417 if (gimple_code (stmt) == GIMPLE_LABEL)
3418 break;
3419 return;
3421 if (!any_clobbers)
3422 return;
3423 FOR_EACH_EDGE (e, ei, bb->preds)
3424 if (e->flags & EDGE_EH)
3425 break;
3426 if (e == NULL)
3427 return;
3428 gsi = gsi_last_bb (bb);
3429 for (gsi_prev (&gsi); !gsi_end_p (gsi); gsi_prev (&gsi))
3431 gimple stmt = gsi_stmt (gsi);
3432 if (!gimple_clobber_p (stmt))
3433 continue;
3434 unlink_stmt_vdef (stmt);
3435 gsi_remove (&gsi, true);
3436 release_defs (stmt);
3440 /* Try to sink var = {v} {CLOBBER} stmts followed just by
3441 internal throw to successor BB. */
3443 static int
3444 sink_clobbers (basic_block bb)
3446 edge e;
3447 edge_iterator ei;
3448 gimple_stmt_iterator gsi, dgsi;
3449 basic_block succbb;
3450 bool any_clobbers = false;
3451 unsigned todo = 0;
3453 /* Only optimize if BB has a single EH successor and
3454 all predecessor edges are EH too. */
3455 if (!single_succ_p (bb)
3456 || (single_succ_edge (bb)->flags & EDGE_EH) == 0)
3457 return 0;
3459 FOR_EACH_EDGE (e, ei, bb->preds)
3461 if ((e->flags & EDGE_EH) == 0)
3462 return 0;
3465 /* And BB contains only CLOBBER stmts before the final
3466 RESX. */
3467 gsi = gsi_last_bb (bb);
3468 for (gsi_prev (&gsi); !gsi_end_p (gsi); gsi_prev (&gsi))
3470 gimple stmt = gsi_stmt (gsi);
3471 if (is_gimple_debug (stmt))
3472 continue;
3473 if (gimple_code (stmt) == GIMPLE_LABEL)
3474 break;
3475 if (!gimple_clobber_p (stmt))
3476 return 0;
3477 any_clobbers = true;
3479 if (!any_clobbers)
3480 return 0;
3482 edge succe = single_succ_edge (bb);
3483 succbb = succe->dest;
3485 /* See if there is a virtual PHI node to take an updated virtual
3486 operand from. */
3487 gphi *vphi = NULL;
3488 tree vuse = NULL_TREE;
3489 for (gphi_iterator gpi = gsi_start_phis (succbb);
3490 !gsi_end_p (gpi); gsi_next (&gpi))
3492 tree res = gimple_phi_result (gpi.phi ());
3493 if (virtual_operand_p (res))
3495 vphi = gpi.phi ();
3496 vuse = res;
3497 break;
3501 dgsi = gsi_after_labels (succbb);
3502 gsi = gsi_last_bb (bb);
3503 for (gsi_prev (&gsi); !gsi_end_p (gsi); gsi_prev (&gsi))
3505 gimple stmt = gsi_stmt (gsi);
3506 tree lhs;
3507 if (is_gimple_debug (stmt))
3508 continue;
3509 if (gimple_code (stmt) == GIMPLE_LABEL)
3510 break;
3511 lhs = gimple_assign_lhs (stmt);
3512 /* Unfortunately we don't have dominance info updated at this
3513 point, so checking if
3514 dominated_by_p (CDI_DOMINATORS, succbb,
3515 gimple_bb (SSA_NAME_DEF_STMT (TREE_OPERAND (lhs, 0)))
3516 would be too costly. Thus, avoid sinking any clobbers that
3517 refer to non-(D) SSA_NAMEs. */
3518 if (TREE_CODE (lhs) == MEM_REF
3519 && TREE_CODE (TREE_OPERAND (lhs, 0)) == SSA_NAME
3520 && !SSA_NAME_IS_DEFAULT_DEF (TREE_OPERAND (lhs, 0)))
3522 unlink_stmt_vdef (stmt);
3523 gsi_remove (&gsi, true);
3524 release_defs (stmt);
3525 continue;
3528 /* As we do not change stmt order when sinking across a
3529 forwarder edge we can keep virtual operands in place. */
3530 gsi_remove (&gsi, false);
3531 gsi_insert_before (&dgsi, stmt, GSI_NEW_STMT);
3533 /* But adjust virtual operands if we sunk across a PHI node. */
3534 if (vuse)
3536 gimple use_stmt;
3537 imm_use_iterator iter;
3538 use_operand_p use_p;
3539 FOR_EACH_IMM_USE_STMT (use_stmt, iter, vuse)
3540 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
3541 SET_USE (use_p, gimple_vdef (stmt));
3542 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (vuse))
3544 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (gimple_vdef (stmt)) = 1;
3545 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (vuse) = 0;
3547 /* Adjust the incoming virtual operand. */
3548 SET_USE (PHI_ARG_DEF_PTR_FROM_EDGE (vphi, succe), gimple_vuse (stmt));
3549 SET_USE (gimple_vuse_op (stmt), vuse);
3551 /* If there isn't a single predecessor but no virtual PHI node
3552 arrange for virtual operands to be renamed. */
3553 else if (gimple_vuse_op (stmt) != NULL_USE_OPERAND_P
3554 && !single_pred_p (succbb))
3556 /* In this case there will be no use of the VDEF of this stmt.
3557 ??? Unless this is a secondary opportunity and we have not
3558 removed unreachable blocks yet, so we cannot assert this.
3559 Which also means we will end up renaming too many times. */
3560 SET_USE (gimple_vuse_op (stmt), gimple_vop (cfun));
3561 mark_virtual_operands_for_renaming (cfun);
3562 todo |= TODO_update_ssa_only_virtuals;
3566 return todo;
3569 /* At the end of inlining, we can lower EH_DISPATCH. Return true when
3570 we have found some duplicate labels and removed some edges. */
3572 static bool
3573 lower_eh_dispatch (basic_block src, geh_dispatch *stmt)
3575 gimple_stmt_iterator gsi;
3576 int region_nr;
3577 eh_region r;
3578 tree filter, fn;
3579 gimple x;
3580 bool redirected = false;
3582 region_nr = gimple_eh_dispatch_region (stmt);
3583 r = get_eh_region_from_number (region_nr);
3585 gsi = gsi_last_bb (src);
3587 switch (r->type)
3589 case ERT_TRY:
3591 auto_vec<tree> labels;
3592 tree default_label = NULL;
3593 eh_catch c;
3594 edge_iterator ei;
3595 edge e;
3596 hash_set<tree> seen_values;
3598 /* Collect the labels for a switch. Zero the post_landing_pad
3599 field becase we'll no longer have anything keeping these labels
3600 in existence and the optimizer will be free to merge these
3601 blocks at will. */
3602 for (c = r->u.eh_try.first_catch; c ; c = c->next_catch)
3604 tree tp_node, flt_node, lab = c->label;
3605 bool have_label = false;
3607 c->label = NULL;
3608 tp_node = c->type_list;
3609 flt_node = c->filter_list;
3611 if (tp_node == NULL)
3613 default_label = lab;
3614 break;
3618 /* Filter out duplicate labels that arise when this handler
3619 is shadowed by an earlier one. When no labels are
3620 attached to the handler anymore, we remove
3621 the corresponding edge and then we delete unreachable
3622 blocks at the end of this pass. */
3623 if (! seen_values.contains (TREE_VALUE (flt_node)))
3625 tree t = build_case_label (TREE_VALUE (flt_node),
3626 NULL, lab);
3627 labels.safe_push (t);
3628 seen_values.add (TREE_VALUE (flt_node));
3629 have_label = true;
3632 tp_node = TREE_CHAIN (tp_node);
3633 flt_node = TREE_CHAIN (flt_node);
3635 while (tp_node);
3636 if (! have_label)
3638 remove_edge (find_edge (src, label_to_block (lab)));
3639 redirected = true;
3643 /* Clean up the edge flags. */
3644 FOR_EACH_EDGE (e, ei, src->succs)
3646 if (e->flags & EDGE_FALLTHRU)
3648 /* If there was no catch-all, use the fallthru edge. */
3649 if (default_label == NULL)
3650 default_label = gimple_block_label (e->dest);
3651 e->flags &= ~EDGE_FALLTHRU;
3654 gcc_assert (default_label != NULL);
3656 /* Don't generate a switch if there's only a default case.
3657 This is common in the form of try { A; } catch (...) { B; }. */
3658 if (!labels.exists ())
3660 e = single_succ_edge (src);
3661 e->flags |= EDGE_FALLTHRU;
3663 else
3665 fn = builtin_decl_implicit (BUILT_IN_EH_FILTER);
3666 x = gimple_build_call (fn, 1, build_int_cst (integer_type_node,
3667 region_nr));
3668 filter = create_tmp_var (TREE_TYPE (TREE_TYPE (fn)));
3669 filter = make_ssa_name (filter, x);
3670 gimple_call_set_lhs (x, filter);
3671 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3673 /* Turn the default label into a default case. */
3674 default_label = build_case_label (NULL, NULL, default_label);
3675 sort_case_labels (labels);
3677 x = gimple_build_switch (filter, default_label, labels);
3678 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3681 break;
3683 case ERT_ALLOWED_EXCEPTIONS:
3685 edge b_e = BRANCH_EDGE (src);
3686 edge f_e = FALLTHRU_EDGE (src);
3688 fn = builtin_decl_implicit (BUILT_IN_EH_FILTER);
3689 x = gimple_build_call (fn, 1, build_int_cst (integer_type_node,
3690 region_nr));
3691 filter = create_tmp_var (TREE_TYPE (TREE_TYPE (fn)));
3692 filter = make_ssa_name (filter, x);
3693 gimple_call_set_lhs (x, filter);
3694 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3696 r->u.allowed.label = NULL;
3697 x = gimple_build_cond (EQ_EXPR, filter,
3698 build_int_cst (TREE_TYPE (filter),
3699 r->u.allowed.filter),
3700 NULL_TREE, NULL_TREE);
3701 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3703 b_e->flags = b_e->flags | EDGE_TRUE_VALUE;
3704 f_e->flags = (f_e->flags & ~EDGE_FALLTHRU) | EDGE_FALSE_VALUE;
3706 break;
3708 default:
3709 gcc_unreachable ();
3712 /* Replace the EH_DISPATCH with the SWITCH or COND generated above. */
3713 gsi_remove (&gsi, true);
3714 return redirected;
3717 namespace {
3719 const pass_data pass_data_lower_eh_dispatch =
3721 GIMPLE_PASS, /* type */
3722 "ehdisp", /* name */
3723 OPTGROUP_NONE, /* optinfo_flags */
3724 TV_TREE_EH, /* tv_id */
3725 PROP_gimple_lcf, /* properties_required */
3726 0, /* properties_provided */
3727 0, /* properties_destroyed */
3728 0, /* todo_flags_start */
3729 0, /* todo_flags_finish */
3732 class pass_lower_eh_dispatch : public gimple_opt_pass
3734 public:
3735 pass_lower_eh_dispatch (gcc::context *ctxt)
3736 : gimple_opt_pass (pass_data_lower_eh_dispatch, ctxt)
3739 /* opt_pass methods: */
3740 virtual bool gate (function *fun) { return fun->eh->region_tree != NULL; }
3741 virtual unsigned int execute (function *);
3743 }; // class pass_lower_eh_dispatch
3745 unsigned
3746 pass_lower_eh_dispatch::execute (function *fun)
3748 basic_block bb;
3749 int flags = 0;
3750 bool redirected = false;
3752 assign_filter_values ();
3754 FOR_EACH_BB_FN (bb, fun)
3756 gimple last = last_stmt (bb);
3757 if (last == NULL)
3758 continue;
3759 if (gimple_code (last) == GIMPLE_EH_DISPATCH)
3761 redirected |= lower_eh_dispatch (bb,
3762 as_a <geh_dispatch *> (last));
3763 flags |= TODO_update_ssa_only_virtuals;
3765 else if (gimple_code (last) == GIMPLE_RESX)
3767 if (stmt_can_throw_external (last))
3768 optimize_clobbers (bb);
3769 else
3770 flags |= sink_clobbers (bb);
3774 if (redirected)
3775 delete_unreachable_blocks ();
3776 return flags;
3779 } // anon namespace
3781 gimple_opt_pass *
3782 make_pass_lower_eh_dispatch (gcc::context *ctxt)
3784 return new pass_lower_eh_dispatch (ctxt);
3787 /* Walk statements, see what regions and, optionally, landing pads
3788 are really referenced.
3790 Returns in R_REACHABLEP an sbitmap with bits set for reachable regions,
3791 and in LP_REACHABLE an sbitmap with bits set for reachable landing pads.
3793 Passing NULL for LP_REACHABLE is valid, in this case only reachable
3794 regions are marked.
3796 The caller is responsible for freeing the returned sbitmaps. */
3798 static void
3799 mark_reachable_handlers (sbitmap *r_reachablep, sbitmap *lp_reachablep)
3801 sbitmap r_reachable, lp_reachable;
3802 basic_block bb;
3803 bool mark_landing_pads = (lp_reachablep != NULL);
3804 gcc_checking_assert (r_reachablep != NULL);
3806 r_reachable = sbitmap_alloc (cfun->eh->region_array->length ());
3807 bitmap_clear (r_reachable);
3808 *r_reachablep = r_reachable;
3810 if (mark_landing_pads)
3812 lp_reachable = sbitmap_alloc (cfun->eh->lp_array->length ());
3813 bitmap_clear (lp_reachable);
3814 *lp_reachablep = lp_reachable;
3816 else
3817 lp_reachable = NULL;
3819 FOR_EACH_BB_FN (bb, cfun)
3821 gimple_stmt_iterator gsi;
3823 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3825 gimple stmt = gsi_stmt (gsi);
3827 if (mark_landing_pads)
3829 int lp_nr = lookup_stmt_eh_lp (stmt);
3831 /* Negative LP numbers are MUST_NOT_THROW regions which
3832 are not considered BB enders. */
3833 if (lp_nr < 0)
3834 bitmap_set_bit (r_reachable, -lp_nr);
3836 /* Positive LP numbers are real landing pads, and BB enders. */
3837 else if (lp_nr > 0)
3839 gcc_assert (gsi_one_before_end_p (gsi));
3840 eh_region region = get_eh_region_from_lp_number (lp_nr);
3841 bitmap_set_bit (r_reachable, region->index);
3842 bitmap_set_bit (lp_reachable, lp_nr);
3846 /* Avoid removing regions referenced from RESX/EH_DISPATCH. */
3847 switch (gimple_code (stmt))
3849 case GIMPLE_RESX:
3850 bitmap_set_bit (r_reachable,
3851 gimple_resx_region (as_a <gresx *> (stmt)));
3852 break;
3853 case GIMPLE_EH_DISPATCH:
3854 bitmap_set_bit (r_reachable,
3855 gimple_eh_dispatch_region (
3856 as_a <geh_dispatch *> (stmt)));
3857 break;
3858 case GIMPLE_CALL:
3859 if (gimple_call_builtin_p (stmt, BUILT_IN_EH_COPY_VALUES))
3860 for (int i = 0; i < 2; ++i)
3862 tree rt = gimple_call_arg (stmt, i);
3863 HOST_WIDE_INT ri = tree_to_shwi (rt);
3865 gcc_assert (ri = (int)ri);
3866 bitmap_set_bit (r_reachable, ri);
3868 break;
3869 default:
3870 break;
3876 /* Remove unreachable handlers and unreachable landing pads. */
3878 static void
3879 remove_unreachable_handlers (void)
3881 sbitmap r_reachable, lp_reachable;
3882 eh_region region;
3883 eh_landing_pad lp;
3884 unsigned i;
3886 mark_reachable_handlers (&r_reachable, &lp_reachable);
3888 if (dump_file)
3890 fprintf (dump_file, "Before removal of unreachable regions:\n");
3891 dump_eh_tree (dump_file, cfun);
3892 fprintf (dump_file, "Reachable regions: ");
3893 dump_bitmap_file (dump_file, r_reachable);
3894 fprintf (dump_file, "Reachable landing pads: ");
3895 dump_bitmap_file (dump_file, lp_reachable);
3898 if (dump_file)
3900 FOR_EACH_VEC_SAFE_ELT (cfun->eh->region_array, i, region)
3901 if (region && !bitmap_bit_p (r_reachable, region->index))
3902 fprintf (dump_file,
3903 "Removing unreachable region %d\n",
3904 region->index);
3907 remove_unreachable_eh_regions (r_reachable);
3909 FOR_EACH_VEC_SAFE_ELT (cfun->eh->lp_array, i, lp)
3910 if (lp && !bitmap_bit_p (lp_reachable, lp->index))
3912 if (dump_file)
3913 fprintf (dump_file,
3914 "Removing unreachable landing pad %d\n",
3915 lp->index);
3916 remove_eh_landing_pad (lp);
3919 if (dump_file)
3921 fprintf (dump_file, "\n\nAfter removal of unreachable regions:\n");
3922 dump_eh_tree (dump_file, cfun);
3923 fprintf (dump_file, "\n\n");
3926 sbitmap_free (r_reachable);
3927 sbitmap_free (lp_reachable);
3929 #ifdef ENABLE_CHECKING
3930 verify_eh_tree (cfun);
3931 #endif
3934 /* Remove unreachable handlers if any landing pads have been removed after
3935 last ehcleanup pass (due to gimple_purge_dead_eh_edges). */
3937 void
3938 maybe_remove_unreachable_handlers (void)
3940 eh_landing_pad lp;
3941 unsigned i;
3943 if (cfun->eh == NULL)
3944 return;
3946 FOR_EACH_VEC_SAFE_ELT (cfun->eh->lp_array, i, lp)
3947 if (lp && lp->post_landing_pad)
3949 if (label_to_block (lp->post_landing_pad) == NULL)
3951 remove_unreachable_handlers ();
3952 return;
3957 /* Remove regions that do not have landing pads. This assumes
3958 that remove_unreachable_handlers has already been run, and
3959 that we've just manipulated the landing pads since then.
3961 Preserve regions with landing pads and regions that prevent
3962 exceptions from propagating further, even if these regions
3963 are not reachable. */
3965 static void
3966 remove_unreachable_handlers_no_lp (void)
3968 eh_region region;
3969 sbitmap r_reachable;
3970 unsigned i;
3972 mark_reachable_handlers (&r_reachable, /*lp_reachablep=*/NULL);
3974 FOR_EACH_VEC_SAFE_ELT (cfun->eh->region_array, i, region)
3976 if (! region)
3977 continue;
3979 if (region->landing_pads != NULL
3980 || region->type == ERT_MUST_NOT_THROW)
3981 bitmap_set_bit (r_reachable, region->index);
3983 if (dump_file
3984 && !bitmap_bit_p (r_reachable, region->index))
3985 fprintf (dump_file,
3986 "Removing unreachable region %d\n",
3987 region->index);
3990 remove_unreachable_eh_regions (r_reachable);
3992 sbitmap_free (r_reachable);
3995 /* Undo critical edge splitting on an EH landing pad. Earlier, we
3996 optimisticaly split all sorts of edges, including EH edges. The
3997 optimization passes in between may not have needed them; if not,
3998 we should undo the split.
4000 Recognize this case by having one EH edge incoming to the BB and
4001 one normal edge outgoing; BB should be empty apart from the
4002 post_landing_pad label.
4004 Note that this is slightly different from the empty handler case
4005 handled by cleanup_empty_eh, in that the actual handler may yet
4006 have actual code but the landing pad has been separated from the
4007 handler. As such, cleanup_empty_eh relies on this transformation
4008 having been done first. */
4010 static bool
4011 unsplit_eh (eh_landing_pad lp)
4013 basic_block bb = label_to_block (lp->post_landing_pad);
4014 gimple_stmt_iterator gsi;
4015 edge e_in, e_out;
4017 /* Quickly check the edge counts on BB for singularity. */
4018 if (!single_pred_p (bb) || !single_succ_p (bb))
4019 return false;
4020 e_in = single_pred_edge (bb);
4021 e_out = single_succ_edge (bb);
4023 /* Input edge must be EH and output edge must be normal. */
4024 if ((e_in->flags & EDGE_EH) == 0 || (e_out->flags & EDGE_EH) != 0)
4025 return false;
4027 /* The block must be empty except for the labels and debug insns. */
4028 gsi = gsi_after_labels (bb);
4029 if (!gsi_end_p (gsi) && is_gimple_debug (gsi_stmt (gsi)))
4030 gsi_next_nondebug (&gsi);
4031 if (!gsi_end_p (gsi))
4032 return false;
4034 /* The destination block must not already have a landing pad
4035 for a different region. */
4036 for (gsi = gsi_start_bb (e_out->dest); !gsi_end_p (gsi); gsi_next (&gsi))
4038 glabel *label_stmt = dyn_cast <glabel *> (gsi_stmt (gsi));
4039 tree lab;
4040 int lp_nr;
4042 if (!label_stmt)
4043 break;
4044 lab = gimple_label_label (label_stmt);
4045 lp_nr = EH_LANDING_PAD_NR (lab);
4046 if (lp_nr && get_eh_region_from_lp_number (lp_nr) != lp->region)
4047 return false;
4050 /* The new destination block must not already be a destination of
4051 the source block, lest we merge fallthru and eh edges and get
4052 all sorts of confused. */
4053 if (find_edge (e_in->src, e_out->dest))
4054 return false;
4056 /* ??? We can get degenerate phis due to cfg cleanups. I would have
4057 thought this should have been cleaned up by a phicprop pass, but
4058 that doesn't appear to handle virtuals. Propagate by hand. */
4059 if (!gimple_seq_empty_p (phi_nodes (bb)))
4061 for (gphi_iterator gpi = gsi_start_phis (bb); !gsi_end_p (gpi); )
4063 gimple use_stmt;
4064 gphi *phi = gpi.phi ();
4065 tree lhs = gimple_phi_result (phi);
4066 tree rhs = gimple_phi_arg_def (phi, 0);
4067 use_operand_p use_p;
4068 imm_use_iterator iter;
4070 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
4072 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
4073 SET_USE (use_p, rhs);
4076 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
4077 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs) = 1;
4079 remove_phi_node (&gpi, true);
4083 if (dump_file && (dump_flags & TDF_DETAILS))
4084 fprintf (dump_file, "Unsplit EH landing pad %d to block %i.\n",
4085 lp->index, e_out->dest->index);
4087 /* Redirect the edge. Since redirect_eh_edge_1 expects to be moving
4088 a successor edge, humor it. But do the real CFG change with the
4089 predecessor of E_OUT in order to preserve the ordering of arguments
4090 to the PHI nodes in E_OUT->DEST. */
4091 redirect_eh_edge_1 (e_in, e_out->dest, false);
4092 redirect_edge_pred (e_out, e_in->src);
4093 e_out->flags = e_in->flags;
4094 e_out->probability = e_in->probability;
4095 e_out->count = e_in->count;
4096 remove_edge (e_in);
4098 return true;
4101 /* Examine each landing pad block and see if it matches unsplit_eh. */
4103 static bool
4104 unsplit_all_eh (void)
4106 bool changed = false;
4107 eh_landing_pad lp;
4108 int i;
4110 for (i = 1; vec_safe_iterate (cfun->eh->lp_array, i, &lp); ++i)
4111 if (lp)
4112 changed |= unsplit_eh (lp);
4114 return changed;
4117 /* A subroutine of cleanup_empty_eh. Redirect all EH edges incoming
4118 to OLD_BB to NEW_BB; return true on success, false on failure.
4120 OLD_BB_OUT is the edge into NEW_BB from OLD_BB, so if we miss any
4121 PHI variables from OLD_BB we can pick them up from OLD_BB_OUT.
4122 Virtual PHIs may be deleted and marked for renaming. */
4124 static bool
4125 cleanup_empty_eh_merge_phis (basic_block new_bb, basic_block old_bb,
4126 edge old_bb_out, bool change_region)
4128 gphi_iterator ngsi, ogsi;
4129 edge_iterator ei;
4130 edge e;
4131 bitmap ophi_handled;
4133 /* The destination block must not be a regular successor for any
4134 of the preds of the landing pad. Thus, avoid turning
4135 <..>
4136 | \ EH
4137 | <..>
4139 <..>
4140 into
4141 <..>
4142 | | EH
4143 <..>
4144 which CFG verification would choke on. See PR45172 and PR51089. */
4145 FOR_EACH_EDGE (e, ei, old_bb->preds)
4146 if (find_edge (e->src, new_bb))
4147 return false;
4149 FOR_EACH_EDGE (e, ei, old_bb->preds)
4150 redirect_edge_var_map_clear (e);
4152 ophi_handled = BITMAP_ALLOC (NULL);
4154 /* First, iterate through the PHIs on NEW_BB and set up the edge_var_map
4155 for the edges we're going to move. */
4156 for (ngsi = gsi_start_phis (new_bb); !gsi_end_p (ngsi); gsi_next (&ngsi))
4158 gphi *ophi, *nphi = ngsi.phi ();
4159 tree nresult, nop;
4161 nresult = gimple_phi_result (nphi);
4162 nop = gimple_phi_arg_def (nphi, old_bb_out->dest_idx);
4164 /* Find the corresponding PHI in OLD_BB so we can forward-propagate
4165 the source ssa_name. */
4166 ophi = NULL;
4167 for (ogsi = gsi_start_phis (old_bb); !gsi_end_p (ogsi); gsi_next (&ogsi))
4169 ophi = ogsi.phi ();
4170 if (gimple_phi_result (ophi) == nop)
4171 break;
4172 ophi = NULL;
4175 /* If we did find the corresponding PHI, copy those inputs. */
4176 if (ophi)
4178 /* If NOP is used somewhere else beyond phis in new_bb, give up. */
4179 if (!has_single_use (nop))
4181 imm_use_iterator imm_iter;
4182 use_operand_p use_p;
4184 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, nop)
4186 if (!gimple_debug_bind_p (USE_STMT (use_p))
4187 && (gimple_code (USE_STMT (use_p)) != GIMPLE_PHI
4188 || gimple_bb (USE_STMT (use_p)) != new_bb))
4189 goto fail;
4192 bitmap_set_bit (ophi_handled, SSA_NAME_VERSION (nop));
4193 FOR_EACH_EDGE (e, ei, old_bb->preds)
4195 location_t oloc;
4196 tree oop;
4198 if ((e->flags & EDGE_EH) == 0)
4199 continue;
4200 oop = gimple_phi_arg_def (ophi, e->dest_idx);
4201 oloc = gimple_phi_arg_location (ophi, e->dest_idx);
4202 redirect_edge_var_map_add (e, nresult, oop, oloc);
4205 /* If we didn't find the PHI, if it's a real variable or a VOP, we know
4206 from the fact that OLD_BB is tree_empty_eh_handler_p that the
4207 variable is unchanged from input to the block and we can simply
4208 re-use the input to NEW_BB from the OLD_BB_OUT edge. */
4209 else
4211 location_t nloc
4212 = gimple_phi_arg_location (nphi, old_bb_out->dest_idx);
4213 FOR_EACH_EDGE (e, ei, old_bb->preds)
4214 redirect_edge_var_map_add (e, nresult, nop, nloc);
4218 /* Second, verify that all PHIs from OLD_BB have been handled. If not,
4219 we don't know what values from the other edges into NEW_BB to use. */
4220 for (ogsi = gsi_start_phis (old_bb); !gsi_end_p (ogsi); gsi_next (&ogsi))
4222 gphi *ophi = ogsi.phi ();
4223 tree oresult = gimple_phi_result (ophi);
4224 if (!bitmap_bit_p (ophi_handled, SSA_NAME_VERSION (oresult)))
4225 goto fail;
4228 /* Finally, move the edges and update the PHIs. */
4229 for (ei = ei_start (old_bb->preds); (e = ei_safe_edge (ei)); )
4230 if (e->flags & EDGE_EH)
4232 /* ??? CFG manipluation routines do not try to update loop
4233 form on edge redirection. Do so manually here for now. */
4234 /* If we redirect a loop entry or latch edge that will either create
4235 a multiple entry loop or rotate the loop. If the loops merge
4236 we may have created a loop with multiple latches.
4237 All of this isn't easily fixed thus cancel the affected loop
4238 and mark the other loop as possibly having multiple latches. */
4239 if (e->dest == e->dest->loop_father->header)
4241 mark_loop_for_removal (e->dest->loop_father);
4242 new_bb->loop_father->latch = NULL;
4243 loops_state_set (LOOPS_MAY_HAVE_MULTIPLE_LATCHES);
4245 redirect_eh_edge_1 (e, new_bb, change_region);
4246 redirect_edge_succ (e, new_bb);
4247 flush_pending_stmts (e);
4249 else
4250 ei_next (&ei);
4252 BITMAP_FREE (ophi_handled);
4253 return true;
4255 fail:
4256 FOR_EACH_EDGE (e, ei, old_bb->preds)
4257 redirect_edge_var_map_clear (e);
4258 BITMAP_FREE (ophi_handled);
4259 return false;
4262 /* A subroutine of cleanup_empty_eh. Move a landing pad LP from its
4263 old region to NEW_REGION at BB. */
4265 static void
4266 cleanup_empty_eh_move_lp (basic_block bb, edge e_out,
4267 eh_landing_pad lp, eh_region new_region)
4269 gimple_stmt_iterator gsi;
4270 eh_landing_pad *pp;
4272 for (pp = &lp->region->landing_pads; *pp != lp; pp = &(*pp)->next_lp)
4273 continue;
4274 *pp = lp->next_lp;
4276 lp->region = new_region;
4277 lp->next_lp = new_region->landing_pads;
4278 new_region->landing_pads = lp;
4280 /* Delete the RESX that was matched within the empty handler block. */
4281 gsi = gsi_last_bb (bb);
4282 unlink_stmt_vdef (gsi_stmt (gsi));
4283 gsi_remove (&gsi, true);
4285 /* Clean up E_OUT for the fallthru. */
4286 e_out->flags = (e_out->flags & ~EDGE_EH) | EDGE_FALLTHRU;
4287 e_out->probability = REG_BR_PROB_BASE;
4290 /* A subroutine of cleanup_empty_eh. Handle more complex cases of
4291 unsplitting than unsplit_eh was prepared to handle, e.g. when
4292 multiple incoming edges and phis are involved. */
4294 static bool
4295 cleanup_empty_eh_unsplit (basic_block bb, edge e_out, eh_landing_pad lp)
4297 gimple_stmt_iterator gsi;
4298 tree lab;
4300 /* We really ought not have totally lost everything following
4301 a landing pad label. Given that BB is empty, there had better
4302 be a successor. */
4303 gcc_assert (e_out != NULL);
4305 /* The destination block must not already have a landing pad
4306 for a different region. */
4307 lab = NULL;
4308 for (gsi = gsi_start_bb (e_out->dest); !gsi_end_p (gsi); gsi_next (&gsi))
4310 glabel *stmt = dyn_cast <glabel *> (gsi_stmt (gsi));
4311 int lp_nr;
4313 if (!stmt)
4314 break;
4315 lab = gimple_label_label (stmt);
4316 lp_nr = EH_LANDING_PAD_NR (lab);
4317 if (lp_nr && get_eh_region_from_lp_number (lp_nr) != lp->region)
4318 return false;
4321 /* Attempt to move the PHIs into the successor block. */
4322 if (cleanup_empty_eh_merge_phis (e_out->dest, bb, e_out, false))
4324 if (dump_file && (dump_flags & TDF_DETAILS))
4325 fprintf (dump_file,
4326 "Unsplit EH landing pad %d to block %i "
4327 "(via cleanup_empty_eh).\n",
4328 lp->index, e_out->dest->index);
4329 return true;
4332 return false;
4335 /* Return true if edge E_FIRST is part of an empty infinite loop
4336 or leads to such a loop through a series of single successor
4337 empty bbs. */
4339 static bool
4340 infinite_empty_loop_p (edge e_first)
4342 bool inf_loop = false;
4343 edge e;
4345 if (e_first->dest == e_first->src)
4346 return true;
4348 e_first->src->aux = (void *) 1;
4349 for (e = e_first; single_succ_p (e->dest); e = single_succ_edge (e->dest))
4351 gimple_stmt_iterator gsi;
4352 if (e->dest->aux)
4354 inf_loop = true;
4355 break;
4357 e->dest->aux = (void *) 1;
4358 gsi = gsi_after_labels (e->dest);
4359 if (!gsi_end_p (gsi) && is_gimple_debug (gsi_stmt (gsi)))
4360 gsi_next_nondebug (&gsi);
4361 if (!gsi_end_p (gsi))
4362 break;
4364 e_first->src->aux = NULL;
4365 for (e = e_first; e->dest->aux; e = single_succ_edge (e->dest))
4366 e->dest->aux = NULL;
4368 return inf_loop;
4371 /* Examine the block associated with LP to determine if it's an empty
4372 handler for its EH region. If so, attempt to redirect EH edges to
4373 an outer region. Return true the CFG was updated in any way. This
4374 is similar to jump forwarding, just across EH edges. */
4376 static bool
4377 cleanup_empty_eh (eh_landing_pad lp)
4379 basic_block bb = label_to_block (lp->post_landing_pad);
4380 gimple_stmt_iterator gsi;
4381 gimple resx;
4382 eh_region new_region;
4383 edge_iterator ei;
4384 edge e, e_out;
4385 bool has_non_eh_pred;
4386 bool ret = false;
4387 int new_lp_nr;
4389 /* There can be zero or one edges out of BB. This is the quickest test. */
4390 switch (EDGE_COUNT (bb->succs))
4392 case 0:
4393 e_out = NULL;
4394 break;
4395 case 1:
4396 e_out = single_succ_edge (bb);
4397 break;
4398 default:
4399 return false;
4402 resx = last_stmt (bb);
4403 if (resx && is_gimple_resx (resx))
4405 if (stmt_can_throw_external (resx))
4406 optimize_clobbers (bb);
4407 else if (sink_clobbers (bb))
4408 ret = true;
4411 gsi = gsi_after_labels (bb);
4413 /* Make sure to skip debug statements. */
4414 if (!gsi_end_p (gsi) && is_gimple_debug (gsi_stmt (gsi)))
4415 gsi_next_nondebug (&gsi);
4417 /* If the block is totally empty, look for more unsplitting cases. */
4418 if (gsi_end_p (gsi))
4420 /* For the degenerate case of an infinite loop bail out.
4421 If bb has no successors and is totally empty, which can happen e.g.
4422 because of incorrect noreturn attribute, bail out too. */
4423 if (e_out == NULL
4424 || infinite_empty_loop_p (e_out))
4425 return ret;
4427 return ret | cleanup_empty_eh_unsplit (bb, e_out, lp);
4430 /* The block should consist only of a single RESX statement, modulo a
4431 preceding call to __builtin_stack_restore if there is no outgoing
4432 edge, since the call can be eliminated in this case. */
4433 resx = gsi_stmt (gsi);
4434 if (!e_out && gimple_call_builtin_p (resx, BUILT_IN_STACK_RESTORE))
4436 gsi_next (&gsi);
4437 resx = gsi_stmt (gsi);
4439 if (!is_gimple_resx (resx))
4440 return ret;
4441 gcc_assert (gsi_one_before_end_p (gsi));
4443 /* Determine if there are non-EH edges, or resx edges into the handler. */
4444 has_non_eh_pred = false;
4445 FOR_EACH_EDGE (e, ei, bb->preds)
4446 if (!(e->flags & EDGE_EH))
4447 has_non_eh_pred = true;
4449 /* Find the handler that's outer of the empty handler by looking at
4450 where the RESX instruction was vectored. */
4451 new_lp_nr = lookup_stmt_eh_lp (resx);
4452 new_region = get_eh_region_from_lp_number (new_lp_nr);
4454 /* If there's no destination region within the current function,
4455 redirection is trivial via removing the throwing statements from
4456 the EH region, removing the EH edges, and allowing the block
4457 to go unreachable. */
4458 if (new_region == NULL)
4460 gcc_assert (e_out == NULL);
4461 for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
4462 if (e->flags & EDGE_EH)
4464 gimple stmt = last_stmt (e->src);
4465 remove_stmt_from_eh_lp (stmt);
4466 remove_edge (e);
4468 else
4469 ei_next (&ei);
4470 goto succeed;
4473 /* If the destination region is a MUST_NOT_THROW, allow the runtime
4474 to handle the abort and allow the blocks to go unreachable. */
4475 if (new_region->type == ERT_MUST_NOT_THROW)
4477 for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
4478 if (e->flags & EDGE_EH)
4480 gimple stmt = last_stmt (e->src);
4481 remove_stmt_from_eh_lp (stmt);
4482 add_stmt_to_eh_lp (stmt, new_lp_nr);
4483 remove_edge (e);
4485 else
4486 ei_next (&ei);
4487 goto succeed;
4490 /* Try to redirect the EH edges and merge the PHIs into the destination
4491 landing pad block. If the merge succeeds, we'll already have redirected
4492 all the EH edges. The handler itself will go unreachable if there were
4493 no normal edges. */
4494 if (cleanup_empty_eh_merge_phis (e_out->dest, bb, e_out, true))
4495 goto succeed;
4497 /* Finally, if all input edges are EH edges, then we can (potentially)
4498 reduce the number of transfers from the runtime by moving the landing
4499 pad from the original region to the new region. This is a win when
4500 we remove the last CLEANUP region along a particular exception
4501 propagation path. Since nothing changes except for the region with
4502 which the landing pad is associated, the PHI nodes do not need to be
4503 adjusted at all. */
4504 if (!has_non_eh_pred)
4506 cleanup_empty_eh_move_lp (bb, e_out, lp, new_region);
4507 if (dump_file && (dump_flags & TDF_DETAILS))
4508 fprintf (dump_file, "Empty EH handler %i moved to EH region %i.\n",
4509 lp->index, new_region->index);
4511 /* ??? The CFG didn't change, but we may have rendered the
4512 old EH region unreachable. Trigger a cleanup there. */
4513 return true;
4516 return ret;
4518 succeed:
4519 if (dump_file && (dump_flags & TDF_DETAILS))
4520 fprintf (dump_file, "Empty EH handler %i removed.\n", lp->index);
4521 remove_eh_landing_pad (lp);
4522 return true;
4525 /* Do a post-order traversal of the EH region tree. Examine each
4526 post_landing_pad block and see if we can eliminate it as empty. */
4528 static bool
4529 cleanup_all_empty_eh (void)
4531 bool changed = false;
4532 eh_landing_pad lp;
4533 int i;
4535 for (i = 1; vec_safe_iterate (cfun->eh->lp_array, i, &lp); ++i)
4536 if (lp)
4537 changed |= cleanup_empty_eh (lp);
4539 return changed;
4542 /* Perform cleanups and lowering of exception handling
4543 1) cleanups regions with handlers doing nothing are optimized out
4544 2) MUST_NOT_THROW regions that became dead because of 1) are optimized out
4545 3) Info about regions that are containing instructions, and regions
4546 reachable via local EH edges is collected
4547 4) Eh tree is pruned for regions no longer necessary.
4549 TODO: Push MUST_NOT_THROW regions to the root of the EH tree.
4550 Unify those that have the same failure decl and locus.
4553 static unsigned int
4554 execute_cleanup_eh_1 (void)
4556 /* Do this first: unsplit_all_eh and cleanup_all_empty_eh can die
4557 looking up unreachable landing pads. */
4558 remove_unreachable_handlers ();
4560 /* Watch out for the region tree vanishing due to all unreachable. */
4561 if (cfun->eh->region_tree)
4563 bool changed = false;
4565 if (optimize)
4566 changed |= unsplit_all_eh ();
4567 changed |= cleanup_all_empty_eh ();
4569 if (changed)
4571 free_dominance_info (CDI_DOMINATORS);
4572 free_dominance_info (CDI_POST_DOMINATORS);
4574 /* We delayed all basic block deletion, as we may have performed
4575 cleanups on EH edges while non-EH edges were still present. */
4576 delete_unreachable_blocks ();
4578 /* We manipulated the landing pads. Remove any region that no
4579 longer has a landing pad. */
4580 remove_unreachable_handlers_no_lp ();
4582 return TODO_cleanup_cfg | TODO_update_ssa_only_virtuals;
4586 return 0;
4589 namespace {
4591 const pass_data pass_data_cleanup_eh =
4593 GIMPLE_PASS, /* type */
4594 "ehcleanup", /* name */
4595 OPTGROUP_NONE, /* optinfo_flags */
4596 TV_TREE_EH, /* tv_id */
4597 PROP_gimple_lcf, /* properties_required */
4598 0, /* properties_provided */
4599 0, /* properties_destroyed */
4600 0, /* todo_flags_start */
4601 0, /* todo_flags_finish */
4604 class pass_cleanup_eh : public gimple_opt_pass
4606 public:
4607 pass_cleanup_eh (gcc::context *ctxt)
4608 : gimple_opt_pass (pass_data_cleanup_eh, ctxt)
4611 /* opt_pass methods: */
4612 opt_pass * clone () { return new pass_cleanup_eh (m_ctxt); }
4613 virtual bool gate (function *fun)
4615 return fun->eh != NULL && fun->eh->region_tree != NULL;
4618 virtual unsigned int execute (function *);
4620 }; // class pass_cleanup_eh
4622 unsigned int
4623 pass_cleanup_eh::execute (function *fun)
4625 int ret = execute_cleanup_eh_1 ();
4627 /* If the function no longer needs an EH personality routine
4628 clear it. This exposes cross-language inlining opportunities
4629 and avoids references to a never defined personality routine. */
4630 if (DECL_FUNCTION_PERSONALITY (current_function_decl)
4631 && function_needs_eh_personality (fun) != eh_personality_lang)
4632 DECL_FUNCTION_PERSONALITY (current_function_decl) = NULL_TREE;
4634 return ret;
4637 } // anon namespace
4639 gimple_opt_pass *
4640 make_pass_cleanup_eh (gcc::context *ctxt)
4642 return new pass_cleanup_eh (ctxt);
4645 /* Verify that BB containing STMT as the last statement, has precisely the
4646 edge that make_eh_edges would create. */
4648 DEBUG_FUNCTION bool
4649 verify_eh_edges (gimple stmt)
4651 basic_block bb = gimple_bb (stmt);
4652 eh_landing_pad lp = NULL;
4653 int lp_nr;
4654 edge_iterator ei;
4655 edge e, eh_edge;
4657 lp_nr = lookup_stmt_eh_lp (stmt);
4658 if (lp_nr > 0)
4659 lp = get_eh_landing_pad_from_number (lp_nr);
4661 eh_edge = NULL;
4662 FOR_EACH_EDGE (e, ei, bb->succs)
4664 if (e->flags & EDGE_EH)
4666 if (eh_edge)
4668 error ("BB %i has multiple EH edges", bb->index);
4669 return true;
4671 else
4672 eh_edge = e;
4676 if (lp == NULL)
4678 if (eh_edge)
4680 error ("BB %i can not throw but has an EH edge", bb->index);
4681 return true;
4683 return false;
4686 if (!stmt_could_throw_p (stmt))
4688 error ("BB %i last statement has incorrectly set lp", bb->index);
4689 return true;
4692 if (eh_edge == NULL)
4694 error ("BB %i is missing an EH edge", bb->index);
4695 return true;
4698 if (eh_edge->dest != label_to_block (lp->post_landing_pad))
4700 error ("Incorrect EH edge %i->%i", bb->index, eh_edge->dest->index);
4701 return true;
4704 return false;
4707 /* Similarly, but handle GIMPLE_EH_DISPATCH specifically. */
4709 DEBUG_FUNCTION bool
4710 verify_eh_dispatch_edge (geh_dispatch *stmt)
4712 eh_region r;
4713 eh_catch c;
4714 basic_block src, dst;
4715 bool want_fallthru = true;
4716 edge_iterator ei;
4717 edge e, fall_edge;
4719 r = get_eh_region_from_number (gimple_eh_dispatch_region (stmt));
4720 src = gimple_bb (stmt);
4722 FOR_EACH_EDGE (e, ei, src->succs)
4723 gcc_assert (e->aux == NULL);
4725 switch (r->type)
4727 case ERT_TRY:
4728 for (c = r->u.eh_try.first_catch; c ; c = c->next_catch)
4730 dst = label_to_block (c->label);
4731 e = find_edge (src, dst);
4732 if (e == NULL)
4734 error ("BB %i is missing an edge", src->index);
4735 return true;
4737 e->aux = (void *)e;
4739 /* A catch-all handler doesn't have a fallthru. */
4740 if (c->type_list == NULL)
4742 want_fallthru = false;
4743 break;
4746 break;
4748 case ERT_ALLOWED_EXCEPTIONS:
4749 dst = label_to_block (r->u.allowed.label);
4750 e = find_edge (src, dst);
4751 if (e == NULL)
4753 error ("BB %i is missing an edge", src->index);
4754 return true;
4756 e->aux = (void *)e;
4757 break;
4759 default:
4760 gcc_unreachable ();
4763 fall_edge = NULL;
4764 FOR_EACH_EDGE (e, ei, src->succs)
4766 if (e->flags & EDGE_FALLTHRU)
4768 if (fall_edge != NULL)
4770 error ("BB %i too many fallthru edges", src->index);
4771 return true;
4773 fall_edge = e;
4775 else if (e->aux)
4776 e->aux = NULL;
4777 else
4779 error ("BB %i has incorrect edge", src->index);
4780 return true;
4783 if ((fall_edge != NULL) ^ want_fallthru)
4785 error ("BB %i has incorrect fallthru edge", src->index);
4786 return true;
4789 return false;