Debian Codegraph @

gcc/tree-eh.cc

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