OSDN Git Service

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