OSDN Git Service

2009-07-17 Aldy Hernandez <aldyh@redhat.com>
[pf3gnuchains/gcc-fork.git] / gcc / cp / except.c
1 /* Handle exceptional things in C++.
2    Copyright (C) 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
3    2000, 2001, 2002, 2003, 2004, 2005, 2007, 2008, 2009
4    Free Software Foundation, Inc.
5    Contributed by Michael Tiemann <tiemann@cygnus.com>
6    Rewritten by Mike Stump <mrs@cygnus.com>, based upon an
7    initial re-implementation courtesy Tad Hunt.
8
9 This file is part of GCC.
10
11 GCC is free software; you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation; either version 3, or (at your option)
14 any later version.
15
16 GCC is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 GNU General Public License for more details.
20
21 You should have received a copy of the GNU General Public License
22 along with GCC; see the file COPYING3.  If not see
23 <http://www.gnu.org/licenses/>.  */
24
25
26 #include "config.h"
27 #include "system.h"
28 #include "coretypes.h"
29 #include "tm.h"
30 #include "tree.h"
31 #include "rtl.h"
32 #include "expr.h"
33 #include "libfuncs.h"
34 #include "cp-tree.h"
35 #include "flags.h"
36 #include "output.h"
37 #include "except.h"
38 #include "toplev.h"
39 #include "tree-inline.h"
40 #include "tree-iterator.h"
41 #include "target.h"
42 #include "gimple.h"
43
44 static void push_eh_cleanup (tree);
45 static tree prepare_eh_type (tree);
46 static tree build_eh_type_type (tree);
47 static tree do_begin_catch (void);
48 static int dtor_nothrow (tree);
49 static tree do_end_catch (tree);
50 static bool decl_is_java_type (tree decl, int err);
51 static void initialize_handler_parm (tree, tree);
52 static tree do_allocate_exception (tree);
53 static tree wrap_cleanups_r (tree *, int *, void *);
54 static int complete_ptr_ref_or_void_ptr_p (tree, tree);
55 static bool is_admissible_throw_operand (tree);
56 static int can_convert_eh (tree, tree);
57 static gimple cp_protect_cleanup_actions (void);
58
59 /* Sets up all the global eh stuff that needs to be initialized at the
60    start of compilation.  */
61
62 void
63 init_exception_processing (void)
64 {
65   tree tmp;
66
67   /* void std::terminate (); */
68   push_namespace (std_identifier);
69   tmp = build_function_type (void_type_node, void_list_node);
70   terminate_node = build_cp_library_fn_ptr ("terminate", tmp);
71   TREE_THIS_VOLATILE (terminate_node) = 1;
72   TREE_NOTHROW (terminate_node) = 1;
73   pop_namespace ();
74
75   /* void __cxa_call_unexpected(void *); */
76   tmp = tree_cons (NULL_TREE, ptr_type_node, void_list_node);
77   tmp = build_function_type (void_type_node, tmp);
78   call_unexpected_node
79     = push_throw_library_fn (get_identifier ("__cxa_call_unexpected"), tmp);
80
81   eh_personality_libfunc = init_one_libfunc (USING_SJLJ_EXCEPTIONS
82                                              ? "__gxx_personality_sj0"
83                                              : "__gxx_personality_v0");
84   if (targetm.arm_eabi_unwinder)
85     unwind_resume_libfunc = init_one_libfunc ("__cxa_end_cleanup");
86   else
87     default_init_unwind_resume_libfunc ();
88
89   lang_eh_runtime_type = build_eh_type_type;
90   lang_protect_cleanup_actions = &cp_protect_cleanup_actions;
91 }
92
93 /* Returns an expression to be executed if an unhandled exception is
94    propagated out of a cleanup region.  */
95
96 static gimple
97 cp_protect_cleanup_actions (void)
98 {
99   /* [except.terminate]
100
101      When the destruction of an object during stack unwinding exits
102      using an exception ... void terminate(); is called.  */
103   return gimple_build_call (terminate_node, 0);
104 }
105
106 static tree
107 prepare_eh_type (tree type)
108 {
109   if (type == NULL_TREE)
110     return type;
111   if (type == error_mark_node)
112     return error_mark_node;
113
114   /* peel back references, so they match.  */
115   type = non_reference (type);
116
117   /* Peel off cv qualifiers.  */
118   type = TYPE_MAIN_VARIANT (type);
119
120   /* Functions and arrays decay to pointers.  */
121   type = type_decays_to (type);
122
123   return type;
124 }
125
126 /* Return the type info for TYPE as used by EH machinery.  */
127 tree
128 eh_type_info (tree type)
129 {
130   tree exp;
131
132   if (type == NULL_TREE || type == error_mark_node)
133     return type;
134
135   if (decl_is_java_type (type, 0))
136     exp = build_java_class_ref (TREE_TYPE (type));
137   else
138     exp = get_tinfo_decl (type);
139
140   return exp;
141 }
142
143 /* Build the address of a typeinfo decl for use in the runtime
144    matching field of the exception model.  */
145
146 static tree
147 build_eh_type_type (tree type)
148 {
149   tree exp = eh_type_info (type);
150
151   if (!exp)
152     return NULL;
153
154   mark_used (exp);
155
156   return convert (ptr_type_node, build_address (exp));
157 }
158
159 tree
160 build_exc_ptr (void)
161 {
162   return build0 (EXC_PTR_EXPR, ptr_type_node);
163 }
164
165 /* Declare a function NAME, returning RETURN_TYPE, taking a single
166    parameter PARM_TYPE, with an empty exception specification.
167
168    Note that the C++ ABI document does not have a throw-specifier on
169    the routines declared below via this function.  The declarations
170    are consistent with the actual implementations in libsupc++.  */
171
172 static tree
173 declare_nothrow_library_fn (tree name, tree return_type, tree parm_type)
174 {
175   tree tmp = tree_cons (NULL_TREE, parm_type, void_list_node);
176   return push_library_fn (name, build_function_type (return_type, tmp),
177                           empty_except_spec);
178 }
179
180 /* Build up a call to __cxa_get_exception_ptr so that we can build a
181    copy constructor for the thrown object.  */
182
183 static tree
184 do_get_exception_ptr (void)
185 {
186   tree fn;
187
188   fn = get_identifier ("__cxa_get_exception_ptr");
189   if (!get_global_value_if_present (fn, &fn))
190     {
191       /* Declare void* __cxa_get_exception_ptr (void *) throw().  */
192       fn = declare_nothrow_library_fn (fn, ptr_type_node, ptr_type_node);
193     }
194
195   return cp_build_function_call (fn, tree_cons (NULL_TREE, build_exc_ptr (),
196                                                 NULL_TREE),
197                                  tf_warning_or_error);
198 }
199
200 /* Build up a call to __cxa_begin_catch, to tell the runtime that the
201    exception has been handled.  */
202
203 static tree
204 do_begin_catch (void)
205 {
206   tree fn;
207
208   fn = get_identifier ("__cxa_begin_catch");
209   if (!get_global_value_if_present (fn, &fn))
210     {
211       /* Declare void* __cxa_begin_catch (void *) throw().  */
212       fn = declare_nothrow_library_fn (fn, ptr_type_node, ptr_type_node);
213     }
214
215   return cp_build_function_call (fn, tree_cons (NULL_TREE, build_exc_ptr (),
216                                                 NULL_TREE),
217                                  tf_warning_or_error);
218 }
219
220 /* Returns nonzero if cleaning up an exception of type TYPE (which can be
221    NULL_TREE for a ... handler) will not throw an exception.  */
222
223 static int
224 dtor_nothrow (tree type)
225 {
226   if (type == NULL_TREE)
227     return 0;
228
229   if (!CLASS_TYPE_P (type))
230     return 1;
231
232   if (CLASSTYPE_LAZY_DESTRUCTOR (type))
233     lazily_declare_fn (sfk_destructor, type);
234
235   return TREE_NOTHROW (CLASSTYPE_DESTRUCTORS (type));
236 }
237
238 /* Build up a call to __cxa_end_catch, to destroy the exception object
239    for the current catch block if no others are currently using it.  */
240
241 static tree
242 do_end_catch (tree type)
243 {
244   tree fn, cleanup;
245
246   fn = get_identifier ("__cxa_end_catch");
247   if (!get_global_value_if_present (fn, &fn))
248     {
249       /* Declare void __cxa_end_catch ().  */
250       fn = push_void_library_fn (fn, void_list_node);
251       /* This can throw if the destructor for the exception throws.  */
252       TREE_NOTHROW (fn) = 0;
253     }
254
255   cleanup = cp_build_function_call (fn, NULL_TREE, tf_warning_or_error);
256   TREE_NOTHROW (cleanup) = dtor_nothrow (type);
257
258   return cleanup;
259 }
260
261 /* This routine creates the cleanup for the current exception.  */
262
263 static void
264 push_eh_cleanup (tree type)
265 {
266   finish_decl_cleanup (NULL_TREE, do_end_catch (type));
267 }
268
269 /* Return nonzero value if DECL is a Java type suitable for catch or
270    throw.  */
271
272 static bool
273 decl_is_java_type (tree decl, int err)
274 {
275   bool r = (TREE_CODE (decl) == POINTER_TYPE
276             && TREE_CODE (TREE_TYPE (decl)) == RECORD_TYPE
277             && TYPE_FOR_JAVA (TREE_TYPE (decl)));
278
279   if (err)
280     {
281       if (TREE_CODE (decl) == REFERENCE_TYPE
282           && TREE_CODE (TREE_TYPE (decl)) == RECORD_TYPE
283           && TYPE_FOR_JAVA (TREE_TYPE (decl)))
284         {
285           /* Can't throw a reference.  */
286           error ("type %qT is disallowed in Java %<throw%> or %<catch%>",
287                  decl);
288         }
289
290       if (r)
291         {
292           tree jthrow_node
293             = IDENTIFIER_GLOBAL_VALUE (get_identifier ("jthrowable"));
294
295           if (jthrow_node == NULL_TREE)
296             fatal_error
297               ("call to Java %<catch%> or %<throw%> with %<jthrowable%> undefined");
298
299           jthrow_node = TREE_TYPE (TREE_TYPE (jthrow_node));
300
301           if (! DERIVED_FROM_P (jthrow_node, TREE_TYPE (decl)))
302             {
303               /* Thrown object must be a Throwable.  */
304               error ("type %qT is not derived from %<java::lang::Throwable%>",
305                      TREE_TYPE (decl));
306             }
307         }
308     }
309
310   return r;
311 }
312
313 /* Select the personality routine to be used for exception handling,
314    or issue an error if we need two different ones in the same
315    translation unit.
316    ??? At present eh_personality_libfunc is set to
317    __gxx_personality_(sj|v)0 in init_exception_processing - should it
318    be done here instead?  */
319 void
320 choose_personality_routine (enum languages lang)
321 {
322   static enum {
323     chose_none,
324     chose_cpp,
325     chose_java,
326     gave_error
327   } state;
328
329   switch (state)
330     {
331     case gave_error:
332       return;
333
334     case chose_cpp:
335       if (lang != lang_cplusplus)
336         goto give_error;
337       return;
338
339     case chose_java:
340       if (lang != lang_java)
341         goto give_error;
342       return;
343
344     case chose_none:
345       ; /* Proceed to language selection.  */
346     }
347
348   switch (lang)
349     {
350     case lang_cplusplus:
351       state = chose_cpp;
352       break;
353
354     case lang_java:
355       state = chose_java;
356       terminate_node = built_in_decls [BUILT_IN_ABORT];
357       eh_personality_libfunc = init_one_libfunc (USING_SJLJ_EXCEPTIONS
358                                                  ? "__gcj_personality_sj0"
359                                                  : "__gcj_personality_v0");
360       break;
361
362     default:
363       gcc_unreachable ();
364     }
365   return;
366
367  give_error:
368   error ("mixing C++ and Java catches in a single translation unit");
369   state = gave_error;
370 }
371
372 /* Initialize the catch parameter DECL.  */
373
374 static void
375 initialize_handler_parm (tree decl, tree exp)
376 {
377   tree init;
378   tree init_type;
379
380   /* Make sure we mark the catch param as used, otherwise we'll get a
381      warning about an unused ((anonymous)).  */
382   TREE_USED (decl) = 1;
383
384   /* Figure out the type that the initializer is.  Pointers are returned
385      adjusted by value from __cxa_begin_catch.  Others are returned by
386      reference.  */
387   init_type = TREE_TYPE (decl);
388   if (!POINTER_TYPE_P (init_type))
389     init_type = build_reference_type (init_type);
390
391   choose_personality_routine (decl_is_java_type (init_type, 0)
392                               ? lang_java : lang_cplusplus);
393
394   /* Since pointers are passed by value, initialize a reference to
395      pointer catch parm with the address of the temporary.  */
396   if (TREE_CODE (init_type) == REFERENCE_TYPE
397       && TYPE_PTR_P (TREE_TYPE (init_type)))
398     exp = cp_build_unary_op (ADDR_EXPR, exp, 1, tf_warning_or_error);
399
400   exp = ocp_convert (init_type, exp, CONV_IMPLICIT|CONV_FORCE_TEMP, 0);
401
402   init = convert_from_reference (exp);
403
404   /* If the constructor for the catch parm exits via an exception, we
405      must call terminate.  See eh23.C.  */
406   if (TYPE_NEEDS_CONSTRUCTING (TREE_TYPE (decl)))
407     {
408       /* Generate the copy constructor call directly so we can wrap it.
409          See also expand_default_init.  */
410       init = ocp_convert (TREE_TYPE (decl), init,
411                           CONV_IMPLICIT|CONV_FORCE_TEMP, 0);
412       /* Force cleanups now to avoid nesting problems with the
413          MUST_NOT_THROW_EXPR.  */
414       init = fold_build_cleanup_point_expr (TREE_TYPE (init), init);
415       init = build1 (MUST_NOT_THROW_EXPR, TREE_TYPE (init), init);
416     }
417
418   decl = pushdecl (decl);
419
420   start_decl_1 (decl, true);
421   cp_finish_decl (decl, init, /*init_const_expr_p=*/false, NULL_TREE,
422                   LOOKUP_ONLYCONVERTING|DIRECT_BIND);
423 }
424
425 /* Call this to start a catch block.  DECL is the catch parameter.  */
426
427 tree
428 expand_start_catch_block (tree decl)
429 {
430   tree exp;
431   tree type;
432
433   if (! doing_eh (1))
434     return NULL_TREE;
435
436   /* Make sure this declaration is reasonable.  */
437   if (decl && !complete_ptr_ref_or_void_ptr_p (TREE_TYPE (decl), NULL_TREE))
438     decl = error_mark_node;
439
440   if (decl)
441     type = prepare_eh_type (TREE_TYPE (decl));
442   else
443     type = NULL_TREE;
444
445   if (decl && decl_is_java_type (type, 1))
446     {
447       /* Java only passes object via pointer and doesn't require
448          adjusting.  The java object is immediately before the
449          generic exception header.  */
450       exp = build_exc_ptr ();
451       exp = build1 (NOP_EXPR, build_pointer_type (type), exp);
452       exp = build2 (POINTER_PLUS_EXPR, TREE_TYPE (exp), exp,
453                     fold_build1_loc (input_location,
454                                  NEGATE_EXPR, sizetype,
455                                  TYPE_SIZE_UNIT (TREE_TYPE (exp))));
456       exp = cp_build_indirect_ref (exp, NULL, tf_warning_or_error);
457       initialize_handler_parm (decl, exp);
458       return type;
459     }
460
461   /* Call __cxa_end_catch at the end of processing the exception.  */
462   push_eh_cleanup (type);
463
464   /* If there's no decl at all, then all we need to do is make sure
465      to tell the runtime that we've begun handling the exception.  */
466   if (decl == NULL || decl == error_mark_node)
467     finish_expr_stmt (do_begin_catch ());
468
469   /* If the C++ object needs constructing, we need to do that before
470      calling __cxa_begin_catch, so that std::uncaught_exception gets
471      the right value during the copy constructor.  */
472   else if (flag_use_cxa_get_exception_ptr
473            && TYPE_NEEDS_CONSTRUCTING (TREE_TYPE (decl)))
474     {
475       exp = do_get_exception_ptr ();
476       initialize_handler_parm (decl, exp);
477       finish_expr_stmt (do_begin_catch ());
478     }
479
480   /* Otherwise the type uses a bitwise copy, and we don't have to worry
481      about the value of std::uncaught_exception and therefore can do the
482      copy with the return value of __cxa_end_catch instead.  */
483   else
484     {
485       tree init = do_begin_catch ();
486       tree init_type = type;
487
488       /* Pointers are passed by values, everything else by reference.  */
489       if (!TYPE_PTR_P (type))
490         init_type = build_pointer_type (type);
491       if (init_type != TREE_TYPE (init))
492         init = build1 (NOP_EXPR, init_type, init);
493       exp = create_temporary_var (init_type);
494       DECL_REGISTER (exp) = 1;
495       cp_finish_decl (exp, init, /*init_const_expr=*/false,
496                       NULL_TREE, LOOKUP_ONLYCONVERTING);
497       initialize_handler_parm (decl, exp);
498     }
499
500   return type;
501 }
502
503
504 /* Call this to end a catch block.  Its responsible for emitting the
505    code to handle jumping back to the correct place, and for emitting
506    the label to jump to if this catch block didn't match.  */
507
508 void
509 expand_end_catch_block (void)
510 {
511   if (! doing_eh (1))
512     return;
513
514   /* The exception being handled is rethrown if control reaches the end of
515      a handler of the function-try-block of a constructor or destructor.  */
516   if (in_function_try_handler
517       && (DECL_CONSTRUCTOR_P (current_function_decl)
518           || DECL_DESTRUCTOR_P (current_function_decl)))
519     finish_expr_stmt (build_throw (NULL_TREE));
520 }
521
522 tree
523 begin_eh_spec_block (void)
524 {
525   tree r = build_stmt (input_location, EH_SPEC_BLOCK, NULL_TREE, NULL_TREE);
526   add_stmt (r);
527   EH_SPEC_STMTS (r) = push_stmt_list ();
528   return r;
529 }
530
531 void
532 finish_eh_spec_block (tree raw_raises, tree eh_spec_block)
533 {
534   tree raises;
535
536   EH_SPEC_STMTS (eh_spec_block) = pop_stmt_list (EH_SPEC_STMTS (eh_spec_block));
537
538   /* Strip cv quals, etc, from the specification types.  */
539   for (raises = NULL_TREE;
540        raw_raises && TREE_VALUE (raw_raises);
541        raw_raises = TREE_CHAIN (raw_raises))
542     {
543       tree type = prepare_eh_type (TREE_VALUE (raw_raises));
544       tree tinfo = eh_type_info (type);
545
546       mark_used (tinfo);
547       raises = tree_cons (NULL_TREE, type, raises);
548     }
549
550   EH_SPEC_RAISES (eh_spec_block) = raises;
551 }
552
553 /* Return a pointer to a buffer for an exception object of type TYPE.  */
554
555 static tree
556 do_allocate_exception (tree type)
557 {
558   tree fn;
559
560   fn = get_identifier ("__cxa_allocate_exception");
561   if (!get_global_value_if_present (fn, &fn))
562     {
563       /* Declare void *__cxa_allocate_exception(size_t) throw().  */
564       fn = declare_nothrow_library_fn (fn, ptr_type_node, size_type_node);
565     }
566
567   return cp_build_function_call (fn, 
568                                  tree_cons (NULL_TREE, size_in_bytes (type),
569                                             NULL_TREE),
570                                  tf_warning_or_error);
571 }
572
573 /* Call __cxa_free_exception from a cleanup.  This is never invoked
574    directly, but see the comment for stabilize_throw_expr.  */
575
576 static tree
577 do_free_exception (tree ptr)
578 {
579   tree fn;
580
581   fn = get_identifier ("__cxa_free_exception");
582   if (!get_global_value_if_present (fn, &fn))
583     {
584       /* Declare void __cxa_free_exception (void *) throw().  */
585       fn = declare_nothrow_library_fn (fn, void_type_node, ptr_type_node);
586     }
587
588   return cp_build_function_call (fn, tree_cons (NULL_TREE, ptr, NULL_TREE),
589                                  tf_warning_or_error);
590 }
591
592 /* Wrap all cleanups for TARGET_EXPRs in MUST_NOT_THROW_EXPR.
593    Called from build_throw via walk_tree_without_duplicates.  */
594
595 static tree
596 wrap_cleanups_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
597                  void *data ATTRIBUTE_UNUSED)
598 {
599   tree exp = *tp;
600   tree cleanup;
601
602   /* Don't walk into types.  */
603   if (TYPE_P (exp))
604     {
605       *walk_subtrees = 0;
606       return NULL_TREE;
607     }
608   if (TREE_CODE (exp) != TARGET_EXPR)
609     return NULL_TREE;
610
611   cleanup = TARGET_EXPR_CLEANUP (exp);
612   if (cleanup)
613     {
614       cleanup = build1 (MUST_NOT_THROW_EXPR, void_type_node, cleanup);
615       TARGET_EXPR_CLEANUP (exp) = cleanup;
616     }
617
618   /* Keep iterating.  */
619   return NULL_TREE;
620 }
621
622 /* Build a throw expression.  */
623
624 tree
625 build_throw (tree exp)
626 {
627   tree fn;
628
629   if (exp == error_mark_node)
630     return exp;
631
632   if (processing_template_decl)
633     {
634       if (cfun)
635         current_function_returns_abnormally = 1;
636       return build_min (THROW_EXPR, void_type_node, exp);
637     }
638
639   if (exp == null_node)
640     warning (0, "throwing NULL, which has integral, not pointer type");
641
642   if (exp != NULL_TREE)
643     {
644       if (!is_admissible_throw_operand (exp))
645         return error_mark_node;
646     }
647
648   if (! doing_eh (1))
649     return error_mark_node;
650
651   if (exp && decl_is_java_type (TREE_TYPE (exp), 1))
652     {
653       tree fn = get_identifier ("_Jv_Throw");
654       if (!get_global_value_if_present (fn, &fn))
655         {
656           /* Declare void _Jv_Throw (void *).  */
657           tree tmp = tree_cons (NULL_TREE, ptr_type_node, void_list_node);
658           tmp = build_function_type (ptr_type_node, tmp);
659           fn = push_throw_library_fn (fn, tmp);
660         }
661       else if (really_overloaded_fn (fn))
662         {
663           error ("%qD should never be overloaded", fn);
664           return error_mark_node;
665         }
666       fn = OVL_CURRENT (fn);
667       exp = cp_build_function_call (fn, tree_cons (NULL_TREE, exp, NULL_TREE),
668                                     tf_warning_or_error);
669     }
670   else if (exp)
671     {
672       tree throw_type;
673       tree temp_type;
674       tree cleanup;
675       tree object, ptr;
676       tree tmp;
677       tree temp_expr, allocate_expr;
678       bool elided;
679
680       /* The CLEANUP_TYPE is the internal type of a destructor.  */
681       if (!cleanup_type)
682         {
683           tmp = void_list_node;
684           tmp = tree_cons (NULL_TREE, ptr_type_node, tmp);
685           tmp = build_function_type (void_type_node, tmp);
686           cleanup_type = build_pointer_type (tmp);
687         }
688
689       fn = get_identifier ("__cxa_throw");
690       if (!get_global_value_if_present (fn, &fn))
691         {
692           /* Declare void __cxa_throw (void*, void*, void (*)(void*)).  */
693           /* ??? Second argument is supposed to be "std::type_info*".  */
694           tmp = void_list_node;
695           tmp = tree_cons (NULL_TREE, cleanup_type, tmp);
696           tmp = tree_cons (NULL_TREE, ptr_type_node, tmp);
697           tmp = tree_cons (NULL_TREE, ptr_type_node, tmp);
698           tmp = build_function_type (void_type_node, tmp);
699           fn = push_throw_library_fn (fn, tmp);
700         }
701
702       /* [except.throw]
703
704          A throw-expression initializes a temporary object, the type
705          of which is determined by removing any top-level
706          cv-qualifiers from the static type of the operand of throw
707          and adjusting the type from "array of T" or "function return
708          T" to "pointer to T" or "pointer to function returning T"
709          respectively.  */
710       temp_type = is_bitfield_expr_with_lowered_type (exp);
711       if (!temp_type)
712         temp_type = type_decays_to (TREE_TYPE (exp));
713
714       /* OK, this is kind of wacky.  The standard says that we call
715          terminate when the exception handling mechanism, after
716          completing evaluation of the expression to be thrown but
717          before the exception is caught (_except.throw_), calls a
718          user function that exits via an uncaught exception.
719
720          So we have to protect the actual initialization of the
721          exception object with terminate(), but evaluate the
722          expression first.  Since there could be temps in the
723          expression, we need to handle that, too.  We also expand
724          the call to __cxa_allocate_exception first (which doesn't
725          matter, since it can't throw).  */
726
727       /* Allocate the space for the exception.  */
728       allocate_expr = do_allocate_exception (temp_type);
729       allocate_expr = get_target_expr (allocate_expr);
730       ptr = TARGET_EXPR_SLOT (allocate_expr);
731       object = build_nop (build_pointer_type (temp_type), ptr);
732       object = cp_build_indirect_ref (object, NULL, tf_warning_or_error);
733
734       elided = (TREE_CODE (exp) == TARGET_EXPR);
735
736       /* And initialize the exception object.  */
737       if (CLASS_TYPE_P (temp_type))
738         {
739           int flags = LOOKUP_NORMAL | LOOKUP_ONLYCONVERTING;
740           VEC(tree,gc) *exp_vec;
741
742           /* Under C++0x [12.8/16 class.copy], a thrown lvalue is sometimes
743              treated as an rvalue for the purposes of overload resolution
744              to favor move constructors over copy constructors.  */
745           if (/* Must be a local, automatic variable.  */
746               TREE_CODE (exp) == VAR_DECL
747               && DECL_CONTEXT (exp) == current_function_decl
748               && ! TREE_STATIC (exp)
749               /* The variable must not have the `volatile' qualifier.  */
750               && !(cp_type_quals (TREE_TYPE (exp)) & TYPE_QUAL_VOLATILE))
751             flags = flags | LOOKUP_PREFER_RVALUE;
752
753           /* Call the copy constructor.  */
754           exp_vec = make_tree_vector_single (exp);
755           exp = (build_special_member_call
756                  (object, complete_ctor_identifier, &exp_vec,
757                   TREE_TYPE (object), flags, tf_warning_or_error));
758           release_tree_vector (exp_vec);
759           if (exp == error_mark_node)
760             {
761               error ("  in thrown expression");
762               return error_mark_node;
763             }
764         }
765       else
766         exp = build2 (INIT_EXPR, temp_type, object,
767                       decay_conversion (exp));
768
769       /* Pre-evaluate the thrown expression first, since if we allocated
770          the space first we would have to deal with cleaning it up if
771          evaluating this expression throws.
772
773          The case where EXP the initializer is a cast or a function
774          returning a class is a bit of a grey area in the standard; it's
775          unclear whether or not it should be allowed to throw.  We used to
776          say no, as that allowed us to optimize this case without worrying
777          about deallocating the exception object if it does.  But that
778          conflicted with expectations (PR 13944) and the EDG compiler; now
779          we wrap the initialization in a TRY_CATCH_EXPR to call
780          do_free_exception rather than in a MUST_NOT_THROW_EXPR, for this
781          case only.
782
783          BUT: Issue 475 may do away with this inconsistency by removing the
784          terminate() in this situation.
785
786          Note that we don't check the return value from stabilize_init
787          because it will only return false in cases where elided is true,
788          and therefore we don't need to work around the failure to
789          preevaluate.  */
790       temp_expr = NULL_TREE;
791       stabilize_init (exp, &temp_expr);
792
793       /* Wrap the initialization in a CLEANUP_POINT_EXPR so that cleanups
794          for temporaries within the initialization are run before the one
795          for the exception object, preserving LIFO order.  */
796       exp = build1 (CLEANUP_POINT_EXPR, void_type_node, exp);
797
798       if (elided)
799         exp = build2 (TRY_CATCH_EXPR, void_type_node, exp,
800                       do_free_exception (ptr));
801       else
802         exp = build1 (MUST_NOT_THROW_EXPR, void_type_node, exp);
803
804       /* Prepend the allocation.  */
805       exp = build2 (COMPOUND_EXPR, TREE_TYPE (exp), allocate_expr, exp);
806       if (temp_expr)
807         {
808           /* Prepend the calculation of the throw expression.  Also, force
809              any cleanups from the expression to be evaluated here so that
810              we don't have to do them during unwinding.  But first wrap
811              them in MUST_NOT_THROW_EXPR, since they are run after the
812              exception object is initialized.  */
813           cp_walk_tree_without_duplicates (&temp_expr, wrap_cleanups_r, 0);
814           exp = build2 (COMPOUND_EXPR, TREE_TYPE (exp), temp_expr, exp);
815           exp = build1 (CLEANUP_POINT_EXPR, TREE_TYPE (exp), exp);
816         }
817
818       throw_type = build_eh_type_type (prepare_eh_type (TREE_TYPE (object)));
819
820       if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (object)))
821         {
822           cleanup = lookup_fnfields (TYPE_BINFO (TREE_TYPE (object)),
823                                      complete_dtor_identifier, 0);
824           cleanup = BASELINK_FUNCTIONS (cleanup);
825           mark_used (cleanup);
826           cxx_mark_addressable (cleanup);
827           /* Pretend it's a normal function.  */
828           cleanup = build1 (ADDR_EXPR, cleanup_type, cleanup);
829         }
830       else
831         cleanup = build_int_cst (cleanup_type, 0);
832
833       tmp = tree_cons (NULL_TREE, cleanup, NULL_TREE);
834       tmp = tree_cons (NULL_TREE, throw_type, tmp);
835       tmp = tree_cons (NULL_TREE, ptr, tmp);
836       /* ??? Indicate that this function call throws throw_type.  */
837       tmp = cp_build_function_call (fn, tmp, tf_warning_or_error);
838
839       /* Tack on the initialization stuff.  */
840       exp = build2 (COMPOUND_EXPR, TREE_TYPE (tmp), exp, tmp);
841     }
842   else
843     {
844       /* Rethrow current exception.  */
845
846       tree fn = get_identifier ("__cxa_rethrow");
847       if (!get_global_value_if_present (fn, &fn))
848         {
849           /* Declare void __cxa_rethrow (void).  */
850           fn = push_throw_library_fn
851             (fn, build_function_type (void_type_node, void_list_node));
852         }
853
854       /* ??? Indicate that this function call allows exceptions of the type
855          of the enclosing catch block (if known).  */
856       exp = cp_build_function_call (fn, NULL_TREE, tf_warning_or_error);
857     }
858
859   exp = build1 (THROW_EXPR, void_type_node, exp);
860
861   return exp;
862 }
863
864 /* Make sure TYPE is complete, pointer to complete, reference to
865    complete, or pointer to cv void. Issue diagnostic on failure.
866    Return the zero on failure and nonzero on success. FROM can be
867    the expr or decl from whence TYPE came, if available.  */
868
869 static int
870 complete_ptr_ref_or_void_ptr_p (tree type, tree from)
871 {
872   int is_ptr;
873
874   /* Check complete.  */
875   type = complete_type_or_else (type, from);
876   if (!type)
877     return 0;
878
879   /* Or a pointer or ref to one, or cv void *.  */
880   is_ptr = TREE_CODE (type) == POINTER_TYPE;
881   if (is_ptr || TREE_CODE (type) == REFERENCE_TYPE)
882     {
883       tree core = TREE_TYPE (type);
884
885       if (is_ptr && VOID_TYPE_P (core))
886         /* OK */;
887       else if (!complete_type_or_else (core, from))
888         return 0;
889     }
890   return 1;
891 }
892
893 /* Return truth-value if EXPRESSION is admissible in throw-expression,
894    i.e. if it is not of incomplete type or a pointer/reference to such
895    a type or of an abstract class type.  */
896
897 static bool
898 is_admissible_throw_operand (tree expr)
899 {
900   tree type = TREE_TYPE (expr);
901
902   /* 15.1/4 [...] The type of the throw-expression shall not be an
903             incomplete type, or a pointer or a reference to an incomplete
904             type, other than void*, const void*, volatile void*, or
905             const volatile void*.  Except for these restriction and the
906             restrictions on type matching mentioned in 15.3, the operand
907             of throw is treated exactly as a function argument in a call
908             (5.2.2) or the operand of a return statement.  */
909   if (!complete_ptr_ref_or_void_ptr_p (type, expr))
910     return false;
911
912   /* 10.4/3 An abstract class shall not be used as a parameter type,
913             as a function return type or as type of an explicit
914             conversion.  */
915   else if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
916     {
917       error ("expression %qE of abstract class type %qT cannot "
918              "be used in throw-expression", expr, type);
919       return false;
920     }
921
922   return true;
923 }
924
925 /* Returns nonzero if FN is a declaration of a standard C library
926    function which is known not to throw.
927
928    [lib.res.on.exception.handling]: None of the functions from the
929    Standard C library shall report an error by throwing an
930    exception, unless it calls a program-supplied function that
931    throws an exception.  */
932
933 #include "cfns.h"
934
935 int
936 nothrow_libfn_p (const_tree fn)
937 {
938   tree id;
939
940   if (TREE_PUBLIC (fn)
941       && DECL_EXTERNAL (fn)
942       && DECL_NAMESPACE_SCOPE_P (fn)
943       && DECL_EXTERN_C_P (fn))
944     /* OK */;
945   else
946     /* Can't be a C library function.  */
947     return 0;
948
949   /* Being a C library function, DECL_ASSEMBLER_NAME == DECL_NAME
950      unless the system headers are playing rename tricks, and if
951      they are, we don't want to be confused by them.  */
952   id = DECL_NAME (fn);
953   return !!libc_name_p (IDENTIFIER_POINTER (id), IDENTIFIER_LENGTH (id));
954 }
955
956 /* Returns nonzero if an exception of type FROM will be caught by a
957    handler for type TO, as per [except.handle].  */
958
959 static int
960 can_convert_eh (tree to, tree from)
961 {
962   to = non_reference (to);
963   from = non_reference (from);
964
965   if (TREE_CODE (to) == POINTER_TYPE && TREE_CODE (from) == POINTER_TYPE)
966     {
967       to = TREE_TYPE (to);
968       from = TREE_TYPE (from);
969
970       if (! at_least_as_qualified_p (to, from))
971         return 0;
972
973       if (TREE_CODE (to) == VOID_TYPE)
974         return 1;
975
976       /* Else fall through.  */
977     }
978
979   if (CLASS_TYPE_P (to) && CLASS_TYPE_P (from)
980       && PUBLICLY_UNIQUELY_DERIVED_P (to, from))
981     return 1;
982
983   return 0;
984 }
985
986 /* Check whether any of the handlers in I are shadowed by another handler
987    accepting TYPE.  Note that the shadowing may not be complete; even if
988    an exception of type B would be caught by a handler for A, there could
989    be a derived class C for which A is an ambiguous base but B is not, so
990    the handler for B would catch an exception of type C.  */
991
992 static void
993 check_handlers_1 (tree master, tree_stmt_iterator i)
994 {
995   tree type = TREE_TYPE (master);
996
997   for (; !tsi_end_p (i); tsi_next (&i))
998     {
999       tree handler = tsi_stmt (i);
1000       if (TREE_TYPE (handler) && can_convert_eh (type, TREE_TYPE (handler)))
1001         {
1002           warning_at (EXPR_LOCATION (handler), 0,
1003                       "exception of type %qT will be caught",
1004                       TREE_TYPE (handler));
1005           warning_at (EXPR_LOCATION (master), 0,
1006                       "   by earlier handler for %qT", type);
1007           break;
1008         }
1009     }
1010 }
1011
1012 /* Given a STATEMENT_LIST of HANDLERs, make sure that they're OK.  */
1013
1014 void
1015 check_handlers (tree handlers)
1016 {
1017   tree_stmt_iterator i;
1018
1019   /* If we don't have a STATEMENT_LIST, then we've just got one
1020      handler, and thus nothing to warn about.  */
1021   if (TREE_CODE (handlers) != STATEMENT_LIST)
1022     return;
1023
1024   i = tsi_start (handlers);
1025   if (!tsi_end_p (i))
1026     while (1)
1027       {
1028         tree handler = tsi_stmt (i);
1029         tsi_next (&i);
1030
1031         /* No more handlers; nothing to shadow.  */
1032         if (tsi_end_p (i))
1033           break;
1034         if (TREE_TYPE (handler) == NULL_TREE)
1035           permerror (EXPR_LOCATION (handler), "%<...%>"
1036                      " handler must be the last handler for its try block");
1037         else
1038           check_handlers_1 (handler, i);
1039       }
1040 }