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