OSDN Git Service

*** empty log message ***
[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
1387   /* Before landing pad creation, each exception handler has its own
1388      label.  After landing pad creation, the exception handlers may
1389      share landing pads.  This is ok, since maybe_remove_eh_handler
1390      only requires the 1-1 mapping before landing pad creation.  */
1391   if (*slot && !cfun->eh->built_landing_pads)
1392     abort ();
1393
1394   *slot = entry;
1395 }
1396
1397 static void
1398 ehl_free (pentry)
1399      PTR pentry;
1400 {
1401   struct ehl_map_entry *entry = (struct ehl_map_entry *)pentry;
1402   LABEL_PRESERVE_P (entry->label) = 0;
1403   free (entry);
1404 }
1405
1406 void
1407 find_exception_handler_labels ()
1408 {
1409   int i;
1410
1411   if (exception_handler_label_map)
1412     htab_empty (exception_handler_label_map);
1413   else
1414     {
1415       /* ??? The expansion factor here (3/2) must be greater than the htab
1416          occupancy factor (4/3) to avoid unnecessary resizing.  */
1417       exception_handler_label_map
1418         = htab_create (cfun->eh->last_region_number * 3 / 2,
1419                        ehl_hash, ehl_eq, ehl_free);
1420     }
1421
1422   if (cfun->eh->region_tree == NULL)
1423     return;
1424
1425   for (i = cfun->eh->last_region_number; i > 0; --i)
1426     {
1427       struct eh_region *region = cfun->eh->region_array[i];
1428       rtx lab;
1429
1430       if (! region || region->region_number != i)
1431         continue;
1432       if (cfun->eh->built_landing_pads)
1433         lab = region->landing_pad;
1434       else
1435         lab = region->label;
1436
1437       if (lab)
1438         add_ehl_entry (lab, region);
1439     }
1440
1441   /* For sjlj exceptions, need the return label to remain live until
1442      after landing pad generation.  */
1443   if (USING_SJLJ_EXCEPTIONS && ! cfun->eh->built_landing_pads)
1444     add_ehl_entry (return_label, NULL);
1445 }
1446
1447 bool
1448 current_function_has_exception_handlers ()
1449 {
1450   int i;
1451
1452   for (i = cfun->eh->last_region_number; i > 0; --i)
1453     {
1454       struct eh_region *region = cfun->eh->region_array[i];
1455
1456       if (! region || region->region_number != i)
1457         continue;
1458       if (region->type != ERT_THROW)
1459         return true;
1460     }
1461
1462   return false;
1463 }
1464 \f
1465 static struct eh_region *
1466 duplicate_eh_region_1 (o, map)
1467      struct eh_region *o;
1468      struct inline_remap *map;
1469 {
1470   struct eh_region *n
1471     = (struct eh_region *) xcalloc (1, sizeof (struct eh_region));
1472
1473   n->region_number = o->region_number + cfun->eh->last_region_number;
1474   n->type = o->type;
1475
1476   switch (n->type)
1477     {
1478     case ERT_CLEANUP:
1479     case ERT_MUST_NOT_THROW:
1480       break;
1481
1482     case ERT_TRY:
1483       if (o->u.try.continue_label)
1484         n->u.try.continue_label
1485           = get_label_from_map (map,
1486                                 CODE_LABEL_NUMBER (o->u.try.continue_label));
1487       break;
1488
1489     case ERT_CATCH:
1490       n->u.catch.type_list = o->u.catch.type_list;
1491       break;
1492
1493     case ERT_ALLOWED_EXCEPTIONS:
1494       n->u.allowed.type_list = o->u.allowed.type_list;
1495       break;
1496
1497     case ERT_THROW:
1498       n->u.throw.type = o->u.throw.type;
1499
1500     default:
1501       abort ();
1502     }
1503
1504   if (o->label)
1505     n->label = get_label_from_map (map, CODE_LABEL_NUMBER (o->label));
1506   if (o->resume)
1507     {
1508       n->resume = map->insn_map[INSN_UID (o->resume)];
1509       if (n->resume == NULL)
1510         abort ();
1511     }
1512
1513   return n;
1514 }
1515
1516 static void
1517 duplicate_eh_region_2 (o, n_array)
1518      struct eh_region *o;
1519      struct eh_region **n_array;
1520 {
1521   struct eh_region *n = n_array[o->region_number];
1522
1523   switch (n->type)
1524     {
1525     case ERT_TRY:
1526       n->u.try.catch = n_array[o->u.try.catch->region_number];
1527       n->u.try.last_catch = n_array[o->u.try.last_catch->region_number];
1528       break;
1529
1530     case ERT_CATCH:
1531       if (o->u.catch.next_catch)
1532         n->u.catch.next_catch = n_array[o->u.catch.next_catch->region_number];
1533       if (o->u.catch.prev_catch)
1534         n->u.catch.prev_catch = n_array[o->u.catch.prev_catch->region_number];
1535       break;
1536
1537     default:
1538       break;
1539     }
1540
1541   if (o->outer)
1542     n->outer = n_array[o->outer->region_number];
1543   if (o->inner)
1544     n->inner = n_array[o->inner->region_number];
1545   if (o->next_peer)
1546     n->next_peer = n_array[o->next_peer->region_number];
1547 }
1548
1549 int
1550 duplicate_eh_regions (ifun, map)
1551      struct function *ifun;
1552      struct inline_remap *map;
1553 {
1554   int ifun_last_region_number = ifun->eh->last_region_number;
1555   struct eh_region **n_array, *root, *cur;
1556   int i;
1557
1558   if (ifun_last_region_number == 0)
1559     return 0;
1560
1561   n_array = xcalloc (ifun_last_region_number + 1, sizeof (*n_array));
1562
1563   for (i = 1; i <= ifun_last_region_number; ++i)
1564     {
1565       cur = ifun->eh->region_array[i];
1566       if (!cur || cur->region_number != i)
1567         continue;
1568       n_array[i] = duplicate_eh_region_1 (cur, map);
1569     }
1570   for (i = 1; i <= ifun_last_region_number; ++i)
1571     {
1572       cur = ifun->eh->region_array[i];
1573       if (!cur || cur->region_number != i)
1574         continue;
1575       duplicate_eh_region_2 (cur, n_array);
1576     }
1577
1578   root = n_array[ifun->eh->region_tree->region_number];
1579   cur = cfun->eh->cur_region;
1580   if (cur)
1581     {
1582       struct eh_region *p = cur->inner;
1583       if (p)
1584         {
1585           while (p->next_peer)
1586             p = p->next_peer;
1587           p->next_peer = root;
1588         }
1589       else
1590         cur->inner = root;
1591
1592       for (i = 1; i <= ifun_last_region_number; ++i)
1593         if (n_array[i] && n_array[i]->outer == NULL)
1594           n_array[i]->outer = cur;
1595     }
1596   else
1597     {
1598       struct eh_region *p = cfun->eh->region_tree;
1599       if (p)
1600         {
1601           while (p->next_peer)
1602             p = p->next_peer;
1603           p->next_peer = root;
1604         }
1605       else
1606         cfun->eh->region_tree = root;
1607     }
1608
1609   free (n_array);
1610
1611   i = cfun->eh->last_region_number;
1612   cfun->eh->last_region_number = i + ifun_last_region_number;
1613   return i;
1614 }
1615
1616 \f
1617 static int
1618 t2r_eq (pentry, pdata)
1619      const PTR pentry;
1620      const PTR pdata;
1621 {
1622   tree entry = (tree) pentry;
1623   tree data = (tree) pdata;
1624
1625   return TREE_PURPOSE (entry) == data;
1626 }
1627
1628 static hashval_t
1629 t2r_hash (pentry)
1630      const PTR pentry;
1631 {
1632   tree entry = (tree) pentry;
1633   return TYPE_HASH (TREE_PURPOSE (entry));
1634 }
1635
1636 static int
1637 t2r_mark_1 (slot, data)
1638      PTR *slot;
1639      PTR data ATTRIBUTE_UNUSED;
1640 {
1641   tree contents = (tree) *slot;
1642   ggc_mark_tree (contents);
1643   return 1;
1644 }
1645
1646 static void
1647 t2r_mark (addr)
1648      PTR addr;
1649 {
1650   htab_traverse (*(htab_t *)addr, t2r_mark_1, NULL);
1651 }
1652
1653 static void
1654 add_type_for_runtime (type)
1655      tree type;
1656 {
1657   tree *slot;
1658
1659   slot = (tree *) htab_find_slot_with_hash (type_to_runtime_map, type,
1660                                             TYPE_HASH (type), INSERT);
1661   if (*slot == NULL)
1662     {
1663       tree runtime = (*lang_eh_runtime_type) (type);
1664       *slot = tree_cons (type, runtime, NULL_TREE);
1665     }
1666 }
1667
1668 static tree
1669 lookup_type_for_runtime (type)
1670      tree type;
1671 {
1672   tree *slot;
1673
1674   slot = (tree *) htab_find_slot_with_hash (type_to_runtime_map, type,
1675                                             TYPE_HASH (type), NO_INSERT);
1676
1677   /* We should have always inserted the data earlier.  */
1678   return TREE_VALUE (*slot);
1679 }
1680
1681 \f
1682 /* Represent an entry in @TTypes for either catch actions
1683    or exception filter actions.  */
1684 struct ttypes_filter
1685 {
1686   tree t;
1687   int filter;
1688 };
1689
1690 /* Compare ENTRY (a ttypes_filter entry in the hash table) with DATA
1691    (a tree) for a @TTypes type node we are thinking about adding.  */
1692
1693 static int
1694 ttypes_filter_eq (pentry, pdata)
1695      const PTR pentry;
1696      const PTR pdata;
1697 {
1698   const struct ttypes_filter *entry = (const struct ttypes_filter *) pentry;
1699   tree data = (tree) pdata;
1700
1701   return entry->t == data;
1702 }
1703
1704 static hashval_t
1705 ttypes_filter_hash (pentry)
1706      const PTR pentry;
1707 {
1708   const struct ttypes_filter *entry = (const struct ttypes_filter *) pentry;
1709   return TYPE_HASH (entry->t);
1710 }
1711
1712 /* Compare ENTRY with DATA (both struct ttypes_filter) for a @TTypes
1713    exception specification list we are thinking about adding.  */
1714 /* ??? Currently we use the type lists in the order given.  Someone
1715    should put these in some canonical order.  */
1716
1717 static int
1718 ehspec_filter_eq (pentry, pdata)
1719      const PTR pentry;
1720      const PTR pdata;
1721 {
1722   const struct ttypes_filter *entry = (const struct ttypes_filter *) pentry;
1723   const struct ttypes_filter *data = (const struct ttypes_filter *) pdata;
1724
1725   return type_list_equal (entry->t, data->t);
1726 }
1727
1728 /* Hash function for exception specification lists.  */
1729
1730 static hashval_t
1731 ehspec_filter_hash (pentry)
1732      const PTR pentry;
1733 {
1734   const struct ttypes_filter *entry = (const struct ttypes_filter *) pentry;
1735   hashval_t h = 0;
1736   tree list;
1737
1738   for (list = entry->t; list ; list = TREE_CHAIN (list))
1739     h = (h << 5) + (h >> 27) + TYPE_HASH (TREE_VALUE (list));
1740   return h;
1741 }
1742
1743 /* Add TYPE to cfun->eh->ttype_data, using TYPES_HASH to speed
1744    up the search.  Return the filter value to be used.  */
1745
1746 static int
1747 add_ttypes_entry (ttypes_hash, type)
1748      htab_t ttypes_hash;
1749      tree type;
1750 {
1751   struct ttypes_filter **slot, *n;
1752
1753   slot = (struct ttypes_filter **)
1754     htab_find_slot_with_hash (ttypes_hash, type, TYPE_HASH (type), INSERT);
1755
1756   if ((n = *slot) == NULL)
1757     {
1758       /* Filter value is a 1 based table index.  */
1759
1760       n = (struct ttypes_filter *) xmalloc (sizeof (*n));
1761       n->t = type;
1762       n->filter = VARRAY_ACTIVE_SIZE (cfun->eh->ttype_data) + 1;
1763       *slot = n;
1764
1765       VARRAY_PUSH_TREE (cfun->eh->ttype_data, type);
1766     }
1767
1768   return n->filter;
1769 }
1770
1771 /* Add LIST to cfun->eh->ehspec_data, using EHSPEC_HASH and TYPES_HASH
1772    to speed up the search.  Return the filter value to be used.  */
1773
1774 static int
1775 add_ehspec_entry (ehspec_hash, ttypes_hash, list)
1776      htab_t ehspec_hash;
1777      htab_t ttypes_hash;
1778      tree list;
1779 {
1780   struct ttypes_filter **slot, *n;
1781   struct ttypes_filter dummy;
1782
1783   dummy.t = list;
1784   slot = (struct ttypes_filter **)
1785     htab_find_slot (ehspec_hash, &dummy, INSERT);
1786
1787   if ((n = *slot) == NULL)
1788     {
1789       /* Filter value is a -1 based byte index into a uleb128 buffer.  */
1790
1791       n = (struct ttypes_filter *) xmalloc (sizeof (*n));
1792       n->t = list;
1793       n->filter = -(VARRAY_ACTIVE_SIZE (cfun->eh->ehspec_data) + 1);
1794       *slot = n;
1795
1796       /* Look up each type in the list and encode its filter
1797          value as a uleb128.  Terminate the list with 0.  */
1798       for (; list ; list = TREE_CHAIN (list))
1799         push_uleb128 (&cfun->eh->ehspec_data,
1800                       add_ttypes_entry (ttypes_hash, TREE_VALUE (list)));
1801       VARRAY_PUSH_UCHAR (cfun->eh->ehspec_data, 0);
1802     }
1803
1804   return n->filter;
1805 }
1806
1807 /* Generate the action filter values to be used for CATCH and
1808    ALLOWED_EXCEPTIONS regions.  When using dwarf2 exception regions,
1809    we use lots of landing pads, and so every type or list can share
1810    the same filter value, which saves table space.  */
1811
1812 static void
1813 assign_filter_values ()
1814 {
1815   int i;
1816   htab_t ttypes, ehspec;
1817
1818   VARRAY_TREE_INIT (cfun->eh->ttype_data, 16, "ttype_data");
1819   VARRAY_UCHAR_INIT (cfun->eh->ehspec_data, 64, "ehspec_data");
1820
1821   ttypes = htab_create (31, ttypes_filter_hash, ttypes_filter_eq, free);
1822   ehspec = htab_create (31, ehspec_filter_hash, ehspec_filter_eq, free);
1823
1824   for (i = cfun->eh->last_region_number; i > 0; --i)
1825     {
1826       struct eh_region *r = cfun->eh->region_array[i];
1827
1828       /* Mind we don't process a region more than once.  */
1829       if (!r || r->region_number != i)
1830         continue;
1831
1832       switch (r->type)
1833         {
1834         case ERT_CATCH:
1835           /* Whatever type_list is (NULL or true list), we build a list
1836              of filters for the region.  */
1837           r->u.catch.filter_list = NULL_TREE;
1838
1839           if (r->u.catch.type_list != NULL)
1840             {
1841               /* Get a filter value for each of the types caught and store
1842                  them in the region's dedicated list.  */
1843               tree tp_node = r->u.catch.type_list;
1844
1845               for (;tp_node; tp_node = TREE_CHAIN (tp_node))
1846                 {
1847                   int flt = add_ttypes_entry (ttypes, TREE_VALUE (tp_node));
1848                   tree flt_node = build_int_2 (flt, 0);
1849
1850                   r->u.catch.filter_list
1851                     = tree_cons (NULL_TREE, flt_node, r->u.catch.filter_list);
1852                 }
1853             }
1854           else
1855             {
1856               /* Get a filter value for the NULL list also since it will need
1857                  an action record anyway.  */
1858               int flt = add_ttypes_entry (ttypes, NULL);
1859               tree flt_node = build_int_2 (flt, 0);
1860
1861               r->u.catch.filter_list
1862                 = tree_cons (NULL_TREE, flt_node, r->u.catch.filter_list);
1863             }
1864
1865           break;
1866
1867         case ERT_ALLOWED_EXCEPTIONS:
1868           r->u.allowed.filter
1869             = add_ehspec_entry (ehspec, ttypes, r->u.allowed.type_list);
1870           break;
1871
1872         default:
1873           break;
1874         }
1875     }
1876
1877   htab_delete (ttypes);
1878   htab_delete (ehspec);
1879 }
1880
1881 static void
1882 build_post_landing_pads ()
1883 {
1884   int i;
1885
1886   for (i = cfun->eh->last_region_number; i > 0; --i)
1887     {
1888       struct eh_region *region = cfun->eh->region_array[i];
1889       rtx seq;
1890
1891       /* Mind we don't process a region more than once.  */
1892       if (!region || region->region_number != i)
1893         continue;
1894
1895       switch (region->type)
1896         {
1897         case ERT_TRY:
1898           /* ??? Collect the set of all non-overlapping catch handlers
1899                all the way up the chain until blocked by a cleanup.  */
1900           /* ??? Outer try regions can share landing pads with inner
1901              try regions if the types are completely non-overlapping,
1902              and there are no intervening cleanups.  */
1903
1904           region->post_landing_pad = gen_label_rtx ();
1905
1906           start_sequence ();
1907
1908           emit_label (region->post_landing_pad);
1909
1910           /* ??? It is mighty inconvenient to call back into the
1911              switch statement generation code in expand_end_case.
1912              Rapid prototyping sez a sequence of ifs.  */
1913           {
1914             struct eh_region *c;
1915             for (c = region->u.try.catch; c ; c = c->u.catch.next_catch)
1916               {
1917                 /* ??? _Unwind_ForcedUnwind wants no match here.  */
1918                 if (c->u.catch.type_list == NULL)
1919                   emit_jump (c->label);
1920                 else
1921                   {
1922                     /* Need for one cmp/jump per type caught. Each type
1923                        list entry has a matching entry in the filter list
1924                        (see assign_filter_values).  */
1925                     tree tp_node = c->u.catch.type_list;
1926                     tree flt_node = c->u.catch.filter_list;
1927
1928                     for (; tp_node; )
1929                       {
1930                         emit_cmp_and_jump_insns
1931                           (cfun->eh->filter,
1932                            GEN_INT (tree_low_cst (TREE_VALUE (flt_node), 0)),
1933                            EQ, NULL_RTX, word_mode, 0, c->label);
1934
1935                         tp_node = TREE_CHAIN (tp_node);
1936                         flt_node = TREE_CHAIN (flt_node);
1937                       }
1938                   }
1939               }
1940           }
1941
1942           /* We delay the generation of the _Unwind_Resume until we generate
1943              landing pads.  We emit a marker here so as to get good control
1944              flow data in the meantime.  */
1945           region->resume
1946             = emit_jump_insn (gen_rtx_RESX (VOIDmode, region->region_number));
1947           emit_barrier ();
1948
1949           seq = get_insns ();
1950           end_sequence ();
1951
1952           emit_insns_before (seq, region->u.try.catch->label);
1953           break;
1954
1955         case ERT_ALLOWED_EXCEPTIONS:
1956           region->post_landing_pad = gen_label_rtx ();
1957
1958           start_sequence ();
1959
1960           emit_label (region->post_landing_pad);
1961
1962           emit_cmp_and_jump_insns (cfun->eh->filter,
1963                                    GEN_INT (region->u.allowed.filter),
1964                                    EQ, NULL_RTX, word_mode, 0, region->label);
1965
1966           /* We delay the generation of the _Unwind_Resume until we generate
1967              landing pads.  We emit a marker here so as to get good control
1968              flow data in the meantime.  */
1969           region->resume
1970             = emit_jump_insn (gen_rtx_RESX (VOIDmode, region->region_number));
1971           emit_barrier ();
1972
1973           seq = get_insns ();
1974           end_sequence ();
1975
1976           emit_insns_before (seq, region->label);
1977           break;
1978
1979         case ERT_CLEANUP:
1980         case ERT_MUST_NOT_THROW:
1981           region->post_landing_pad = region->label;
1982           break;
1983
1984         case ERT_CATCH:
1985         case ERT_THROW:
1986           /* Nothing to do.  */
1987           break;
1988
1989         default:
1990           abort ();
1991         }
1992     }
1993 }
1994
1995 /* Replace RESX patterns with jumps to the next handler if any, or calls to
1996    _Unwind_Resume otherwise.  */
1997
1998 static void
1999 connect_post_landing_pads ()
2000 {
2001   int i;
2002
2003   for (i = cfun->eh->last_region_number; i > 0; --i)
2004     {
2005       struct eh_region *region = cfun->eh->region_array[i];
2006       struct eh_region *outer;
2007       rtx seq;
2008
2009       /* Mind we don't process a region more than once.  */
2010       if (!region || region->region_number != i)
2011         continue;
2012
2013       /* If there is no RESX, or it has been deleted by flow, there's
2014          nothing to fix up.  */
2015       if (! region->resume || INSN_DELETED_P (region->resume))
2016         continue;
2017
2018       /* Search for another landing pad in this function.  */
2019       for (outer = region->outer; outer ; outer = outer->outer)
2020         if (outer->post_landing_pad)
2021           break;
2022
2023       start_sequence ();
2024
2025       if (outer)
2026         emit_jump (outer->post_landing_pad);
2027       else
2028         emit_library_call (unwind_resume_libfunc, LCT_THROW,
2029                            VOIDmode, 1, cfun->eh->exc_ptr, Pmode);
2030
2031       seq = get_insns ();
2032       end_sequence ();
2033       emit_insns_before (seq, region->resume);
2034       delete_insn (region->resume);
2035     }
2036 }
2037
2038 \f
2039 static void
2040 dw2_build_landing_pads ()
2041 {
2042   int i;
2043   unsigned int j;
2044
2045   for (i = cfun->eh->last_region_number; i > 0; --i)
2046     {
2047       struct eh_region *region = cfun->eh->region_array[i];
2048       rtx seq;
2049       bool clobbers_hard_regs = false;
2050
2051       /* Mind we don't process a region more than once.  */
2052       if (!region || region->region_number != i)
2053         continue;
2054
2055       if (region->type != ERT_CLEANUP
2056           && region->type != ERT_TRY
2057           && region->type != ERT_ALLOWED_EXCEPTIONS)
2058         continue;
2059
2060       start_sequence ();
2061
2062       region->landing_pad = gen_label_rtx ();
2063       emit_label (region->landing_pad);
2064
2065 #ifdef HAVE_exception_receiver
2066       if (HAVE_exception_receiver)
2067         emit_insn (gen_exception_receiver ());
2068       else
2069 #endif
2070 #ifdef HAVE_nonlocal_goto_receiver
2071         if (HAVE_nonlocal_goto_receiver)
2072           emit_insn (gen_nonlocal_goto_receiver ());
2073         else
2074 #endif
2075           { /* Nothing */ }
2076
2077       /* If the eh_return data registers are call-saved, then we
2078          won't have considered them clobbered from the call that
2079          threw.  Kill them now.  */
2080       for (j = 0; ; ++j)
2081         {
2082           unsigned r = EH_RETURN_DATA_REGNO (j);
2083           if (r == INVALID_REGNUM)
2084             break;
2085           if (! call_used_regs[r])
2086             {
2087               emit_insn (gen_rtx_CLOBBER (VOIDmode, gen_rtx_REG (Pmode, r)));
2088               clobbers_hard_regs = true;
2089             }
2090         }
2091
2092       if (clobbers_hard_regs)
2093         {
2094           /* @@@ This is a kludge.  Not all machine descriptions define a
2095              blockage insn, but we must not allow the code we just generated
2096              to be reordered by scheduling.  So emit an ASM_INPUT to act as
2097              blockage insn.  */
2098           emit_insn (gen_rtx_ASM_INPUT (VOIDmode, ""));
2099         }
2100
2101       emit_move_insn (cfun->eh->exc_ptr,
2102                       gen_rtx_REG (Pmode, EH_RETURN_DATA_REGNO (0)));
2103       emit_move_insn (cfun->eh->filter,
2104                       gen_rtx_REG (word_mode, EH_RETURN_DATA_REGNO (1)));
2105
2106       seq = get_insns ();
2107       end_sequence ();
2108
2109       emit_insns_before (seq, region->post_landing_pad);
2110     }
2111 }
2112
2113 \f
2114 struct sjlj_lp_info
2115 {
2116   int directly_reachable;
2117   int action_index;
2118   int dispatch_index;
2119   int call_site_index;
2120 };
2121
2122 static bool
2123 sjlj_find_directly_reachable_regions (lp_info)
2124      struct sjlj_lp_info *lp_info;
2125 {
2126   rtx insn;
2127   bool found_one = false;
2128
2129   for (insn = get_insns (); insn ; insn = NEXT_INSN (insn))
2130     {
2131       struct eh_region *region;
2132       enum reachable_code rc;
2133       tree type_thrown;
2134       rtx note;
2135
2136       if (! INSN_P (insn))
2137         continue;
2138
2139       note = find_reg_note (insn, REG_EH_REGION, NULL_RTX);
2140       if (!note || INTVAL (XEXP (note, 0)) <= 0)
2141         continue;
2142
2143       region = cfun->eh->region_array[INTVAL (XEXP (note, 0))];
2144
2145       type_thrown = NULL_TREE;
2146       if (region->type == ERT_THROW)
2147         {
2148           type_thrown = region->u.throw.type;
2149           region = region->outer;
2150         }
2151
2152       /* Find the first containing region that might handle the exception.
2153          That's the landing pad to which we will transfer control.  */
2154       rc = RNL_NOT_CAUGHT;
2155       for (; region; region = region->outer)
2156         {
2157           rc = reachable_next_level (region, type_thrown, 0);
2158           if (rc != RNL_NOT_CAUGHT)
2159             break;
2160         }
2161       if (rc == RNL_MAYBE_CAUGHT || rc == RNL_CAUGHT)
2162         {
2163           lp_info[region->region_number].directly_reachable = 1;
2164           found_one = true;
2165         }
2166     }
2167
2168   return found_one;
2169 }
2170
2171 static void
2172 sjlj_assign_call_site_values (dispatch_label, lp_info)
2173      rtx dispatch_label;
2174      struct sjlj_lp_info *lp_info;
2175 {
2176   htab_t ar_hash;
2177   int i, index;
2178
2179   /* First task: build the action table.  */
2180
2181   VARRAY_UCHAR_INIT (cfun->eh->action_record_data, 64, "action_record_data");
2182   ar_hash = htab_create (31, action_record_hash, action_record_eq, free);
2183
2184   for (i = cfun->eh->last_region_number; i > 0; --i)
2185     if (lp_info[i].directly_reachable)
2186       {
2187         struct eh_region *r = cfun->eh->region_array[i];
2188         r->landing_pad = dispatch_label;
2189         lp_info[i].action_index = collect_one_action_chain (ar_hash, r);
2190         if (lp_info[i].action_index != -1)
2191           cfun->uses_eh_lsda = 1;
2192       }
2193
2194   htab_delete (ar_hash);
2195
2196   /* Next: assign dispatch values.  In dwarf2 terms, this would be the
2197      landing pad label for the region.  For sjlj though, there is one
2198      common landing pad from which we dispatch to the post-landing pads.
2199
2200      A region receives a dispatch index if it is directly reachable
2201      and requires in-function processing.  Regions that share post-landing
2202      pads may share dispatch indices.  */
2203   /* ??? Post-landing pad sharing doesn't actually happen at the moment
2204      (see build_post_landing_pads) so we don't bother checking for it.  */
2205
2206   index = 0;
2207   for (i = cfun->eh->last_region_number; i > 0; --i)
2208     if (lp_info[i].directly_reachable)
2209       lp_info[i].dispatch_index = index++;
2210
2211   /* Finally: assign call-site values.  If dwarf2 terms, this would be
2212      the region number assigned by convert_to_eh_region_ranges, but
2213      handles no-action and must-not-throw differently.  */
2214
2215   call_site_base = 1;
2216   for (i = cfun->eh->last_region_number; i > 0; --i)
2217     if (lp_info[i].directly_reachable)
2218       {
2219         int action = lp_info[i].action_index;
2220
2221         /* Map must-not-throw to otherwise unused call-site index 0.  */
2222         if (action == -2)
2223           index = 0;
2224         /* Map no-action to otherwise unused call-site index -1.  */
2225         else if (action == -1)
2226           index = -1;
2227         /* Otherwise, look it up in the table.  */
2228         else
2229           index = add_call_site (GEN_INT (lp_info[i].dispatch_index), action);
2230
2231         lp_info[i].call_site_index = index;
2232       }
2233 }
2234
2235 static void
2236 sjlj_mark_call_sites (lp_info)
2237      struct sjlj_lp_info *lp_info;
2238 {
2239   int last_call_site = -2;
2240   rtx insn, mem;
2241
2242   for (insn = get_insns (); insn ; insn = NEXT_INSN (insn))
2243     {
2244       struct eh_region *region;
2245       int this_call_site;
2246       rtx note, before, p;
2247
2248       /* Reset value tracking at extended basic block boundaries.  */
2249       if (GET_CODE (insn) == CODE_LABEL)
2250         last_call_site = -2;
2251
2252       if (! INSN_P (insn))
2253         continue;
2254
2255       note = find_reg_note (insn, REG_EH_REGION, NULL_RTX);
2256       if (!note)
2257         {
2258           /* Calls (and trapping insns) without notes are outside any
2259              exception handling region in this function.  Mark them as
2260              no action.  */
2261           if (GET_CODE (insn) == CALL_INSN
2262               || (flag_non_call_exceptions
2263                   && may_trap_p (PATTERN (insn))))
2264             this_call_site = -1;
2265           else
2266             continue;
2267         }
2268       else
2269         {
2270           /* Calls that are known to not throw need not be marked.  */
2271           if (INTVAL (XEXP (note, 0)) <= 0)
2272             continue;
2273
2274           region = cfun->eh->region_array[INTVAL (XEXP (note, 0))];
2275           this_call_site = lp_info[region->region_number].call_site_index;
2276         }
2277
2278       if (this_call_site == last_call_site)
2279         continue;
2280
2281       /* Don't separate a call from it's argument loads.  */
2282       before = insn;
2283       if (GET_CODE (insn) == CALL_INSN)
2284          before = find_first_parameter_load (insn, NULL_RTX);
2285
2286       start_sequence ();
2287       mem = adjust_address (cfun->eh->sjlj_fc, TYPE_MODE (integer_type_node),
2288                             sjlj_fc_call_site_ofs);
2289       emit_move_insn (mem, GEN_INT (this_call_site));
2290       p = get_insns ();
2291       end_sequence ();
2292
2293       emit_insns_before (p, before);
2294       last_call_site = this_call_site;
2295     }
2296 }
2297
2298 /* Construct the SjLj_Function_Context.  */
2299
2300 static void
2301 sjlj_emit_function_enter (dispatch_label)
2302      rtx dispatch_label;
2303 {
2304   rtx fn_begin, fc, mem, seq;
2305
2306   fc = cfun->eh->sjlj_fc;
2307
2308   start_sequence ();
2309
2310   /* We're storing this libcall's address into memory instead of
2311      calling it directly.  Thus, we must call assemble_external_libcall
2312      here, as we can not depend on emit_library_call to do it for us.  */
2313   assemble_external_libcall (eh_personality_libfunc);
2314   mem = adjust_address (fc, Pmode, sjlj_fc_personality_ofs);
2315   emit_move_insn (mem, eh_personality_libfunc);
2316
2317   mem = adjust_address (fc, Pmode, sjlj_fc_lsda_ofs);
2318   if (cfun->uses_eh_lsda)
2319     {
2320       char buf[20];
2321       ASM_GENERATE_INTERNAL_LABEL (buf, "LLSDA", sjlj_funcdef_number);
2322       emit_move_insn (mem, gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (buf)));
2323     }
2324   else
2325     emit_move_insn (mem, const0_rtx);
2326
2327 #ifdef DONT_USE_BUILTIN_SETJMP
2328   {
2329     rtx x, note;
2330     x = emit_library_call_value (setjmp_libfunc, NULL_RTX, LCT_RETURNS_TWICE,
2331                                  TYPE_MODE (integer_type_node), 1,
2332                                  plus_constant (XEXP (fc, 0),
2333                                                 sjlj_fc_jbuf_ofs), Pmode);
2334
2335     note = emit_note (NULL, NOTE_INSN_EXPECTED_VALUE);
2336     NOTE_EXPECTED_VALUE (note) = gen_rtx_EQ (VOIDmode, x, const0_rtx);
2337
2338     emit_cmp_and_jump_insns (x, const0_rtx, NE, 0,
2339                              TYPE_MODE (integer_type_node), 0, dispatch_label);
2340   }
2341 #else
2342   expand_builtin_setjmp_setup (plus_constant (XEXP (fc, 0), sjlj_fc_jbuf_ofs),
2343                                dispatch_label);
2344 #endif
2345
2346   emit_library_call (unwind_sjlj_register_libfunc, LCT_NORMAL, VOIDmode,
2347                      1, XEXP (fc, 0), Pmode);
2348
2349   seq = get_insns ();
2350   end_sequence ();
2351
2352   /* ??? Instead of doing this at the beginning of the function,
2353      do this in a block that is at loop level 0 and dominates all
2354      can_throw_internal instructions.  */
2355
2356   for (fn_begin = get_insns (); ; fn_begin = NEXT_INSN (fn_begin))
2357     if (GET_CODE (fn_begin) == NOTE
2358         && NOTE_LINE_NUMBER (fn_begin) == NOTE_INSN_FUNCTION_BEG)
2359       break;
2360   emit_insns_after (seq, fn_begin);
2361 }
2362
2363 /* Call back from expand_function_end to know where we should put
2364    the call to unwind_sjlj_unregister_libfunc if needed.  */
2365
2366 void
2367 sjlj_emit_function_exit_after (after)
2368      rtx after;
2369 {
2370   cfun->eh->sjlj_exit_after = after;
2371 }
2372
2373 static void
2374 sjlj_emit_function_exit ()
2375 {
2376   rtx seq;
2377
2378   start_sequence ();
2379
2380   emit_library_call (unwind_sjlj_unregister_libfunc, LCT_NORMAL, VOIDmode,
2381                      1, XEXP (cfun->eh->sjlj_fc, 0), Pmode);
2382
2383   seq = get_insns ();
2384   end_sequence ();
2385
2386   /* ??? Really this can be done in any block at loop level 0 that
2387      post-dominates all can_throw_internal instructions.  This is
2388      the last possible moment.  */
2389
2390   emit_insns_after (seq, cfun->eh->sjlj_exit_after);
2391 }
2392
2393 static void
2394 sjlj_emit_dispatch_table (dispatch_label, lp_info)
2395      rtx dispatch_label;
2396      struct sjlj_lp_info *lp_info;
2397 {
2398   int i, first_reachable;
2399   rtx mem, dispatch, seq, fc;
2400
2401   fc = cfun->eh->sjlj_fc;
2402
2403   start_sequence ();
2404
2405   emit_label (dispatch_label);
2406
2407 #ifndef DONT_USE_BUILTIN_SETJMP
2408   expand_builtin_setjmp_receiver (dispatch_label);
2409 #endif
2410
2411   /* Load up dispatch index, exc_ptr and filter values from the
2412      function context.  */
2413   mem = adjust_address (fc, TYPE_MODE (integer_type_node),
2414                         sjlj_fc_call_site_ofs);
2415   dispatch = copy_to_reg (mem);
2416
2417   mem = adjust_address (fc, word_mode, sjlj_fc_data_ofs);
2418   if (word_mode != Pmode)
2419     {
2420 #ifdef POINTERS_EXTEND_UNSIGNED
2421       mem = convert_memory_address (Pmode, mem);
2422 #else
2423       mem = convert_to_mode (Pmode, mem, 0);
2424 #endif
2425     }
2426   emit_move_insn (cfun->eh->exc_ptr, mem);
2427
2428   mem = adjust_address (fc, word_mode, sjlj_fc_data_ofs + UNITS_PER_WORD);
2429   emit_move_insn (cfun->eh->filter, mem);
2430
2431   /* Jump to one of the directly reachable regions.  */
2432   /* ??? This really ought to be using a switch statement.  */
2433
2434   first_reachable = 0;
2435   for (i = cfun->eh->last_region_number; i > 0; --i)
2436     {
2437       if (! lp_info[i].directly_reachable)
2438         continue;
2439
2440       if (! first_reachable)
2441         {
2442           first_reachable = i;
2443           continue;
2444         }
2445
2446       emit_cmp_and_jump_insns (dispatch, GEN_INT (lp_info[i].dispatch_index),
2447                                EQ, NULL_RTX, TYPE_MODE (integer_type_node), 0,
2448                                cfun->eh->region_array[i]->post_landing_pad);
2449     }
2450
2451   seq = get_insns ();
2452   end_sequence ();
2453
2454   emit_insns_before (seq, (cfun->eh->region_array[first_reachable]
2455                            ->post_landing_pad));
2456 }
2457
2458 static void
2459 sjlj_build_landing_pads ()
2460 {
2461   struct sjlj_lp_info *lp_info;
2462
2463   lp_info = (struct sjlj_lp_info *) xcalloc (cfun->eh->last_region_number + 1,
2464                                              sizeof (struct sjlj_lp_info));
2465
2466   if (sjlj_find_directly_reachable_regions (lp_info))
2467     {
2468       rtx dispatch_label = gen_label_rtx ();
2469
2470       cfun->eh->sjlj_fc
2471         = assign_stack_local (TYPE_MODE (sjlj_fc_type_node),
2472                               int_size_in_bytes (sjlj_fc_type_node),
2473                               TYPE_ALIGN (sjlj_fc_type_node));
2474
2475       sjlj_assign_call_site_values (dispatch_label, lp_info);
2476       sjlj_mark_call_sites (lp_info);
2477
2478       sjlj_emit_function_enter (dispatch_label);
2479       sjlj_emit_dispatch_table (dispatch_label, lp_info);
2480       sjlj_emit_function_exit ();
2481     }
2482
2483   free (lp_info);
2484 }
2485
2486 void
2487 finish_eh_generation ()
2488 {
2489   /* Nothing to do if no regions created.  */
2490   if (cfun->eh->region_tree == NULL)
2491     return;
2492
2493   /* The object here is to provide find_basic_blocks with detailed
2494      information (via reachable_handlers) on how exception control
2495      flows within the function.  In this first pass, we can include
2496      type information garnered from ERT_THROW and ERT_ALLOWED_EXCEPTIONS
2497      regions, and hope that it will be useful in deleting unreachable
2498      handlers.  Subsequently, we will generate landing pads which will
2499      connect many of the handlers, and then type information will not
2500      be effective.  Still, this is a win over previous implementations.  */
2501
2502   rebuild_jump_labels (get_insns ());
2503   find_basic_blocks (get_insns (), max_reg_num (), 0);
2504   cleanup_cfg (CLEANUP_PRE_LOOP | CLEANUP_NO_INSN_DEL);
2505
2506   /* These registers are used by the landing pads.  Make sure they
2507      have been generated.  */
2508   get_exception_pointer (cfun);
2509   get_exception_filter (cfun);
2510
2511   /* Construct the landing pads.  */
2512
2513   assign_filter_values ();
2514   build_post_landing_pads ();
2515   connect_post_landing_pads ();
2516   if (USING_SJLJ_EXCEPTIONS)
2517     sjlj_build_landing_pads ();
2518   else
2519     dw2_build_landing_pads ();
2520
2521   cfun->eh->built_landing_pads = 1;
2522
2523   /* We've totally changed the CFG.  Start over.  */
2524   find_exception_handler_labels ();
2525   rebuild_jump_labels (get_insns ());
2526   find_basic_blocks (get_insns (), max_reg_num (), 0);
2527   cleanup_cfg (CLEANUP_PRE_LOOP | CLEANUP_NO_INSN_DEL);
2528 }
2529 \f
2530 static hashval_t
2531 ehl_hash (pentry)
2532      const PTR pentry;
2533 {
2534   struct ehl_map_entry *entry = (struct ehl_map_entry *) pentry;
2535
2536   /* 2^32 * ((sqrt(5) - 1) / 2) */
2537   const hashval_t scaled_golden_ratio = 0x9e3779b9;
2538   return CODE_LABEL_NUMBER (entry->label) * scaled_golden_ratio;
2539 }
2540
2541 static int
2542 ehl_eq (pentry, pdata)
2543      const PTR pentry;
2544      const PTR pdata;
2545 {
2546   struct ehl_map_entry *entry = (struct ehl_map_entry *) pentry;
2547   struct ehl_map_entry *data = (struct ehl_map_entry *) pdata;
2548
2549   return entry->label == data->label;
2550 }
2551
2552 /* This section handles removing dead code for flow.  */
2553
2554 /* Remove LABEL from exception_handler_label_map.  */
2555
2556 static void
2557 remove_exception_handler_label (label)
2558      rtx label;
2559 {
2560   struct ehl_map_entry **slot, tmp;
2561
2562   /* If exception_handler_label_map was not built yet,
2563      there is nothing to do.  */
2564   if (exception_handler_label_map == NULL)
2565     return;
2566
2567   tmp.label = label;
2568   slot = (struct ehl_map_entry **)
2569     htab_find_slot (exception_handler_label_map, &tmp, NO_INSERT);
2570   if (! slot)
2571     abort ();
2572
2573   htab_clear_slot (exception_handler_label_map, (void **) slot);
2574 }
2575
2576 /* Splice REGION from the region tree etc.  */
2577
2578 static void
2579 remove_eh_handler (region)
2580      struct eh_region *region;
2581 {
2582   struct eh_region **pp, **pp_start, *p, *outer, *inner;
2583   rtx lab;
2584
2585   /* For the benefit of efficiently handling REG_EH_REGION notes,
2586      replace this region in the region array with its containing
2587      region.  Note that previous region deletions may result in
2588      multiple copies of this region in the array, so we have a
2589      list of alternate numbers by which we are known.  */
2590
2591   outer = region->outer;
2592   cfun->eh->region_array[region->region_number] = outer;
2593   if (region->aka)
2594     {
2595       int i;
2596       EXECUTE_IF_SET_IN_BITMAP (region->aka, 0, i,
2597         { cfun->eh->region_array[i] = outer; });
2598     }
2599
2600   if (outer)
2601     {
2602       if (!outer->aka)
2603         outer->aka = BITMAP_XMALLOC ();
2604       if (region->aka)
2605         bitmap_a_or_b (outer->aka, outer->aka, region->aka);
2606       bitmap_set_bit (outer->aka, region->region_number);
2607     }
2608
2609   if (cfun->eh->built_landing_pads)
2610     lab = region->landing_pad;
2611   else
2612     lab = region->label;
2613   if (lab)
2614     remove_exception_handler_label (lab);
2615
2616   if (outer)
2617     pp_start = &outer->inner;
2618   else
2619     pp_start = &cfun->eh->region_tree;
2620   for (pp = pp_start, p = *pp; p != region; pp = &p->next_peer, p = *pp)
2621     continue;
2622   *pp = region->next_peer;
2623
2624   inner = region->inner;
2625   if (inner)
2626     {
2627       for (p = inner; p->next_peer ; p = p->next_peer)
2628         p->outer = outer;
2629       p->outer = outer;
2630
2631       p->next_peer = *pp_start;
2632       *pp_start = inner;
2633     }
2634
2635   if (region->type == ERT_CATCH)
2636     {
2637       struct eh_region *try, *next, *prev;
2638
2639       for (try = region->next_peer;
2640            try->type == ERT_CATCH;
2641            try = try->next_peer)
2642         continue;
2643       if (try->type != ERT_TRY)
2644         abort ();
2645
2646       next = region->u.catch.next_catch;
2647       prev = region->u.catch.prev_catch;
2648
2649       if (next)
2650         next->u.catch.prev_catch = prev;
2651       else
2652         try->u.try.last_catch = prev;
2653       if (prev)
2654         prev->u.catch.next_catch = next;
2655       else
2656         {
2657           try->u.try.catch = next;
2658           if (! next)
2659             remove_eh_handler (try);
2660         }
2661     }
2662
2663   free_region (region);
2664 }
2665
2666 /* LABEL heads a basic block that is about to be deleted.  If this
2667    label corresponds to an exception region, we may be able to
2668    delete the region.  */
2669
2670 void
2671 maybe_remove_eh_handler (label)
2672      rtx label;
2673 {
2674   struct ehl_map_entry **slot, tmp;
2675   struct eh_region *region;
2676
2677   /* ??? After generating landing pads, it's not so simple to determine
2678      if the region data is completely unused.  One must examine the
2679      landing pad and the post landing pad, and whether an inner try block
2680      is referencing the catch handlers directly.  */
2681   if (cfun->eh->built_landing_pads)
2682     return;
2683
2684   tmp.label = label;
2685   slot = (struct ehl_map_entry **)
2686     htab_find_slot (exception_handler_label_map, &tmp, NO_INSERT);
2687   if (! slot)
2688     return;
2689   region = (*slot)->region;
2690   if (! region)
2691     return;
2692
2693   /* Flow will want to remove MUST_NOT_THROW regions as unreachable
2694      because there is no path to the fallback call to terminate.
2695      But the region continues to affect call-site data until there
2696      are no more contained calls, which we don't see here.  */
2697   if (region->type == ERT_MUST_NOT_THROW)
2698     {
2699       htab_clear_slot (exception_handler_label_map, (void **) slot);
2700       region->label = NULL_RTX;
2701     }
2702   else
2703     remove_eh_handler (region);
2704 }
2705
2706 /* Invokes CALLBACK for every exception handler label.  Only used by old
2707    loop hackery; should not be used by new code.  */
2708
2709 void
2710 for_each_eh_label (callback)
2711      void (*callback) PARAMS ((rtx));
2712 {
2713   htab_traverse (exception_handler_label_map, for_each_eh_label_1,
2714                  (void *)callback);
2715 }
2716
2717 static int
2718 for_each_eh_label_1 (pentry, data)
2719      PTR *pentry;
2720      PTR data;
2721 {
2722   struct ehl_map_entry *entry = *(struct ehl_map_entry **)pentry;
2723   void (*callback) PARAMS ((rtx)) = (void (*) PARAMS ((rtx))) data;
2724
2725   (*callback) (entry->label);
2726   return 1;
2727 }
2728 \f
2729 /* This section describes CFG exception edges for flow.  */
2730
2731 /* For communicating between calls to reachable_next_level.  */
2732 struct reachable_info
2733 {
2734   tree types_caught;
2735   tree types_allowed;
2736   rtx handlers;
2737 };
2738
2739 /* A subroutine of reachable_next_level.  Return true if TYPE, or a
2740    base class of TYPE, is in HANDLED.  */
2741
2742 static int
2743 check_handled (handled, type)
2744      tree handled, type;
2745 {
2746   tree t;
2747
2748   /* We can check for exact matches without front-end help.  */
2749   if (! lang_eh_type_covers)
2750     {
2751       for (t = handled; t ; t = TREE_CHAIN (t))
2752         if (TREE_VALUE (t) == type)
2753           return 1;
2754     }
2755   else
2756     {
2757       for (t = handled; t ; t = TREE_CHAIN (t))
2758         if ((*lang_eh_type_covers) (TREE_VALUE (t), type))
2759           return 1;
2760     }
2761
2762   return 0;
2763 }
2764
2765 /* A subroutine of reachable_next_level.  If we are collecting a list
2766    of handlers, add one.  After landing pad generation, reference
2767    it instead of the handlers themselves.  Further, the handlers are
2768    all wired together, so by referencing one, we've got them all.
2769    Before landing pad generation we reference each handler individually.
2770
2771    LP_REGION contains the landing pad; REGION is the handler.  */
2772
2773 static void
2774 add_reachable_handler (info, lp_region, region)
2775      struct reachable_info *info;
2776      struct eh_region *lp_region;
2777      struct eh_region *region;
2778 {
2779   if (! info)
2780     return;
2781
2782   if (cfun->eh->built_landing_pads)
2783     {
2784       if (! info->handlers)
2785         info->handlers = alloc_INSN_LIST (lp_region->landing_pad, NULL_RTX);
2786     }
2787   else
2788     info->handlers = alloc_INSN_LIST (region->label, info->handlers);
2789 }
2790
2791 /* Process one level of exception regions for reachability.
2792    If TYPE_THROWN is non-null, then it is the *exact* type being
2793    propagated.  If INFO is non-null, then collect handler labels
2794    and caught/allowed type information between invocations.  */
2795
2796 static enum reachable_code
2797 reachable_next_level (region, type_thrown, info)
2798      struct eh_region *region;
2799      tree type_thrown;
2800      struct reachable_info *info;
2801 {
2802   switch (region->type)
2803     {
2804     case ERT_CLEANUP:
2805       /* Before landing-pad generation, we model control flow
2806          directly to the individual handlers.  In this way we can
2807          see that catch handler types may shadow one another.  */
2808       add_reachable_handler (info, region, region);
2809       return RNL_MAYBE_CAUGHT;
2810
2811     case ERT_TRY:
2812       {
2813         struct eh_region *c;
2814         enum reachable_code ret = RNL_NOT_CAUGHT;
2815
2816         for (c = region->u.try.catch; c ; c = c->u.catch.next_catch)
2817           {
2818             /* A catch-all handler ends the search.  */
2819             /* ??? _Unwind_ForcedUnwind will want outer cleanups
2820                to be run as well.  */
2821             if (c->u.catch.type_list == NULL)
2822               {
2823                 add_reachable_handler (info, region, c);
2824                 return RNL_CAUGHT;
2825               }
2826
2827             if (type_thrown)
2828               {
2829                 /* If we have at least one type match, end the search.  */
2830                 tree tp_node = c->u.catch.type_list;
2831
2832                 for (; tp_node; tp_node = TREE_CHAIN (tp_node))
2833                   {
2834                     tree type = TREE_VALUE (tp_node);
2835
2836                     if (type == type_thrown
2837                         || (lang_eh_type_covers
2838                             && (*lang_eh_type_covers) (type, type_thrown)))
2839                       {
2840                         add_reachable_handler (info, region, c);
2841                         return RNL_CAUGHT;
2842                       }
2843                   }
2844
2845                 /* If we have definitive information of a match failure,
2846                    the catch won't trigger.  */
2847                 if (lang_eh_type_covers)
2848                   return RNL_NOT_CAUGHT;
2849               }
2850
2851             /* At this point, we either don't know what type is thrown or
2852                don't have front-end assistance to help deciding if it is
2853                covered by one of the types in the list for this region.
2854
2855                We'd then like to add this region to the list of reachable
2856                handlers since it is indeed potentially reachable based on the
2857                information we have.
2858
2859                Actually, this handler is for sure not reachable if all the
2860                types it matches have already been caught. That is, it is only
2861                potentially reachable if at least one of the types it catches
2862                has not been previously caught.  */
2863
2864             if (! info)
2865               ret = RNL_MAYBE_CAUGHT;
2866             else
2867               {
2868                 tree tp_node = c->u.catch.type_list;
2869                 bool maybe_reachable = false;
2870
2871                 /* Compute the potential reachability of this handler and
2872                    update the list of types caught at the same time.  */
2873                 for (; tp_node; tp_node = TREE_CHAIN (tp_node))
2874                   {
2875                     tree type = TREE_VALUE (tp_node);
2876
2877                     if (! check_handled (info->types_caught, type))
2878                       {
2879                         info->types_caught
2880                           = tree_cons (NULL, type, info->types_caught);
2881
2882                         maybe_reachable = true;
2883                       }
2884                   }
2885
2886                 if (maybe_reachable)
2887                   {
2888                     add_reachable_handler (info, region, c);
2889
2890                     /* ??? If the catch type is a base class of every allowed
2891                        type, then we know we can stop the search.  */
2892                     ret = RNL_MAYBE_CAUGHT;
2893                   }
2894               }
2895           }
2896
2897         return ret;
2898       }
2899
2900     case ERT_ALLOWED_EXCEPTIONS:
2901       /* An empty list of types definitely ends the search.  */
2902       if (region->u.allowed.type_list == NULL_TREE)
2903         {
2904           add_reachable_handler (info, region, region);
2905           return RNL_CAUGHT;
2906         }
2907
2908       /* Collect a list of lists of allowed types for use in detecting
2909          when a catch may be transformed into a catch-all.  */
2910       if (info)
2911         info->types_allowed = tree_cons (NULL_TREE,
2912                                          region->u.allowed.type_list,
2913                                          info->types_allowed);
2914
2915       /* If we have definitive information about the type hierarchy,
2916          then we can tell if the thrown type will pass through the
2917          filter.  */
2918       if (type_thrown && lang_eh_type_covers)
2919         {
2920           if (check_handled (region->u.allowed.type_list, type_thrown))
2921             return RNL_NOT_CAUGHT;
2922           else
2923             {
2924               add_reachable_handler (info, region, region);
2925               return RNL_CAUGHT;
2926             }
2927         }
2928
2929       add_reachable_handler (info, region, region);
2930       return RNL_MAYBE_CAUGHT;
2931
2932     case ERT_CATCH:
2933       /* Catch regions are handled by their controling try region.  */
2934       return RNL_NOT_CAUGHT;
2935
2936     case ERT_MUST_NOT_THROW:
2937       /* Here we end our search, since no exceptions may propagate.
2938          If we've touched down at some landing pad previous, then the
2939          explicit function call we generated may be used.  Otherwise
2940          the call is made by the runtime.  */
2941       if (info && info->handlers)
2942         {
2943           add_reachable_handler (info, region, region);
2944           return RNL_CAUGHT;
2945         }
2946       else
2947         return RNL_BLOCKED;
2948
2949     case ERT_THROW:
2950     case ERT_FIXUP:
2951     case ERT_UNKNOWN:
2952       /* Shouldn't see these here.  */
2953       break;
2954     }
2955
2956   abort ();
2957 }
2958
2959 /* Retrieve a list of labels of exception handlers which can be
2960    reached by a given insn.  */
2961
2962 rtx
2963 reachable_handlers (insn)
2964      rtx insn;
2965 {
2966   struct reachable_info info;
2967   struct eh_region *region;
2968   tree type_thrown;
2969   int region_number;
2970
2971   if (GET_CODE (insn) == JUMP_INSN
2972       && GET_CODE (PATTERN (insn)) == RESX)
2973     region_number = XINT (PATTERN (insn), 0);
2974   else
2975     {
2976       rtx note = find_reg_note (insn, REG_EH_REGION, NULL_RTX);
2977       if (!note || INTVAL (XEXP (note, 0)) <= 0)
2978         return NULL;
2979       region_number = INTVAL (XEXP (note, 0));
2980     }
2981
2982   memset (&info, 0, sizeof (info));
2983
2984   region = cfun->eh->region_array[region_number];
2985
2986   type_thrown = NULL_TREE;
2987   if (GET_CODE (insn) == JUMP_INSN
2988       && GET_CODE (PATTERN (insn)) == RESX)
2989     {
2990       /* A RESX leaves a region instead of entering it.  Thus the
2991          region itself may have been deleted out from under us.  */
2992       if (region == NULL)
2993         return NULL;
2994       region = region->outer;
2995     }
2996   else if (region->type == ERT_THROW)
2997     {
2998       type_thrown = region->u.throw.type;
2999       region = region->outer;
3000     }
3001
3002   for (; region; region = region->outer)
3003     if (reachable_next_level (region, type_thrown, &info) >= RNL_CAUGHT)
3004       break;
3005
3006   return info.handlers;
3007 }
3008
3009 /* Determine if the given INSN can throw an exception that is caught
3010    within the function.  */
3011
3012 bool
3013 can_throw_internal (insn)
3014      rtx insn;
3015 {
3016   struct eh_region *region;
3017   tree type_thrown;
3018   rtx note;
3019
3020   if (! INSN_P (insn))
3021     return false;
3022
3023   if (GET_CODE (insn) == INSN
3024       && GET_CODE (PATTERN (insn)) == SEQUENCE)
3025     insn = XVECEXP (PATTERN (insn), 0, 0);
3026
3027   if (GET_CODE (insn) == CALL_INSN
3028       && GET_CODE (PATTERN (insn)) == CALL_PLACEHOLDER)
3029     {
3030       int i;
3031       for (i = 0; i < 3; ++i)
3032         {
3033           rtx sub = XEXP (PATTERN (insn), i);
3034           for (; sub ; sub = NEXT_INSN (sub))
3035             if (can_throw_internal (sub))
3036               return true;
3037         }
3038       return false;
3039     }
3040
3041   /* Every insn that might throw has an EH_REGION note.  */
3042   note = find_reg_note (insn, REG_EH_REGION, NULL_RTX);
3043   if (!note || INTVAL (XEXP (note, 0)) <= 0)
3044     return false;
3045
3046   region = cfun->eh->region_array[INTVAL (XEXP (note, 0))];
3047
3048   type_thrown = NULL_TREE;
3049   if (region->type == ERT_THROW)
3050     {
3051       type_thrown = region->u.throw.type;
3052       region = region->outer;
3053     }
3054
3055   /* If this exception is ignored by each and every containing region,
3056      then control passes straight out.  The runtime may handle some
3057      regions, which also do not require processing internally.  */
3058   for (; region; region = region->outer)
3059     {
3060       enum reachable_code how = reachable_next_level (region, type_thrown, 0);
3061       if (how == RNL_BLOCKED)
3062         return false;
3063       if (how != RNL_NOT_CAUGHT)
3064         return true;
3065     }
3066
3067   return false;
3068 }
3069
3070 /* Determine if the given INSN can throw an exception that is
3071    visible outside the function.  */
3072
3073 bool
3074 can_throw_external (insn)
3075      rtx insn;
3076 {
3077   struct eh_region *region;
3078   tree type_thrown;
3079   rtx note;
3080
3081   if (! INSN_P (insn))
3082     return false;
3083
3084   if (GET_CODE (insn) == INSN
3085       && GET_CODE (PATTERN (insn)) == SEQUENCE)
3086     insn = XVECEXP (PATTERN (insn), 0, 0);
3087
3088   if (GET_CODE (insn) == CALL_INSN
3089       && GET_CODE (PATTERN (insn)) == CALL_PLACEHOLDER)
3090     {
3091       int i;
3092       for (i = 0; i < 3; ++i)
3093         {
3094           rtx sub = XEXP (PATTERN (insn), i);
3095           for (; sub ; sub = NEXT_INSN (sub))
3096             if (can_throw_external (sub))
3097               return true;
3098         }
3099       return false;
3100     }
3101
3102   note = find_reg_note (insn, REG_EH_REGION, NULL_RTX);
3103   if (!note)
3104     {
3105       /* Calls (and trapping insns) without notes are outside any
3106          exception handling region in this function.  We have to
3107          assume it might throw.  Given that the front end and middle
3108          ends mark known NOTHROW functions, this isn't so wildly
3109          inaccurate.  */
3110       return (GET_CODE (insn) == CALL_INSN
3111               || (flag_non_call_exceptions
3112                   && may_trap_p (PATTERN (insn))));
3113     }
3114   if (INTVAL (XEXP (note, 0)) <= 0)
3115     return false;
3116
3117   region = cfun->eh->region_array[INTVAL (XEXP (note, 0))];
3118
3119   type_thrown = NULL_TREE;
3120   if (region->type == ERT_THROW)
3121     {
3122       type_thrown = region->u.throw.type;
3123       region = region->outer;
3124     }
3125
3126   /* If the exception is caught or blocked by any containing region,
3127      then it is not seen by any calling function.  */
3128   for (; region ; region = region->outer)
3129     if (reachable_next_level (region, type_thrown, NULL) >= RNL_CAUGHT)
3130       return false;
3131
3132   return true;
3133 }
3134
3135 /* True if nothing in this function can throw outside this function.  */
3136
3137 bool
3138 nothrow_function_p ()
3139 {
3140   rtx insn;
3141
3142   if (! flag_exceptions)
3143     return true;
3144
3145   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
3146     if (can_throw_external (insn))
3147       return false;
3148   for (insn = current_function_epilogue_delay_list; insn;
3149        insn = XEXP (insn, 1))
3150     if (can_throw_external (XEXP (insn, 0)))
3151       return false;
3152
3153   return true;
3154 }
3155
3156 \f
3157 /* Various hooks for unwind library.  */
3158
3159 /* Do any necessary initialization to access arbitrary stack frames.
3160    On the SPARC, this means flushing the register windows.  */
3161
3162 void
3163 expand_builtin_unwind_init ()
3164 {
3165   /* Set this so all the registers get saved in our frame; we need to be
3166      able to copy the saved values for any registers from frames we unwind.  */
3167   current_function_has_nonlocal_label = 1;
3168
3169 #ifdef SETUP_FRAME_ADDRESSES
3170   SETUP_FRAME_ADDRESSES ();
3171 #endif
3172 }
3173
3174 rtx
3175 expand_builtin_eh_return_data_regno (arglist)
3176      tree arglist;
3177 {
3178   tree which = TREE_VALUE (arglist);
3179   unsigned HOST_WIDE_INT iwhich;
3180
3181   if (TREE_CODE (which) != INTEGER_CST)
3182     {
3183       error ("argument of `__builtin_eh_return_regno' must be constant");
3184       return constm1_rtx;
3185     }
3186
3187   iwhich = tree_low_cst (which, 1);
3188   iwhich = EH_RETURN_DATA_REGNO (iwhich);
3189   if (iwhich == INVALID_REGNUM)
3190     return constm1_rtx;
3191
3192 #ifdef DWARF_FRAME_REGNUM
3193   iwhich = DWARF_FRAME_REGNUM (iwhich);
3194 #else
3195   iwhich = DBX_REGISTER_NUMBER (iwhich);
3196 #endif
3197
3198   return GEN_INT (iwhich);
3199 }
3200
3201 /* Given a value extracted from the return address register or stack slot,
3202    return the actual address encoded in that value.  */
3203
3204 rtx
3205 expand_builtin_extract_return_addr (addr_tree)
3206      tree addr_tree;
3207 {
3208   rtx addr = expand_expr (addr_tree, NULL_RTX, Pmode, 0);
3209
3210   /* First mask out any unwanted bits.  */
3211 #ifdef MASK_RETURN_ADDR
3212   expand_and (Pmode, addr, MASK_RETURN_ADDR, addr);
3213 #endif
3214
3215   /* Then adjust to find the real return address.  */
3216 #if defined (RETURN_ADDR_OFFSET)
3217   addr = plus_constant (addr, RETURN_ADDR_OFFSET);
3218 #endif
3219
3220   return addr;
3221 }
3222
3223 /* Given an actual address in addr_tree, do any necessary encoding
3224    and return the value to be stored in the return address register or
3225    stack slot so the epilogue will return to that address.  */
3226
3227 rtx
3228 expand_builtin_frob_return_addr (addr_tree)
3229      tree addr_tree;
3230 {
3231   rtx addr = expand_expr (addr_tree, NULL_RTX, ptr_mode, 0);
3232
3233 #ifdef POINTERS_EXTEND_UNSIGNED
3234   if (GET_MODE (addr) != Pmode)
3235     addr = convert_memory_address (Pmode, addr);
3236 #endif
3237
3238 #ifdef RETURN_ADDR_OFFSET
3239   addr = force_reg (Pmode, addr);
3240   addr = plus_constant (addr, -RETURN_ADDR_OFFSET);
3241 #endif
3242
3243   return addr;
3244 }
3245
3246 /* Set up the epilogue with the magic bits we'll need to return to the
3247    exception handler.  */
3248
3249 void
3250 expand_builtin_eh_return (stackadj_tree, handler_tree)
3251     tree stackadj_tree, handler_tree;
3252 {
3253   rtx stackadj, handler;
3254
3255   stackadj = expand_expr (stackadj_tree, cfun->eh->ehr_stackadj, VOIDmode, 0);
3256   handler = expand_expr (handler_tree, cfun->eh->ehr_handler, VOIDmode, 0);
3257
3258 #ifdef POINTERS_EXTEND_UNSIGNED
3259   if (GET_MODE (stackadj) != Pmode)
3260     stackadj = convert_memory_address (Pmode, stackadj);
3261
3262   if (GET_MODE (handler) != Pmode)
3263     handler = convert_memory_address (Pmode, handler);
3264 #endif
3265
3266   if (! cfun->eh->ehr_label)
3267     {
3268       cfun->eh->ehr_stackadj = copy_to_reg (stackadj);
3269       cfun->eh->ehr_handler = copy_to_reg (handler);
3270       cfun->eh->ehr_label = gen_label_rtx ();
3271     }
3272   else
3273     {
3274       if (stackadj != cfun->eh->ehr_stackadj)
3275         emit_move_insn (cfun->eh->ehr_stackadj, stackadj);
3276       if (handler != cfun->eh->ehr_handler)
3277         emit_move_insn (cfun->eh->ehr_handler, handler);
3278     }
3279
3280   emit_jump (cfun->eh->ehr_label);
3281 }
3282
3283 void
3284 expand_eh_return ()
3285 {
3286   rtx sa, ra, around_label;
3287
3288   if (! cfun->eh->ehr_label)
3289     return;
3290
3291   sa = EH_RETURN_STACKADJ_RTX;
3292   if (! sa)
3293     {
3294       error ("__builtin_eh_return not supported on this target");
3295       return;
3296     }
3297
3298   current_function_calls_eh_return = 1;
3299
3300   around_label = gen_label_rtx ();
3301   emit_move_insn (sa, const0_rtx);
3302   emit_jump (around_label);
3303
3304   emit_label (cfun->eh->ehr_label);
3305   clobber_return_register ();
3306
3307 #ifdef HAVE_eh_return
3308   if (HAVE_eh_return)
3309     emit_insn (gen_eh_return (cfun->eh->ehr_stackadj, cfun->eh->ehr_handler));
3310   else
3311 #endif
3312     {
3313       ra = EH_RETURN_HANDLER_RTX;
3314       if (! ra)
3315         {
3316           error ("__builtin_eh_return not supported on this target");
3317           ra = gen_reg_rtx (Pmode);
3318         }
3319
3320       emit_move_insn (sa, cfun->eh->ehr_stackadj);
3321       emit_move_insn (ra, cfun->eh->ehr_handler);
3322     }
3323
3324   emit_label (around_label);
3325 }
3326 \f
3327 /* In the following functions, we represent entries in the action table
3328    as 1-based indices.  Special cases are:
3329
3330          0:     null action record, non-null landing pad; implies cleanups
3331         -1:     null action record, null landing pad; implies no action
3332         -2:     no call-site entry; implies must_not_throw
3333         -3:     we have yet to process outer regions
3334
3335    Further, no special cases apply to the "next" field of the record.
3336    For next, 0 means end of list.  */
3337
3338 struct action_record
3339 {
3340   int offset;
3341   int filter;
3342   int next;
3343 };
3344
3345 static int
3346 action_record_eq (pentry, pdata)
3347      const PTR pentry;
3348      const PTR pdata;
3349 {
3350   const struct action_record *entry = (const struct action_record *) pentry;
3351   const struct action_record *data = (const struct action_record *) pdata;
3352   return entry->filter == data->filter && entry->next == data->next;
3353 }
3354
3355 static hashval_t
3356 action_record_hash (pentry)
3357      const PTR pentry;
3358 {
3359   const struct action_record *entry = (const struct action_record *) pentry;
3360   return entry->next * 1009 + entry->filter;
3361 }
3362
3363 static int
3364 add_action_record (ar_hash, filter, next)
3365      htab_t ar_hash;
3366      int filter, next;
3367 {
3368   struct action_record **slot, *new, tmp;
3369
3370   tmp.filter = filter;
3371   tmp.next = next;
3372   slot = (struct action_record **) htab_find_slot (ar_hash, &tmp, INSERT);
3373
3374   if ((new = *slot) == NULL)
3375     {
3376       new = (struct action_record *) xmalloc (sizeof (*new));
3377       new->offset = VARRAY_ACTIVE_SIZE (cfun->eh->action_record_data) + 1;
3378       new->filter = filter;
3379       new->next = next;
3380       *slot = new;
3381
3382       /* The filter value goes in untouched.  The link to the next
3383          record is a "self-relative" byte offset, or zero to indicate
3384          that there is no next record.  So convert the absolute 1 based
3385          indices we've been carrying around into a displacement.  */
3386
3387       push_sleb128 (&cfun->eh->action_record_data, filter);
3388       if (next)
3389         next -= VARRAY_ACTIVE_SIZE (cfun->eh->action_record_data) + 1;
3390       push_sleb128 (&cfun->eh->action_record_data, next);
3391     }
3392
3393   return new->offset;
3394 }
3395
3396 static int
3397 collect_one_action_chain (ar_hash, region)
3398      htab_t ar_hash;
3399      struct eh_region *region;
3400 {
3401   struct eh_region *c;
3402   int next;
3403
3404   /* If we've reached the top of the region chain, then we have
3405      no actions, and require no landing pad.  */
3406   if (region == NULL)
3407     return -1;
3408
3409   switch (region->type)
3410     {
3411     case ERT_CLEANUP:
3412       /* A cleanup adds a zero filter to the beginning of the chain, but
3413          there are special cases to look out for.  If there are *only*
3414          cleanups along a path, then it compresses to a zero action.
3415          Further, if there are multiple cleanups along a path, we only
3416          need to represent one of them, as that is enough to trigger
3417          entry to the landing pad at runtime.  */
3418       next = collect_one_action_chain (ar_hash, region->outer);
3419       if (next <= 0)
3420         return 0;
3421       for (c = region->outer; c ; c = c->outer)
3422         if (c->type == ERT_CLEANUP)
3423           return next;
3424       return add_action_record (ar_hash, 0, next);
3425
3426     case ERT_TRY:
3427       /* Process the associated catch regions in reverse order.
3428          If there's a catch-all handler, then we don't need to
3429          search outer regions.  Use a magic -3 value to record
3430          that we haven't done the outer search.  */
3431       next = -3;
3432       for (c = region->u.try.last_catch; c ; c = c->u.catch.prev_catch)
3433         {
3434           if (c->u.catch.type_list == NULL)
3435             {
3436               /* Retrieve the filter from the head of the filter list
3437                  where we have stored it (see assign_filter_values).  */
3438               int filter
3439                 = TREE_INT_CST_LOW (TREE_VALUE (c->u.catch.filter_list));
3440
3441               next = add_action_record (ar_hash, filter, 0);
3442             }
3443           else
3444             {
3445               /* Once the outer search is done, trigger an action record for
3446                  each filter we have.  */
3447               tree flt_node;
3448
3449               if (next == -3)
3450                 {
3451                   next = collect_one_action_chain (ar_hash, region->outer);
3452
3453                   /* If there is no next action, terminate the chain.  */
3454                   if (next == -1)
3455                     next = 0;
3456                   /* If all outer actions are cleanups or must_not_throw,
3457                      we'll have no action record for it, since we had wanted
3458                      to encode these states in the call-site record directly.
3459                      Add a cleanup action to the chain to catch these.  */
3460                   else if (next <= 0)
3461                     next = add_action_record (ar_hash, 0, 0);
3462                 }
3463
3464               flt_node = c->u.catch.filter_list;
3465               for (; flt_node; flt_node = TREE_CHAIN (flt_node))
3466                 {
3467                   int filter = TREE_INT_CST_LOW (TREE_VALUE (flt_node));
3468                   next = add_action_record (ar_hash, filter, next);
3469                 }
3470             }
3471         }
3472       return next;
3473
3474     case ERT_ALLOWED_EXCEPTIONS:
3475       /* An exception specification adds its filter to the
3476          beginning of the chain.  */
3477       next = collect_one_action_chain (ar_hash, region->outer);
3478       return add_action_record (ar_hash, region->u.allowed.filter,
3479                                 next < 0 ? 0 : next);
3480
3481     case ERT_MUST_NOT_THROW:
3482       /* A must-not-throw region with no inner handlers or cleanups
3483          requires no call-site entry.  Note that this differs from
3484          the no handler or cleanup case in that we do require an lsda
3485          to be generated.  Return a magic -2 value to record this.  */
3486       return -2;
3487
3488     case ERT_CATCH:
3489     case ERT_THROW:
3490       /* CATCH regions are handled in TRY above.  THROW regions are
3491          for optimization information only and produce no output.  */
3492       return collect_one_action_chain (ar_hash, region->outer);
3493
3494     default:
3495       abort ();
3496     }
3497 }
3498
3499 static int
3500 add_call_site (landing_pad, action)
3501      rtx landing_pad;
3502      int action;
3503 {
3504   struct call_site_record *data = cfun->eh->call_site_data;
3505   int used = cfun->eh->call_site_data_used;
3506   int size = cfun->eh->call_site_data_size;
3507
3508   if (used >= size)
3509     {
3510       size = (size ? size * 2 : 64);
3511       data = (struct call_site_record *)
3512         xrealloc (data, sizeof (*data) * size);
3513       cfun->eh->call_site_data = data;
3514       cfun->eh->call_site_data_size = size;
3515     }
3516
3517   data[used].landing_pad = landing_pad;
3518   data[used].action = action;
3519
3520   cfun->eh->call_site_data_used = used + 1;
3521
3522   return used + call_site_base;
3523 }
3524
3525 /* Turn REG_EH_REGION notes back into NOTE_INSN_EH_REGION notes.
3526    The new note numbers will not refer to region numbers, but
3527    instead to call site entries.  */
3528
3529 void
3530 convert_to_eh_region_ranges ()
3531 {
3532   rtx insn, iter, note;
3533   htab_t ar_hash;
3534   int last_action = -3;
3535   rtx last_action_insn = NULL_RTX;
3536   rtx last_landing_pad = NULL_RTX;
3537   rtx first_no_action_insn = NULL_RTX;
3538   int call_site = 0;
3539
3540   if (USING_SJLJ_EXCEPTIONS || cfun->eh->region_tree == NULL)
3541     return;
3542
3543   VARRAY_UCHAR_INIT (cfun->eh->action_record_data, 64, "action_record_data");
3544
3545   ar_hash = htab_create (31, action_record_hash, action_record_eq, free);
3546
3547   for (iter = get_insns (); iter ; iter = NEXT_INSN (iter))
3548     if (INSN_P (iter))
3549       {
3550         struct eh_region *region;
3551         int this_action;
3552         rtx this_landing_pad;
3553
3554         insn = iter;
3555         if (GET_CODE (insn) == INSN
3556             && GET_CODE (PATTERN (insn)) == SEQUENCE)
3557           insn = XVECEXP (PATTERN (insn), 0, 0);
3558
3559         note = find_reg_note (insn, REG_EH_REGION, NULL_RTX);
3560         if (!note)
3561           {
3562             if (! (GET_CODE (insn) == CALL_INSN
3563                    || (flag_non_call_exceptions
3564                        && may_trap_p (PATTERN (insn)))))
3565               continue;
3566             this_action = -1;
3567             region = NULL;
3568           }
3569         else
3570           {
3571             if (INTVAL (XEXP (note, 0)) <= 0)
3572               continue;
3573             region = cfun->eh->region_array[INTVAL (XEXP (note, 0))];
3574             this_action = collect_one_action_chain (ar_hash, region);
3575           }
3576
3577         /* Existence of catch handlers, or must-not-throw regions
3578            implies that an lsda is needed (even if empty).  */
3579         if (this_action != -1)
3580           cfun->uses_eh_lsda = 1;
3581
3582         /* Delay creation of region notes for no-action regions
3583            until we're sure that an lsda will be required.  */
3584         else if (last_action == -3)
3585           {
3586             first_no_action_insn = iter;
3587             last_action = -1;
3588           }
3589
3590         /* Cleanups and handlers may share action chains but not
3591            landing pads.  Collect the landing pad for this region.  */
3592         if (this_action >= 0)
3593           {
3594             struct eh_region *o;
3595             for (o = region; ! o->landing_pad ; o = o->outer)
3596               continue;
3597             this_landing_pad = o->landing_pad;
3598           }
3599         else
3600           this_landing_pad = NULL_RTX;
3601
3602         /* Differing actions or landing pads implies a change in call-site
3603            info, which implies some EH_REGION note should be emitted.  */
3604         if (last_action != this_action
3605             || last_landing_pad != this_landing_pad)
3606           {
3607             /* If we'd not seen a previous action (-3) or the previous
3608                action was must-not-throw (-2), then we do not need an
3609                end note.  */
3610             if (last_action >= -1)
3611               {
3612                 /* If we delayed the creation of the begin, do it now.  */
3613                 if (first_no_action_insn)
3614                   {
3615                     call_site = add_call_site (NULL_RTX, 0);
3616                     note = emit_note_before (NOTE_INSN_EH_REGION_BEG,
3617                                              first_no_action_insn);
3618                     NOTE_EH_HANDLER (note) = call_site;
3619                     first_no_action_insn = NULL_RTX;
3620                   }
3621
3622                 note = emit_note_after (NOTE_INSN_EH_REGION_END,
3623                                         last_action_insn);
3624                 NOTE_EH_HANDLER (note) = call_site;
3625               }
3626
3627             /* If the new action is must-not-throw, then no region notes
3628                are created.  */
3629             if (this_action >= -1)
3630               {
3631                 call_site = add_call_site (this_landing_pad,
3632                                            this_action < 0 ? 0 : this_action);
3633                 note = emit_note_before (NOTE_INSN_EH_REGION_BEG, iter);
3634                 NOTE_EH_HANDLER (note) = call_site;
3635               }
3636
3637             last_action = this_action;
3638             last_landing_pad = this_landing_pad;
3639           }
3640         last_action_insn = iter;
3641       }
3642
3643   if (last_action >= -1 && ! first_no_action_insn)
3644     {
3645       note = emit_note_after (NOTE_INSN_EH_REGION_END, last_action_insn);
3646       NOTE_EH_HANDLER (note) = call_site;
3647     }
3648
3649   htab_delete (ar_hash);
3650 }
3651
3652 \f
3653 static void
3654 push_uleb128 (data_area, value)
3655      varray_type *data_area;
3656      unsigned int value;
3657 {
3658   do
3659     {
3660       unsigned char byte = value & 0x7f;
3661       value >>= 7;
3662       if (value)
3663         byte |= 0x80;
3664       VARRAY_PUSH_UCHAR (*data_area, byte);
3665     }
3666   while (value);
3667 }
3668
3669 static void
3670 push_sleb128 (data_area, value)
3671      varray_type *data_area;
3672      int value;
3673 {
3674   unsigned char byte;
3675   int more;
3676
3677   do
3678     {
3679       byte = value & 0x7f;
3680       value >>= 7;
3681       more = ! ((value == 0 && (byte & 0x40) == 0)
3682                 || (value == -1 && (byte & 0x40) != 0));
3683       if (more)
3684         byte |= 0x80;
3685       VARRAY_PUSH_UCHAR (*data_area, byte);
3686     }
3687   while (more);
3688 }
3689
3690 \f
3691 #ifndef HAVE_AS_LEB128
3692 static int
3693 dw2_size_of_call_site_table ()
3694 {
3695   int n = cfun->eh->call_site_data_used;
3696   int size = n * (4 + 4 + 4);
3697   int i;
3698
3699   for (i = 0; i < n; ++i)
3700     {
3701       struct call_site_record *cs = &cfun->eh->call_site_data[i];
3702       size += size_of_uleb128 (cs->action);
3703     }
3704
3705   return size;
3706 }
3707
3708 static int
3709 sjlj_size_of_call_site_table ()
3710 {
3711   int n = cfun->eh->call_site_data_used;
3712   int size = 0;
3713   int i;
3714
3715   for (i = 0; i < n; ++i)
3716     {
3717       struct call_site_record *cs = &cfun->eh->call_site_data[i];
3718       size += size_of_uleb128 (INTVAL (cs->landing_pad));
3719       size += size_of_uleb128 (cs->action);
3720     }
3721
3722   return size;
3723 }
3724 #endif
3725
3726 static void
3727 dw2_output_call_site_table ()
3728 {
3729   const char *const function_start_lab
3730     = IDENTIFIER_POINTER (current_function_func_begin_label);
3731   int n = cfun->eh->call_site_data_used;
3732   int i;
3733
3734   for (i = 0; i < n; ++i)
3735     {
3736       struct call_site_record *cs = &cfun->eh->call_site_data[i];
3737       char reg_start_lab[32];
3738       char reg_end_lab[32];
3739       char landing_pad_lab[32];
3740
3741       ASM_GENERATE_INTERNAL_LABEL (reg_start_lab, "LEHB", call_site_base + i);
3742       ASM_GENERATE_INTERNAL_LABEL (reg_end_lab, "LEHE", call_site_base + i);
3743
3744       if (cs->landing_pad)
3745         ASM_GENERATE_INTERNAL_LABEL (landing_pad_lab, "L",
3746                                      CODE_LABEL_NUMBER (cs->landing_pad));
3747
3748       /* ??? Perhaps use insn length scaling if the assembler supports
3749          generic arithmetic.  */
3750       /* ??? Perhaps use attr_length to choose data1 or data2 instead of
3751          data4 if the function is small enough.  */
3752 #ifdef HAVE_AS_LEB128
3753       dw2_asm_output_delta_uleb128 (reg_start_lab, function_start_lab,
3754                                     "region %d start", i);
3755       dw2_asm_output_delta_uleb128 (reg_end_lab, reg_start_lab,
3756                                     "length");
3757       if (cs->landing_pad)
3758         dw2_asm_output_delta_uleb128 (landing_pad_lab, function_start_lab,
3759                                       "landing pad");
3760       else
3761         dw2_asm_output_data_uleb128 (0, "landing pad");
3762 #else
3763       dw2_asm_output_delta (4, reg_start_lab, function_start_lab,
3764                             "region %d start", i);
3765       dw2_asm_output_delta (4, reg_end_lab, reg_start_lab, "length");
3766       if (cs->landing_pad)
3767         dw2_asm_output_delta (4, landing_pad_lab, function_start_lab,
3768                               "landing pad");
3769       else
3770         dw2_asm_output_data (4, 0, "landing pad");
3771 #endif
3772       dw2_asm_output_data_uleb128 (cs->action, "action");
3773     }
3774
3775   call_site_base += n;
3776 }
3777
3778 static void
3779 sjlj_output_call_site_table ()
3780 {
3781   int n = cfun->eh->call_site_data_used;
3782   int i;
3783
3784   for (i = 0; i < n; ++i)
3785     {
3786       struct call_site_record *cs = &cfun->eh->call_site_data[i];
3787
3788       dw2_asm_output_data_uleb128 (INTVAL (cs->landing_pad),
3789                                    "region %d landing pad", i);
3790       dw2_asm_output_data_uleb128 (cs->action, "action");
3791     }
3792
3793   call_site_base += n;
3794 }
3795
3796 void
3797 output_function_exception_table ()
3798 {
3799   int tt_format, cs_format, lp_format, i, n;
3800 #ifdef HAVE_AS_LEB128
3801   char ttype_label[32];
3802   char cs_after_size_label[32];
3803   char cs_end_label[32];
3804 #else
3805   int call_site_len;
3806 #endif
3807   int have_tt_data;
3808   int funcdef_number;
3809   int tt_format_size = 0;
3810
3811   /* Not all functions need anything.  */
3812   if (! cfun->uses_eh_lsda)
3813     return;
3814
3815   funcdef_number = (USING_SJLJ_EXCEPTIONS
3816                     ? sjlj_funcdef_number
3817                     : current_funcdef_number);
3818
3819 #ifdef IA64_UNWIND_INFO
3820   fputs ("\t.personality\t", asm_out_file);
3821   output_addr_const (asm_out_file, eh_personality_libfunc);
3822   fputs ("\n\t.handlerdata\n", asm_out_file);
3823   /* Note that varasm still thinks we're in the function's code section.
3824      The ".endp" directive that will immediately follow will take us back.  */
3825 #else
3826   (*targetm.asm_out.exception_section) ();
3827 #endif
3828
3829   have_tt_data = (VARRAY_ACTIVE_SIZE (cfun->eh->ttype_data) > 0
3830                   || VARRAY_ACTIVE_SIZE (cfun->eh->ehspec_data) > 0);
3831
3832   /* Indicate the format of the @TType entries.  */
3833   if (! have_tt_data)
3834     tt_format = DW_EH_PE_omit;
3835   else
3836     {
3837       tt_format = ASM_PREFERRED_EH_DATA_FORMAT (/*code=*/0, /*global=*/1);
3838 #ifdef HAVE_AS_LEB128
3839       ASM_GENERATE_INTERNAL_LABEL (ttype_label, "LLSDATT", funcdef_number);
3840 #endif
3841       tt_format_size = size_of_encoded_value (tt_format);
3842
3843       assemble_align (tt_format_size * BITS_PER_UNIT);
3844     }
3845
3846   ASM_OUTPUT_INTERNAL_LABEL (asm_out_file, "LLSDA", funcdef_number);
3847
3848   /* The LSDA header.  */
3849
3850   /* Indicate the format of the landing pad start pointer.  An omitted
3851      field implies @LPStart == @Start.  */
3852   /* Currently we always put @LPStart == @Start.  This field would
3853      be most useful in moving the landing pads completely out of
3854      line to another section, but it could also be used to minimize
3855      the size of uleb128 landing pad offsets.  */
3856   lp_format = DW_EH_PE_omit;
3857   dw2_asm_output_data (1, lp_format, "@LPStart format (%s)",
3858                        eh_data_format_name (lp_format));
3859
3860   /* @LPStart pointer would go here.  */
3861
3862   dw2_asm_output_data (1, tt_format, "@TType format (%s)",
3863                        eh_data_format_name (tt_format));
3864
3865 #ifndef HAVE_AS_LEB128
3866   if (USING_SJLJ_EXCEPTIONS)
3867     call_site_len = sjlj_size_of_call_site_table ();
3868   else
3869     call_site_len = dw2_size_of_call_site_table ();
3870 #endif
3871
3872   /* A pc-relative 4-byte displacement to the @TType data.  */
3873   if (have_tt_data)
3874     {
3875 #ifdef HAVE_AS_LEB128
3876       char ttype_after_disp_label[32];
3877       ASM_GENERATE_INTERNAL_LABEL (ttype_after_disp_label, "LLSDATTD",
3878                                    funcdef_number);
3879       dw2_asm_output_delta_uleb128 (ttype_label, ttype_after_disp_label,
3880                                     "@TType base offset");
3881       ASM_OUTPUT_LABEL (asm_out_file, ttype_after_disp_label);
3882 #else
3883       /* Ug.  Alignment queers things.  */
3884       unsigned int before_disp, after_disp, last_disp, disp;
3885
3886       before_disp = 1 + 1;
3887       after_disp = (1 + size_of_uleb128 (call_site_len)
3888                     + call_site_len
3889                     + VARRAY_ACTIVE_SIZE (cfun->eh->action_record_data)
3890                     + (VARRAY_ACTIVE_SIZE (cfun->eh->ttype_data)
3891                        * tt_format_size));
3892
3893       disp = after_disp;
3894       do
3895         {
3896           unsigned int disp_size, pad;
3897
3898           last_disp = disp;
3899           disp_size = size_of_uleb128 (disp);
3900           pad = before_disp + disp_size + after_disp;
3901           if (pad % tt_format_size)
3902             pad = tt_format_size - (pad % tt_format_size);
3903           else
3904             pad = 0;
3905           disp = after_disp + pad;
3906         }
3907       while (disp != last_disp);
3908
3909       dw2_asm_output_data_uleb128 (disp, "@TType base offset");
3910 #endif
3911     }
3912
3913   /* Indicate the format of the call-site offsets.  */
3914 #ifdef HAVE_AS_LEB128
3915   cs_format = DW_EH_PE_uleb128;
3916 #else
3917   cs_format = DW_EH_PE_udata4;
3918 #endif
3919   dw2_asm_output_data (1, cs_format, "call-site format (%s)",
3920                        eh_data_format_name (cs_format));
3921
3922 #ifdef HAVE_AS_LEB128
3923   ASM_GENERATE_INTERNAL_LABEL (cs_after_size_label, "LLSDACSB",
3924                                funcdef_number);
3925   ASM_GENERATE_INTERNAL_LABEL (cs_end_label, "LLSDACSE",
3926                                funcdef_number);
3927   dw2_asm_output_delta_uleb128 (cs_end_label, cs_after_size_label,
3928                                 "Call-site table length");
3929   ASM_OUTPUT_LABEL (asm_out_file, cs_after_size_label);
3930   if (USING_SJLJ_EXCEPTIONS)
3931     sjlj_output_call_site_table ();
3932   else
3933     dw2_output_call_site_table ();
3934   ASM_OUTPUT_LABEL (asm_out_file, cs_end_label);
3935 #else
3936   dw2_asm_output_data_uleb128 (call_site_len,"Call-site table length");
3937   if (USING_SJLJ_EXCEPTIONS)
3938     sjlj_output_call_site_table ();
3939   else
3940     dw2_output_call_site_table ();
3941 #endif
3942
3943   /* ??? Decode and interpret the data for flag_debug_asm.  */
3944   n = VARRAY_ACTIVE_SIZE (cfun->eh->action_record_data);
3945   for (i = 0; i < n; ++i)
3946     dw2_asm_output_data (1, VARRAY_UCHAR (cfun->eh->action_record_data, i),
3947                          (i ? NULL : "Action record table"));
3948
3949   if (have_tt_data)
3950     assemble_align (tt_format_size * BITS_PER_UNIT);
3951
3952   i = VARRAY_ACTIVE_SIZE (cfun->eh->ttype_data);
3953   while (i-- > 0)
3954     {
3955       tree type = VARRAY_TREE (cfun->eh->ttype_data, i);
3956       rtx value;
3957
3958       if (type == NULL_TREE)
3959         type = integer_zero_node;
3960       else
3961         type = lookup_type_for_runtime (type);
3962
3963       value = expand_expr (type, NULL_RTX, VOIDmode, EXPAND_INITIALIZER);
3964       if (tt_format == DW_EH_PE_absptr || tt_format == DW_EH_PE_aligned)
3965         assemble_integer (value, tt_format_size,
3966                           tt_format_size * BITS_PER_UNIT, 1);
3967       else
3968         dw2_asm_output_encoded_addr_rtx (tt_format, value, NULL);
3969     }
3970
3971 #ifdef HAVE_AS_LEB128
3972   if (have_tt_data)
3973       ASM_OUTPUT_LABEL (asm_out_file, ttype_label);
3974 #endif
3975
3976   /* ??? Decode and interpret the data for flag_debug_asm.  */
3977   n = VARRAY_ACTIVE_SIZE (cfun->eh->ehspec_data);
3978   for (i = 0; i < n; ++i)
3979     dw2_asm_output_data (1, VARRAY_UCHAR (cfun->eh->ehspec_data, i),
3980                          (i ? NULL : "Exception specification table"));
3981
3982   function_section (current_function_decl);
3983
3984   if (USING_SJLJ_EXCEPTIONS)
3985     sjlj_funcdef_number += 1;
3986 }