OSDN Git Service

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