OSDN Git Service

PR target/32325
[pf3gnuchains/gcc-fork.git] / gcc / except.c
1 /* Implements exception handling.
2    Copyright (C) 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3    1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007
4    Free Software Foundation, Inc.
5    Contributed by Mike Stump <mrs@cygnus.com>.
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 3, or (at your option) any later
12 version.
13
14 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
17 for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.  */
22
23
24 /* An exception is an event that can be signaled from within a
25    function. This event can then be "caught" or "trapped" by the
26    callers of this function. This potentially allows program flow to
27    be transferred to any arbitrary code associated with a function call
28    several levels up the stack.
29
30    The intended use for this mechanism is for signaling "exceptional
31    events" in an out-of-band fashion, hence its name. The C++ language
32    (and many other OO-styled or functional languages) practically
33    requires such a mechanism, as otherwise it becomes very difficult
34    or even impossible to signal failure conditions in complex
35    situations.  The traditional C++ example is when an error occurs in
36    the process of constructing an object; without such a mechanism, it
37    is impossible to signal that the error occurs without adding global
38    state variables and error checks around every object construction.
39
40    The act of causing this event to occur is referred to as "throwing
41    an exception". (Alternate terms include "raising an exception" or
42    "signaling an exception".) The term "throw" is used because control
43    is returned to the callers of the function that is signaling the
44    exception, and thus there is the concept of "throwing" the
45    exception up the call stack.
46
47    [ Add updated documentation on how to use this.  ]  */
48
49
50 #include "config.h"
51 #include "system.h"
52 #include "coretypes.h"
53 #include "tm.h"
54 #include "rtl.h"
55 #include "tree.h"
56 #include "flags.h"
57 #include "function.h"
58 #include "expr.h"
59 #include "libfuncs.h"
60 #include "insn-config.h"
61 #include "except.h"
62 #include "integrate.h"
63 #include "hard-reg-set.h"
64 #include "basic-block.h"
65 #include "output.h"
66 #include "dwarf2asm.h"
67 #include "dwarf2out.h"
68 #include "dwarf2.h"
69 #include "toplev.h"
70 #include "hashtab.h"
71 #include "intl.h"
72 #include "ggc.h"
73 #include "tm_p.h"
74 #include "target.h"
75 #include "langhooks.h"
76 #include "cgraph.h"
77 #include "diagnostic.h"
78 #include "tree-pass.h"
79 #include "timevar.h"
80
81 /* Provide defaults for stuff that may not be defined when using
82    sjlj exceptions.  */
83 #ifndef EH_RETURN_DATA_REGNO
84 #define EH_RETURN_DATA_REGNO(N) INVALID_REGNUM
85 #endif
86
87
88 /* Protect cleanup actions with must-not-throw regions, with a call
89    to the given failure handler.  */
90 tree (*lang_protect_cleanup_actions) (void);
91
92 /* Return true if type A catches type B.  */
93 int (*lang_eh_type_covers) (tree a, tree b);
94
95 /* Map a type to a runtime object to match type.  */
96 tree (*lang_eh_runtime_type) (tree);
97
98 /* A hash table of label to region number.  */
99
100 struct ehl_map_entry GTY(())
101 {
102   rtx label;
103   struct eh_region *region;
104 };
105
106 static GTY(()) int call_site_base;
107 static GTY ((param_is (union tree_node)))
108   htab_t type_to_runtime_map;
109
110 /* Describe the SjLj_Function_Context structure.  */
111 static GTY(()) tree sjlj_fc_type_node;
112 static int sjlj_fc_call_site_ofs;
113 static int sjlj_fc_data_ofs;
114 static int sjlj_fc_personality_ofs;
115 static int sjlj_fc_lsda_ofs;
116 static int sjlj_fc_jbuf_ofs;
117 \f
118 /* Describes one exception region.  */
119 struct eh_region GTY(())
120 {
121   /* The immediately surrounding region.  */
122   struct eh_region *outer;
123
124   /* The list of immediately contained regions.  */
125   struct eh_region *inner;
126   struct eh_region *next_peer;
127
128   /* An identifier for this region.  */
129   int region_number;
130
131   /* When a region is deleted, its parents inherit the REG_EH_REGION
132      numbers already assigned.  */
133   bitmap aka;
134
135   /* Each region does exactly one thing.  */
136   enum eh_region_type
137   {
138     ERT_UNKNOWN = 0,
139     ERT_CLEANUP,
140     ERT_TRY,
141     ERT_CATCH,
142     ERT_ALLOWED_EXCEPTIONS,
143     ERT_MUST_NOT_THROW,
144     ERT_THROW
145   } type;
146
147   /* Holds the action to perform based on the preceding type.  */
148   union eh_region_u {
149     /* A list of catch blocks, a surrounding try block,
150        and the label for continuing after a catch.  */
151     struct eh_region_u_try {
152       struct eh_region *catch;
153       struct eh_region *last_catch;
154     } GTY ((tag ("ERT_TRY"))) try;
155
156     /* The list through the catch handlers, the list of type objects
157        matched, and the list of associated filters.  */
158     struct eh_region_u_catch {
159       struct eh_region *next_catch;
160       struct eh_region *prev_catch;
161       tree type_list;
162       tree filter_list;
163     } GTY ((tag ("ERT_CATCH"))) catch;
164
165     /* A tree_list of allowed types.  */
166     struct eh_region_u_allowed {
167       tree type_list;
168       int filter;
169     } GTY ((tag ("ERT_ALLOWED_EXCEPTIONS"))) allowed;
170
171     /* The type given by a call to "throw foo();", or discovered
172        for a throw.  */
173     struct eh_region_u_throw {
174       tree type;
175     } GTY ((tag ("ERT_THROW"))) throw;
176
177     /* Retain the cleanup expression even after expansion so that
178        we can match up fixup regions.  */
179     struct eh_region_u_cleanup {
180       struct eh_region *prev_try;
181     } GTY ((tag ("ERT_CLEANUP"))) cleanup;
182   } GTY ((desc ("%0.type"))) u;
183
184   /* Entry point for this region's handler before landing pads are built.  */
185   rtx label;
186   tree tree_label;
187
188   /* Entry point for this region's handler from the runtime eh library.  */
189   rtx landing_pad;
190
191   /* Entry point for this region's handler from an inner region.  */
192   rtx post_landing_pad;
193
194   /* The RESX insn for handing off control to the next outermost handler,
195      if appropriate.  */
196   rtx resume;
197
198   /* True if something in this region may throw.  */
199   unsigned may_contain_throw : 1;
200 };
201
202 typedef struct eh_region *eh_region;
203
204 struct call_site_record GTY(())
205 {
206   rtx landing_pad;
207   int action;
208 };
209
210 DEF_VEC_P(eh_region);
211 DEF_VEC_ALLOC_P(eh_region, gc);
212
213 /* Used to save exception status for each function.  */
214 struct eh_status GTY(())
215 {
216   /* The tree of all regions for this function.  */
217   struct eh_region *region_tree;
218
219   /* The same information as an indexable array.  */
220   VEC(eh_region,gc) *region_array;
221
222   /* The most recently open region.  */
223   struct eh_region *cur_region;
224
225   /* This is the region for which we are processing catch blocks.  */
226   struct eh_region *try_region;
227
228   rtx filter;
229   rtx exc_ptr;
230
231   int built_landing_pads;
232   int last_region_number;
233
234   VEC(tree,gc) *ttype_data;
235   varray_type ehspec_data;
236   varray_type action_record_data;
237
238   htab_t GTY ((param_is (struct ehl_map_entry))) exception_handler_label_map;
239
240   struct call_site_record * GTY ((length ("%h.call_site_data_used")))
241     call_site_data;
242   int call_site_data_used;
243   int call_site_data_size;
244
245   rtx ehr_stackadj;
246   rtx ehr_handler;
247   rtx ehr_label;
248
249   rtx sjlj_fc;
250   rtx sjlj_exit_after;
251
252   htab_t GTY((param_is (struct throw_stmt_node))) throw_stmt_table;
253 };
254 \f
255 static int t2r_eq (const void *, const void *);
256 static hashval_t t2r_hash (const void *);
257 static void add_type_for_runtime (tree);
258 static tree lookup_type_for_runtime (tree);
259
260 static void remove_unreachable_regions (rtx);
261
262 static int ttypes_filter_eq (const void *, const void *);
263 static hashval_t ttypes_filter_hash (const void *);
264 static int ehspec_filter_eq (const void *, const void *);
265 static hashval_t ehspec_filter_hash (const void *);
266 static int add_ttypes_entry (htab_t, tree);
267 static int add_ehspec_entry (htab_t, htab_t, tree);
268 static void assign_filter_values (void);
269 static void build_post_landing_pads (void);
270 static void connect_post_landing_pads (void);
271 static void dw2_build_landing_pads (void);
272
273 struct sjlj_lp_info;
274 static bool sjlj_find_directly_reachable_regions (struct sjlj_lp_info *);
275 static void sjlj_assign_call_site_values (rtx, struct sjlj_lp_info *);
276 static void sjlj_mark_call_sites (struct sjlj_lp_info *);
277 static void sjlj_emit_function_enter (rtx);
278 static void sjlj_emit_function_exit (void);
279 static void sjlj_emit_dispatch_table (rtx, struct sjlj_lp_info *);
280 static void sjlj_build_landing_pads (void);
281
282 static hashval_t ehl_hash (const void *);
283 static int ehl_eq (const void *, const void *);
284 static void add_ehl_entry (rtx, struct eh_region *);
285 static void remove_exception_handler_label (rtx);
286 static void remove_eh_handler (struct eh_region *);
287 static int for_each_eh_label_1 (void **, void *);
288
289 /* The return value of reachable_next_level.  */
290 enum reachable_code
291 {
292   /* The given exception is not processed by the given region.  */
293   RNL_NOT_CAUGHT,
294   /* The given exception may need processing by the given region.  */
295   RNL_MAYBE_CAUGHT,
296   /* The given exception is completely processed by the given region.  */
297   RNL_CAUGHT,
298   /* The given exception is completely processed by the runtime.  */
299   RNL_BLOCKED
300 };
301
302 struct reachable_info;
303 static enum reachable_code reachable_next_level (struct eh_region *, tree,
304                                                  struct reachable_info *);
305
306 static int action_record_eq (const void *, const void *);
307 static hashval_t action_record_hash (const void *);
308 static int add_action_record (htab_t, int, int);
309 static int collect_one_action_chain (htab_t, struct eh_region *);
310 static int add_call_site (rtx, int);
311
312 static void push_uleb128 (varray_type *, unsigned int);
313 static void push_sleb128 (varray_type *, int);
314 #ifndef HAVE_AS_LEB128
315 static int dw2_size_of_call_site_table (void);
316 static int sjlj_size_of_call_site_table (void);
317 #endif
318 static void dw2_output_call_site_table (void);
319 static void sjlj_output_call_site_table (void);
320
321 \f
322 /* Routine to see if exception handling is turned on.
323    DO_WARN is nonzero if we want to inform the user that exception
324    handling is turned off.
325
326    This is used to ensure that -fexceptions has been specified if the
327    compiler tries to use any exception-specific functions.  */
328
329 int
330 doing_eh (int do_warn)
331 {
332   if (! flag_exceptions)
333     {
334       static int warned = 0;
335       if (! warned && do_warn)
336         {
337           error ("exception handling disabled, use -fexceptions to enable");
338           warned = 1;
339         }
340       return 0;
341     }
342   return 1;
343 }
344
345 \f
346 void
347 init_eh (void)
348 {
349   if (! flag_exceptions)
350     return;
351
352   type_to_runtime_map = htab_create_ggc (31, t2r_hash, t2r_eq, NULL);
353
354   /* Create the SjLj_Function_Context structure.  This should match
355      the definition in unwind-sjlj.c.  */
356   if (USING_SJLJ_EXCEPTIONS)
357     {
358       tree f_jbuf, f_per, f_lsda, f_prev, f_cs, f_data, tmp;
359
360       sjlj_fc_type_node = lang_hooks.types.make_type (RECORD_TYPE);
361
362       f_prev = build_decl (FIELD_DECL, get_identifier ("__prev"),
363                            build_pointer_type (sjlj_fc_type_node));
364       DECL_FIELD_CONTEXT (f_prev) = sjlj_fc_type_node;
365
366       f_cs = build_decl (FIELD_DECL, get_identifier ("__call_site"),
367                          integer_type_node);
368       DECL_FIELD_CONTEXT (f_cs) = sjlj_fc_type_node;
369
370       tmp = build_index_type (build_int_cst (NULL_TREE, 4 - 1));
371       tmp = build_array_type (lang_hooks.types.type_for_mode (word_mode, 1),
372                               tmp);
373       f_data = build_decl (FIELD_DECL, get_identifier ("__data"), tmp);
374       DECL_FIELD_CONTEXT (f_data) = sjlj_fc_type_node;
375
376       f_per = build_decl (FIELD_DECL, get_identifier ("__personality"),
377                           ptr_type_node);
378       DECL_FIELD_CONTEXT (f_per) = sjlj_fc_type_node;
379
380       f_lsda = build_decl (FIELD_DECL, get_identifier ("__lsda"),
381                            ptr_type_node);
382       DECL_FIELD_CONTEXT (f_lsda) = sjlj_fc_type_node;
383
384 #ifdef DONT_USE_BUILTIN_SETJMP
385 #ifdef JMP_BUF_SIZE
386       tmp = build_int_cst (NULL_TREE, JMP_BUF_SIZE - 1);
387 #else
388       /* Should be large enough for most systems, if it is not,
389          JMP_BUF_SIZE should be defined with the proper value.  It will
390          also tend to be larger than necessary for most systems, a more
391          optimal port will define JMP_BUF_SIZE.  */
392       tmp = build_int_cst (NULL_TREE, FIRST_PSEUDO_REGISTER + 2 - 1);
393 #endif
394 #else
395       /* builtin_setjmp takes a pointer to 5 words.  */
396       tmp = build_int_cst (NULL_TREE, 5 * BITS_PER_WORD / POINTER_SIZE - 1);
397 #endif
398       tmp = build_index_type (tmp);
399       tmp = build_array_type (ptr_type_node, tmp);
400       f_jbuf = build_decl (FIELD_DECL, get_identifier ("__jbuf"), tmp);
401 #ifdef DONT_USE_BUILTIN_SETJMP
402       /* We don't know what the alignment requirements of the
403          runtime's jmp_buf has.  Overestimate.  */
404       DECL_ALIGN (f_jbuf) = BIGGEST_ALIGNMENT;
405       DECL_USER_ALIGN (f_jbuf) = 1;
406 #endif
407       DECL_FIELD_CONTEXT (f_jbuf) = sjlj_fc_type_node;
408
409       TYPE_FIELDS (sjlj_fc_type_node) = f_prev;
410       TREE_CHAIN (f_prev) = f_cs;
411       TREE_CHAIN (f_cs) = f_data;
412       TREE_CHAIN (f_data) = f_per;
413       TREE_CHAIN (f_per) = f_lsda;
414       TREE_CHAIN (f_lsda) = f_jbuf;
415
416       layout_type (sjlj_fc_type_node);
417
418       /* Cache the interesting field offsets so that we have
419          easy access from rtl.  */
420       sjlj_fc_call_site_ofs
421         = (tree_low_cst (DECL_FIELD_OFFSET (f_cs), 1)
422            + tree_low_cst (DECL_FIELD_BIT_OFFSET (f_cs), 1) / BITS_PER_UNIT);
423       sjlj_fc_data_ofs
424         = (tree_low_cst (DECL_FIELD_OFFSET (f_data), 1)
425            + tree_low_cst (DECL_FIELD_BIT_OFFSET (f_data), 1) / BITS_PER_UNIT);
426       sjlj_fc_personality_ofs
427         = (tree_low_cst (DECL_FIELD_OFFSET (f_per), 1)
428            + tree_low_cst (DECL_FIELD_BIT_OFFSET (f_per), 1) / BITS_PER_UNIT);
429       sjlj_fc_lsda_ofs
430         = (tree_low_cst (DECL_FIELD_OFFSET (f_lsda), 1)
431            + tree_low_cst (DECL_FIELD_BIT_OFFSET (f_lsda), 1) / BITS_PER_UNIT);
432       sjlj_fc_jbuf_ofs
433         = (tree_low_cst (DECL_FIELD_OFFSET (f_jbuf), 1)
434            + tree_low_cst (DECL_FIELD_BIT_OFFSET (f_jbuf), 1) / BITS_PER_UNIT);
435     }
436 }
437
438 void
439 init_eh_for_function (void)
440 {
441   cfun->eh = ggc_alloc_cleared (sizeof (struct eh_status));
442 }
443 \f
444 /* Routines to generate the exception tree somewhat directly.
445    These are used from tree-eh.c when processing exception related
446    nodes during tree optimization.  */
447
448 static struct eh_region *
449 gen_eh_region (enum eh_region_type type, struct eh_region *outer)
450 {
451   struct eh_region *new;
452
453 #ifdef ENABLE_CHECKING
454   gcc_assert (doing_eh (0));
455 #endif
456
457   /* Insert a new blank region as a leaf in the tree.  */
458   new = ggc_alloc_cleared (sizeof (*new));
459   new->type = type;
460   new->outer = outer;
461   if (outer)
462     {
463       new->next_peer = outer->inner;
464       outer->inner = new;
465     }
466   else
467     {
468       new->next_peer = cfun->eh->region_tree;
469       cfun->eh->region_tree = new;
470     }
471
472   new->region_number = ++cfun->eh->last_region_number;
473
474   return new;
475 }
476
477 struct eh_region *
478 gen_eh_region_cleanup (struct eh_region *outer, struct eh_region *prev_try)
479 {
480   struct eh_region *cleanup = gen_eh_region (ERT_CLEANUP, outer);
481   cleanup->u.cleanup.prev_try = prev_try;
482   return cleanup;
483 }
484
485 struct eh_region *
486 gen_eh_region_try (struct eh_region *outer)
487 {
488   return gen_eh_region (ERT_TRY, outer);
489 }
490
491 struct eh_region *
492 gen_eh_region_catch (struct eh_region *t, tree type_or_list)
493 {
494   struct eh_region *c, *l;
495   tree type_list, type_node;
496
497   /* Ensure to always end up with a type list to normalize further
498      processing, then register each type against the runtime types map.  */
499   type_list = type_or_list;
500   if (type_or_list)
501     {
502       if (TREE_CODE (type_or_list) != TREE_LIST)
503         type_list = tree_cons (NULL_TREE, type_or_list, NULL_TREE);
504
505       type_node = type_list;
506       for (; type_node; type_node = TREE_CHAIN (type_node))
507         add_type_for_runtime (TREE_VALUE (type_node));
508     }
509
510   c = gen_eh_region (ERT_CATCH, t->outer);
511   c->u.catch.type_list = type_list;
512   l = t->u.try.last_catch;
513   c->u.catch.prev_catch = l;
514   if (l)
515     l->u.catch.next_catch = c;
516   else
517     t->u.try.catch = c;
518   t->u.try.last_catch = c;
519
520   return c;
521 }
522
523 struct eh_region *
524 gen_eh_region_allowed (struct eh_region *outer, tree allowed)
525 {
526   struct eh_region *region = gen_eh_region (ERT_ALLOWED_EXCEPTIONS, outer);
527   region->u.allowed.type_list = allowed;
528
529   for (; allowed ; allowed = TREE_CHAIN (allowed))
530     add_type_for_runtime (TREE_VALUE (allowed));
531
532   return region;
533 }
534
535 struct eh_region *
536 gen_eh_region_must_not_throw (struct eh_region *outer)
537 {
538   return gen_eh_region (ERT_MUST_NOT_THROW, outer);
539 }
540
541 int
542 get_eh_region_number (struct eh_region *region)
543 {
544   return region->region_number;
545 }
546
547 bool
548 get_eh_region_may_contain_throw (struct eh_region *region)
549 {
550   return region->may_contain_throw;
551 }
552
553 tree
554 get_eh_region_tree_label (struct eh_region *region)
555 {
556   return region->tree_label;
557 }
558
559 void
560 set_eh_region_tree_label (struct eh_region *region, tree lab)
561 {
562   region->tree_label = lab;
563 }
564 \f
565 void
566 expand_resx_expr (tree exp)
567 {
568   int region_nr = TREE_INT_CST_LOW (TREE_OPERAND (exp, 0));
569   struct eh_region *reg = VEC_index (eh_region,
570                                      cfun->eh->region_array, region_nr);
571
572   gcc_assert (!reg->resume);
573   reg->resume = emit_jump_insn (gen_rtx_RESX (VOIDmode, region_nr));
574   emit_barrier ();
575 }
576
577 /* Note that the current EH region (if any) may contain a throw, or a
578    call to a function which itself may contain a throw.  */
579
580 void
581 note_eh_region_may_contain_throw (struct eh_region *region)
582 {
583   while (region && !region->may_contain_throw)
584     {
585       region->may_contain_throw = 1;
586       region = region->outer;
587     }
588 }
589
590 void
591 note_current_region_may_contain_throw (void)
592 {
593   note_eh_region_may_contain_throw (cfun->eh->cur_region);
594 }
595
596
597 /* Return an rtl expression for a pointer to the exception object
598    within a handler.  */
599
600 rtx
601 get_exception_pointer (struct function *fun)
602 {
603   rtx exc_ptr = fun->eh->exc_ptr;
604   if (fun == cfun && ! exc_ptr)
605     {
606       exc_ptr = gen_reg_rtx (ptr_mode);
607       fun->eh->exc_ptr = exc_ptr;
608     }
609   return exc_ptr;
610 }
611
612 /* Return an rtl expression for the exception dispatch filter
613    within a handler.  */
614
615 rtx
616 get_exception_filter (struct function *fun)
617 {
618   rtx filter = fun->eh->filter;
619   if (fun == cfun && ! filter)
620     {
621       filter = gen_reg_rtx (targetm.eh_return_filter_mode ());
622       fun->eh->filter = filter;
623     }
624   return filter;
625 }
626 \f
627 /* This section is for the exception handling specific optimization pass.  */
628
629 /* Random access the exception region tree.  */
630
631 void
632 collect_eh_region_array (void)
633 {
634   struct eh_region *i;
635
636   i = cfun->eh->region_tree;
637   if (! i)
638     return;
639
640   VEC_safe_grow (eh_region, gc, cfun->eh->region_array,
641                  cfun->eh->last_region_number + 1);
642   VEC_replace (eh_region, cfun->eh->region_array, 0, 0);
643
644   while (1)
645     {
646       VEC_replace (eh_region, cfun->eh->region_array, i->region_number, i);
647
648       /* If there are sub-regions, process them.  */
649       if (i->inner)
650         i = i->inner;
651       /* If there are peers, process them.  */
652       else if (i->next_peer)
653         i = i->next_peer;
654       /* Otherwise, step back up the tree to the next peer.  */
655       else
656         {
657           do {
658             i = i->outer;
659             if (i == NULL)
660               return;
661           } while (i->next_peer == NULL);
662           i = i->next_peer;
663         }
664     }
665 }
666
667 /* Remove all regions whose labels are not reachable from insns.  */
668
669 static void
670 remove_unreachable_regions (rtx insns)
671 {
672   int i, *uid_region_num;
673   bool *reachable;
674   struct eh_region *r;
675   rtx insn;
676
677   uid_region_num = xcalloc (get_max_uid (), sizeof(int));
678   reachable = xcalloc (cfun->eh->last_region_number + 1, sizeof(bool));
679
680   for (i = cfun->eh->last_region_number; i > 0; --i)
681     {
682       r = VEC_index (eh_region, cfun->eh->region_array, i);
683       if (!r || r->region_number != i)
684         continue;
685
686       if (r->resume)
687         {
688           gcc_assert (!uid_region_num[INSN_UID (r->resume)]);
689           uid_region_num[INSN_UID (r->resume)] = i;
690         }
691       if (r->label)
692         {
693           gcc_assert (!uid_region_num[INSN_UID (r->label)]);
694           uid_region_num[INSN_UID (r->label)] = i;
695         }
696     }
697
698   for (insn = insns; insn; insn = NEXT_INSN (insn))
699     reachable[uid_region_num[INSN_UID (insn)]] = true;
700
701   for (i = cfun->eh->last_region_number; i > 0; --i)
702     {
703       r = VEC_index (eh_region, cfun->eh->region_array, i);
704       if (r && r->region_number == i && !reachable[i])
705         {
706           bool kill_it = true;
707           switch (r->type)
708             {
709             case ERT_THROW:
710               /* Don't remove ERT_THROW regions if their outer region
711                  is reachable.  */
712               if (r->outer && reachable[r->outer->region_number])
713                 kill_it = false;
714               break;
715
716             case ERT_MUST_NOT_THROW:
717               /* MUST_NOT_THROW regions are implementable solely in the
718                  runtime, but their existence continues to affect calls
719                  within that region.  Never delete them here.  */
720               kill_it = false;
721               break;
722
723             case ERT_TRY:
724               {
725                 /* TRY regions are reachable if any of its CATCH regions
726                    are reachable.  */
727                 struct eh_region *c;
728                 for (c = r->u.try.catch; c ; c = c->u.catch.next_catch)
729                   if (reachable[c->region_number])
730                     {
731                       kill_it = false;
732                       break;
733                     }
734                 break;
735               }
736
737             default:
738               break;
739             }
740
741           if (kill_it)
742             remove_eh_handler (r);
743         }
744     }
745
746   free (reachable);
747   free (uid_region_num);
748 }
749
750 /* Set up EH labels for RTL.  */
751
752 void
753 convert_from_eh_region_ranges (void)
754 {
755   rtx insns = get_insns ();
756   int i, n = cfun->eh->last_region_number;
757
758   /* Most of the work is already done at the tree level.  All we need to
759      do is collect the rtl labels that correspond to the tree labels that
760      collect the rtl labels that correspond to the tree labels
761      we allocated earlier.  */
762   for (i = 1; i <= n; ++i)
763     {
764       struct eh_region *region;
765
766       region = VEC_index (eh_region, cfun->eh->region_array, i);
767       if (region && region->tree_label)
768         region->label = DECL_RTL_IF_SET (region->tree_label);
769     }
770
771   remove_unreachable_regions (insns);
772 }
773
774 static void
775 add_ehl_entry (rtx label, struct eh_region *region)
776 {
777   struct ehl_map_entry **slot, *entry;
778
779   LABEL_PRESERVE_P (label) = 1;
780
781   entry = ggc_alloc (sizeof (*entry));
782   entry->label = label;
783   entry->region = region;
784
785   slot = (struct ehl_map_entry **)
786     htab_find_slot (cfun->eh->exception_handler_label_map, entry, INSERT);
787
788   /* Before landing pad creation, each exception handler has its own
789      label.  After landing pad creation, the exception handlers may
790      share landing pads.  This is ok, since maybe_remove_eh_handler
791      only requires the 1-1 mapping before landing pad creation.  */
792   gcc_assert (!*slot || cfun->eh->built_landing_pads);
793
794   *slot = entry;
795 }
796
797 void
798 find_exception_handler_labels (void)
799 {
800   int i;
801
802   if (cfun->eh->exception_handler_label_map)
803     htab_empty (cfun->eh->exception_handler_label_map);
804   else
805     {
806       /* ??? The expansion factor here (3/2) must be greater than the htab
807          occupancy factor (4/3) to avoid unnecessary resizing.  */
808       cfun->eh->exception_handler_label_map
809         = htab_create_ggc (cfun->eh->last_region_number * 3 / 2,
810                            ehl_hash, ehl_eq, NULL);
811     }
812
813   if (cfun->eh->region_tree == NULL)
814     return;
815
816   for (i = cfun->eh->last_region_number; i > 0; --i)
817     {
818       struct eh_region *region;
819       rtx lab;
820
821       region = VEC_index (eh_region, cfun->eh->region_array, i);
822       if (! region || region->region_number != i)
823         continue;
824       if (cfun->eh->built_landing_pads)
825         lab = region->landing_pad;
826       else
827         lab = region->label;
828
829       if (lab)
830         add_ehl_entry (lab, region);
831     }
832
833   /* For sjlj exceptions, need the return label to remain live until
834      after landing pad generation.  */
835   if (USING_SJLJ_EXCEPTIONS && ! cfun->eh->built_landing_pads)
836     add_ehl_entry (return_label, NULL);
837 }
838
839 /* Returns true if the current function has exception handling regions.  */
840
841 bool
842 current_function_has_exception_handlers (void)
843 {
844   int i;
845
846   for (i = cfun->eh->last_region_number; i > 0; --i)
847     {
848       struct eh_region *region;
849
850       region = VEC_index (eh_region, cfun->eh->region_array, i);
851       if (region
852           && region->region_number == i
853           && region->type != ERT_THROW)
854         return true;
855     }
856
857   return false;
858 }
859 \f
860 /* A subroutine of duplicate_eh_regions.  Search the region tree under O
861    for the minimum and maximum region numbers.  Update *MIN and *MAX.  */
862
863 static void
864 duplicate_eh_regions_0 (eh_region o, int *min, int *max)
865 {
866   if (o->region_number < *min)
867     *min = o->region_number;
868   if (o->region_number > *max)
869     *max = o->region_number;
870
871   if (o->inner)
872     {
873       o = o->inner;
874       duplicate_eh_regions_0 (o, min, max);
875       while (o->next_peer)
876         {
877           o = o->next_peer;
878           duplicate_eh_regions_0 (o, min, max);
879         }
880     }
881 }
882
883 /* A subroutine of duplicate_eh_regions.  Copy the region tree under OLD.
884    Root it at OUTER, and apply EH_OFFSET to the region number.  Don't worry
885    about the other internal pointers just yet, just the tree-like pointers.  */
886
887 static eh_region
888 duplicate_eh_regions_1 (eh_region old, eh_region outer, int eh_offset)
889 {
890   eh_region ret, n;
891
892   ret = n = ggc_alloc (sizeof (struct eh_region));
893
894   *n = *old;
895   n->outer = outer;
896   n->next_peer = NULL;
897   gcc_assert (!old->aka);
898
899   n->region_number += eh_offset;
900   VEC_replace (eh_region, cfun->eh->region_array, n->region_number, n);
901
902   if (old->inner)
903     {
904       old = old->inner;
905       n = n->inner = duplicate_eh_regions_1 (old, ret, eh_offset);
906       while (old->next_peer)
907         {
908           old = old->next_peer;
909           n = n->next_peer = duplicate_eh_regions_1 (old, ret, eh_offset);
910         }
911     }
912
913   return ret;
914 }
915
916 /* Duplicate the EH regions of IFUN, rooted at COPY_REGION, into current
917    function and root the tree below OUTER_REGION.  Remap labels using MAP
918    callback.  The special case of COPY_REGION of 0 means all regions.  */
919
920 int
921 duplicate_eh_regions (struct function *ifun, duplicate_eh_regions_map map,
922                       void *data, int copy_region, int outer_region)
923 {
924   eh_region cur, prev_try, outer, *splice;
925   int i, min_region, max_region, eh_offset, cfun_last_region_number;
926   int num_regions;
927
928   if (!ifun->eh->region_tree)
929     return 0;
930
931   /* Find the range of region numbers to be copied.  The interface we 
932      provide here mandates a single offset to find new number from old,
933      which means we must look at the numbers present, instead of the
934      count or something else.  */
935   if (copy_region > 0)
936     {
937       min_region = INT_MAX;
938       max_region = 0;
939
940       cur = VEC_index (eh_region, ifun->eh->region_array, copy_region);
941       duplicate_eh_regions_0 (cur, &min_region, &max_region);
942     }
943   else
944     min_region = 1, max_region = ifun->eh->last_region_number;
945   num_regions = max_region - min_region + 1;
946   cfun_last_region_number = cfun->eh->last_region_number;
947   eh_offset = cfun_last_region_number + 1 - min_region;
948
949   /* If we've not yet created a region array, do so now.  */
950   VEC_safe_grow (eh_region, gc, cfun->eh->region_array,
951                  cfun_last_region_number + 1 + num_regions);
952   cfun->eh->last_region_number = max_region + eh_offset;
953
954   /* We may have just allocated the array for the first time.
955      Make sure that element zero is null.  */
956   VEC_replace (eh_region, cfun->eh->region_array, 0, 0);
957
958   /* Zero all entries in the range allocated.  */
959   memset (VEC_address (eh_region, cfun->eh->region_array)
960           + cfun_last_region_number + 1, 0, num_regions * sizeof (eh_region));
961
962   /* Locate the spot at which to insert the new tree.  */
963   if (outer_region > 0)
964     {
965       outer = VEC_index (eh_region, cfun->eh->region_array, outer_region);
966       splice = &outer->inner;
967     }
968   else
969     {
970       outer = NULL;
971       splice = &cfun->eh->region_tree;
972     }
973   while (*splice)
974     splice = &(*splice)->next_peer;
975
976   /* Copy all the regions in the subtree.  */
977   if (copy_region > 0)
978     {
979       cur = VEC_index (eh_region, ifun->eh->region_array, copy_region);
980       *splice = duplicate_eh_regions_1 (cur, outer, eh_offset);
981     }
982   else
983     {
984       eh_region n;
985
986       cur = ifun->eh->region_tree;
987       *splice = n = duplicate_eh_regions_1 (cur, outer, eh_offset);
988       while (cur->next_peer)
989         {
990           cur = cur->next_peer;
991           n = n->next_peer = duplicate_eh_regions_1 (cur, outer, eh_offset);
992         }
993     }
994
995   /* Remap all the labels in the new regions.  */
996   for (i = cfun_last_region_number + 1;
997        VEC_iterate (eh_region, cfun->eh->region_array, i, cur); ++i)
998     if (cur && cur->tree_label)
999       cur->tree_label = map (cur->tree_label, data);
1000
1001   /* Search for the containing ERT_TRY region to fix up
1002      the prev_try short-cuts for ERT_CLEANUP regions.  */
1003   prev_try = NULL;
1004   if (outer_region > 0)
1005     for (prev_try = VEC_index (eh_region, cfun->eh->region_array, outer_region);
1006          prev_try && prev_try->type != ERT_TRY;
1007          prev_try = prev_try->outer)
1008       if (prev_try->type == ERT_MUST_NOT_THROW)
1009         {
1010           prev_try = NULL;
1011           break;
1012         }
1013
1014   /* Remap all of the internal catch and cleanup linkages.  Since we 
1015      duplicate entire subtrees, all of the referenced regions will have
1016      been copied too.  And since we renumbered them as a block, a simple
1017      bit of arithmetic finds us the index for the replacement region.  */
1018   for (i = cfun_last_region_number + 1;
1019        VEC_iterate (eh_region, cfun->eh->region_array, i, cur); ++i)
1020     {
1021       if (cur == NULL)
1022         continue;
1023
1024 #define REMAP(REG) \
1025         (REG) = VEC_index (eh_region, cfun->eh->region_array, \
1026                            (REG)->region_number + eh_offset)
1027
1028       switch (cur->type)
1029         {
1030         case ERT_TRY:
1031           if (cur->u.try.catch)
1032             REMAP (cur->u.try.catch);
1033           if (cur->u.try.last_catch)
1034             REMAP (cur->u.try.last_catch);
1035           break;
1036
1037         case ERT_CATCH:
1038           if (cur->u.catch.next_catch)
1039             REMAP (cur->u.catch.next_catch);
1040           if (cur->u.catch.prev_catch)
1041             REMAP (cur->u.catch.prev_catch);
1042           break;
1043
1044         case ERT_CLEANUP:
1045           if (cur->u.cleanup.prev_try)
1046             REMAP (cur->u.cleanup.prev_try);
1047           else
1048             cur->u.cleanup.prev_try = prev_try;
1049           break;
1050
1051         default:
1052           break;
1053         }
1054
1055 #undef REMAP
1056     }
1057
1058   return eh_offset;
1059 }
1060
1061 /* Return true if REGION_A is outer to REGION_B in IFUN.  */
1062
1063 bool
1064 eh_region_outer_p (struct function *ifun, int region_a, int region_b)
1065 {
1066   struct eh_region *rp_a, *rp_b;
1067
1068   gcc_assert (ifun->eh->last_region_number > 0);
1069   gcc_assert (ifun->eh->region_tree);
1070
1071   rp_a = VEC_index (eh_region, ifun->eh->region_array, region_a);
1072   rp_b = VEC_index (eh_region, ifun->eh->region_array, region_b);
1073   gcc_assert (rp_a != NULL);
1074   gcc_assert (rp_b != NULL);
1075
1076   do
1077     {
1078       if (rp_a == rp_b)
1079         return true;
1080       rp_b = rp_b->outer;
1081     }
1082   while (rp_b);
1083
1084   return false;
1085 }
1086
1087 /* Return region number of region that is outer to both if REGION_A and
1088    REGION_B in IFUN.  */
1089
1090 int
1091 eh_region_outermost (struct function *ifun, int region_a, int region_b)
1092 {
1093   struct eh_region *rp_a, *rp_b;
1094   sbitmap b_outer;
1095
1096   gcc_assert (ifun->eh->last_region_number > 0);
1097   gcc_assert (ifun->eh->region_tree);
1098
1099   rp_a = VEC_index (eh_region, ifun->eh->region_array, region_a);
1100   rp_b = VEC_index (eh_region, ifun->eh->region_array, region_b);
1101   gcc_assert (rp_a != NULL);
1102   gcc_assert (rp_b != NULL);
1103
1104   b_outer = sbitmap_alloc (ifun->eh->last_region_number + 1);
1105   sbitmap_zero (b_outer);
1106
1107   do
1108     {
1109       SET_BIT (b_outer, rp_b->region_number);
1110       rp_b = rp_b->outer;
1111     }
1112   while (rp_b);
1113
1114   do
1115     {
1116       if (TEST_BIT (b_outer, rp_a->region_number))
1117         {
1118           sbitmap_free (b_outer);
1119           return rp_a->region_number;
1120         }
1121       rp_a = rp_a->outer;
1122     }
1123   while (rp_a);
1124
1125   sbitmap_free (b_outer);
1126   return -1;
1127 }
1128 \f
1129 static int
1130 t2r_eq (const void *pentry, const void *pdata)
1131 {
1132   const_tree const entry = (const_tree) pentry;
1133   const_tree const data = (const_tree) pdata;
1134
1135   return TREE_PURPOSE (entry) == data;
1136 }
1137
1138 static hashval_t
1139 t2r_hash (const void *pentry)
1140 {
1141   const_tree const entry = (const_tree) pentry;
1142   return TREE_HASH (TREE_PURPOSE (entry));
1143 }
1144
1145 static void
1146 add_type_for_runtime (tree type)
1147 {
1148   tree *slot;
1149
1150   slot = (tree *) htab_find_slot_with_hash (type_to_runtime_map, type,
1151                                             TREE_HASH (type), INSERT);
1152   if (*slot == NULL)
1153     {
1154       tree runtime = (*lang_eh_runtime_type) (type);
1155       *slot = tree_cons (type, runtime, NULL_TREE);
1156     }
1157 }
1158
1159 static tree
1160 lookup_type_for_runtime (tree type)
1161 {
1162   tree *slot;
1163
1164   slot = (tree *) htab_find_slot_with_hash (type_to_runtime_map, type,
1165                                             TREE_HASH (type), NO_INSERT);
1166
1167   /* We should have always inserted the data earlier.  */
1168   return TREE_VALUE (*slot);
1169 }
1170
1171 \f
1172 /* Represent an entry in @TTypes for either catch actions
1173    or exception filter actions.  */
1174 struct ttypes_filter GTY(())
1175 {
1176   tree t;
1177   int filter;
1178 };
1179
1180 /* Compare ENTRY (a ttypes_filter entry in the hash table) with DATA
1181    (a tree) for a @TTypes type node we are thinking about adding.  */
1182
1183 static int
1184 ttypes_filter_eq (const void *pentry, const void *pdata)
1185 {
1186   const struct ttypes_filter *const entry
1187     = (const struct ttypes_filter *) pentry;
1188   const_tree const data = (const_tree) pdata;
1189
1190   return entry->t == data;
1191 }
1192
1193 static hashval_t
1194 ttypes_filter_hash (const void *pentry)
1195 {
1196   const struct ttypes_filter *entry = (const struct ttypes_filter *) pentry;
1197   return TREE_HASH (entry->t);
1198 }
1199
1200 /* Compare ENTRY with DATA (both struct ttypes_filter) for a @TTypes
1201    exception specification list we are thinking about adding.  */
1202 /* ??? Currently we use the type lists in the order given.  Someone
1203    should put these in some canonical order.  */
1204
1205 static int
1206 ehspec_filter_eq (const void *pentry, const void *pdata)
1207 {
1208   const struct ttypes_filter *entry = (const struct ttypes_filter *) pentry;
1209   const struct ttypes_filter *data = (const struct ttypes_filter *) pdata;
1210
1211   return type_list_equal (entry->t, data->t);
1212 }
1213
1214 /* Hash function for exception specification lists.  */
1215
1216 static hashval_t
1217 ehspec_filter_hash (const void *pentry)
1218 {
1219   const struct ttypes_filter *entry = (const struct ttypes_filter *) pentry;
1220   hashval_t h = 0;
1221   tree list;
1222
1223   for (list = entry->t; list ; list = TREE_CHAIN (list))
1224     h = (h << 5) + (h >> 27) + TREE_HASH (TREE_VALUE (list));
1225   return h;
1226 }
1227
1228 /* Add TYPE (which may be NULL) to cfun->eh->ttype_data, using TYPES_HASH
1229    to speed up the search.  Return the filter value to be used.  */
1230
1231 static int
1232 add_ttypes_entry (htab_t ttypes_hash, tree type)
1233 {
1234   struct ttypes_filter **slot, *n;
1235
1236   slot = (struct ttypes_filter **)
1237     htab_find_slot_with_hash (ttypes_hash, type, TREE_HASH (type), INSERT);
1238
1239   if ((n = *slot) == NULL)
1240     {
1241       /* Filter value is a 1 based table index.  */
1242
1243       n = XNEW (struct ttypes_filter);
1244       n->t = type;
1245       n->filter = VEC_length (tree, cfun->eh->ttype_data) + 1;
1246       *slot = n;
1247
1248       VEC_safe_push (tree, gc, cfun->eh->ttype_data, type);
1249     }
1250
1251   return n->filter;
1252 }
1253
1254 /* Add LIST to cfun->eh->ehspec_data, using EHSPEC_HASH and TYPES_HASH
1255    to speed up the search.  Return the filter value to be used.  */
1256
1257 static int
1258 add_ehspec_entry (htab_t ehspec_hash, htab_t ttypes_hash, tree list)
1259 {
1260   struct ttypes_filter **slot, *n;
1261   struct ttypes_filter dummy;
1262
1263   dummy.t = list;
1264   slot = (struct ttypes_filter **)
1265     htab_find_slot (ehspec_hash, &dummy, INSERT);
1266
1267   if ((n = *slot) == NULL)
1268     {
1269       /* Filter value is a -1 based byte index into a uleb128 buffer.  */
1270
1271       n = XNEW (struct ttypes_filter);
1272       n->t = list;
1273       n->filter = -(VARRAY_ACTIVE_SIZE (cfun->eh->ehspec_data) + 1);
1274       *slot = n;
1275
1276       /* Generate a 0 terminated list of filter values.  */
1277       for (; list ; list = TREE_CHAIN (list))
1278         {
1279           if (targetm.arm_eabi_unwinder)
1280             VARRAY_PUSH_TREE (cfun->eh->ehspec_data, TREE_VALUE (list));
1281           else
1282             {
1283               /* Look up each type in the list and encode its filter
1284                  value as a uleb128.  */
1285               push_uleb128 (&cfun->eh->ehspec_data,
1286                   add_ttypes_entry (ttypes_hash, TREE_VALUE (list)));
1287             }
1288         }
1289       if (targetm.arm_eabi_unwinder)
1290         VARRAY_PUSH_TREE (cfun->eh->ehspec_data, NULL_TREE);
1291       else
1292         VARRAY_PUSH_UCHAR (cfun->eh->ehspec_data, 0);
1293     }
1294
1295   return n->filter;
1296 }
1297
1298 /* Generate the action filter values to be used for CATCH and
1299    ALLOWED_EXCEPTIONS regions.  When using dwarf2 exception regions,
1300    we use lots of landing pads, and so every type or list can share
1301    the same filter value, which saves table space.  */
1302
1303 static void
1304 assign_filter_values (void)
1305 {
1306   int i;
1307   htab_t ttypes, ehspec;
1308
1309   cfun->eh->ttype_data = VEC_alloc (tree, gc, 16);
1310   if (targetm.arm_eabi_unwinder)
1311     VARRAY_TREE_INIT (cfun->eh->ehspec_data, 64, "ehspec_data");
1312   else
1313     VARRAY_UCHAR_INIT (cfun->eh->ehspec_data, 64, "ehspec_data");
1314
1315   ttypes = htab_create (31, ttypes_filter_hash, ttypes_filter_eq, free);
1316   ehspec = htab_create (31, ehspec_filter_hash, ehspec_filter_eq, free);
1317
1318   for (i = cfun->eh->last_region_number; i > 0; --i)
1319     {
1320       struct eh_region *r;
1321
1322       r = VEC_index (eh_region, cfun->eh->region_array, i);
1323
1324       /* Mind we don't process a region more than once.  */
1325       if (!r || r->region_number != i)
1326         continue;
1327
1328       switch (r->type)
1329         {
1330         case ERT_CATCH:
1331           /* Whatever type_list is (NULL or true list), we build a list
1332              of filters for the region.  */
1333           r->u.catch.filter_list = NULL_TREE;
1334
1335           if (r->u.catch.type_list != NULL)
1336             {
1337               /* Get a filter value for each of the types caught and store
1338                  them in the region's dedicated list.  */
1339               tree tp_node = r->u.catch.type_list;
1340
1341               for (;tp_node; tp_node = TREE_CHAIN (tp_node))
1342                 {
1343                   int flt = add_ttypes_entry (ttypes, TREE_VALUE (tp_node));
1344                   tree flt_node = build_int_cst (NULL_TREE, flt);
1345
1346                   r->u.catch.filter_list
1347                     = tree_cons (NULL_TREE, flt_node, r->u.catch.filter_list);
1348                 }
1349             }
1350           else
1351             {
1352               /* Get a filter value for the NULL list also since it will need
1353                  an action record anyway.  */
1354               int flt = add_ttypes_entry (ttypes, NULL);
1355               tree flt_node = build_int_cst (NULL_TREE, flt);
1356
1357               r->u.catch.filter_list
1358                 = tree_cons (NULL_TREE, flt_node, r->u.catch.filter_list);
1359             }
1360
1361           break;
1362
1363         case ERT_ALLOWED_EXCEPTIONS:
1364           r->u.allowed.filter
1365             = add_ehspec_entry (ehspec, ttypes, r->u.allowed.type_list);
1366           break;
1367
1368         default:
1369           break;
1370         }
1371     }
1372
1373   htab_delete (ttypes);
1374   htab_delete (ehspec);
1375 }
1376
1377 /* Emit SEQ into basic block just before INSN (that is assumed to be
1378    first instruction of some existing BB and return the newly
1379    produced block.  */
1380 static basic_block
1381 emit_to_new_bb_before (rtx seq, rtx insn)
1382 {
1383   rtx last;
1384   basic_block bb;
1385   edge e;
1386   edge_iterator ei;
1387
1388   /* If there happens to be a fallthru edge (possibly created by cleanup_cfg
1389      call), we don't want it to go into newly created landing pad or other EH
1390      construct.  */
1391   for (ei = ei_start (BLOCK_FOR_INSN (insn)->preds); (e = ei_safe_edge (ei)); )
1392     if (e->flags & EDGE_FALLTHRU)
1393       force_nonfallthru (e);
1394     else
1395       ei_next (&ei);
1396   last = emit_insn_before (seq, insn);
1397   if (BARRIER_P (last))
1398     last = PREV_INSN (last);
1399   bb = create_basic_block (seq, last, BLOCK_FOR_INSN (insn)->prev_bb);
1400   update_bb_for_insn (bb);
1401   bb->flags |= BB_SUPERBLOCK;
1402   return bb;
1403 }
1404
1405 /* Generate the code to actually handle exceptions, which will follow the
1406    landing pads.  */
1407
1408 static void
1409 build_post_landing_pads (void)
1410 {
1411   int i;
1412
1413   for (i = cfun->eh->last_region_number; i > 0; --i)
1414     {
1415       struct eh_region *region;
1416       rtx seq;
1417
1418       region = VEC_index (eh_region, cfun->eh->region_array, i);
1419       /* Mind we don't process a region more than once.  */
1420       if (!region || region->region_number != i)
1421         continue;
1422
1423       switch (region->type)
1424         {
1425         case ERT_TRY:
1426           /* ??? Collect the set of all non-overlapping catch handlers
1427                all the way up the chain until blocked by a cleanup.  */
1428           /* ??? Outer try regions can share landing pads with inner
1429              try regions if the types are completely non-overlapping,
1430              and there are no intervening cleanups.  */
1431
1432           region->post_landing_pad = gen_label_rtx ();
1433
1434           start_sequence ();
1435
1436           emit_label (region->post_landing_pad);
1437
1438           /* ??? It is mighty inconvenient to call back into the
1439              switch statement generation code in expand_end_case.
1440              Rapid prototyping sez a sequence of ifs.  */
1441           {
1442             struct eh_region *c;
1443             for (c = region->u.try.catch; c ; c = c->u.catch.next_catch)
1444               {
1445                 if (c->u.catch.type_list == NULL)
1446                   emit_jump (c->label);
1447                 else
1448                   {
1449                     /* Need for one cmp/jump per type caught. Each type
1450                        list entry has a matching entry in the filter list
1451                        (see assign_filter_values).  */
1452                     tree tp_node = c->u.catch.type_list;
1453                     tree flt_node = c->u.catch.filter_list;
1454
1455                     for (; tp_node; )
1456                       {
1457                         emit_cmp_and_jump_insns
1458                           (cfun->eh->filter,
1459                            GEN_INT (tree_low_cst (TREE_VALUE (flt_node), 0)),
1460                            EQ, NULL_RTX,
1461                            targetm.eh_return_filter_mode (), 0, c->label);
1462
1463                         tp_node = TREE_CHAIN (tp_node);
1464                         flt_node = TREE_CHAIN (flt_node);
1465                       }
1466                   }
1467               }
1468           }
1469
1470           /* We delay the generation of the _Unwind_Resume until we generate
1471              landing pads.  We emit a marker here so as to get good control
1472              flow data in the meantime.  */
1473           region->resume
1474             = emit_jump_insn (gen_rtx_RESX (VOIDmode, region->region_number));
1475           emit_barrier ();
1476
1477           seq = get_insns ();
1478           end_sequence ();
1479
1480           emit_to_new_bb_before (seq, region->u.try.catch->label);
1481
1482           break;
1483
1484         case ERT_ALLOWED_EXCEPTIONS:
1485           region->post_landing_pad = gen_label_rtx ();
1486
1487           start_sequence ();
1488
1489           emit_label (region->post_landing_pad);
1490
1491           emit_cmp_and_jump_insns (cfun->eh->filter,
1492                                    GEN_INT (region->u.allowed.filter),
1493                                    EQ, NULL_RTX,
1494                                    targetm.eh_return_filter_mode (), 0, region->label);
1495
1496           /* We delay the generation of the _Unwind_Resume until we generate
1497              landing pads.  We emit a marker here so as to get good control
1498              flow data in the meantime.  */
1499           region->resume
1500             = emit_jump_insn (gen_rtx_RESX (VOIDmode, region->region_number));
1501           emit_barrier ();
1502
1503           seq = get_insns ();
1504           end_sequence ();
1505
1506           emit_to_new_bb_before (seq, region->label);
1507           break;
1508
1509         case ERT_CLEANUP:
1510         case ERT_MUST_NOT_THROW:
1511           region->post_landing_pad = region->label;
1512           break;
1513
1514         case ERT_CATCH:
1515         case ERT_THROW:
1516           /* Nothing to do.  */
1517           break;
1518
1519         default:
1520           gcc_unreachable ();
1521         }
1522     }
1523 }
1524
1525 /* Replace RESX patterns with jumps to the next handler if any, or calls to
1526    _Unwind_Resume otherwise.  */
1527
1528 static void
1529 connect_post_landing_pads (void)
1530 {
1531   int i;
1532
1533   for (i = cfun->eh->last_region_number; i > 0; --i)
1534     {
1535       struct eh_region *region;
1536       struct eh_region *outer;
1537       rtx seq;
1538       rtx barrier;
1539
1540       region = VEC_index (eh_region, cfun->eh->region_array, i);
1541       /* Mind we don't process a region more than once.  */
1542       if (!region || region->region_number != i)
1543         continue;
1544
1545       /* If there is no RESX, or it has been deleted by flow, there's
1546          nothing to fix up.  */
1547       if (! region->resume || INSN_DELETED_P (region->resume))
1548         continue;
1549
1550       /* Search for another landing pad in this function.  */
1551       for (outer = region->outer; outer ; outer = outer->outer)
1552         if (outer->post_landing_pad)
1553           break;
1554
1555       start_sequence ();
1556
1557       if (outer)
1558         {
1559           edge e;
1560           basic_block src, dest;
1561
1562           emit_jump (outer->post_landing_pad);
1563           src = BLOCK_FOR_INSN (region->resume);
1564           dest = BLOCK_FOR_INSN (outer->post_landing_pad);
1565           while (EDGE_COUNT (src->succs) > 0)
1566             remove_edge (EDGE_SUCC (src, 0));
1567           e = make_edge (src, dest, 0);
1568           e->probability = REG_BR_PROB_BASE;
1569           e->count = src->count;
1570         }
1571       else
1572         {
1573           emit_library_call (unwind_resume_libfunc, LCT_THROW,
1574                              VOIDmode, 1, cfun->eh->exc_ptr, ptr_mode);
1575
1576           /* What we just emitted was a throwing libcall, so it got a
1577              barrier automatically added after it.  If the last insn in
1578              the libcall sequence isn't the barrier, it's because the
1579              target emits multiple insns for a call, and there are insns
1580              after the actual call insn (which are redundant and would be
1581              optimized away).  The barrier is inserted exactly after the
1582              call insn, so let's go get that and delete the insns after
1583              it, because below we need the barrier to be the last insn in
1584              the sequence.  */
1585           delete_insns_since (NEXT_INSN (last_call_insn ()));
1586         }
1587
1588       seq = get_insns ();
1589       end_sequence ();
1590       barrier = emit_insn_before (seq, region->resume);
1591       /* Avoid duplicate barrier.  */
1592       gcc_assert (BARRIER_P (barrier));
1593       delete_insn (barrier);
1594       delete_insn (region->resume);
1595
1596       /* ??? From tree-ssa we can wind up with catch regions whose
1597          label is not instantiated, but whose resx is present.  Now
1598          that we've dealt with the resx, kill the region.  */
1599       if (region->label == NULL && region->type == ERT_CLEANUP)
1600         remove_eh_handler (region);
1601     }
1602 }
1603
1604 \f
1605 static void
1606 dw2_build_landing_pads (void)
1607 {
1608   int i;
1609
1610   for (i = cfun->eh->last_region_number; i > 0; --i)
1611     {
1612       struct eh_region *region;
1613       rtx seq;
1614       basic_block bb;
1615       edge e;
1616
1617       region = VEC_index (eh_region, cfun->eh->region_array, i);
1618       /* Mind we don't process a region more than once.  */
1619       if (!region || region->region_number != i)
1620         continue;
1621
1622       if (region->type != ERT_CLEANUP
1623           && region->type != ERT_TRY
1624           && region->type != ERT_ALLOWED_EXCEPTIONS)
1625         continue;
1626
1627       start_sequence ();
1628
1629       region->landing_pad = gen_label_rtx ();
1630       emit_label (region->landing_pad);
1631
1632 #ifdef HAVE_exception_receiver
1633       if (HAVE_exception_receiver)
1634         emit_insn (gen_exception_receiver ());
1635       else
1636 #endif
1637 #ifdef HAVE_nonlocal_goto_receiver
1638         if (HAVE_nonlocal_goto_receiver)
1639           emit_insn (gen_nonlocal_goto_receiver ());
1640         else
1641 #endif
1642           { /* Nothing */ }
1643
1644       emit_move_insn (cfun->eh->exc_ptr,
1645                       gen_rtx_REG (ptr_mode, EH_RETURN_DATA_REGNO (0)));
1646       emit_move_insn (cfun->eh->filter,
1647                       gen_rtx_REG (targetm.eh_return_filter_mode (),
1648                                    EH_RETURN_DATA_REGNO (1)));
1649
1650       seq = get_insns ();
1651       end_sequence ();
1652
1653       bb = emit_to_new_bb_before (seq, region->post_landing_pad);
1654       e = make_edge (bb, bb->next_bb, EDGE_FALLTHRU);
1655       e->count = bb->count;
1656       e->probability = REG_BR_PROB_BASE;
1657     }
1658 }
1659
1660 \f
1661 struct sjlj_lp_info
1662 {
1663   int directly_reachable;
1664   int action_index;
1665   int dispatch_index;
1666   int call_site_index;
1667 };
1668
1669 static bool
1670 sjlj_find_directly_reachable_regions (struct sjlj_lp_info *lp_info)
1671 {
1672   rtx insn;
1673   bool found_one = false;
1674
1675   for (insn = get_insns (); insn ; insn = NEXT_INSN (insn))
1676     {
1677       struct eh_region *region;
1678       enum reachable_code rc;
1679       tree type_thrown;
1680       rtx note;
1681
1682       if (! INSN_P (insn))
1683         continue;
1684
1685       note = find_reg_note (insn, REG_EH_REGION, NULL_RTX);
1686       if (!note || INTVAL (XEXP (note, 0)) <= 0)
1687         continue;
1688
1689       region = VEC_index (eh_region, cfun->eh->region_array, INTVAL (XEXP (note, 0)));
1690
1691       type_thrown = NULL_TREE;
1692       if (region->type == ERT_THROW)
1693         {
1694           type_thrown = region->u.throw.type;
1695           region = region->outer;
1696         }
1697
1698       /* Find the first containing region that might handle the exception.
1699          That's the landing pad to which we will transfer control.  */
1700       rc = RNL_NOT_CAUGHT;
1701       for (; region; region = region->outer)
1702         {
1703           rc = reachable_next_level (region, type_thrown, NULL);
1704           if (rc != RNL_NOT_CAUGHT)
1705             break;
1706         }
1707       if (rc == RNL_MAYBE_CAUGHT || rc == RNL_CAUGHT)
1708         {
1709           lp_info[region->region_number].directly_reachable = 1;
1710           found_one = true;
1711         }
1712     }
1713
1714   return found_one;
1715 }
1716
1717 static void
1718 sjlj_assign_call_site_values (rtx dispatch_label, struct sjlj_lp_info *lp_info)
1719 {
1720   htab_t ar_hash;
1721   int i, index;
1722
1723   /* First task: build the action table.  */
1724
1725   VARRAY_UCHAR_INIT (cfun->eh->action_record_data, 64, "action_record_data");
1726   ar_hash = htab_create (31, action_record_hash, action_record_eq, free);
1727
1728   for (i = cfun->eh->last_region_number; i > 0; --i)
1729     if (lp_info[i].directly_reachable)
1730       {
1731         struct eh_region *r = VEC_index (eh_region, cfun->eh->region_array, i);
1732
1733         r->landing_pad = dispatch_label;
1734         lp_info[i].action_index = collect_one_action_chain (ar_hash, r);
1735         if (lp_info[i].action_index != -1)
1736           cfun->uses_eh_lsda = 1;
1737       }
1738
1739   htab_delete (ar_hash);
1740
1741   /* Next: assign dispatch values.  In dwarf2 terms, this would be the
1742      landing pad label for the region.  For sjlj though, there is one
1743      common landing pad from which we dispatch to the post-landing pads.
1744
1745      A region receives a dispatch index if it is directly reachable
1746      and requires in-function processing.  Regions that share post-landing
1747      pads may share dispatch indices.  */
1748   /* ??? Post-landing pad sharing doesn't actually happen at the moment
1749      (see build_post_landing_pads) so we don't bother checking for it.  */
1750
1751   index = 0;
1752   for (i = cfun->eh->last_region_number; i > 0; --i)
1753     if (lp_info[i].directly_reachable)
1754       lp_info[i].dispatch_index = index++;
1755
1756   /* Finally: assign call-site values.  If dwarf2 terms, this would be
1757      the region number assigned by convert_to_eh_region_ranges, but
1758      handles no-action and must-not-throw differently.  */
1759
1760   call_site_base = 1;
1761   for (i = cfun->eh->last_region_number; i > 0; --i)
1762     if (lp_info[i].directly_reachable)
1763       {
1764         int action = lp_info[i].action_index;
1765
1766         /* Map must-not-throw to otherwise unused call-site index 0.  */
1767         if (action == -2)
1768           index = 0;
1769         /* Map no-action to otherwise unused call-site index -1.  */
1770         else if (action == -1)
1771           index = -1;
1772         /* Otherwise, look it up in the table.  */
1773         else
1774           index = add_call_site (GEN_INT (lp_info[i].dispatch_index), action);
1775
1776         lp_info[i].call_site_index = index;
1777       }
1778 }
1779
1780 static void
1781 sjlj_mark_call_sites (struct sjlj_lp_info *lp_info)
1782 {
1783   int last_call_site = -2;
1784   rtx insn, mem;
1785
1786   for (insn = get_insns (); insn ; insn = NEXT_INSN (insn))
1787     {
1788       struct eh_region *region;
1789       int this_call_site;
1790       rtx note, before, p;
1791
1792       /* Reset value tracking at extended basic block boundaries.  */
1793       if (LABEL_P (insn))
1794         last_call_site = -2;
1795
1796       if (! INSN_P (insn))
1797         continue;
1798
1799       note = find_reg_note (insn, REG_EH_REGION, NULL_RTX);
1800       if (!note)
1801         {
1802           /* Calls (and trapping insns) without notes are outside any
1803              exception handling region in this function.  Mark them as
1804              no action.  */
1805           if (CALL_P (insn)
1806               || (flag_non_call_exceptions
1807                   && may_trap_p (PATTERN (insn))))
1808             this_call_site = -1;
1809           else
1810             continue;
1811         }
1812       else
1813         {
1814           /* Calls that are known to not throw need not be marked.  */
1815           if (INTVAL (XEXP (note, 0)) <= 0)
1816             continue;
1817
1818           region = VEC_index (eh_region, cfun->eh->region_array, INTVAL (XEXP (note, 0)));
1819           this_call_site = lp_info[region->region_number].call_site_index;
1820         }
1821
1822       if (this_call_site == last_call_site)
1823         continue;
1824
1825       /* Don't separate a call from it's argument loads.  */
1826       before = insn;
1827       if (CALL_P (insn))
1828         before = find_first_parameter_load (insn, NULL_RTX);
1829
1830       start_sequence ();
1831       mem = adjust_address (cfun->eh->sjlj_fc, TYPE_MODE (integer_type_node),
1832                             sjlj_fc_call_site_ofs);
1833       emit_move_insn (mem, GEN_INT (this_call_site));
1834       p = get_insns ();
1835       end_sequence ();
1836
1837       emit_insn_before (p, before);
1838       last_call_site = this_call_site;
1839     }
1840 }
1841
1842 /* Construct the SjLj_Function_Context.  */
1843
1844 static void
1845 sjlj_emit_function_enter (rtx dispatch_label)
1846 {
1847   rtx fn_begin, fc, mem, seq;
1848   bool fn_begin_outside_block;
1849
1850   fc = cfun->eh->sjlj_fc;
1851
1852   start_sequence ();
1853
1854   /* We're storing this libcall's address into memory instead of
1855      calling it directly.  Thus, we must call assemble_external_libcall
1856      here, as we can not depend on emit_library_call to do it for us.  */
1857   assemble_external_libcall (eh_personality_libfunc);
1858   mem = adjust_address (fc, Pmode, sjlj_fc_personality_ofs);
1859   emit_move_insn (mem, eh_personality_libfunc);
1860
1861   mem = adjust_address (fc, Pmode, sjlj_fc_lsda_ofs);
1862   if (cfun->uses_eh_lsda)
1863     {
1864       char buf[20];
1865       rtx sym;
1866
1867       ASM_GENERATE_INTERNAL_LABEL (buf, "LLSDA", current_function_funcdef_no);
1868       sym = gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (buf));
1869       SYMBOL_REF_FLAGS (sym) = SYMBOL_FLAG_LOCAL;
1870       emit_move_insn (mem, sym);
1871     }
1872   else
1873     emit_move_insn (mem, const0_rtx);
1874
1875 #ifdef DONT_USE_BUILTIN_SETJMP
1876   {
1877     rtx x;
1878     x = emit_library_call_value (setjmp_libfunc, NULL_RTX, LCT_RETURNS_TWICE,
1879                                  TYPE_MODE (integer_type_node), 1,
1880                                  plus_constant (XEXP (fc, 0),
1881                                                 sjlj_fc_jbuf_ofs), Pmode);
1882
1883     emit_cmp_and_jump_insns (x, const0_rtx, NE, 0,
1884                              TYPE_MODE (integer_type_node), 0, dispatch_label);
1885     add_reg_br_prob_note (get_insns (), REG_BR_PROB_BASE/100);
1886   }
1887 #else
1888   expand_builtin_setjmp_setup (plus_constant (XEXP (fc, 0), sjlj_fc_jbuf_ofs),
1889                                dispatch_label);
1890 #endif
1891
1892   emit_library_call (unwind_sjlj_register_libfunc, LCT_NORMAL, VOIDmode,
1893                      1, XEXP (fc, 0), Pmode);
1894
1895   seq = get_insns ();
1896   end_sequence ();
1897
1898   /* ??? Instead of doing this at the beginning of the function,
1899      do this in a block that is at loop level 0 and dominates all
1900      can_throw_internal instructions.  */
1901
1902   fn_begin_outside_block = true;
1903   for (fn_begin = get_insns (); ; fn_begin = NEXT_INSN (fn_begin))
1904     if (NOTE_P (fn_begin))
1905       {
1906         if (NOTE_KIND (fn_begin) == NOTE_INSN_FUNCTION_BEG)
1907           break;
1908         else if (NOTE_INSN_BASIC_BLOCK_P (fn_begin))
1909           fn_begin_outside_block = false;
1910       }
1911
1912   if (fn_begin_outside_block)
1913     insert_insn_on_edge (seq, single_succ_edge (ENTRY_BLOCK_PTR));
1914   else
1915     emit_insn_after (seq, fn_begin);
1916 }
1917
1918 /* Call back from expand_function_end to know where we should put
1919    the call to unwind_sjlj_unregister_libfunc if needed.  */
1920
1921 void
1922 sjlj_emit_function_exit_after (rtx after)
1923 {
1924   cfun->eh->sjlj_exit_after = after;
1925 }
1926
1927 static void
1928 sjlj_emit_function_exit (void)
1929 {
1930   rtx seq;
1931   edge e;
1932   edge_iterator ei;
1933
1934   start_sequence ();
1935
1936   emit_library_call (unwind_sjlj_unregister_libfunc, LCT_NORMAL, VOIDmode,
1937                      1, XEXP (cfun->eh->sjlj_fc, 0), Pmode);
1938
1939   seq = get_insns ();
1940   end_sequence ();
1941
1942   /* ??? Really this can be done in any block at loop level 0 that
1943      post-dominates all can_throw_internal instructions.  This is
1944      the last possible moment.  */
1945
1946   FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
1947     if (e->flags & EDGE_FALLTHRU)
1948       break;
1949   if (e)
1950     {
1951       rtx insn;
1952
1953       /* Figure out whether the place we are supposed to insert libcall
1954          is inside the last basic block or after it.  In the other case
1955          we need to emit to edge.  */
1956       gcc_assert (e->src->next_bb == EXIT_BLOCK_PTR);
1957       for (insn = BB_HEAD (e->src); ; insn = NEXT_INSN (insn))
1958         {
1959           if (insn == cfun->eh->sjlj_exit_after)
1960             {
1961               if (LABEL_P (insn))
1962                 insn = NEXT_INSN (insn);
1963               emit_insn_after (seq, insn);
1964               return;
1965             }
1966           if (insn == BB_END (e->src))
1967             break;
1968         }
1969       insert_insn_on_edge (seq, e);
1970     }
1971 }
1972
1973 static void
1974 sjlj_emit_dispatch_table (rtx dispatch_label, struct sjlj_lp_info *lp_info)
1975 {
1976   int i, first_reachable;
1977   rtx mem, dispatch, seq, fc;
1978   rtx before;
1979   basic_block bb;
1980   edge e;
1981
1982   fc = cfun->eh->sjlj_fc;
1983
1984   start_sequence ();
1985
1986   emit_label (dispatch_label);
1987
1988 #ifndef DONT_USE_BUILTIN_SETJMP
1989   expand_builtin_setjmp_receiver (dispatch_label);
1990 #endif
1991
1992   /* Load up dispatch index, exc_ptr and filter values from the
1993      function context.  */
1994   mem = adjust_address (fc, TYPE_MODE (integer_type_node),
1995                         sjlj_fc_call_site_ofs);
1996   dispatch = copy_to_reg (mem);
1997
1998   mem = adjust_address (fc, word_mode, sjlj_fc_data_ofs);
1999   if (word_mode != ptr_mode)
2000     {
2001 #ifdef POINTERS_EXTEND_UNSIGNED
2002       mem = convert_memory_address (ptr_mode, mem);
2003 #else
2004       mem = convert_to_mode (ptr_mode, mem, 0);
2005 #endif
2006     }
2007   emit_move_insn (cfun->eh->exc_ptr, mem);
2008
2009   mem = adjust_address (fc, word_mode, sjlj_fc_data_ofs + UNITS_PER_WORD);
2010   emit_move_insn (cfun->eh->filter, mem);
2011
2012   /* Jump to one of the directly reachable regions.  */
2013   /* ??? This really ought to be using a switch statement.  */
2014
2015   first_reachable = 0;
2016   for (i = cfun->eh->last_region_number; i > 0; --i)
2017     {
2018       if (! lp_info[i].directly_reachable)
2019         continue;
2020
2021       if (! first_reachable)
2022         {
2023           first_reachable = i;
2024           continue;
2025         }
2026
2027       emit_cmp_and_jump_insns (dispatch, GEN_INT (lp_info[i].dispatch_index),
2028                                EQ, NULL_RTX, TYPE_MODE (integer_type_node), 0,
2029                                ((struct eh_region *)VEC_index (eh_region, cfun->eh->region_array, i))
2030                                 ->post_landing_pad);
2031     }
2032
2033   seq = get_insns ();
2034   end_sequence ();
2035
2036   before = (((struct eh_region *)VEC_index (eh_region, cfun->eh->region_array, first_reachable))
2037             ->post_landing_pad);
2038
2039   bb = emit_to_new_bb_before (seq, before);
2040   e = make_edge (bb, bb->next_bb, EDGE_FALLTHRU);
2041   e->count = bb->count;
2042   e->probability = REG_BR_PROB_BASE;
2043 }
2044
2045 static void
2046 sjlj_build_landing_pads (void)
2047 {
2048   struct sjlj_lp_info *lp_info;
2049
2050   lp_info = XCNEWVEC (struct sjlj_lp_info, cfun->eh->last_region_number + 1);
2051
2052   if (sjlj_find_directly_reachable_regions (lp_info))
2053     {
2054       rtx dispatch_label = gen_label_rtx ();
2055
2056       cfun->eh->sjlj_fc
2057         = assign_stack_local (TYPE_MODE (sjlj_fc_type_node),
2058                               int_size_in_bytes (sjlj_fc_type_node),
2059                               TYPE_ALIGN (sjlj_fc_type_node));
2060
2061       sjlj_assign_call_site_values (dispatch_label, lp_info);
2062       sjlj_mark_call_sites (lp_info);
2063
2064       sjlj_emit_function_enter (dispatch_label);
2065       sjlj_emit_dispatch_table (dispatch_label, lp_info);
2066       sjlj_emit_function_exit ();
2067     }
2068
2069   free (lp_info);
2070 }
2071
2072 void
2073 finish_eh_generation (void)
2074 {
2075   basic_block bb;
2076
2077   /* Nothing to do if no regions created.  */
2078   if (cfun->eh->region_tree == NULL)
2079     return;
2080
2081   /* The object here is to provide find_basic_blocks with detailed
2082      information (via reachable_handlers) on how exception control
2083      flows within the function.  In this first pass, we can include
2084      type information garnered from ERT_THROW and ERT_ALLOWED_EXCEPTIONS
2085      regions, and hope that it will be useful in deleting unreachable
2086      handlers.  Subsequently, we will generate landing pads which will
2087      connect many of the handlers, and then type information will not
2088      be effective.  Still, this is a win over previous implementations.  */
2089
2090   /* These registers are used by the landing pads.  Make sure they
2091      have been generated.  */
2092   get_exception_pointer (cfun);
2093   get_exception_filter (cfun);
2094
2095   /* Construct the landing pads.  */
2096
2097   assign_filter_values ();
2098   build_post_landing_pads ();
2099   connect_post_landing_pads ();
2100   if (USING_SJLJ_EXCEPTIONS)
2101     sjlj_build_landing_pads ();
2102   else
2103     dw2_build_landing_pads ();
2104
2105   cfun->eh->built_landing_pads = 1;
2106
2107   /* We've totally changed the CFG.  Start over.  */
2108   find_exception_handler_labels ();
2109   break_superblocks ();
2110   if (USING_SJLJ_EXCEPTIONS
2111       /* Kludge for Alpha/Tru64 (see alpha_gp_save_rtx).  */
2112       || single_succ_edge (ENTRY_BLOCK_PTR)->insns.r)
2113     commit_edge_insertions ();
2114   FOR_EACH_BB (bb)
2115     {
2116       edge e;
2117       edge_iterator ei;
2118       bool eh = false;
2119       for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
2120         {
2121           if (e->flags & EDGE_EH)
2122             {
2123               remove_edge (e);
2124               eh = true;
2125             }
2126           else
2127             ei_next (&ei);
2128         }
2129       if (eh)
2130         rtl_make_eh_edge (NULL, bb, BB_END (bb));
2131     }
2132 }
2133 \f
2134 static hashval_t
2135 ehl_hash (const void *pentry)
2136 {
2137   const struct ehl_map_entry *const entry
2138     = (const struct ehl_map_entry *) pentry;
2139
2140   /* 2^32 * ((sqrt(5) - 1) / 2) */
2141   const hashval_t scaled_golden_ratio = 0x9e3779b9;
2142   return CODE_LABEL_NUMBER (entry->label) * scaled_golden_ratio;
2143 }
2144
2145 static int
2146 ehl_eq (const void *pentry, const void *pdata)
2147 {
2148   const struct ehl_map_entry *const entry
2149     = (const struct ehl_map_entry *) pentry;
2150   const struct ehl_map_entry *const data
2151     = (const struct ehl_map_entry *) pdata;
2152
2153   return entry->label == data->label;
2154 }
2155
2156 /* This section handles removing dead code for flow.  */
2157
2158 /* Remove LABEL from exception_handler_label_map.  */
2159
2160 static void
2161 remove_exception_handler_label (rtx label)
2162 {
2163   struct ehl_map_entry **slot, tmp;
2164
2165   /* If exception_handler_label_map was not built yet,
2166      there is nothing to do.  */
2167   if (cfun->eh->exception_handler_label_map == NULL)
2168     return;
2169
2170   tmp.label = label;
2171   slot = (struct ehl_map_entry **)
2172     htab_find_slot (cfun->eh->exception_handler_label_map, &tmp, NO_INSERT);
2173   gcc_assert (slot);
2174
2175   htab_clear_slot (cfun->eh->exception_handler_label_map, (void **) slot);
2176 }
2177
2178 /* Splice REGION from the region tree etc.  */
2179
2180 static void
2181 remove_eh_handler (struct eh_region *region)
2182 {
2183   struct eh_region **pp, **pp_start, *p, *outer, *inner;
2184   rtx lab;
2185
2186   /* For the benefit of efficiently handling REG_EH_REGION notes,
2187      replace this region in the region array with its containing
2188      region.  Note that previous region deletions may result in
2189      multiple copies of this region in the array, so we have a
2190      list of alternate numbers by which we are known.  */
2191
2192   outer = region->outer;
2193   VEC_replace (eh_region, cfun->eh->region_array, region->region_number, outer);
2194   if (region->aka)
2195     {
2196       unsigned i;
2197       bitmap_iterator bi;
2198
2199       EXECUTE_IF_SET_IN_BITMAP (region->aka, 0, i, bi)
2200         {
2201           VEC_replace (eh_region, cfun->eh->region_array, i, outer);
2202         }
2203     }
2204
2205   if (outer)
2206     {
2207       if (!outer->aka)
2208         outer->aka = BITMAP_GGC_ALLOC ();
2209       if (region->aka)
2210         bitmap_ior_into (outer->aka, region->aka);
2211       bitmap_set_bit (outer->aka, region->region_number);
2212     }
2213
2214   if (cfun->eh->built_landing_pads)
2215     lab = region->landing_pad;
2216   else
2217     lab = region->label;
2218   if (lab)
2219     remove_exception_handler_label (lab);
2220
2221   if (outer)
2222     pp_start = &outer->inner;
2223   else
2224     pp_start = &cfun->eh->region_tree;
2225   for (pp = pp_start, p = *pp; p != region; pp = &p->next_peer, p = *pp)
2226     continue;
2227   *pp = region->next_peer;
2228
2229   inner = region->inner;
2230   if (inner)
2231     {
2232       for (p = inner; p->next_peer ; p = p->next_peer)
2233         p->outer = outer;
2234       p->outer = outer;
2235
2236       p->next_peer = *pp_start;
2237       *pp_start = inner;
2238     }
2239
2240   if (region->type == ERT_CATCH)
2241     {
2242       struct eh_region *try, *next, *prev;
2243
2244       for (try = region->next_peer;
2245            try->type == ERT_CATCH;
2246            try = try->next_peer)
2247         continue;
2248       gcc_assert (try->type == ERT_TRY);
2249
2250       next = region->u.catch.next_catch;
2251       prev = region->u.catch.prev_catch;
2252
2253       if (next)
2254         next->u.catch.prev_catch = prev;
2255       else
2256         try->u.try.last_catch = prev;
2257       if (prev)
2258         prev->u.catch.next_catch = next;
2259       else
2260         {
2261           try->u.try.catch = next;
2262           if (! next)
2263             remove_eh_handler (try);
2264         }
2265     }
2266 }
2267
2268 /* LABEL heads a basic block that is about to be deleted.  If this
2269    label corresponds to an exception region, we may be able to
2270    delete the region.  */
2271
2272 void
2273 maybe_remove_eh_handler (rtx label)
2274 {
2275   struct ehl_map_entry **slot, tmp;
2276   struct eh_region *region;
2277
2278   /* ??? After generating landing pads, it's not so simple to determine
2279      if the region data is completely unused.  One must examine the
2280      landing pad and the post landing pad, and whether an inner try block
2281      is referencing the catch handlers directly.  */
2282   if (cfun->eh->built_landing_pads)
2283     return;
2284
2285   tmp.label = label;
2286   slot = (struct ehl_map_entry **)
2287     htab_find_slot (cfun->eh->exception_handler_label_map, &tmp, NO_INSERT);
2288   if (! slot)
2289     return;
2290   region = (*slot)->region;
2291   if (! region)
2292     return;
2293
2294   /* Flow will want to remove MUST_NOT_THROW regions as unreachable
2295      because there is no path to the fallback call to terminate.
2296      But the region continues to affect call-site data until there
2297      are no more contained calls, which we don't see here.  */
2298   if (region->type == ERT_MUST_NOT_THROW)
2299     {
2300       htab_clear_slot (cfun->eh->exception_handler_label_map, (void **) slot);
2301       region->label = NULL_RTX;
2302     }
2303   else
2304     remove_eh_handler (region);
2305 }
2306
2307 /* Invokes CALLBACK for every exception handler label.  Only used by old
2308    loop hackery; should not be used by new code.  */
2309
2310 void
2311 for_each_eh_label (void (*callback) (rtx))
2312 {
2313   htab_traverse (cfun->eh->exception_handler_label_map, for_each_eh_label_1,
2314                  (void *) &callback);
2315 }
2316
2317 static int
2318 for_each_eh_label_1 (void **pentry, void *data)
2319 {
2320   struct ehl_map_entry *entry = *(struct ehl_map_entry **)pentry;
2321   void (*callback) (rtx) = *(void (**) (rtx)) data;
2322
2323   (*callback) (entry->label);
2324   return 1;
2325 }
2326
2327 /* Invoke CALLBACK for every exception region in the current function.  */
2328
2329 void
2330 for_each_eh_region (void (*callback) (struct eh_region *))
2331 {
2332   int i, n = cfun->eh->last_region_number;
2333   for (i = 1; i <= n; ++i)
2334     {
2335       struct eh_region *region;
2336
2337       region = VEC_index (eh_region, cfun->eh->region_array, i);
2338       if (region)
2339         (*callback) (region);
2340     }
2341 }
2342 \f
2343 /* This section describes CFG exception edges for flow.  */
2344
2345 /* For communicating between calls to reachable_next_level.  */
2346 struct reachable_info
2347 {
2348   tree types_caught;
2349   tree types_allowed;
2350   void (*callback) (struct eh_region *, void *);
2351   void *callback_data;
2352   bool saw_any_handlers;
2353 };
2354
2355 /* A subroutine of reachable_next_level.  Return true if TYPE, or a
2356    base class of TYPE, is in HANDLED.  */
2357
2358 static int
2359 check_handled (tree handled, tree type)
2360 {
2361   tree t;
2362
2363   /* We can check for exact matches without front-end help.  */
2364   if (! lang_eh_type_covers)
2365     {
2366       for (t = handled; t ; t = TREE_CHAIN (t))
2367         if (TREE_VALUE (t) == type)
2368           return 1;
2369     }
2370   else
2371     {
2372       for (t = handled; t ; t = TREE_CHAIN (t))
2373         if ((*lang_eh_type_covers) (TREE_VALUE (t), type))
2374           return 1;
2375     }
2376
2377   return 0;
2378 }
2379
2380 /* A subroutine of reachable_next_level.  If we are collecting a list
2381    of handlers, add one.  After landing pad generation, reference
2382    it instead of the handlers themselves.  Further, the handlers are
2383    all wired together, so by referencing one, we've got them all.
2384    Before landing pad generation we reference each handler individually.
2385
2386    LP_REGION contains the landing pad; REGION is the handler.  */
2387
2388 static void
2389 add_reachable_handler (struct reachable_info *info,
2390                        struct eh_region *lp_region, struct eh_region *region)
2391 {
2392   if (! info)
2393     return;
2394
2395   info->saw_any_handlers = true;
2396
2397   if (cfun->eh->built_landing_pads)
2398     info->callback (lp_region, info->callback_data);
2399   else
2400     info->callback (region, info->callback_data);
2401 }
2402
2403 /* Process one level of exception regions for reachability.
2404    If TYPE_THROWN is non-null, then it is the *exact* type being
2405    propagated.  If INFO is non-null, then collect handler labels
2406    and caught/allowed type information between invocations.  */
2407
2408 static enum reachable_code
2409 reachable_next_level (struct eh_region *region, tree type_thrown,
2410                       struct reachable_info *info)
2411 {
2412   switch (region->type)
2413     {
2414     case ERT_CLEANUP:
2415       /* Before landing-pad generation, we model control flow
2416          directly to the individual handlers.  In this way we can
2417          see that catch handler types may shadow one another.  */
2418       add_reachable_handler (info, region, region);
2419       return RNL_MAYBE_CAUGHT;
2420
2421     case ERT_TRY:
2422       {
2423         struct eh_region *c;
2424         enum reachable_code ret = RNL_NOT_CAUGHT;
2425
2426         for (c = region->u.try.catch; c ; c = c->u.catch.next_catch)
2427           {
2428             /* A catch-all handler ends the search.  */
2429             if (c->u.catch.type_list == NULL)
2430               {
2431                 add_reachable_handler (info, region, c);
2432                 return RNL_CAUGHT;
2433               }
2434
2435             if (type_thrown)
2436               {
2437                 /* If we have at least one type match, end the search.  */
2438                 tree tp_node = c->u.catch.type_list;
2439
2440                 for (; tp_node; tp_node = TREE_CHAIN (tp_node))
2441                   {
2442                     tree type = TREE_VALUE (tp_node);
2443
2444                     if (type == type_thrown
2445                         || (lang_eh_type_covers
2446                             && (*lang_eh_type_covers) (type, type_thrown)))
2447                       {
2448                         add_reachable_handler (info, region, c);
2449                         return RNL_CAUGHT;
2450                       }
2451                   }
2452
2453                 /* If we have definitive information of a match failure,
2454                    the catch won't trigger.  */
2455                 if (lang_eh_type_covers)
2456                   return RNL_NOT_CAUGHT;
2457               }
2458
2459             /* At this point, we either don't know what type is thrown or
2460                don't have front-end assistance to help deciding if it is
2461                covered by one of the types in the list for this region.
2462
2463                We'd then like to add this region to the list of reachable
2464                handlers since it is indeed potentially reachable based on the
2465                information we have.
2466
2467                Actually, this handler is for sure not reachable if all the
2468                types it matches have already been caught. That is, it is only
2469                potentially reachable if at least one of the types it catches
2470                has not been previously caught.  */
2471
2472             if (! info)
2473               ret = RNL_MAYBE_CAUGHT;
2474             else
2475               {
2476                 tree tp_node = c->u.catch.type_list;
2477                 bool maybe_reachable = false;
2478
2479                 /* Compute the potential reachability of this handler and
2480                    update the list of types caught at the same time.  */
2481                 for (; tp_node; tp_node = TREE_CHAIN (tp_node))
2482                   {
2483                     tree type = TREE_VALUE (tp_node);
2484
2485                     if (! check_handled (info->types_caught, type))
2486                       {
2487                         info->types_caught
2488                           = tree_cons (NULL, type, info->types_caught);
2489
2490                         maybe_reachable = true;
2491                       }
2492                   }
2493
2494                 if (maybe_reachable)
2495                   {
2496                     add_reachable_handler (info, region, c);
2497
2498                     /* ??? If the catch type is a base class of every allowed
2499                        type, then we know we can stop the search.  */
2500                     ret = RNL_MAYBE_CAUGHT;
2501                   }
2502               }
2503           }
2504
2505         return ret;
2506       }
2507
2508     case ERT_ALLOWED_EXCEPTIONS:
2509       /* An empty list of types definitely ends the search.  */
2510       if (region->u.allowed.type_list == NULL_TREE)
2511         {
2512           add_reachable_handler (info, region, region);
2513           return RNL_CAUGHT;
2514         }
2515
2516       /* Collect a list of lists of allowed types for use in detecting
2517          when a catch may be transformed into a catch-all.  */
2518       if (info)
2519         info->types_allowed = tree_cons (NULL_TREE,
2520                                          region->u.allowed.type_list,
2521                                          info->types_allowed);
2522
2523       /* If we have definitive information about the type hierarchy,
2524          then we can tell if the thrown type will pass through the
2525          filter.  */
2526       if (type_thrown && lang_eh_type_covers)
2527         {
2528           if (check_handled (region->u.allowed.type_list, type_thrown))
2529             return RNL_NOT_CAUGHT;
2530           else
2531             {
2532               add_reachable_handler (info, region, region);
2533               return RNL_CAUGHT;
2534             }
2535         }
2536
2537       add_reachable_handler (info, region, region);
2538       return RNL_MAYBE_CAUGHT;
2539
2540     case ERT_CATCH:
2541       /* Catch regions are handled by their controlling try region.  */
2542       return RNL_NOT_CAUGHT;
2543
2544     case ERT_MUST_NOT_THROW:
2545       /* Here we end our search, since no exceptions may propagate.
2546          If we've touched down at some landing pad previous, then the
2547          explicit function call we generated may be used.  Otherwise
2548          the call is made by the runtime.
2549
2550          Before inlining, do not perform this optimization.  We may
2551          inline a subroutine that contains handlers, and that will
2552          change the value of saw_any_handlers.  */
2553
2554       if ((info && info->saw_any_handlers) || !cfun->after_inlining)
2555         {
2556           add_reachable_handler (info, region, region);
2557           return RNL_CAUGHT;
2558         }
2559       else
2560         return RNL_BLOCKED;
2561
2562     case ERT_THROW:
2563     case ERT_UNKNOWN:
2564       /* Shouldn't see these here.  */
2565       gcc_unreachable ();
2566       break;
2567     default:
2568       gcc_unreachable ();
2569     }
2570 }
2571
2572 /* Invoke CALLBACK on each region reachable from REGION_NUMBER.  */
2573
2574 void
2575 foreach_reachable_handler (int region_number, bool is_resx,
2576                            void (*callback) (struct eh_region *, void *),
2577                            void *callback_data)
2578 {
2579   struct reachable_info info;
2580   struct eh_region *region;
2581   tree type_thrown;
2582
2583   memset (&info, 0, sizeof (info));
2584   info.callback = callback;
2585   info.callback_data = callback_data;
2586
2587   region = VEC_index (eh_region, cfun->eh->region_array, region_number);
2588
2589   type_thrown = NULL_TREE;
2590   if (is_resx)
2591     {
2592       /* A RESX leaves a region instead of entering it.  Thus the
2593          region itself may have been deleted out from under us.  */
2594       if (region == NULL)
2595         return;
2596       region = region->outer;
2597     }
2598   else if (region->type == ERT_THROW)
2599     {
2600       type_thrown = region->u.throw.type;
2601       region = region->outer;
2602     }
2603
2604   while (region)
2605     {
2606       if (reachable_next_level (region, type_thrown, &info) >= RNL_CAUGHT)
2607         break;
2608       /* If we have processed one cleanup, there is no point in
2609          processing any more of them.  Each cleanup will have an edge
2610          to the next outer cleanup region, so the flow graph will be
2611          accurate.  */
2612       if (region->type == ERT_CLEANUP)
2613         region = region->u.cleanup.prev_try;
2614       else
2615         region = region->outer;
2616     }
2617 }
2618
2619 /* Retrieve a list of labels of exception handlers which can be
2620    reached by a given insn.  */
2621
2622 static void
2623 arh_to_landing_pad (struct eh_region *region, void *data)
2624 {
2625   rtx *p_handlers = data;
2626   if (! *p_handlers)
2627     *p_handlers = alloc_INSN_LIST (region->landing_pad, NULL_RTX);
2628 }
2629
2630 static void
2631 arh_to_label (struct eh_region *region, void *data)
2632 {
2633   rtx *p_handlers = data;
2634   *p_handlers = alloc_INSN_LIST (region->label, *p_handlers);
2635 }
2636
2637 rtx
2638 reachable_handlers (rtx insn)
2639 {
2640   bool is_resx = false;
2641   rtx handlers = NULL;
2642   int region_number;
2643
2644   if (JUMP_P (insn)
2645       && GET_CODE (PATTERN (insn)) == RESX)
2646     {
2647       region_number = XINT (PATTERN (insn), 0);
2648       is_resx = true;
2649     }
2650   else
2651     {
2652       rtx note = find_reg_note (insn, REG_EH_REGION, NULL_RTX);
2653       if (!note || INTVAL (XEXP (note, 0)) <= 0)
2654         return NULL;
2655       region_number = INTVAL (XEXP (note, 0));
2656     }
2657
2658   foreach_reachable_handler (region_number, is_resx,
2659                              (cfun->eh->built_landing_pads
2660                               ? arh_to_landing_pad
2661                               : arh_to_label),
2662                              &handlers);
2663
2664   return handlers;
2665 }
2666
2667 /* Determine if the given INSN can throw an exception that is caught
2668    within the function.  */
2669
2670 bool
2671 can_throw_internal_1 (int region_number, bool is_resx)
2672 {
2673   struct eh_region *region;
2674   tree type_thrown;
2675
2676   region = VEC_index (eh_region, cfun->eh->region_array, region_number);
2677
2678   type_thrown = NULL_TREE;
2679   if (is_resx)
2680     region = region->outer;
2681   else if (region->type == ERT_THROW)
2682     {
2683       type_thrown = region->u.throw.type;
2684       region = region->outer;
2685     }
2686
2687   /* If this exception is ignored by each and every containing region,
2688      then control passes straight out.  The runtime may handle some
2689      regions, which also do not require processing internally.  */
2690   for (; region; region = region->outer)
2691     {
2692       enum reachable_code how = reachable_next_level (region, type_thrown, 0);
2693       if (how == RNL_BLOCKED)
2694         return false;
2695       if (how != RNL_NOT_CAUGHT)
2696         return true;
2697     }
2698
2699   return false;
2700 }
2701
2702 bool
2703 can_throw_internal (const_rtx insn)
2704 {
2705   rtx note;
2706
2707   if (! INSN_P (insn))
2708     return false;
2709
2710   if (JUMP_P (insn)
2711       && GET_CODE (PATTERN (insn)) == RESX
2712       && XINT (PATTERN (insn), 0) > 0)
2713     return can_throw_internal_1 (XINT (PATTERN (insn), 0), true);
2714
2715   if (NONJUMP_INSN_P (insn)
2716       && GET_CODE (PATTERN (insn)) == SEQUENCE)
2717     insn = XVECEXP (PATTERN (insn), 0, 0);
2718
2719   /* Every insn that might throw has an EH_REGION note.  */
2720   note = find_reg_note (insn, REG_EH_REGION, NULL_RTX);
2721   if (!note || INTVAL (XEXP (note, 0)) <= 0)
2722     return false;
2723
2724   return can_throw_internal_1 (INTVAL (XEXP (note, 0)), false);
2725 }
2726
2727 /* Determine if the given INSN can throw an exception that is
2728    visible outside the function.  */
2729
2730 bool
2731 can_throw_external_1 (int region_number, bool is_resx)
2732 {
2733   struct eh_region *region;
2734   tree type_thrown;
2735
2736   region = VEC_index (eh_region, cfun->eh->region_array, region_number);
2737
2738   type_thrown = NULL_TREE;
2739   if (is_resx)
2740     region = region->outer;
2741   else if (region->type == ERT_THROW)
2742     {
2743       type_thrown = region->u.throw.type;
2744       region = region->outer;
2745     }
2746
2747   /* If the exception is caught or blocked by any containing region,
2748      then it is not seen by any calling function.  */
2749   for (; region ; region = region->outer)
2750     if (reachable_next_level (region, type_thrown, NULL) >= RNL_CAUGHT)
2751       return false;
2752
2753   return true;
2754 }
2755
2756 bool
2757 can_throw_external (const_rtx insn)
2758 {
2759   rtx note;
2760
2761   if (! INSN_P (insn))
2762     return false;
2763
2764   if (JUMP_P (insn)
2765       && GET_CODE (PATTERN (insn)) == RESX
2766       && XINT (PATTERN (insn), 0) > 0)
2767     return can_throw_external_1 (XINT (PATTERN (insn), 0), true);
2768
2769   if (NONJUMP_INSN_P (insn)
2770       && GET_CODE (PATTERN (insn)) == SEQUENCE)
2771     insn = XVECEXP (PATTERN (insn), 0, 0);
2772
2773   note = find_reg_note (insn, REG_EH_REGION, NULL_RTX);
2774   if (!note)
2775     {
2776       /* Calls (and trapping insns) without notes are outside any
2777          exception handling region in this function.  We have to
2778          assume it might throw.  Given that the front end and middle
2779          ends mark known NOTHROW functions, this isn't so wildly
2780          inaccurate.  */
2781       return (CALL_P (insn)
2782               || (flag_non_call_exceptions
2783                   && may_trap_p (PATTERN (insn))));
2784     }
2785   if (INTVAL (XEXP (note, 0)) <= 0)
2786     return false;
2787
2788   return can_throw_external_1 (INTVAL (XEXP (note, 0)), false);
2789 }
2790
2791 /* Set TREE_NOTHROW and cfun->all_throwers_are_sibcalls.  */
2792
2793 unsigned int
2794 set_nothrow_function_flags (void)
2795 {
2796   rtx insn;
2797
2798   /* If we don't know that this implementation of the function will
2799      actually be used, then we must not set TREE_NOTHROW, since
2800      callers must not assume that this function does not throw.  */
2801   if (DECL_REPLACEABLE_P (current_function_decl))
2802     return 0;
2803
2804   TREE_NOTHROW (current_function_decl) = 1;
2805
2806   /* Assume cfun->all_throwers_are_sibcalls until we encounter
2807      something that can throw an exception.  We specifically exempt
2808      CALL_INSNs that are SIBLING_CALL_P, as these are really jumps,
2809      and can't throw.  Most CALL_INSNs are not SIBLING_CALL_P, so this
2810      is optimistic.  */
2811
2812   cfun->all_throwers_are_sibcalls = 1;
2813
2814   if (! flag_exceptions)
2815     return 0;
2816
2817   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
2818     if (can_throw_external (insn))
2819       {
2820         TREE_NOTHROW (current_function_decl) = 0;
2821
2822         if (!CALL_P (insn) || !SIBLING_CALL_P (insn))
2823           {
2824             cfun->all_throwers_are_sibcalls = 0;
2825             return 0;
2826           }
2827       }
2828
2829   for (insn = current_function_epilogue_delay_list; insn;
2830        insn = XEXP (insn, 1))
2831     if (can_throw_external (insn))
2832       {
2833         TREE_NOTHROW (current_function_decl) = 0;
2834
2835         if (!CALL_P (insn) || !SIBLING_CALL_P (insn))
2836           {
2837             cfun->all_throwers_are_sibcalls = 0;
2838             return 0;
2839           }
2840       }
2841   return 0;
2842 }
2843
2844 struct tree_opt_pass pass_set_nothrow_function_flags =
2845 {
2846   NULL,                                 /* name */
2847   NULL,                                 /* gate */
2848   set_nothrow_function_flags,           /* execute */
2849   NULL,                                 /* sub */
2850   NULL,                                 /* next */
2851   0,                                    /* static_pass_number */
2852   0,                                    /* tv_id */
2853   0,                                    /* properties_required */
2854   0,                                    /* properties_provided */
2855   0,                                    /* properties_destroyed */
2856   0,                                    /* todo_flags_start */
2857   0,                                    /* todo_flags_finish */
2858   0                                     /* letter */
2859 };
2860
2861 \f
2862 /* Various hooks for unwind library.  */
2863
2864 /* Do any necessary initialization to access arbitrary stack frames.
2865    On the SPARC, this means flushing the register windows.  */
2866
2867 void
2868 expand_builtin_unwind_init (void)
2869 {
2870   /* Set this so all the registers get saved in our frame; we need to be
2871      able to copy the saved values for any registers from frames we unwind.  */
2872   current_function_saves_all_registers = 1;
2873
2874 #ifdef SETUP_FRAME_ADDRESSES
2875   SETUP_FRAME_ADDRESSES ();
2876 #endif
2877 }
2878
2879 rtx
2880 expand_builtin_eh_return_data_regno (tree exp)
2881 {
2882   tree which = CALL_EXPR_ARG (exp, 0);
2883   unsigned HOST_WIDE_INT iwhich;
2884
2885   if (TREE_CODE (which) != INTEGER_CST)
2886     {
2887       error ("argument of %<__builtin_eh_return_regno%> must be constant");
2888       return constm1_rtx;
2889     }
2890
2891   iwhich = tree_low_cst (which, 1);
2892   iwhich = EH_RETURN_DATA_REGNO (iwhich);
2893   if (iwhich == INVALID_REGNUM)
2894     return constm1_rtx;
2895
2896 #ifdef DWARF_FRAME_REGNUM
2897   iwhich = DWARF_FRAME_REGNUM (iwhich);
2898 #else
2899   iwhich = DBX_REGISTER_NUMBER (iwhich);
2900 #endif
2901
2902   return GEN_INT (iwhich);
2903 }
2904
2905 /* Given a value extracted from the return address register or stack slot,
2906    return the actual address encoded in that value.  */
2907
2908 rtx
2909 expand_builtin_extract_return_addr (tree addr_tree)
2910 {
2911   rtx addr = expand_expr (addr_tree, NULL_RTX, Pmode, EXPAND_NORMAL);
2912
2913   if (GET_MODE (addr) != Pmode
2914       && GET_MODE (addr) != VOIDmode)
2915     {
2916 #ifdef POINTERS_EXTEND_UNSIGNED
2917       addr = convert_memory_address (Pmode, addr);
2918 #else
2919       addr = convert_to_mode (Pmode, addr, 0);
2920 #endif
2921     }
2922
2923   /* First mask out any unwanted bits.  */
2924 #ifdef MASK_RETURN_ADDR
2925   expand_and (Pmode, addr, MASK_RETURN_ADDR, addr);
2926 #endif
2927
2928   /* Then adjust to find the real return address.  */
2929 #if defined (RETURN_ADDR_OFFSET)
2930   addr = plus_constant (addr, RETURN_ADDR_OFFSET);
2931 #endif
2932
2933   return addr;
2934 }
2935
2936 /* Given an actual address in addr_tree, do any necessary encoding
2937    and return the value to be stored in the return address register or
2938    stack slot so the epilogue will return to that address.  */
2939
2940 rtx
2941 expand_builtin_frob_return_addr (tree addr_tree)
2942 {
2943   rtx addr = expand_expr (addr_tree, NULL_RTX, ptr_mode, EXPAND_NORMAL);
2944
2945   addr = convert_memory_address (Pmode, addr);
2946
2947 #ifdef RETURN_ADDR_OFFSET
2948   addr = force_reg (Pmode, addr);
2949   addr = plus_constant (addr, -RETURN_ADDR_OFFSET);
2950 #endif
2951
2952   return addr;
2953 }
2954
2955 /* Set up the epilogue with the magic bits we'll need to return to the
2956    exception handler.  */
2957
2958 void
2959 expand_builtin_eh_return (tree stackadj_tree ATTRIBUTE_UNUSED,
2960                           tree handler_tree)
2961 {
2962   rtx tmp;
2963
2964 #ifdef EH_RETURN_STACKADJ_RTX
2965   tmp = expand_expr (stackadj_tree, cfun->eh->ehr_stackadj,
2966                      VOIDmode, EXPAND_NORMAL);
2967   tmp = convert_memory_address (Pmode, tmp);
2968   if (!cfun->eh->ehr_stackadj)
2969     cfun->eh->ehr_stackadj = copy_to_reg (tmp);
2970   else if (tmp != cfun->eh->ehr_stackadj)
2971     emit_move_insn (cfun->eh->ehr_stackadj, tmp);
2972 #endif
2973
2974   tmp = expand_expr (handler_tree, cfun->eh->ehr_handler,
2975                      VOIDmode, EXPAND_NORMAL);
2976   tmp = convert_memory_address (Pmode, tmp);
2977   if (!cfun->eh->ehr_handler)
2978     cfun->eh->ehr_handler = copy_to_reg (tmp);
2979   else if (tmp != cfun->eh->ehr_handler)
2980     emit_move_insn (cfun->eh->ehr_handler, tmp);
2981
2982   if (!cfun->eh->ehr_label)
2983     cfun->eh->ehr_label = gen_label_rtx ();
2984   emit_jump (cfun->eh->ehr_label);
2985 }
2986
2987 void
2988 expand_eh_return (void)
2989 {
2990   rtx around_label;
2991
2992   if (! cfun->eh->ehr_label)
2993     return;
2994
2995   current_function_calls_eh_return = 1;
2996
2997 #ifdef EH_RETURN_STACKADJ_RTX
2998   emit_move_insn (EH_RETURN_STACKADJ_RTX, const0_rtx);
2999 #endif
3000
3001   around_label = gen_label_rtx ();
3002   emit_jump (around_label);
3003
3004   emit_label (cfun->eh->ehr_label);
3005   clobber_return_register ();
3006
3007 #ifdef EH_RETURN_STACKADJ_RTX
3008   emit_move_insn (EH_RETURN_STACKADJ_RTX, cfun->eh->ehr_stackadj);
3009 #endif
3010
3011 #ifdef HAVE_eh_return
3012   if (HAVE_eh_return)
3013     emit_insn (gen_eh_return (cfun->eh->ehr_handler));
3014   else
3015 #endif
3016     {
3017 #ifdef EH_RETURN_HANDLER_RTX
3018       emit_move_insn (EH_RETURN_HANDLER_RTX, cfun->eh->ehr_handler);
3019 #else
3020       error ("__builtin_eh_return not supported on this target");
3021 #endif
3022     }
3023
3024   emit_label (around_label);
3025 }
3026
3027 /* Convert a ptr_mode address ADDR_TREE to a Pmode address controlled by
3028    POINTERS_EXTEND_UNSIGNED and return it.  */
3029
3030 rtx
3031 expand_builtin_extend_pointer (tree addr_tree)
3032 {
3033   rtx addr = expand_expr (addr_tree, NULL_RTX, ptr_mode, EXPAND_NORMAL);
3034   int extend;
3035
3036 #ifdef POINTERS_EXTEND_UNSIGNED
3037   extend = POINTERS_EXTEND_UNSIGNED;
3038 #else
3039   /* The previous EH code did an unsigned extend by default, so we do this also
3040      for consistency.  */
3041   extend = 1;
3042 #endif
3043
3044   return convert_modes (word_mode, ptr_mode, addr, extend);
3045 }
3046 \f
3047 /* In the following functions, we represent entries in the action table
3048    as 1-based indices.  Special cases are:
3049
3050          0:     null action record, non-null landing pad; implies cleanups
3051         -1:     null action record, null landing pad; implies no action
3052         -2:     no call-site entry; implies must_not_throw
3053         -3:     we have yet to process outer regions
3054
3055    Further, no special cases apply to the "next" field of the record.
3056    For next, 0 means end of list.  */
3057
3058 struct action_record
3059 {
3060   int offset;
3061   int filter;
3062   int next;
3063 };
3064
3065 static int
3066 action_record_eq (const void *pentry, const void *pdata)
3067 {
3068   const struct action_record *entry = (const struct action_record *) pentry;
3069   const struct action_record *data = (const struct action_record *) pdata;
3070   return entry->filter == data->filter && entry->next == data->next;
3071 }
3072
3073 static hashval_t
3074 action_record_hash (const void *pentry)
3075 {
3076   const struct action_record *entry = (const struct action_record *) pentry;
3077   return entry->next * 1009 + entry->filter;
3078 }
3079
3080 static int
3081 add_action_record (htab_t ar_hash, int filter, int next)
3082 {
3083   struct action_record **slot, *new, tmp;
3084
3085   tmp.filter = filter;
3086   tmp.next = next;
3087   slot = (struct action_record **) htab_find_slot (ar_hash, &tmp, INSERT);
3088
3089   if ((new = *slot) == NULL)
3090     {
3091       new = xmalloc (sizeof (*new));
3092       new->offset = VARRAY_ACTIVE_SIZE (cfun->eh->action_record_data) + 1;
3093       new->filter = filter;
3094       new->next = next;
3095       *slot = new;
3096
3097       /* The filter value goes in untouched.  The link to the next
3098          record is a "self-relative" byte offset, or zero to indicate
3099          that there is no next record.  So convert the absolute 1 based
3100          indices we've been carrying around into a displacement.  */
3101
3102       push_sleb128 (&cfun->eh->action_record_data, filter);
3103       if (next)
3104         next -= VARRAY_ACTIVE_SIZE (cfun->eh->action_record_data) + 1;
3105       push_sleb128 (&cfun->eh->action_record_data, next);
3106     }
3107
3108   return new->offset;
3109 }
3110
3111 static int
3112 collect_one_action_chain (htab_t ar_hash, struct eh_region *region)
3113 {
3114   struct eh_region *c;
3115   int next;
3116
3117   /* If we've reached the top of the region chain, then we have
3118      no actions, and require no landing pad.  */
3119   if (region == NULL)
3120     return -1;
3121
3122   switch (region->type)
3123     {
3124     case ERT_CLEANUP:
3125       /* A cleanup adds a zero filter to the beginning of the chain, but
3126          there are special cases to look out for.  If there are *only*
3127          cleanups along a path, then it compresses to a zero action.
3128          Further, if there are multiple cleanups along a path, we only
3129          need to represent one of them, as that is enough to trigger
3130          entry to the landing pad at runtime.  */
3131       next = collect_one_action_chain (ar_hash, region->outer);
3132       if (next <= 0)
3133         return 0;
3134       for (c = region->outer; c ; c = c->outer)
3135         if (c->type == ERT_CLEANUP)
3136           return next;
3137       return add_action_record (ar_hash, 0, next);
3138
3139     case ERT_TRY:
3140       /* Process the associated catch regions in reverse order.
3141          If there's a catch-all handler, then we don't need to
3142          search outer regions.  Use a magic -3 value to record
3143          that we haven't done the outer search.  */
3144       next = -3;
3145       for (c = region->u.try.last_catch; c ; c = c->u.catch.prev_catch)
3146         {
3147           if (c->u.catch.type_list == NULL)
3148             {
3149               /* Retrieve the filter from the head of the filter list
3150                  where we have stored it (see assign_filter_values).  */
3151               int filter
3152                 = TREE_INT_CST_LOW (TREE_VALUE (c->u.catch.filter_list));
3153
3154               next = add_action_record (ar_hash, filter, 0);
3155             }
3156           else
3157             {
3158               /* Once the outer search is done, trigger an action record for
3159                  each filter we have.  */
3160               tree flt_node;
3161
3162               if (next == -3)
3163                 {
3164                   next = collect_one_action_chain (ar_hash, region->outer);
3165
3166                   /* If there is no next action, terminate the chain.  */
3167                   if (next == -1)
3168                     next = 0;
3169                   /* If all outer actions are cleanups or must_not_throw,
3170                      we'll have no action record for it, since we had wanted
3171                      to encode these states in the call-site record directly.
3172                      Add a cleanup action to the chain to catch these.  */
3173                   else if (next <= 0)
3174                     next = add_action_record (ar_hash, 0, 0);
3175                 }
3176
3177               flt_node = c->u.catch.filter_list;
3178               for (; flt_node; flt_node = TREE_CHAIN (flt_node))
3179                 {
3180                   int filter = TREE_INT_CST_LOW (TREE_VALUE (flt_node));
3181                   next = add_action_record (ar_hash, filter, next);
3182                 }
3183             }
3184         }
3185       return next;
3186
3187     case ERT_ALLOWED_EXCEPTIONS:
3188       /* An exception specification adds its filter to the
3189          beginning of the chain.  */
3190       next = collect_one_action_chain (ar_hash, region->outer);
3191
3192       /* If there is no next action, terminate the chain.  */
3193       if (next == -1)
3194         next = 0;
3195       /* If all outer actions are cleanups or must_not_throw,
3196          we'll have no action record for it, since we had wanted
3197          to encode these states in the call-site record directly.
3198          Add a cleanup action to the chain to catch these.  */
3199       else if (next <= 0)
3200         next = add_action_record (ar_hash, 0, 0);
3201
3202       return add_action_record (ar_hash, region->u.allowed.filter, next);
3203
3204     case ERT_MUST_NOT_THROW:
3205       /* A must-not-throw region with no inner handlers or cleanups
3206          requires no call-site entry.  Note that this differs from
3207          the no handler or cleanup case in that we do require an lsda
3208          to be generated.  Return a magic -2 value to record this.  */
3209       return -2;
3210
3211     case ERT_CATCH:
3212     case ERT_THROW:
3213       /* CATCH regions are handled in TRY above.  THROW regions are
3214          for optimization information only and produce no output.  */
3215       return collect_one_action_chain (ar_hash, region->outer);
3216
3217     default:
3218       gcc_unreachable ();
3219     }
3220 }
3221
3222 static int
3223 add_call_site (rtx landing_pad, int action)
3224 {
3225   struct call_site_record *data = cfun->eh->call_site_data;
3226   int used = cfun->eh->call_site_data_used;
3227   int size = cfun->eh->call_site_data_size;
3228
3229   if (used >= size)
3230     {
3231       size = (size ? size * 2 : 64);
3232       data = ggc_realloc (data, sizeof (*data) * size);
3233       cfun->eh->call_site_data = data;
3234       cfun->eh->call_site_data_size = size;
3235     }
3236
3237   data[used].landing_pad = landing_pad;
3238   data[used].action = action;
3239
3240   cfun->eh->call_site_data_used = used + 1;
3241
3242   return used + call_site_base;
3243 }
3244
3245 /* Turn REG_EH_REGION notes back into NOTE_INSN_EH_REGION notes.
3246    The new note numbers will not refer to region numbers, but
3247    instead to call site entries.  */
3248
3249 unsigned int
3250 convert_to_eh_region_ranges (void)
3251 {
3252   rtx insn, iter, note;
3253   htab_t ar_hash;
3254   int last_action = -3;
3255   rtx last_action_insn = NULL_RTX;
3256   rtx last_landing_pad = NULL_RTX;
3257   rtx first_no_action_insn = NULL_RTX;
3258   int call_site = 0;
3259
3260   if (USING_SJLJ_EXCEPTIONS || cfun->eh->region_tree == NULL)
3261     return 0;
3262
3263   VARRAY_UCHAR_INIT (cfun->eh->action_record_data, 64, "action_record_data");
3264
3265   ar_hash = htab_create (31, action_record_hash, action_record_eq, free);
3266
3267   for (iter = get_insns (); iter ; iter = NEXT_INSN (iter))
3268     if (INSN_P (iter))
3269       {
3270         struct eh_region *region;
3271         int this_action;
3272         rtx this_landing_pad;
3273
3274         insn = iter;
3275         if (NONJUMP_INSN_P (insn)
3276             && GET_CODE (PATTERN (insn)) == SEQUENCE)
3277           insn = XVECEXP (PATTERN (insn), 0, 0);
3278
3279         note = find_reg_note (insn, REG_EH_REGION, NULL_RTX);
3280         if (!note)
3281           {
3282             if (! (CALL_P (insn)
3283                    || (flag_non_call_exceptions
3284                        && may_trap_p (PATTERN (insn)))))
3285               continue;
3286             this_action = -1;
3287             region = NULL;
3288           }
3289         else
3290           {
3291             if (INTVAL (XEXP (note, 0)) <= 0)
3292               continue;
3293             region = VEC_index (eh_region, cfun->eh->region_array, INTVAL (XEXP (note, 0)));
3294             this_action = collect_one_action_chain (ar_hash, region);
3295           }
3296
3297         /* Existence of catch handlers, or must-not-throw regions
3298            implies that an lsda is needed (even if empty).  */
3299         if (this_action != -1)
3300           cfun->uses_eh_lsda = 1;
3301
3302         /* Delay creation of region notes for no-action regions
3303            until we're sure that an lsda will be required.  */
3304         else if (last_action == -3)
3305           {
3306             first_no_action_insn = iter;
3307             last_action = -1;
3308           }
3309
3310         /* Cleanups and handlers may share action chains but not
3311            landing pads.  Collect the landing pad for this region.  */
3312         if (this_action >= 0)
3313           {
3314             struct eh_region *o;
3315             for (o = region; ! o->landing_pad ; o = o->outer)
3316               continue;
3317             this_landing_pad = o->landing_pad;
3318           }
3319         else
3320           this_landing_pad = NULL_RTX;
3321
3322         /* Differing actions or landing pads implies a change in call-site
3323            info, which implies some EH_REGION note should be emitted.  */
3324         if (last_action != this_action
3325             || last_landing_pad != this_landing_pad)
3326           {
3327             /* If we'd not seen a previous action (-3) or the previous
3328                action was must-not-throw (-2), then we do not need an
3329                end note.  */
3330             if (last_action >= -1)
3331               {
3332                 /* If we delayed the creation of the begin, do it now.  */
3333                 if (first_no_action_insn)
3334                   {
3335                     call_site = add_call_site (NULL_RTX, 0);
3336                     note = emit_note_before (NOTE_INSN_EH_REGION_BEG,
3337                                              first_no_action_insn);
3338                     NOTE_EH_HANDLER (note) = call_site;
3339                     first_no_action_insn = NULL_RTX;
3340                   }
3341
3342                 note = emit_note_after (NOTE_INSN_EH_REGION_END,
3343                                         last_action_insn);
3344                 NOTE_EH_HANDLER (note) = call_site;
3345               }
3346
3347             /* If the new action is must-not-throw, then no region notes
3348                are created.  */
3349             if (this_action >= -1)
3350               {
3351                 call_site = add_call_site (this_landing_pad,
3352                                            this_action < 0 ? 0 : this_action);
3353                 note = emit_note_before (NOTE_INSN_EH_REGION_BEG, iter);
3354                 NOTE_EH_HANDLER (note) = call_site;
3355               }
3356
3357             last_action = this_action;
3358             last_landing_pad = this_landing_pad;
3359           }
3360         last_action_insn = iter;
3361       }
3362
3363   if (last_action >= -1 && ! first_no_action_insn)
3364     {
3365       note = emit_note_after (NOTE_INSN_EH_REGION_END, last_action_insn);
3366       NOTE_EH_HANDLER (note) = call_site;
3367     }
3368
3369   htab_delete (ar_hash);
3370   return 0;
3371 }
3372
3373 struct tree_opt_pass pass_convert_to_eh_region_ranges =
3374 {
3375   "eh-ranges",                          /* name */
3376   NULL,                                 /* gate */
3377   convert_to_eh_region_ranges,          /* execute */
3378   NULL,                                 /* sub */
3379   NULL,                                 /* next */
3380   0,                                    /* static_pass_number */
3381   0,                                    /* tv_id */
3382   0,                                    /* properties_required */
3383   0,                                    /* properties_provided */
3384   0,                                    /* properties_destroyed */
3385   0,                                    /* todo_flags_start */
3386   TODO_dump_func,                       /* todo_flags_finish */
3387   0                                     /* letter */
3388 };
3389
3390 \f
3391 static void
3392 push_uleb128 (varray_type *data_area, unsigned int value)
3393 {
3394   do
3395     {
3396       unsigned char byte = value & 0x7f;
3397       value >>= 7;
3398       if (value)
3399         byte |= 0x80;
3400       VARRAY_PUSH_UCHAR (*data_area, byte);
3401     }
3402   while (value);
3403 }
3404
3405 static void
3406 push_sleb128 (varray_type *data_area, int value)
3407 {
3408   unsigned char byte;
3409   int more;
3410
3411   do
3412     {
3413       byte = value & 0x7f;
3414       value >>= 7;
3415       more = ! ((value == 0 && (byte & 0x40) == 0)
3416                 || (value == -1 && (byte & 0x40) != 0));
3417       if (more)
3418         byte |= 0x80;
3419       VARRAY_PUSH_UCHAR (*data_area, byte);
3420     }
3421   while (more);
3422 }
3423
3424 \f
3425 #ifndef HAVE_AS_LEB128
3426 static int
3427 dw2_size_of_call_site_table (void)
3428 {
3429   int n = cfun->eh->call_site_data_used;
3430   int size = n * (4 + 4 + 4);
3431   int i;
3432
3433   for (i = 0; i < n; ++i)
3434     {
3435       struct call_site_record *cs = &cfun->eh->call_site_data[i];
3436       size += size_of_uleb128 (cs->action);
3437     }
3438
3439   return size;
3440 }
3441
3442 static int
3443 sjlj_size_of_call_site_table (void)
3444 {
3445   int n = cfun->eh->call_site_data_used;
3446   int size = 0;
3447   int i;
3448
3449   for (i = 0; i < n; ++i)
3450     {
3451       struct call_site_record *cs = &cfun->eh->call_site_data[i];
3452       size += size_of_uleb128 (INTVAL (cs->landing_pad));
3453       size += size_of_uleb128 (cs->action);
3454     }
3455
3456   return size;
3457 }
3458 #endif
3459
3460 static void
3461 dw2_output_call_site_table (void)
3462 {
3463   int n = cfun->eh->call_site_data_used;
3464   int i;
3465
3466   for (i = 0; i < n; ++i)
3467     {
3468       struct call_site_record *cs = &cfun->eh->call_site_data[i];
3469       char reg_start_lab[32];
3470       char reg_end_lab[32];
3471       char landing_pad_lab[32];
3472
3473       ASM_GENERATE_INTERNAL_LABEL (reg_start_lab, "LEHB", call_site_base + i);
3474       ASM_GENERATE_INTERNAL_LABEL (reg_end_lab, "LEHE", call_site_base + i);
3475
3476       if (cs->landing_pad)
3477         ASM_GENERATE_INTERNAL_LABEL (landing_pad_lab, "L",
3478                                      CODE_LABEL_NUMBER (cs->landing_pad));
3479
3480       /* ??? Perhaps use insn length scaling if the assembler supports
3481          generic arithmetic.  */
3482       /* ??? Perhaps use attr_length to choose data1 or data2 instead of
3483          data4 if the function is small enough.  */
3484 #ifdef HAVE_AS_LEB128
3485       dw2_asm_output_delta_uleb128 (reg_start_lab,
3486                                     current_function_func_begin_label,
3487                                     "region %d start", i);
3488       dw2_asm_output_delta_uleb128 (reg_end_lab, reg_start_lab,
3489                                     "length");
3490       if (cs->landing_pad)
3491         dw2_asm_output_delta_uleb128 (landing_pad_lab,
3492                                       current_function_func_begin_label,
3493                                       "landing pad");
3494       else
3495         dw2_asm_output_data_uleb128 (0, "landing pad");
3496 #else
3497       dw2_asm_output_delta (4, reg_start_lab,
3498                             current_function_func_begin_label,
3499                             "region %d start", i);
3500       dw2_asm_output_delta (4, reg_end_lab, reg_start_lab, "length");
3501       if (cs->landing_pad)
3502         dw2_asm_output_delta (4, landing_pad_lab,
3503                               current_function_func_begin_label,
3504                               "landing pad");
3505       else
3506         dw2_asm_output_data (4, 0, "landing pad");
3507 #endif
3508       dw2_asm_output_data_uleb128 (cs->action, "action");
3509     }
3510
3511   call_site_base += n;
3512 }
3513
3514 static void
3515 sjlj_output_call_site_table (void)
3516 {
3517   int n = cfun->eh->call_site_data_used;
3518   int i;
3519
3520   for (i = 0; i < n; ++i)
3521     {
3522       struct call_site_record *cs = &cfun->eh->call_site_data[i];
3523
3524       dw2_asm_output_data_uleb128 (INTVAL (cs->landing_pad),
3525                                    "region %d landing pad", i);
3526       dw2_asm_output_data_uleb128 (cs->action, "action");
3527     }
3528
3529   call_site_base += n;
3530 }
3531
3532 #ifndef TARGET_UNWIND_INFO
3533 /* Switch to the section that should be used for exception tables.  */
3534
3535 static void
3536 switch_to_exception_section (const char * ARG_UNUSED (fnname))
3537 {
3538   section *s;
3539
3540   if (exception_section)
3541     s = exception_section;
3542   else
3543     {
3544       /* Compute the section and cache it into exception_section,
3545          unless it depends on the function name.  */
3546       if (targetm.have_named_sections)
3547         {
3548           int flags;
3549
3550           if (EH_TABLES_CAN_BE_READ_ONLY)
3551             {
3552               int tt_format =
3553                 ASM_PREFERRED_EH_DATA_FORMAT (/*code=*/0, /*global=*/1);
3554               flags = ((! flag_pic
3555                         || ((tt_format & 0x70) != DW_EH_PE_absptr
3556                             && (tt_format & 0x70) != DW_EH_PE_aligned))
3557                        ? 0 : SECTION_WRITE);
3558             }
3559           else
3560             flags = SECTION_WRITE;
3561
3562 #ifdef HAVE_LD_EH_GC_SECTIONS
3563           if (flag_function_sections)
3564             {
3565               char *section_name = xmalloc (strlen (fnname) + 32);
3566               sprintf (section_name, ".gcc_except_table.%s", fnname);
3567               s = get_section (section_name, flags, NULL);
3568               free (section_name);
3569             }
3570           else
3571 #endif
3572             exception_section
3573               = s = get_section (".gcc_except_table", flags, NULL);
3574         }
3575       else
3576         exception_section
3577           = s = flag_pic ? data_section : readonly_data_section;
3578     }
3579
3580   switch_to_section (s);
3581 }
3582 #endif
3583
3584
3585 /* Output a reference from an exception table to the type_info object TYPE.
3586    TT_FORMAT and TT_FORMAT_SIZE describe the DWARF encoding method used for
3587    the value.  */
3588
3589 static void
3590 output_ttype (tree type, int tt_format, int tt_format_size)
3591 {
3592   rtx value;
3593   bool public = true;
3594
3595   if (type == NULL_TREE)
3596     value = const0_rtx;
3597   else
3598     {
3599       struct varpool_node *node;
3600
3601       type = lookup_type_for_runtime (type);
3602       value = expand_expr (type, NULL_RTX, VOIDmode, EXPAND_INITIALIZER);
3603
3604       /* Let cgraph know that the rtti decl is used.  Not all of the
3605          paths below go through assemble_integer, which would take
3606          care of this for us.  */
3607       STRIP_NOPS (type);
3608       if (TREE_CODE (type) == ADDR_EXPR)
3609         {
3610           type = TREE_OPERAND (type, 0);
3611           if (TREE_CODE (type) == VAR_DECL)
3612             {
3613               node = varpool_node (type);
3614               if (node)
3615                 varpool_mark_needed_node (node);
3616               public = TREE_PUBLIC (type);
3617             }
3618         }
3619       else
3620         gcc_assert (TREE_CODE (type) == INTEGER_CST);
3621     }
3622
3623   /* Allow the target to override the type table entry format.  */
3624   if (targetm.asm_out.ttype (value))
3625     return;
3626
3627   if (tt_format == DW_EH_PE_absptr || tt_format == DW_EH_PE_aligned)
3628     assemble_integer (value, tt_format_size,
3629                       tt_format_size * BITS_PER_UNIT, 1);
3630   else
3631     dw2_asm_output_encoded_addr_rtx (tt_format, value, public, NULL);
3632 }
3633
3634 void
3635 output_function_exception_table (const char * ARG_UNUSED (fnname))
3636 {
3637   int tt_format, cs_format, lp_format, i, n;
3638 #ifdef HAVE_AS_LEB128
3639   char ttype_label[32];
3640   char cs_after_size_label[32];
3641   char cs_end_label[32];
3642 #else
3643   int call_site_len;
3644 #endif
3645   int have_tt_data;
3646   int tt_format_size = 0;
3647
3648   /* Not all functions need anything.  */
3649   if (! cfun->uses_eh_lsda)
3650     return;
3651
3652   if (eh_personality_libfunc)
3653     assemble_external_libcall (eh_personality_libfunc);
3654
3655 #ifdef TARGET_UNWIND_INFO
3656   /* TODO: Move this into target file.  */
3657   fputs ("\t.personality\t", asm_out_file);
3658   output_addr_const (asm_out_file, eh_personality_libfunc);
3659   fputs ("\n\t.handlerdata\n", asm_out_file);
3660   /* Note that varasm still thinks we're in the function's code section.
3661      The ".endp" directive that will immediately follow will take us back.  */
3662 #else
3663   switch_to_exception_section (fnname);
3664 #endif
3665
3666   /* If the target wants a label to begin the table, emit it here.  */
3667   targetm.asm_out.except_table_label (asm_out_file);
3668
3669   have_tt_data = (VEC_length (tree, cfun->eh->ttype_data) > 0
3670                   || VARRAY_ACTIVE_SIZE (cfun->eh->ehspec_data) > 0);
3671
3672   /* Indicate the format of the @TType entries.  */
3673   if (! have_tt_data)
3674     tt_format = DW_EH_PE_omit;
3675   else
3676     {
3677       tt_format = ASM_PREFERRED_EH_DATA_FORMAT (/*code=*/0, /*global=*/1);
3678 #ifdef HAVE_AS_LEB128
3679       ASM_GENERATE_INTERNAL_LABEL (ttype_label, "LLSDATT",
3680                                    current_function_funcdef_no);
3681 #endif
3682       tt_format_size = size_of_encoded_value (tt_format);
3683
3684       assemble_align (tt_format_size * BITS_PER_UNIT);
3685     }
3686
3687   targetm.asm_out.internal_label (asm_out_file, "LLSDA",
3688                              current_function_funcdef_no);
3689
3690   /* The LSDA header.  */
3691
3692   /* Indicate the format of the landing pad start pointer.  An omitted
3693      field implies @LPStart == @Start.  */
3694   /* Currently we always put @LPStart == @Start.  This field would
3695      be most useful in moving the landing pads completely out of
3696      line to another section, but it could also be used to minimize
3697      the size of uleb128 landing pad offsets.  */
3698   lp_format = DW_EH_PE_omit;
3699   dw2_asm_output_data (1, lp_format, "@LPStart format (%s)",
3700                        eh_data_format_name (lp_format));
3701
3702   /* @LPStart pointer would go here.  */
3703
3704   dw2_asm_output_data (1, tt_format, "@TType format (%s)",
3705                        eh_data_format_name (tt_format));
3706
3707 #ifndef HAVE_AS_LEB128
3708   if (USING_SJLJ_EXCEPTIONS)
3709     call_site_len = sjlj_size_of_call_site_table ();
3710   else
3711     call_site_len = dw2_size_of_call_site_table ();
3712 #endif
3713
3714   /* A pc-relative 4-byte displacement to the @TType data.  */
3715   if (have_tt_data)
3716     {
3717 #ifdef HAVE_AS_LEB128
3718       char ttype_after_disp_label[32];
3719       ASM_GENERATE_INTERNAL_LABEL (ttype_after_disp_label, "LLSDATTD",
3720                                    current_function_funcdef_no);
3721       dw2_asm_output_delta_uleb128 (ttype_label, ttype_after_disp_label,
3722                                     "@TType base offset");
3723       ASM_OUTPUT_LABEL (asm_out_file, ttype_after_disp_label);
3724 #else
3725       /* Ug.  Alignment queers things.  */
3726       unsigned int before_disp, after_disp, last_disp, disp;
3727
3728       before_disp = 1 + 1;
3729       after_disp = (1 + size_of_uleb128 (call_site_len)
3730                     + call_site_len
3731                     + VARRAY_ACTIVE_SIZE (cfun->eh->action_record_data)
3732                     + (VEC_length (tree, cfun->eh->ttype_data)
3733                        * tt_format_size));
3734
3735       disp = after_disp;
3736       do
3737         {
3738           unsigned int disp_size, pad;
3739
3740           last_disp = disp;
3741           disp_size = size_of_uleb128 (disp);
3742           pad = before_disp + disp_size + after_disp;
3743           if (pad % tt_format_size)
3744             pad = tt_format_size - (pad % tt_format_size);
3745           else
3746             pad = 0;
3747           disp = after_disp + pad;
3748         }
3749       while (disp != last_disp);
3750
3751       dw2_asm_output_data_uleb128 (disp, "@TType base offset");
3752 #endif
3753     }
3754
3755   /* Indicate the format of the call-site offsets.  */
3756 #ifdef HAVE_AS_LEB128
3757   cs_format = DW_EH_PE_uleb128;
3758 #else
3759   cs_format = DW_EH_PE_udata4;
3760 #endif
3761   dw2_asm_output_data (1, cs_format, "call-site format (%s)",
3762                        eh_data_format_name (cs_format));
3763
3764 #ifdef HAVE_AS_LEB128
3765   ASM_GENERATE_INTERNAL_LABEL (cs_after_size_label, "LLSDACSB",
3766                                current_function_funcdef_no);
3767   ASM_GENERATE_INTERNAL_LABEL (cs_end_label, "LLSDACSE",
3768                                current_function_funcdef_no);
3769   dw2_asm_output_delta_uleb128 (cs_end_label, cs_after_size_label,
3770                                 "Call-site table length");
3771   ASM_OUTPUT_LABEL (asm_out_file, cs_after_size_label);
3772   if (USING_SJLJ_EXCEPTIONS)
3773     sjlj_output_call_site_table ();
3774   else
3775     dw2_output_call_site_table ();
3776   ASM_OUTPUT_LABEL (asm_out_file, cs_end_label);
3777 #else
3778   dw2_asm_output_data_uleb128 (call_site_len,"Call-site table length");
3779   if (USING_SJLJ_EXCEPTIONS)
3780     sjlj_output_call_site_table ();
3781   else
3782     dw2_output_call_site_table ();
3783 #endif
3784
3785   /* ??? Decode and interpret the data for flag_debug_asm.  */
3786   n = VARRAY_ACTIVE_SIZE (cfun->eh->action_record_data);
3787   for (i = 0; i < n; ++i)
3788     dw2_asm_output_data (1, VARRAY_UCHAR (cfun->eh->action_record_data, i),
3789                          (i ? NULL : "Action record table"));
3790
3791   if (have_tt_data)
3792     assemble_align (tt_format_size * BITS_PER_UNIT);
3793
3794   i = VEC_length (tree, cfun->eh->ttype_data);
3795   while (i-- > 0)
3796     {
3797       tree type = VEC_index (tree, cfun->eh->ttype_data, i);
3798       output_ttype (type, tt_format, tt_format_size);
3799     }
3800
3801 #ifdef HAVE_AS_LEB128
3802   if (have_tt_data)
3803       ASM_OUTPUT_LABEL (asm_out_file, ttype_label);
3804 #endif
3805
3806   /* ??? Decode and interpret the data for flag_debug_asm.  */
3807   n = VARRAY_ACTIVE_SIZE (cfun->eh->ehspec_data);
3808   for (i = 0; i < n; ++i)
3809     {
3810       if (targetm.arm_eabi_unwinder)
3811         {
3812           tree type = VARRAY_TREE (cfun->eh->ehspec_data, i);
3813           output_ttype (type, tt_format, tt_format_size);
3814         }
3815       else
3816         dw2_asm_output_data (1, VARRAY_UCHAR (cfun->eh->ehspec_data, i),
3817                              (i ? NULL : "Exception specification table"));
3818     }
3819
3820   switch_to_section (current_function_section ());
3821 }
3822
3823 void
3824 set_eh_throw_stmt_table (struct function *fun, struct htab *table)
3825 {
3826   fun->eh->throw_stmt_table = table;
3827 }
3828
3829 htab_t
3830 get_eh_throw_stmt_table (struct function *fun)
3831 {
3832   return fun->eh->throw_stmt_table;
3833 }
3834
3835 /* Dump EH information to OUT.  */
3836 void
3837 dump_eh_tree (FILE *out, struct function *fun)
3838 {
3839   struct eh_region *i;
3840   int depth = 0;
3841   static const char * const type_name[] = {"unknown", "cleanup", "try", "catch",
3842                                            "allowed_exceptions", "must_not_throw",
3843                                            "throw"};
3844
3845   i = fun->eh->region_tree;
3846   if (! i)
3847     return;
3848
3849   fprintf (out, "Eh tree:\n");
3850   while (1)
3851     {
3852       fprintf (out, "  %*s %i %s", depth * 2, "",
3853                i->region_number, type_name [(int)i->type]);
3854       if (i->tree_label)
3855         {
3856           fprintf (out, " tree_label:");
3857           print_generic_expr (out, i->tree_label, 0);
3858         }
3859       fprintf (out, "\n");
3860       /* If there are sub-regions, process them.  */
3861       if (i->inner)
3862         i = i->inner, depth++;
3863       /* If there are peers, process them.  */
3864       else if (i->next_peer)
3865         i = i->next_peer;
3866       /* Otherwise, step back up the tree to the next peer.  */
3867       else
3868         {
3869           do {
3870             i = i->outer;
3871             depth--;
3872             if (i == NULL)
3873               return;
3874           } while (i->next_peer == NULL);
3875           i = i->next_peer;
3876         }
3877     }
3878 }
3879
3880 /* Verify some basic invariants on EH datastructures.  Could be extended to
3881    catch more.  */
3882 void
3883 verify_eh_tree (struct function *fun)
3884 {
3885   struct eh_region *i, *outer = NULL;
3886   bool err = false;
3887   int nvisited = 0;
3888   int count = 0;
3889   int j;
3890   int depth = 0;
3891
3892   i = fun->eh->region_tree;
3893   if (! i)
3894     return;
3895   for (j = fun->eh->last_region_number; j > 0; --j)
3896     if ((i = VEC_index (eh_region, cfun->eh->region_array, j)))
3897       {
3898         count++;
3899         if (i->region_number != j)
3900           {
3901             error ("region_array is corrupted for region %i", i->region_number);
3902             err = true;
3903           }
3904       }
3905
3906   while (1)
3907     {
3908       if (VEC_index (eh_region, cfun->eh->region_array, i->region_number) != i)
3909         {
3910           error ("region_array is corrupted for region %i", i->region_number);
3911           err = true;
3912         }
3913       if (i->outer != outer)
3914         {
3915           error ("outer block of region %i is wrong", i->region_number);
3916           err = true;
3917         }
3918       if (i->may_contain_throw && outer && !outer->may_contain_throw)
3919         {
3920           error ("region %i may contain throw and is contained in region that may not",
3921                  i->region_number);
3922           err = true;
3923         }
3924       if (depth < 0)
3925         {
3926           error ("negative nesting depth of region %i", i->region_number);
3927           err = true;
3928         }
3929       nvisited ++;
3930       /* If there are sub-regions, process them.  */
3931       if (i->inner)
3932         outer = i, i = i->inner, depth++;
3933       /* If there are peers, process them.  */
3934       else if (i->next_peer)
3935         i = i->next_peer;
3936       /* Otherwise, step back up the tree to the next peer.  */
3937       else
3938         {
3939           do {
3940             i = i->outer;
3941             depth--;
3942             if (i == NULL)
3943               {
3944                 if (depth != -1)
3945                   {
3946                     error ("tree list ends on depth %i", depth + 1);
3947                     err = true;
3948                   }
3949                 if (count != nvisited)
3950                   {
3951                     error ("array does not match the region tree");
3952                     err = true;
3953                   }
3954                 if (err)
3955                   {
3956                     dump_eh_tree (stderr, fun);
3957                     internal_error ("verify_eh_tree failed");
3958                   }
3959                 return;
3960               }
3961             outer = i->outer;
3962           } while (i->next_peer == NULL);
3963           i = i->next_peer;
3964         }
3965     }
3966 }
3967
3968 /* Initialize unwind_resume_libfunc.  */
3969
3970 void
3971 default_init_unwind_resume_libfunc (void)
3972 {
3973   /* The default c++ routines aren't actually c++ specific, so use those.  */
3974   unwind_resume_libfunc =
3975     init_one_libfunc ( USING_SJLJ_EXCEPTIONS ? "_Unwind_SjLj_Resume"
3976                                              : "_Unwind_Resume");
3977 }
3978
3979 \f
3980 static bool
3981 gate_handle_eh (void)
3982 {
3983   return doing_eh (0);
3984 }
3985
3986 /* Complete generation of exception handling code.  */
3987 static unsigned int
3988 rest_of_handle_eh (void)
3989 {
3990   cleanup_cfg (CLEANUP_NO_INSN_DEL);
3991   finish_eh_generation ();
3992   cleanup_cfg (CLEANUP_NO_INSN_DEL);
3993   return 0;
3994 }
3995
3996 struct tree_opt_pass pass_rtl_eh =
3997 {
3998   "eh",                                 /* name */
3999   gate_handle_eh,                       /* gate */
4000   rest_of_handle_eh,                    /* execute */
4001   NULL,                                 /* sub */
4002   NULL,                                 /* next */
4003   0,                                    /* static_pass_number */
4004   TV_JUMP,                              /* tv_id */
4005   0,                                    /* properties_required */
4006   0,                                    /* properties_provided */
4007   0,                                    /* properties_destroyed */
4008   0,                                    /* todo_flags_start */
4009   TODO_dump_func,                       /* todo_flags_finish */
4010   'h'                                   /* letter */
4011 };
4012
4013 #include "gt-except.h"