OSDN Git Service

2002-08-24 Matt Austern <austern@apple.com>
[pf3gnuchains/gcc-fork.git] / gcc / cp / decl2.c
1 /* Process declarations and variables for C compiler.
2    Copyright (C) 1988, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3    1999, 2000, 2001, 2002 Free Software Foundation, Inc.
4    Hacked by Michael Tiemann (tiemann@cygnus.com)
5
6 This file is part of GNU CC.
7
8 GNU CC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2, or (at your option)
11 any later version.
12
13 GNU CC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GNU CC; see the file COPYING.  If not, write to
20 the Free Software Foundation, 59 Temple Place - Suite 330,
21 Boston, MA 02111-1307, USA.  */
22
23
24 /* Process declarations and symbol lookup for C front end.
25    Also constructs types; the standard scalar types at initialization,
26    and structure, union, array and enum types when they are declared.  */
27
28 /* ??? not all decl nodes are given the most useful possible
29    line numbers.  For example, the CONST_DECLs for enum values.  */
30
31 #include "config.h"
32 #include "system.h"
33 #include "tree.h"
34 #include "rtl.h"
35 #include "expr.h"
36 #include "flags.h"
37 #include "cp-tree.h"
38 #include "decl.h"
39 #include "lex.h"
40 #include "output.h"
41 #include "except.h"
42 #include "toplev.h"
43 #include "ggc.h"
44 #include "timevar.h"
45 #include "cpplib.h"
46 #include "target.h"
47 #include "c-common.h"
48 extern cpp_reader *parse_in;
49
50 /* This structure contains information about the initializations
51    and/or destructions required for a particular priority level.  */
52 typedef struct priority_info_s {
53   /* Non-zero if there have been any initializations at this priority
54      throughout the translation unit.  */
55   int initializations_p;
56   /* Non-zero if there have been any destructions at this priority
57      throughout the translation unit.  */
58   int destructions_p;
59 } *priority_info;
60
61 static void mark_vtable_entries PARAMS ((tree));
62 static void grok_function_init PARAMS ((tree, tree));
63 static int finish_vtable_vardecl PARAMS ((tree *, void *));
64 static int prune_vtable_vardecl PARAMS ((tree *, void *));
65 static int is_namespace_ancestor PARAMS ((tree, tree));
66 static void add_using_namespace PARAMS ((tree, tree, int));
67 static tree ambiguous_decl PARAMS ((tree, tree, tree,int));
68 static tree build_anon_union_vars PARAMS ((tree, tree*, int, int));
69 static int acceptable_java_type PARAMS ((tree));
70 static void output_vtable_inherit PARAMS ((tree));
71 static tree start_objects PARAMS ((int, int));
72 static void finish_objects PARAMS ((int, int, tree));
73 static tree merge_functions PARAMS ((tree, tree));
74 static tree decl_namespace PARAMS ((tree));
75 static tree validate_nonmember_using_decl PARAMS ((tree, tree *, tree *));
76 static void do_nonmember_using_decl PARAMS ((tree, tree, tree, tree,
77                                            tree *, tree *));
78 static tree start_static_storage_duration_function PARAMS ((void));
79 static void finish_static_storage_duration_function PARAMS ((tree));
80 static priority_info get_priority_info PARAMS ((int));
81 static void do_static_initialization PARAMS ((tree, tree));
82 static void do_static_destruction PARAMS ((tree));
83 static tree start_static_initialization_or_destruction PARAMS ((tree, int));
84 static void finish_static_initialization_or_destruction PARAMS ((tree));
85 static void generate_ctor_or_dtor_function PARAMS ((int, int));
86 static int generate_ctor_and_dtor_functions_for_priority
87                                   PARAMS ((splay_tree_node, void *));
88 static tree prune_vars_needing_no_initialization PARAMS ((tree));
89 static void write_out_vars PARAMS ((tree));
90 static void import_export_class PARAMS ((tree));
91 static tree key_method PARAMS ((tree));
92 static tree get_guard_bits PARAMS ((tree));
93
94 /* A list of static class variables.  This is needed, because a
95    static class variable can be declared inside the class without
96    an initializer, and then initialized, statically, outside the class.  */
97 static GTY(()) varray_type pending_statics;
98 #define pending_statics_used \
99   (pending_statics ? pending_statics->elements_used : 0)
100
101 /* A list of functions which were declared inline, but which we
102    may need to emit outline anyway.  */
103 static GTY(()) varray_type deferred_fns;
104 #define deferred_fns_used \
105   (deferred_fns ? deferred_fns->elements_used : 0)
106
107 /* Flag used when debugging spew.c */
108
109 extern int spew_debug;
110
111 /* Nonzero if we're done parsing and into end-of-file activities.  */
112
113 int at_eof;
114
115 /* Functions called along with real static constructors and destructors.  */
116
117 tree static_ctors;
118 tree static_dtors;
119
120 /* The :: namespace. */
121
122 tree global_namespace;
123 \f
124 /* Incorporate `const' and `volatile' qualifiers for member functions.
125    FUNCTION is a TYPE_DECL or a FUNCTION_DECL.
126    QUALS is a list of qualifiers.  Returns any explicit
127    top-level qualifiers of the method's this pointer, anything other than
128    TYPE_UNQUALIFIED will be an extension.  */
129
130 int
131 grok_method_quals (ctype, function, quals)
132      tree ctype, function, quals;
133 {
134   tree fntype = TREE_TYPE (function);
135   tree raises = TYPE_RAISES_EXCEPTIONS (fntype);
136   int type_quals = TYPE_UNQUALIFIED;
137   int dup_quals = TYPE_UNQUALIFIED;
138   int this_quals = TYPE_UNQUALIFIED;
139
140   do
141     {
142       int tq = cp_type_qual_from_rid (TREE_VALUE (quals));
143       
144       if ((type_quals | this_quals) & tq)
145         dup_quals |= tq;
146       else if (tq & TYPE_QUAL_RESTRICT)
147         this_quals |= tq;
148       else
149         type_quals |= tq;
150       quals = TREE_CHAIN (quals);
151     } 
152   while (quals);
153
154   if (dup_quals != TYPE_UNQUALIFIED)
155     error ("duplicate type qualifiers in %s declaration",
156               TREE_CODE (function) == FUNCTION_DECL 
157               ? "member function" : "type");
158
159   ctype = cp_build_qualified_type (ctype, type_quals);
160   fntype = build_cplus_method_type (ctype, TREE_TYPE (fntype),
161                                     (TREE_CODE (fntype) == METHOD_TYPE
162                                      ? TREE_CHAIN (TYPE_ARG_TYPES (fntype))
163                                      : TYPE_ARG_TYPES (fntype)));
164   if (raises)
165     fntype = build_exception_variant (fntype, raises);
166
167   TREE_TYPE (function) = fntype;
168   return this_quals;
169 }
170
171 /* Warn when -fexternal-templates is used and #pragma
172    interface/implementation is not used all the times it should be,
173    inform the user.  */
174
175 void
176 warn_if_unknown_interface (decl)
177      tree decl;
178 {
179   static int already_warned = 0;
180   if (already_warned++)
181     return;
182
183   if (flag_alt_external_templates)
184     {
185       tree til = tinst_for_decl ();
186       int sl = lineno;
187       const char *sf = input_filename;
188
189       if (til)
190         {
191           lineno = TINST_LINE (til);
192           input_filename = TINST_FILE (til);
193         }
194       warning ("template `%#D' instantiated in file without #pragma interface",
195                   decl);
196       lineno = sl;
197       input_filename = sf;
198     }
199   else
200     cp_warning_at ("template `%#D' defined in file without #pragma interface",
201                    decl);
202 }
203
204 /* A subroutine of the parser, to handle a component list.  */
205
206 void
207 grok_x_components (specs)
208      tree specs;
209 {
210   tree t;
211
212   specs = strip_attrs (specs);
213
214   check_tag_decl (specs);
215   t = groktypename (build_tree_list (specs, NULL_TREE)); 
216
217   /* The only case where we need to do anything additional here is an
218      anonymous union field, e.g.: `struct S { union { int i; }; };'.  */
219   if (t == NULL_TREE || !ANON_AGGR_TYPE_P (t))
220     return;
221
222   fixup_anonymous_aggr (t);
223   finish_member_declaration (build_decl (FIELD_DECL, NULL_TREE, t)); 
224 }
225
226 /* Build a PARM_DECL with NAME and TYPE, and set DECL_ARG_TYPE
227    appropriately.  */
228
229 tree
230 cp_build_parm_decl (name, type)
231      tree name;
232      tree type;
233 {
234   tree parm = build_decl (PARM_DECL, name, type);
235   DECL_ARG_TYPE (parm) = type_passed_as (type);
236   return parm;
237 }
238
239 /* Returns a PARM_DECL for a parameter of the indicated TYPE, with the
240    indicated NAME.  */
241
242 tree
243 build_artificial_parm (name, type)
244      tree name;
245      tree type;
246 {
247   tree parm = cp_build_parm_decl (name, type);
248   DECL_ARTIFICIAL (parm) = 1;
249   /* All our artificial parms are implicitly `const'; they cannot be
250      assigned to.  */
251   TREE_READONLY (parm) = 1;
252   return parm;
253 }
254
255 /* Constructors for types with virtual baseclasses need an "in-charge" flag
256    saying whether this constructor is responsible for initialization of
257    virtual baseclasses or not.  All destructors also need this "in-charge"
258    flag, which additionally determines whether or not the destructor should
259    free the memory for the object.
260
261    This function adds the "in-charge" flag to member function FN if
262    appropriate.  It is called from grokclassfn and tsubst.
263    FN must be either a constructor or destructor.
264
265    The in-charge flag follows the 'this' parameter, and is followed by the
266    VTT parm (if any), then the user-written parms.  */
267
268 void
269 maybe_retrofit_in_chrg (fn)
270      tree fn;
271 {
272   tree basetype, arg_types, parms, parm, fntype;
273
274   /* If we've already add the in-charge parameter don't do it again.  */
275   if (DECL_HAS_IN_CHARGE_PARM_P (fn))
276     return;
277
278   /* When processing templates we can't know, in general, whether or
279      not we're going to have virtual baseclasses.  */
280   if (uses_template_parms (fn))
281     return;
282
283   /* We don't need an in-charge parameter for constructors that don't
284      have virtual bases.  */
285   if (DECL_CONSTRUCTOR_P (fn)
286       && !TYPE_USES_VIRTUAL_BASECLASSES (DECL_CONTEXT (fn)))
287     return;
288
289   arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
290   basetype = TREE_TYPE (TREE_VALUE (arg_types));
291   arg_types = TREE_CHAIN (arg_types);
292
293   parms = TREE_CHAIN (DECL_ARGUMENTS (fn));
294
295   /* If this is a subobject constructor or destructor, our caller will
296      pass us a pointer to our VTT.  */
297   if (TYPE_USES_VIRTUAL_BASECLASSES (DECL_CONTEXT (fn)))
298     {
299       parm = build_artificial_parm (vtt_parm_identifier, vtt_parm_type);
300
301       /* First add it to DECL_ARGUMENTS between 'this' and the real args...  */
302       TREE_CHAIN (parm) = parms;
303       parms = parm;
304
305       /* ...and then to TYPE_ARG_TYPES.  */
306       arg_types = hash_tree_chain (vtt_parm_type, arg_types);
307
308       DECL_HAS_VTT_PARM_P (fn) = 1;
309     }
310
311   /* Then add the in-charge parm (before the VTT parm).  */
312   parm = build_artificial_parm (in_charge_identifier, integer_type_node);
313   TREE_CHAIN (parm) = parms;
314   parms = parm;
315   arg_types = hash_tree_chain (integer_type_node, arg_types);
316
317   /* Insert our new parameter(s) into the list.  */
318   TREE_CHAIN (DECL_ARGUMENTS (fn)) = parms;
319
320   /* And rebuild the function type.  */
321   fntype = build_cplus_method_type (basetype, TREE_TYPE (TREE_TYPE (fn)),
322                                     arg_types);
323   if (TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn)))
324     fntype = build_exception_variant (fntype,
325                                       TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn)));
326   TREE_TYPE (fn) = fntype;
327
328   /* Now we've got the in-charge parameter.  */
329   DECL_HAS_IN_CHARGE_PARM_P (fn) = 1;
330 }
331
332 /* Classes overload their constituent function names automatically.
333    When a function name is declared in a record structure,
334    its name is changed to it overloaded name.  Since names for
335    constructors and destructors can conflict, we place a leading
336    '$' for destructors.
337
338    CNAME is the name of the class we are grokking for.
339
340    FUNCTION is a FUNCTION_DECL.  It was created by `grokdeclarator'.
341
342    FLAGS contains bits saying what's special about today's
343    arguments.  1 == DESTRUCTOR.  2 == OPERATOR.
344
345    If FUNCTION is a destructor, then we must add the `auto-delete' field
346    as a second parameter.  There is some hair associated with the fact
347    that we must "declare" this variable in the manner consistent with the
348    way the rest of the arguments were declared.
349
350    QUALS are the qualifiers for the this pointer.  */
351
352 void
353 grokclassfn (ctype, function, flags, quals)
354      tree ctype, function;
355      enum overload_flags flags;
356      tree quals;
357 {
358   tree fn_name = DECL_NAME (function);
359   int this_quals = TYPE_UNQUALIFIED;
360
361   /* Even within an `extern "C"' block, members get C++ linkage.  See
362      [dcl.link] for details.  */
363   SET_DECL_LANGUAGE (function, lang_cplusplus);
364
365   if (fn_name == NULL_TREE)
366     {
367       error ("name missing for member function");
368       fn_name = get_identifier ("<anonymous>");
369       DECL_NAME (function) = fn_name;
370     }
371
372   if (quals)
373     this_quals = grok_method_quals (ctype, function, quals);
374
375   if (TREE_CODE (TREE_TYPE (function)) == METHOD_TYPE)
376     {
377       /* Must add the class instance variable up front.  */
378       /* Right now we just make this a pointer.  But later
379          we may wish to make it special.  */
380       tree type = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (function)));
381       tree qual_type;
382       tree parm;
383
384       /* The `this' parameter is implicitly `const'; it cannot be
385          assigned to.  */
386       this_quals |= TYPE_QUAL_CONST;
387       qual_type = cp_build_qualified_type (type, this_quals);
388       parm = build_artificial_parm (this_identifier, qual_type);
389       c_apply_type_quals_to_decl (this_quals, parm);
390       TREE_CHAIN (parm) = last_function_parms;
391       last_function_parms = parm;
392     }
393
394   DECL_ARGUMENTS (function) = last_function_parms;
395   DECL_CONTEXT (function) = ctype;
396
397   if (flags == DTOR_FLAG)
398     DECL_DESTRUCTOR_P (function) = 1;
399
400   if (flags == DTOR_FLAG || DECL_CONSTRUCTOR_P (function))
401     maybe_retrofit_in_chrg (function);
402
403   if (flags == DTOR_FLAG)
404     {
405       DECL_DESTRUCTOR_P (function) = 1;
406       TYPE_HAS_DESTRUCTOR (ctype) = 1;
407     }
408 }
409
410 /* Create an ARRAY_REF, checking for the user doing things backwards
411    along the way.  */
412
413 tree
414 grok_array_decl (array_expr, index_exp)
415      tree array_expr, index_exp;
416 {
417   tree type = TREE_TYPE (array_expr);
418   tree p1, p2, i1, i2;
419
420   if (type == error_mark_node || index_exp == error_mark_node)
421     return error_mark_node;
422   if (processing_template_decl)
423     return build_min (ARRAY_REF, type ? TREE_TYPE (type) : NULL_TREE,
424                       array_expr, index_exp);
425
426   if (type == NULL_TREE)
427     {
428       /* Something has gone very wrong.  Assume we are mistakenly reducing
429          an expression instead of a declaration.  */
430       error ("parser may be lost: is there a '{' missing somewhere?");
431       return NULL_TREE;
432     }
433
434   if (TREE_CODE (type) == OFFSET_TYPE
435       || TREE_CODE (type) == REFERENCE_TYPE)
436     type = TREE_TYPE (type);
437
438   /* If they have an `operator[]', use that.  */
439   if (IS_AGGR_TYPE (type) || IS_AGGR_TYPE (TREE_TYPE (index_exp)))
440     return build_opfncall (ARRAY_REF, LOOKUP_NORMAL,
441                            array_expr, index_exp, NULL_TREE);
442
443   /* Otherwise, create an ARRAY_REF for a pointer or array type.  It
444      is a little-known fact that, if `a' is an array and `i' is an
445      int, you can write `i[a]', which means the same thing as `a[i]'.  */
446
447   if (TREE_CODE (type) == ARRAY_TYPE)
448     p1 = array_expr;
449   else
450     p1 = build_expr_type_conversion (WANT_POINTER, array_expr, 0);
451
452   if (TREE_CODE (TREE_TYPE (index_exp)) == ARRAY_TYPE)
453     p2 = index_exp;
454   else
455     p2 = build_expr_type_conversion (WANT_POINTER, index_exp, 0);
456
457   i1 = build_expr_type_conversion (WANT_INT | WANT_ENUM, array_expr, 0);
458   i2 = build_expr_type_conversion (WANT_INT | WANT_ENUM, index_exp, 0);
459
460   if ((p1 && i2) && (i1 && p2))
461     error ("ambiguous conversion for array subscript");
462
463   if (p1 && i2)
464     array_expr = p1, index_exp = i2;
465   else if (i1 && p2)
466     array_expr = p2, index_exp = i1;
467   else
468     {
469       error ("invalid types `%T[%T]' for array subscript",
470                 type, TREE_TYPE (index_exp));
471       return error_mark_node;
472     }
473
474   if (array_expr == error_mark_node || index_exp == error_mark_node)
475     error ("ambiguous conversion for array subscript");
476
477   return build_array_ref (array_expr, index_exp);
478 }
479
480 /* Given the cast expression EXP, checking out its validity.   Either return
481    an error_mark_node if there was an unavoidable error, return a cast to
482    void for trying to delete a pointer w/ the value 0, or return the
483    call to delete.  If DOING_VEC is 1, we handle things differently
484    for doing an array delete.  If DOING_VEC is 2, they gave us the
485    array size as an argument to delete.
486    Implements ARM $5.3.4.  This is called from the parser.  */
487
488 tree
489 delete_sanity (exp, size, doing_vec, use_global_delete)
490      tree exp, size;
491      int doing_vec, use_global_delete;
492 {
493   tree t, type;
494   /* For a regular vector delete (aka, no size argument) we will pass
495      this down as a NULL_TREE into build_vec_delete.  */
496   tree maxindex = NULL_TREE;
497
498   if (exp == error_mark_node)
499     return exp;
500
501   if (processing_template_decl)
502     {
503       t = build_min (DELETE_EXPR, void_type_node, exp, size);
504       DELETE_EXPR_USE_GLOBAL (t) = use_global_delete;
505       DELETE_EXPR_USE_VEC (t) = doing_vec;
506       return t;
507     }
508
509   if (TREE_CODE (exp) == OFFSET_REF)
510     exp = resolve_offset_ref (exp);
511   exp = convert_from_reference (exp);
512   t = stabilize_reference (exp);
513   t = build_expr_type_conversion (WANT_POINTER, t, 1);
514
515   if (t == NULL_TREE || t == error_mark_node)
516     {
517       error ("type `%#T' argument given to `delete', expected pointer",
518                 TREE_TYPE (exp));
519       return error_mark_node;
520     }
521
522   if (doing_vec == 2)
523     {
524       maxindex = cp_build_binary_op (MINUS_EXPR, size, integer_one_node);
525       pedwarn ("anachronistic use of array size in vector delete");
526     }
527
528   type = TREE_TYPE (t);
529
530   /* As of Valley Forge, you can delete a pointer to const.  */
531
532   /* You can't delete functions.  */
533   if (TREE_CODE (TREE_TYPE (type)) == FUNCTION_TYPE)
534     {
535       error ("cannot delete a function.  Only pointer-to-objects are valid arguments to `delete'");
536       return error_mark_node;
537     }
538
539   /* Deleting ptr to void is undefined behaviour [expr.delete/3].  */
540   if (TREE_CODE (TREE_TYPE (type)) == VOID_TYPE)
541     {
542       warning ("deleting `%T' is undefined", type);
543       doing_vec = 0;
544     }
545
546   /* An array can't have been allocated by new, so complain.  */
547   if (TREE_CODE (t) == ADDR_EXPR
548       && TREE_CODE (TREE_OPERAND (t, 0)) == VAR_DECL
549       && TREE_CODE (TREE_TYPE (TREE_OPERAND (t, 0))) == ARRAY_TYPE)
550     warning ("deleting array `%#D'", TREE_OPERAND (t, 0));
551
552   /* Deleting a pointer with the value zero is valid and has no effect.  */
553   if (integer_zerop (t))
554     return build1 (NOP_EXPR, void_type_node, t);
555
556   if (doing_vec)
557     return build_vec_delete (t, maxindex, sfk_deleting_destructor,
558                              use_global_delete);
559   else
560     return build_delete (type, t, sfk_deleting_destructor,
561                          LOOKUP_NORMAL, use_global_delete);
562 }
563
564 /* Report an error if the indicated template declaration is not the
565    sort of thing that should be a member template.  */
566
567 void
568 check_member_template (tmpl)
569      tree tmpl;
570 {
571   tree decl;
572
573   my_friendly_assert (TREE_CODE (tmpl) == TEMPLATE_DECL, 0);
574   decl = DECL_TEMPLATE_RESULT (tmpl);
575
576   if (TREE_CODE (decl) == FUNCTION_DECL
577       || (TREE_CODE (decl) == TYPE_DECL
578           && IS_AGGR_TYPE (TREE_TYPE (decl))))
579     {
580       if (current_function_decl)
581         /* 14.5.2.2 [temp.mem]
582            
583            A local class shall not have member templates. */
584         error ("invalid declaration of member template `%#D' in local class",
585                   decl);
586       
587       if (TREE_CODE (decl) == FUNCTION_DECL && DECL_VIRTUAL_P (decl))
588         {
589           /* 14.5.2.3 [temp.mem]
590
591              A member function template shall not be virtual.  */
592           error 
593             ("invalid use of `virtual' in template declaration of `%#D'",
594              decl);
595           DECL_VIRTUAL_P (decl) = 0;
596         }
597
598       /* The debug-information generating code doesn't know what to do
599          with member templates.  */ 
600       DECL_IGNORED_P (tmpl) = 1;
601     } 
602   else
603     error ("template declaration of `%#D'", decl);
604 }
605
606 /* Return true iff TYPE is a valid Java parameter or return type. */
607
608 static int
609 acceptable_java_type (type)
610      tree type;
611 {
612   if (TREE_CODE (type) == VOID_TYPE || TYPE_FOR_JAVA (type))
613     return 1;
614   if (TREE_CODE (type) == POINTER_TYPE || TREE_CODE (type) == REFERENCE_TYPE)
615     {
616       type = TREE_TYPE (type);
617       if (TREE_CODE (type) == RECORD_TYPE)
618         {
619           tree args;  int i;
620           if (! TYPE_FOR_JAVA (type))
621             return 0;
622           if (! CLASSTYPE_TEMPLATE_INFO (type))
623             return 1;
624           args = CLASSTYPE_TI_ARGS (type);
625           i = TREE_VEC_LENGTH (args);
626           while (--i >= 0)
627             {
628               type = TREE_VEC_ELT (args, i);
629               if (TREE_CODE (type) == POINTER_TYPE)
630                 type = TREE_TYPE (type);
631               if (! TYPE_FOR_JAVA (type))
632                 return 0;
633             }
634           return 1;
635         }
636     }
637   return 0;
638 }
639
640 /* For a METHOD in a Java class CTYPE, return 1 if
641    the parameter and return types are valid Java types.
642    Otherwise, print appropriate error messages, and return 0.  */
643
644 int
645 check_java_method (method)
646      tree method;
647 {
648   int jerr = 0;
649   tree arg_types = TYPE_ARG_TYPES (TREE_TYPE (method));
650   tree ret_type = TREE_TYPE (TREE_TYPE (method));
651   if (! acceptable_java_type (ret_type))
652     {
653       error ("Java method '%D' has non-Java return type `%T'",
654                 method, ret_type);
655       jerr++;
656     }
657   for (; arg_types != NULL_TREE; arg_types = TREE_CHAIN (arg_types))
658     {
659       tree type = TREE_VALUE (arg_types);
660       if (! acceptable_java_type (type))
661         {
662           error ("Java method '%D' has non-Java parameter type `%T'",
663                     method, type);
664           jerr++;
665         }
666     }
667   return jerr ? 0 : 1;
668 }
669
670 /* Sanity check: report error if this function FUNCTION is not
671    really a member of the class (CTYPE) it is supposed to belong to.
672    CNAME is the same here as it is for grokclassfn above.  */
673
674 tree
675 check_classfn (ctype, function)
676      tree ctype, function;
677 {
678   tree fn_name = DECL_NAME (function);
679   tree fndecl, fndecls;
680   tree method_vec = CLASSTYPE_METHOD_VEC (complete_type (ctype));
681   tree *methods = 0;
682   tree *end = 0;
683   
684   if (DECL_USE_TEMPLATE (function)
685       && !(TREE_CODE (function) == TEMPLATE_DECL
686            && DECL_TEMPLATE_SPECIALIZATION (function))
687       && is_member_template (DECL_TI_TEMPLATE (function)))
688     /* Since this is a specialization of a member template,
689        we're not going to find the declaration in the class.
690        For example, in:
691        
692          struct S { template <typename T> void f(T); };
693          template <> void S::f(int);
694        
695        we're not going to find `S::f(int)', but there's no
696        reason we should, either.  We let our callers know we didn't
697        find the method, but we don't complain.  */
698     return NULL_TREE;
699       
700   if (method_vec != 0)
701     {
702       methods = &TREE_VEC_ELT (method_vec, 0);
703       end = TREE_VEC_END (method_vec);
704
705       /* First suss out ctors and dtors.  */
706       if (*methods && fn_name == DECL_NAME (OVL_CURRENT (*methods))
707           && DECL_CONSTRUCTOR_P (function))
708         goto got_it;
709       if (*++methods && fn_name == DECL_NAME (OVL_CURRENT (*methods))
710           && DECL_DESTRUCTOR_P (function))
711         goto got_it;
712
713       while (++methods != end && *methods)
714         {
715           fndecl = *methods;
716           if (fn_name == DECL_NAME (OVL_CURRENT (*methods)))
717             {
718             got_it:
719               for (fndecls = *methods; fndecls != NULL_TREE;
720                    fndecls = OVL_NEXT (fndecls))
721                 {
722                   fndecl = OVL_CURRENT (fndecls);
723
724                   /* We cannot simply call decls_match because this
725                      doesn't work for static member functions that are 
726                      pretending to be methods, and because the name
727                      may have been changed by asm("new_name").  */ 
728                   if (DECL_NAME (function) == DECL_NAME (fndecl))
729                     {
730                       tree p1 = TYPE_ARG_TYPES (TREE_TYPE (function));
731                       tree p2 = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
732
733                       /* Get rid of the this parameter on functions that become
734                          static.  */
735                       if (DECL_STATIC_FUNCTION_P (fndecl)
736                           && TREE_CODE (TREE_TYPE (function)) == METHOD_TYPE)
737                         p1 = TREE_CHAIN (p1);
738
739                       if (same_type_p (TREE_TYPE (TREE_TYPE (function)),
740                                        TREE_TYPE (TREE_TYPE (fndecl)))
741                           && compparms (p1, p2)
742                           && (DECL_TEMPLATE_SPECIALIZATION (function)
743                               == DECL_TEMPLATE_SPECIALIZATION (fndecl))
744                           && (!DECL_TEMPLATE_SPECIALIZATION (function)
745                               || (DECL_TI_TEMPLATE (function) 
746                                   == DECL_TI_TEMPLATE (fndecl))))
747                         return fndecl;
748                     }
749                 }
750               break;            /* loser */
751             }
752         }
753     }
754
755   if (methods != end && *methods)
756     {
757       tree fndecl = *methods;
758       error ("prototype for `%#D' does not match any in class `%T'",
759                 function, ctype);
760       cp_error_at ("candidate%s: %+#D", OVL_NEXT (fndecl) ? "s are" : " is",
761                    OVL_CURRENT (fndecl));
762       while (fndecl = OVL_NEXT (fndecl), fndecl)
763         cp_error_at ("                %#D", OVL_CURRENT(fndecl));
764     }
765   else
766     {
767       methods = 0;
768       if (!COMPLETE_TYPE_P (ctype))
769         cxx_incomplete_type_error (function, ctype);
770       else
771         error ("no `%#D' member function declared in class `%T'",
772                   function, ctype);
773     }
774
775   /* If we did not find the method in the class, add it to avoid
776      spurious errors (unless the CTYPE is not yet defined, in which
777      case we'll only confuse ourselves when the function is declared
778      properly within the class.  */
779   if (COMPLETE_TYPE_P (ctype))
780     add_method (ctype, function, /*error_p=*/1);
781   return NULL_TREE;
782 }
783
784 /* We have just processed the DECL, which is a static data member.
785    Its initializer, if present, is INIT.  The ASMSPEC_TREE, if
786    present, is the assembly-language name for the data member.
787    FLAGS is as for cp_finish_decl.  */
788
789 void
790 finish_static_data_member_decl (decl, init, asmspec_tree, flags)
791      tree decl;
792      tree init;
793      tree asmspec_tree;
794      int flags;
795 {
796   my_friendly_assert (TREE_PUBLIC (decl), 0);
797
798   DECL_CONTEXT (decl) = current_class_type;
799
800   /* We cannot call pushdecl here, because that would fill in the
801      TREE_CHAIN of our decl.  Instead, we modify cp_finish_decl to do
802      the right thing, namely, to put this decl out straight away.  */
803   /* current_class_type can be NULL_TREE in case of error.  */
804   if (!asmspec_tree && current_class_type)
805     DECL_INITIAL (decl) = error_mark_node;
806
807   if (! processing_template_decl)
808     {
809       if (!pending_statics)
810         VARRAY_TREE_INIT (pending_statics, 32, "pending_statics");
811       VARRAY_PUSH_TREE (pending_statics, decl);
812     }
813
814   if (LOCAL_CLASS_P (current_class_type))
815     pedwarn ("local class `%#T' shall not have static data member `%#D'",
816              current_class_type, decl);
817
818   /* Static consts need not be initialized in the class definition.  */
819   if (init != NULL_TREE && TYPE_NEEDS_CONSTRUCTING (TREE_TYPE (decl)))
820     {
821       static int explained = 0;
822           
823       error ("initializer invalid for static member with constructor");
824       if (!explained)
825         {
826           error ("(an out of class initialization is required)");
827           explained = 1;
828         }
829       init = NULL_TREE;
830     }
831   /* Force the compiler to know when an uninitialized static const
832      member is being used.  */
833   if (CP_TYPE_CONST_P (TREE_TYPE (decl)) && init == 0)
834     TREE_USED (decl) = 1;
835   DECL_INITIAL (decl) = init;
836   DECL_IN_AGGR_P (decl) = 1;
837
838   cp_finish_decl (decl, init, asmspec_tree, flags);
839 }
840
841 /* Process the specs, declarator (NULL if omitted) and width (NULL if omitted)
842    of a structure component, returning a _DECL node.
843    QUALS is a list of type qualifiers for this decl (such as for declaring
844    const member functions).
845
846    This is done during the parsing of the struct declaration.
847    The _DECL nodes are chained together and the lot of them
848    are ultimately passed to `build_struct' to make the RECORD_TYPE node.
849
850    If class A defines that certain functions in class B are friends, then
851    the way I have set things up, it is B who is interested in permission
852    granted by A.  However, it is in A's context that these declarations
853    are parsed.  By returning a void_type_node, class A does not attempt
854    to incorporate the declarations of the friends within its structure.
855
856    DO NOT MAKE ANY CHANGES TO THIS CODE WITHOUT MAKING CORRESPONDING
857    CHANGES TO CODE IN `start_method'.  */
858
859 tree
860 grokfield (declarator, declspecs, init, asmspec_tree, attrlist)
861      tree declarator, declspecs, init, asmspec_tree, attrlist;
862 {
863   tree value;
864   const char *asmspec = 0;
865   int flags = LOOKUP_ONLYCONVERTING;
866
867   /* Convert () initializers to = initializers.  */
868   if (init == NULL_TREE && declarator != NULL_TREE
869       && TREE_CODE (declarator) == CALL_EXPR
870       && TREE_OPERAND (declarator, 0)
871       && (TREE_CODE (TREE_OPERAND (declarator, 0)) == IDENTIFIER_NODE
872           || TREE_CODE (TREE_OPERAND (declarator, 0)) == SCOPE_REF)
873       && parmlist_is_exprlist (CALL_DECLARATOR_PARMS (declarator)))
874     {
875       /* It's invalid to try to initialize a data member using a
876          functional notation, e.g.:
877          
878             struct S {
879               static int i (3);
880             };
881             
882          Explain that to the user.  */
883       static int explained;
884
885       error ("invalid data member initialization");
886       if (!explained)
887         {
888           error ("(use `=' to initialize static data members)");
889           explained = 1;
890         }
891
892       declarator = TREE_OPERAND (declarator, 0);
893       flags = 0;
894     }
895
896   if (declspecs == NULL_TREE
897       && TREE_CODE (declarator) == SCOPE_REF
898       && TREE_CODE (TREE_OPERAND (declarator, 1)) == IDENTIFIER_NODE)
899     {
900       /* Access declaration */
901       if (! IS_AGGR_TYPE_CODE (TREE_CODE (TREE_OPERAND (declarator, 0))))
902         ;
903       else if (TREE_COMPLEXITY (declarator) == current_class_depth)
904         pop_nested_class ();
905       return do_class_using_decl (declarator);
906     }
907
908   if (init
909       && TREE_CODE (init) == TREE_LIST
910       && TREE_VALUE (init) == error_mark_node
911       && TREE_CHAIN (init) == NULL_TREE)
912     init = NULL_TREE;
913
914   value = grokdeclarator (declarator, declspecs, FIELD, init != 0, &attrlist);
915   if (! value || value == error_mark_node)
916     /* friend or constructor went bad.  */
917     return value;
918   if (TREE_TYPE (value) == error_mark_node)
919     return error_mark_node;  
920
921   /* Pass friendly classes back.  */
922   if (TREE_CODE (value) == VOID_TYPE)
923     return void_type_node;
924
925   if (DECL_NAME (value) != NULL_TREE
926       && IDENTIFIER_POINTER (DECL_NAME (value))[0] == '_'
927       && ! strcmp (IDENTIFIER_POINTER (DECL_NAME (value)), "_vptr"))
928     error ("member `%D' conflicts with virtual function table field name",
929               value);
930
931   /* Stash away type declarations.  */
932   if (TREE_CODE (value) == TYPE_DECL)
933     {
934       DECL_NONLOCAL (value) = 1;
935       DECL_CONTEXT (value) = current_class_type;
936
937       if (CLASS_TYPE_P (TREE_TYPE (value)))
938         CLASSTYPE_GOT_SEMICOLON (TREE_TYPE (value)) = 1;
939       
940       if (processing_template_decl)
941         value = push_template_decl (value);
942
943       return value;
944     }
945
946   if (DECL_IN_AGGR_P (value))
947     {
948       error ("`%D' is already defined in `%T'", value,
949                 DECL_CONTEXT (value));
950       return void_type_node;
951     }
952
953   if (asmspec_tree)
954     asmspec = TREE_STRING_POINTER (asmspec_tree);
955
956   if (init)
957     {
958       if (TREE_CODE (value) == FUNCTION_DECL)
959         {
960           grok_function_init (value, init);
961           init = NULL_TREE;
962         }
963       else if (pedantic && TREE_CODE (value) != VAR_DECL)
964         /* Already complained in grokdeclarator.  */
965         init = NULL_TREE;
966       else
967         {
968           /* We allow initializers to become parameters to base
969              initializers.  */
970           if (TREE_CODE (init) == TREE_LIST)
971             {
972               if (TREE_CHAIN (init) == NULL_TREE)
973                 init = TREE_VALUE (init);
974               else
975                 init = digest_init (TREE_TYPE (value), init, (tree *)0);
976             }
977           
978           if (TREE_CODE (init) == CONST_DECL)
979             init = DECL_INITIAL (init);
980           else if (TREE_READONLY_DECL_P (init))
981             init = decl_constant_value (init);
982           else if (TREE_CODE (init) == CONSTRUCTOR)
983             init = digest_init (TREE_TYPE (value), init, (tree *)0);
984           if (init == error_mark_node)
985             /* We must make this look different than `error_mark_node'
986                because `decl_const_value' would mis-interpret it
987                as only meaning that this VAR_DECL is defined.  */
988             init = build1 (NOP_EXPR, TREE_TYPE (value), init);
989           else if (processing_template_decl)
990             ;
991           else if (! TREE_CONSTANT (init))
992             {
993               /* We can allow references to things that are effectively
994                  static, since references are initialized with the address.  */
995               if (TREE_CODE (TREE_TYPE (value)) != REFERENCE_TYPE
996                   || (TREE_STATIC (init) == 0
997                       && (!DECL_P (init) || DECL_EXTERNAL (init) == 0)))
998                 {
999                   error ("field initializer is not constant");
1000                   init = error_mark_node;
1001                 }
1002             }
1003         }
1004     }
1005
1006   if (processing_template_decl && ! current_function_decl
1007       && (TREE_CODE (value) == VAR_DECL || TREE_CODE (value) == FUNCTION_DECL))
1008     value = push_template_decl (value);
1009
1010   if (attrlist)
1011     cplus_decl_attributes (&value, attrlist, 0);
1012
1013   if (TREE_CODE (value) == VAR_DECL)
1014     {
1015       finish_static_data_member_decl (value, init, asmspec_tree, 
1016                                       flags);
1017       return value;
1018     }
1019   if (TREE_CODE (value) == FIELD_DECL)
1020     {
1021       if (asmspec)
1022         error ("`asm' specifiers are not permitted on non-static data members");
1023       if (DECL_INITIAL (value) == error_mark_node)
1024         init = error_mark_node;
1025       cp_finish_decl (value, init, NULL_TREE, flags);
1026       DECL_INITIAL (value) = init;
1027       DECL_IN_AGGR_P (value) = 1;
1028       return value;
1029     }
1030   if (TREE_CODE (value) == FUNCTION_DECL)
1031     {
1032       if (asmspec)
1033         {
1034           /* This must override the asm specifier which was placed
1035              by grokclassfn.  Lay this out fresh.  */
1036           SET_DECL_RTL (value, NULL_RTX);
1037           SET_DECL_ASSEMBLER_NAME (value, get_identifier (asmspec));
1038         }
1039       if (!DECL_FRIEND_P (value))
1040         grok_special_member_properties (value);
1041       
1042       cp_finish_decl (value, init, asmspec_tree, flags);
1043
1044       /* Pass friends back this way.  */
1045       if (DECL_FRIEND_P (value))
1046         return void_type_node;
1047
1048       DECL_IN_AGGR_P (value) = 1;
1049       return value;
1050     }
1051   abort ();
1052   /* NOTREACHED */
1053   return NULL_TREE;
1054 }
1055
1056 /* Like `grokfield', but for bitfields.
1057    WIDTH is non-NULL for bit fields only, and is an INTEGER_CST node.  */
1058
1059 tree
1060 grokbitfield (declarator, declspecs, width)
1061      tree declarator, declspecs, width;
1062 {
1063   register tree value = grokdeclarator (declarator, declspecs, BITFIELD,
1064                                         0, NULL);
1065
1066   if (! value) return NULL_TREE; /* friends went bad.  */
1067
1068   /* Pass friendly classes back.  */
1069   if (TREE_CODE (value) == VOID_TYPE)
1070     return void_type_node;
1071
1072   if (TREE_CODE (value) == TYPE_DECL)
1073     {
1074       error ("cannot declare `%D' to be a bit-field type", value);
1075       return NULL_TREE;
1076     }
1077
1078   /* Usually, finish_struct_1 catches bitfields with invalid types.
1079      But, in the case of bitfields with function type, we confuse
1080      ourselves into thinking they are member functions, so we must
1081      check here.  */
1082   if (TREE_CODE (value) == FUNCTION_DECL)
1083     {
1084       error ("cannot declare bit-field `%D' with function type",
1085              DECL_NAME (value));
1086       return NULL_TREE;
1087     }
1088
1089   if (DECL_IN_AGGR_P (value))
1090     {
1091       error ("`%D' is already defined in the class %T", value,
1092                   DECL_CONTEXT (value));
1093       return void_type_node;
1094     }
1095
1096   if (TREE_STATIC (value))
1097     {
1098       error ("static member `%D' cannot be a bit-field", value);
1099       return NULL_TREE;
1100     }
1101   cp_finish_decl (value, NULL_TREE, NULL_TREE, 0);
1102
1103   if (width != error_mark_node)
1104     {
1105       constant_expression_warning (width);
1106       DECL_INITIAL (value) = width;
1107       SET_DECL_C_BIT_FIELD (value);
1108     }
1109
1110   DECL_IN_AGGR_P (value) = 1;
1111   return value;
1112 }
1113
1114 tree
1115 grokoptypename (declspecs, declarator)
1116      tree declspecs, declarator;
1117 {
1118   tree t = grokdeclarator (declarator, declspecs, TYPENAME, 0, NULL);
1119   return mangle_conv_op_name_for_type (t);
1120 }
1121
1122 /* When a function is declared with an initializer,
1123    do the right thing.  Currently, there are two possibilities:
1124
1125    class B
1126    {
1127     public:
1128      // initialization possibility #1.
1129      virtual void f () = 0;
1130      int g ();
1131    };
1132    
1133    class D1 : B
1134    {
1135     public:
1136      int d1;
1137      // error, no f ();
1138    };
1139    
1140    class D2 : B
1141    {
1142     public:
1143      int d2;
1144      void f ();
1145    };
1146    
1147    class D3 : B
1148    {
1149     public:
1150      int d3;
1151      // initialization possibility #2
1152      void f () = B::f;
1153    };
1154
1155 */
1156
1157 static void
1158 grok_function_init (decl, init)
1159      tree decl;
1160      tree init;
1161 {
1162   /* An initializer for a function tells how this function should
1163      be inherited.  */
1164   tree type = TREE_TYPE (decl);
1165
1166   if (TREE_CODE (type) == FUNCTION_TYPE)
1167     error ("initializer specified for non-member function `%D'", decl);
1168   else if (integer_zerop (init))
1169     DECL_PURE_VIRTUAL_P (decl) = 1;
1170   else
1171     error ("invalid initializer for virtual method `%D'", decl);
1172 }
1173 \f
1174 void
1175 cplus_decl_attributes (decl, attributes, flags)
1176      tree *decl, attributes;
1177      int flags;
1178 {
1179   if (*decl == NULL_TREE || *decl == void_type_node)
1180     return;
1181
1182   if (TREE_CODE (*decl) == TEMPLATE_DECL)
1183     decl = &DECL_TEMPLATE_RESULT (*decl);
1184
1185   decl_attributes (decl, attributes, flags);
1186
1187   if (TREE_CODE (*decl) == TYPE_DECL)
1188     SET_IDENTIFIER_TYPE_VALUE (DECL_NAME (*decl), TREE_TYPE (*decl));
1189 }
1190 \f
1191 /* CONSTRUCTOR_NAME:
1192    Return the name for the constructor (or destructor) for the
1193    specified class.  Argument can be RECORD_TYPE, TYPE_DECL, or
1194    IDENTIFIER_NODE.  When given a template, this routine doesn't
1195    lose the specialization.  */
1196
1197 tree
1198 constructor_name_full (thing)
1199      tree thing;
1200 {
1201   if (TREE_CODE (thing) == TEMPLATE_TYPE_PARM
1202       || TREE_CODE (thing) == BOUND_TEMPLATE_TEMPLATE_PARM
1203       || TREE_CODE (thing) == TYPENAME_TYPE)
1204     thing = TYPE_NAME (thing);
1205   else if (IS_AGGR_TYPE_CODE (TREE_CODE (thing)))
1206     {
1207       if (TYPE_WAS_ANONYMOUS (thing) && TYPE_HAS_CONSTRUCTOR (thing))
1208         thing = DECL_NAME (OVL_CURRENT (TREE_VEC_ELT (CLASSTYPE_METHOD_VEC (thing), 0)));
1209       else
1210         thing = TYPE_NAME (thing);
1211     }
1212   if (TREE_CODE (thing) == TYPE_DECL
1213       || (TREE_CODE (thing) == TEMPLATE_DECL
1214           && TREE_CODE (DECL_TEMPLATE_RESULT (thing)) == TYPE_DECL))
1215     thing = DECL_NAME (thing);
1216   my_friendly_assert (TREE_CODE (thing) == IDENTIFIER_NODE, 197);
1217   return thing;
1218 }
1219
1220 /* CONSTRUCTOR_NAME:
1221    Return the name for the constructor (or destructor) for the
1222    specified class.  Argument can be RECORD_TYPE, TYPE_DECL, or
1223    IDENTIFIER_NODE.  When given a template, return the plain
1224    unspecialized name.  */
1225
1226 tree
1227 constructor_name (thing)
1228      tree thing;
1229 {
1230   tree t;
1231   thing = constructor_name_full (thing);
1232   t = IDENTIFIER_TEMPLATE (thing);
1233   if (!t)
1234     return thing;
1235   return t;
1236 }
1237
1238 /* Returns TRUE if NAME is the name for the constructor for TYPE.  */
1239
1240 bool
1241 constructor_name_p (tree name, tree type)
1242 {
1243   return (name == constructor_name (type)
1244           || name == constructor_name_full (type));
1245 }
1246
1247 \f
1248 /* Defer the compilation of the FN until the end of compilation.  */
1249
1250 void
1251 defer_fn (fn)
1252      tree fn;
1253 {
1254   if (DECL_DEFERRED_FN (fn))
1255     return;
1256   DECL_DEFERRED_FN (fn) = 1;
1257   if (!deferred_fns)
1258     VARRAY_TREE_INIT (deferred_fns, 32, "deferred_fns");
1259
1260   VARRAY_PUSH_TREE (deferred_fns, fn);
1261 }
1262
1263 /* Hunts through the global anonymous union ANON_DECL, building
1264    appropriate VAR_DECLs.  Stores cleanups on the list of ELEMS, and
1265    returns a VAR_DECL whose size is the same as the size of the
1266    ANON_DECL, if one is available.
1267
1268    FIXME: we should really handle anonymous unions by binding the names
1269    of the members to COMPONENT_REFs rather than this kludge.  */
1270
1271 static tree 
1272 build_anon_union_vars (anon_decl, elems, static_p, external_p)
1273      tree anon_decl;
1274      tree* elems;
1275      int static_p;
1276      int external_p;
1277 {
1278   tree type = TREE_TYPE (anon_decl);
1279   tree main_decl = NULL_TREE;
1280   tree field;
1281
1282   /* Rather than write the code to handle the non-union case,
1283      just give an error.  */
1284   if (TREE_CODE (type) != UNION_TYPE)
1285     error ("anonymous struct not inside named type");
1286
1287   for (field = TYPE_FIELDS (type); 
1288        field != NULL_TREE; 
1289        field = TREE_CHAIN (field))
1290     {
1291       tree decl;
1292
1293       if (DECL_ARTIFICIAL (field))
1294         continue;
1295       if (TREE_CODE (field) != FIELD_DECL)
1296         {
1297           cp_pedwarn_at ("`%#D' invalid; an anonymous union can only have non-static data members",
1298                          field);
1299           continue;
1300         }
1301
1302       if (TREE_PRIVATE (field))
1303         cp_pedwarn_at ("private member `%#D' in anonymous union", field);
1304       else if (TREE_PROTECTED (field))
1305         cp_pedwarn_at ("protected member `%#D' in anonymous union", field);
1306
1307       if (DECL_NAME (field) == NULL_TREE
1308           && ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1309         {
1310           decl = build_anon_union_vars (field, elems, static_p, external_p);
1311           if (!decl)
1312             continue;
1313         }
1314       else if (DECL_NAME (field) == NULL_TREE)
1315         continue;
1316       else
1317         {
1318           decl = build_decl (VAR_DECL, DECL_NAME (field), TREE_TYPE (field));
1319           /* tell `pushdecl' that this is not tentative.  */
1320           DECL_INITIAL (decl) = error_mark_node;
1321           TREE_PUBLIC (decl) = 0;
1322           TREE_STATIC (decl) = static_p;
1323           DECL_EXTERNAL (decl) = external_p;
1324           decl = pushdecl (decl);
1325           DECL_INITIAL (decl) = NULL_TREE;
1326         }
1327
1328       /* Only write out one anon union element--choose the largest
1329          one.  We used to try to find one the same size as the union,
1330          but that fails if the ABI forces us to align the union more
1331          strictly.  */
1332       if (main_decl == NULL_TREE
1333           || tree_int_cst_lt (DECL_SIZE (main_decl), DECL_SIZE (decl)))
1334         {
1335           if (main_decl)
1336             TREE_ASM_WRITTEN (main_decl) = 1;
1337           main_decl = decl;
1338         }
1339       else 
1340         /* ??? This causes there to be no debug info written out
1341            about this decl.  */
1342         TREE_ASM_WRITTEN (decl) = 1;
1343       
1344       if (DECL_NAME (field) == NULL_TREE
1345           && ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1346         /* The remainder of the processing was already done in the
1347            recursive call.  */
1348         continue;
1349
1350       /* If there's a cleanup to do, it belongs in the
1351          TREE_PURPOSE of the following TREE_LIST.  */
1352       *elems = tree_cons (NULL_TREE, decl, *elems);
1353       TREE_TYPE (*elems) = type;
1354     }
1355   
1356   return main_decl;
1357 }
1358
1359 /* Finish off the processing of a UNION_TYPE structure.  If the union is an
1360    anonymous union, then all members must be laid out together.  PUBLIC_P
1361    is nonzero if this union is not declared static.  */
1362
1363 void
1364 finish_anon_union (anon_union_decl)
1365      tree anon_union_decl;
1366 {
1367   tree type = TREE_TYPE (anon_union_decl);
1368   tree main_decl;
1369   int public_p = TREE_PUBLIC (anon_union_decl);
1370   int static_p = TREE_STATIC (anon_union_decl);
1371   int external_p = DECL_EXTERNAL (anon_union_decl);
1372
1373   /* The VAR_DECL's context is the same as the TYPE's context. */
1374   DECL_CONTEXT (anon_union_decl) = DECL_CONTEXT (TYPE_NAME (type));
1375   
1376   if (TYPE_FIELDS (type) == NULL_TREE)
1377     return;
1378
1379   if (public_p)
1380     {
1381       error ("namespace-scope anonymous aggregates must be static");
1382       return;
1383     }
1384
1385   main_decl = build_anon_union_vars (anon_union_decl,
1386                                      &DECL_ANON_UNION_ELEMS (anon_union_decl),
1387                                      static_p, external_p);
1388
1389   if (main_decl == NULL_TREE)
1390     {
1391       warning ("anonymous aggregate with no members");
1392       return;
1393     }
1394
1395   if (static_p)
1396     {
1397       make_decl_rtl (main_decl, 0);
1398       COPY_DECL_RTL (main_decl, anon_union_decl);
1399       expand_anon_union_decl (anon_union_decl, 
1400                               NULL_TREE,
1401                               DECL_ANON_UNION_ELEMS (anon_union_decl));
1402     }
1403   else
1404     add_decl_stmt (anon_union_decl);
1405 }
1406
1407 /* Finish processing a builtin type TYPE.  It's name is NAME,
1408    its fields are in the array FIELDS.  LEN is the number of elements
1409    in FIELDS minus one, or put another way, it is the maximum subscript
1410    used in FIELDS.
1411
1412    It is given the same alignment as ALIGN_TYPE.  */
1413
1414 void
1415 finish_builtin_type (type, name, fields, len, align_type)
1416      tree type;
1417      const char *name;
1418      tree fields[];
1419      int len;
1420      tree align_type;
1421 {
1422   register int i;
1423
1424   TYPE_FIELDS (type) = fields[0];
1425   for (i = 0; i < len; i++)
1426     {
1427       layout_type (TREE_TYPE (fields[i]));
1428       DECL_FIELD_CONTEXT (fields[i]) = type;
1429       TREE_CHAIN (fields[i]) = fields[i+1];
1430     }
1431   DECL_FIELD_CONTEXT (fields[i]) = type;
1432   TYPE_ALIGN (type) = TYPE_ALIGN (align_type);
1433   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (align_type);
1434   layout_type (type);
1435 #if 0 /* not yet, should get fixed properly later */
1436   TYPE_NAME (type) = make_type_decl (get_identifier (name), type);
1437 #else
1438   TYPE_NAME (type) = build_decl (TYPE_DECL, get_identifier (name), type);
1439 #endif
1440   TYPE_STUB_DECL (type) = TYPE_NAME (type);
1441   layout_decl (TYPE_NAME (type), 0);
1442 }
1443 \f
1444 /* Auxiliary functions to make type signatures for
1445    `operator new' and `operator delete' correspond to
1446    what compiler will be expecting.  */
1447
1448 tree
1449 coerce_new_type (type)
1450      tree type;
1451 {
1452   int e = 0;
1453   tree args = TYPE_ARG_TYPES (type);
1454
1455   my_friendly_assert (TREE_CODE (type) == FUNCTION_TYPE, 20001107);
1456   
1457   if (!same_type_p (TREE_TYPE (type), ptr_type_node))
1458     e = 1, error ("`operator new' must return type `%T'", ptr_type_node);
1459
1460   if (!args || args == void_list_node
1461       || !same_type_p (TREE_VALUE (args), c_size_type_node))
1462     {
1463       e = 2;
1464       if (args && args != void_list_node)
1465         args = TREE_CHAIN (args);
1466       pedwarn ("`operator new' takes type `size_t' (`%T') as first parameter", c_size_type_node);
1467     }
1468   switch (e)
1469   {
1470     case 2:
1471       args = tree_cons (NULL_TREE, c_size_type_node, args);
1472       /* FALLTHROUGH */
1473     case 1:
1474       type = build_exception_variant
1475               (build_function_type (ptr_type_node, args),
1476                TYPE_RAISES_EXCEPTIONS (type));
1477       /* FALLTHROUGH */
1478     default:;
1479   }
1480   return type;
1481 }
1482
1483 tree
1484 coerce_delete_type (type)
1485      tree type;
1486 {
1487   int e = 0;
1488   tree args = TYPE_ARG_TYPES (type);
1489   
1490   my_friendly_assert (TREE_CODE (type) == FUNCTION_TYPE, 20001107);
1491
1492   if (!same_type_p (TREE_TYPE (type), void_type_node))
1493     e = 1, error ("`operator delete' must return type `%T'", void_type_node);
1494
1495   if (!args || args == void_list_node
1496       || !same_type_p (TREE_VALUE (args), ptr_type_node))
1497     {
1498       e = 2;
1499       if (args && args != void_list_node)
1500         args = TREE_CHAIN (args);
1501       error ("`operator delete' takes type `%T' as first parameter", ptr_type_node);
1502     }
1503   switch (e)
1504   {
1505     case 2:
1506       args = tree_cons (NULL_TREE, ptr_type_node, args);
1507       /* FALLTHROUGH */
1508     case 1:
1509       type = build_exception_variant
1510               (build_function_type (void_type_node, args),
1511                TYPE_RAISES_EXCEPTIONS (type));
1512       /* FALLTHROUGH */
1513     default:;
1514   }
1515
1516   return type;
1517 }
1518 \f
1519 static void
1520 mark_vtable_entries (decl)
1521      tree decl;
1522 {
1523   tree entries = CONSTRUCTOR_ELTS (DECL_INITIAL (decl));
1524
1525   for (; entries; entries = TREE_CHAIN (entries))
1526     {
1527       tree fnaddr = TREE_VALUE (entries);
1528       tree fn;
1529       
1530       if (TREE_CODE (fnaddr) != ADDR_EXPR
1531           && TREE_CODE (fnaddr) != FDESC_EXPR)
1532         /* This entry is an offset: a virtual base class offset, a
1533            virtual call offset, an RTTI offset, etc.  */
1534         continue;
1535
1536       fn = TREE_OPERAND (fnaddr, 0);
1537       TREE_ADDRESSABLE (fn) = 1;
1538       /* When we don't have vcall offsets, we output thunks whenever
1539          we output the vtables that contain them.  With vcall offsets,
1540          we know all the thunks we'll need when we emit a virtual
1541          function, so we emit the thunks there instead.  */
1542       if (DECL_THUNK_P (fn)) 
1543         use_thunk (fn, /*emit_p=*/0);
1544       mark_used (fn);
1545     }
1546 }
1547
1548 /* Set DECL up to have the closest approximation of "initialized common"
1549    linkage available.  */
1550
1551 void
1552 comdat_linkage (decl)
1553      tree decl;
1554 {
1555   if (flag_weak)
1556     make_decl_one_only (decl);
1557   else if (TREE_CODE (decl) == FUNCTION_DECL 
1558            || (TREE_CODE (decl) == VAR_DECL && DECL_ARTIFICIAL (decl)))
1559     /* We can just emit function and compiler-generated variables
1560        statically; having multiple copies is (for the most part) only
1561        a waste of space.  
1562
1563        There are two correctness issues, however: the address of a
1564        template instantiation with external linkage should be the
1565        same, independent of what translation unit asks for the
1566        address, and this will not hold when we emit multiple copies of
1567        the function.  However, there's little else we can do.  
1568
1569        Also, by default, the typeinfo implementation assumes that
1570        there will be only one copy of the string used as the name for
1571        each type.  Therefore, if weak symbols are unavailable, the
1572        run-time library should perform a more conservative check; it
1573        should perform a string comparison, rather than an address
1574        comparison.  */
1575     TREE_PUBLIC (decl) = 0;
1576   else
1577     {
1578       /* Static data member template instantiations, however, cannot
1579          have multiple copies.  */
1580       if (DECL_INITIAL (decl) == 0
1581           || DECL_INITIAL (decl) == error_mark_node)
1582         DECL_COMMON (decl) = 1;
1583       else if (EMPTY_CONSTRUCTOR_P (DECL_INITIAL (decl)))
1584         {
1585           DECL_COMMON (decl) = 1;
1586           DECL_INITIAL (decl) = error_mark_node;
1587         }
1588       else
1589         {
1590           /* We can't do anything useful; leave vars for explicit
1591              instantiation.  */
1592           DECL_EXTERNAL (decl) = 1;
1593           DECL_NOT_REALLY_EXTERN (decl) = 0;
1594         }
1595     }
1596
1597   if (DECL_LANG_SPECIFIC (decl))
1598     DECL_COMDAT (decl) = 1;
1599 }
1600
1601 /* For win32 we also want to put explicit instantiations in
1602    linkonce sections, so that they will be merged with implicit
1603    instantiations; otherwise we get duplicate symbol errors.  */
1604
1605 void
1606 maybe_make_one_only (decl)
1607      tree decl;
1608 {
1609   /* We used to say that this was not necessary on targets that support weak
1610      symbols, because the implicit instantiations will defer to the explicit
1611      one.  However, that's not actually the case in SVR4; a strong definition
1612      after a weak one is an error.  Also, not making explicit
1613      instantiations one_only means that we can end up with two copies of
1614      some template instantiations. */
1615   if (! flag_weak)
1616     return;
1617
1618   /* We can't set DECL_COMDAT on functions, or finish_file will think
1619      we can get away with not emitting them if they aren't used.  We need
1620      to for variables so that cp_finish_decl will update their linkage,
1621      because their DECL_INITIAL may not have been set properly yet.  */
1622
1623   make_decl_one_only (decl);
1624
1625   if (TREE_CODE (decl) == VAR_DECL)
1626     {
1627       DECL_COMDAT (decl) = 1;
1628       /* Mark it needed so we don't forget to emit it.  */
1629       TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (decl)) = 1;
1630     }
1631 }
1632
1633 /* Returns the virtual function with which the vtable for TYPE is
1634    emitted, or NULL_TREE if that heuristic is not applicable to TYPE.  */
1635
1636 static tree
1637 key_method (type)
1638      tree type;
1639 {
1640   tree method;
1641
1642   if (TYPE_FOR_JAVA (type)
1643       || CLASSTYPE_TEMPLATE_INSTANTIATION (type)
1644       || CLASSTYPE_INTERFACE_KNOWN (type))
1645     return NULL_TREE;
1646
1647   for (method = TYPE_METHODS (type); method != NULL_TREE;
1648        method = TREE_CHAIN (method))
1649     if (DECL_VINDEX (method) != NULL_TREE
1650         && ! DECL_DECLARED_INLINE_P (method)
1651         && (! DECL_PURE_VIRTUAL_P (method)
1652 #if 0
1653             /* This would be nice, but we didn't think of it in time.  */
1654             || DECL_DESTRUCTOR_P (method)
1655 #endif
1656             ))
1657       return method;
1658
1659   return NULL_TREE;
1660 }
1661
1662 /* Set TREE_PUBLIC and/or DECL_EXTERN on the vtable DECL,
1663    based on TYPE and other static flags.
1664
1665    Note that anything public is tagged TREE_PUBLIC, whether
1666    it's public in this file or in another one.  */
1667
1668 void
1669 import_export_vtable (decl, type, final)
1670      tree decl, type;
1671      int final;
1672 {
1673   if (DECL_INTERFACE_KNOWN (decl))
1674     return;
1675
1676   if (TYPE_FOR_JAVA (type))
1677     {
1678       TREE_PUBLIC (decl) = 1;
1679       DECL_EXTERNAL (decl) = 1;
1680       DECL_INTERFACE_KNOWN (decl) = 1;
1681     }
1682   else if (CLASSTYPE_INTERFACE_KNOWN (type))
1683     {
1684       TREE_PUBLIC (decl) = 1;
1685       DECL_EXTERNAL (decl) = CLASSTYPE_INTERFACE_ONLY (type);
1686       DECL_INTERFACE_KNOWN (decl) = 1;
1687     }
1688   else
1689     {
1690       /* We can only wait to decide if we have real non-inline virtual
1691          functions in our class, or if we come from a template.  */
1692
1693       int found = (CLASSTYPE_TEMPLATE_INSTANTIATION (type)
1694                    || key_method (type));
1695
1696       if (final || ! found)
1697         {
1698           comdat_linkage (decl);
1699           DECL_EXTERNAL (decl) = 0;
1700         }
1701       else
1702         {
1703           TREE_PUBLIC (decl) = 1;
1704           DECL_EXTERNAL (decl) = 1;
1705         }
1706     }
1707 }
1708
1709 /* Determine whether or not we want to specifically import or export CTYPE,
1710    using various heuristics.  */
1711
1712 static void
1713 import_export_class (ctype)
1714      tree ctype;
1715 {
1716   /* -1 for imported, 1 for exported.  */
1717   int import_export = 0;
1718
1719   /* It only makes sense to call this function at EOF.  The reason is
1720      that this function looks at whether or not the first non-inline
1721      non-abstract virtual member function has been defined in this
1722      translation unit.  But, we can't possibly know that until we've
1723      seen the entire translation unit.  */
1724   my_friendly_assert (at_eof, 20000226);
1725
1726   if (CLASSTYPE_INTERFACE_KNOWN (ctype))
1727     return;
1728
1729   /* If MULTIPLE_SYMBOL_SPACES is defined and we saw a #pragma interface,
1730      we will have CLASSTYPE_INTERFACE_ONLY set but not
1731      CLASSTYPE_INTERFACE_KNOWN.  In that case, we don't want to use this
1732      heuristic because someone will supply a #pragma implementation
1733      elsewhere, and deducing it here would produce a conflict.  */
1734   if (CLASSTYPE_INTERFACE_ONLY (ctype))
1735     return;
1736
1737   if (lookup_attribute ("dllimport", TYPE_ATTRIBUTES (ctype)))
1738     import_export = -1;
1739   else if (lookup_attribute ("dllexport", TYPE_ATTRIBUTES (ctype)))
1740     import_export = 1;
1741
1742   /* If we got -fno-implicit-templates, we import template classes that
1743      weren't explicitly instantiated.  */
1744   if (import_export == 0
1745       && CLASSTYPE_IMPLICIT_INSTANTIATION (ctype)
1746       && ! flag_implicit_templates)
1747     import_export = -1;
1748
1749   /* Base our import/export status on that of the first non-inline,
1750      non-pure virtual function, if any.  */
1751   if (import_export == 0
1752       && TYPE_POLYMORPHIC_P (ctype))
1753     {
1754       tree method = key_method (ctype);
1755       if (method)
1756         import_export = (DECL_REALLY_EXTERN (method) ? -1 : 1);
1757     }
1758
1759 #ifdef MULTIPLE_SYMBOL_SPACES
1760   if (import_export == -1)
1761     import_export = 0;
1762 #endif
1763
1764   if (import_export)
1765     {
1766       SET_CLASSTYPE_INTERFACE_KNOWN (ctype);
1767       CLASSTYPE_INTERFACE_ONLY (ctype) = (import_export < 0);
1768     }
1769 }
1770     
1771 /* We need to describe to the assembler the relationship between
1772    a vtable and the vtable of the parent class.  */
1773
1774 static void
1775 output_vtable_inherit (vars)
1776      tree vars;
1777 {
1778   tree parent;
1779   rtx child_rtx, parent_rtx;
1780
1781   child_rtx = XEXP (DECL_RTL (vars), 0);          /* strip the mem ref  */
1782
1783   parent = binfo_for_vtable (vars);
1784
1785   if (parent == TYPE_BINFO (DECL_CONTEXT (vars)))
1786     parent_rtx = const0_rtx;
1787   else if (parent)
1788     {
1789       parent = get_vtbl_decl_for_binfo (TYPE_BINFO (BINFO_TYPE (parent)));
1790       parent_rtx = XEXP (DECL_RTL (parent), 0);  /* strip the mem ref  */
1791     }
1792   else
1793     abort ();
1794
1795   assemble_vtable_inherit (child_rtx, parent_rtx);
1796 }
1797
1798 static int
1799 finish_vtable_vardecl (t, data)
1800      tree *t;
1801      void *data ATTRIBUTE_UNUSED;
1802 {
1803   tree vars = *t;
1804   tree ctype = DECL_CONTEXT (vars);
1805   import_export_class (ctype);
1806   import_export_vtable (vars, ctype, 1);
1807
1808   if (! DECL_EXTERNAL (vars)
1809       && DECL_NEEDED_P (vars)
1810       && ! TREE_ASM_WRITTEN (vars))
1811     {
1812       if (TREE_TYPE (vars) == void_type_node)
1813         /* It is a dummy vtable made by get_vtable_decl. Ignore it.  */
1814         return 0;
1815       
1816       /* Write it out.  */
1817       mark_vtable_entries (vars);
1818       if (TREE_TYPE (DECL_INITIAL (vars)) == 0)
1819         store_init_value (vars, DECL_INITIAL (vars));
1820
1821       if (write_symbols == DWARF_DEBUG || write_symbols == DWARF2_DEBUG)
1822         {
1823           /* Mark the VAR_DECL node representing the vtable itself as a
1824              "gratuitous" one, thereby forcing dwarfout.c to ignore it.
1825              It is rather important that such things be ignored because
1826              any effort to actually generate DWARF for them will run
1827              into trouble when/if we encounter code like:
1828
1829                 #pragma interface
1830                 struct S { virtual void member (); };
1831
1832               because the artificial declaration of the vtable itself (as
1833               manufactured by the g++ front end) will say that the vtable
1834               is a static member of `S' but only *after* the debug output
1835               for the definition of `S' has already been output.  This causes
1836               grief because the DWARF entry for the definition of the vtable
1837               will try to refer back to an earlier *declaration* of the
1838               vtable as a static member of `S' and there won't be one.
1839               We might be able to arrange to have the "vtable static member"
1840               attached to the member list for `S' before the debug info for
1841               `S' get written (which would solve the problem) but that would
1842               require more intrusive changes to the g++ front end.  */
1843
1844           DECL_IGNORED_P (vars) = 1;
1845         }
1846
1847       /* Always make vtables weak.  */
1848       if (flag_weak)
1849         comdat_linkage (vars);
1850
1851       rest_of_decl_compilation (vars, NULL, 1, 1);
1852
1853       if (flag_vtable_gc)
1854         output_vtable_inherit (vars);
1855
1856       /* Because we're only doing syntax-checking, we'll never end up
1857          actually marking the variable as written.  */
1858       if (flag_syntax_only)
1859         TREE_ASM_WRITTEN (vars) = 1;
1860
1861       /* Since we're writing out the vtable here, also write the debug 
1862          info.  */
1863       note_debug_info_needed (ctype);
1864
1865       return 1;
1866     }
1867
1868   /* If the references to this class' vtables were optimized away, still
1869      emit the appropriate debugging information.  See dfs_debug_mark.  */
1870   if (DECL_COMDAT (vars)
1871       && CLASSTYPE_DEBUG_REQUESTED (ctype))
1872     note_debug_info_needed (ctype);
1873
1874   return 0;
1875 }
1876
1877 static int
1878 prune_vtable_vardecl (t, data)
1879      tree *t;
1880      void *data ATTRIBUTE_UNUSED;
1881 {
1882   *t = TREE_CHAIN (*t);
1883   return 1;
1884 }
1885
1886 /* Determines the proper settings of TREE_PUBLIC and DECL_EXTERNAL for an
1887    inline function or template instantiation at end-of-file.  */
1888
1889 void
1890 import_export_decl (decl)
1891      tree decl;
1892 {
1893   if (DECL_INTERFACE_KNOWN (decl))
1894     return;
1895
1896   if (DECL_TEMPLATE_INSTANTIATION (decl)
1897       || DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl))
1898     {
1899       DECL_NOT_REALLY_EXTERN (decl) = 1;
1900       if ((DECL_IMPLICIT_INSTANTIATION (decl)
1901            || DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl))
1902           && (flag_implicit_templates
1903               || (flag_implicit_inline_templates 
1904                   && DECL_DECLARED_INLINE_P (decl))))
1905         {
1906           if (!TREE_PUBLIC (decl))
1907             /* Templates are allowed to have internal linkage.  See 
1908                [basic.link].  */
1909             ;
1910           else
1911             comdat_linkage (decl);
1912         }
1913       else
1914         {
1915           DECL_EXTERNAL (decl) = 1;
1916           DECL_NOT_REALLY_EXTERN (decl) = 0;
1917         }
1918     }
1919   else if (DECL_FUNCTION_MEMBER_P (decl))
1920     {
1921       if (!DECL_DECLARED_INLINE_P (decl))
1922         {
1923           tree ctype = DECL_CONTEXT (decl);
1924           import_export_class (ctype);
1925           if (CLASSTYPE_INTERFACE_KNOWN (ctype))
1926             {
1927               DECL_NOT_REALLY_EXTERN (decl)
1928                 = ! (CLASSTYPE_INTERFACE_ONLY (ctype)
1929                      || (DECL_DECLARED_INLINE_P (decl) 
1930                          && ! flag_implement_inlines
1931                          && !DECL_VINDEX (decl)));
1932
1933               if (!DECL_NOT_REALLY_EXTERN (decl))
1934                 DECL_EXTERNAL (decl) = 1;
1935
1936               /* Always make artificials weak.  */
1937               if (DECL_ARTIFICIAL (decl) && flag_weak)
1938                 comdat_linkage (decl);
1939               else
1940                 maybe_make_one_only (decl);
1941             }
1942         }
1943       else
1944         comdat_linkage (decl);
1945     }
1946   else
1947     comdat_linkage (decl);
1948
1949   DECL_INTERFACE_KNOWN (decl) = 1;
1950 }
1951
1952 /* Here, we only decide whether or not the tinfo node should be
1953    emitted with the vtable.  IS_IN_LIBRARY is non-zero iff the
1954    typeinfo for TYPE should be in the runtime library.  */
1955
1956 void
1957 import_export_tinfo (decl, type, is_in_library)
1958      tree decl;
1959      tree type;
1960      int is_in_library;
1961 {
1962   if (DECL_INTERFACE_KNOWN (decl))
1963     return;
1964   
1965   if (IS_AGGR_TYPE (type))
1966     import_export_class (type);
1967       
1968   if (IS_AGGR_TYPE (type) && CLASSTYPE_INTERFACE_KNOWN (type)
1969       && TYPE_POLYMORPHIC_P (type)
1970       /* If -fno-rtti, we're not necessarily emitting this stuff with
1971          the class, so go ahead and emit it now.  This can happen when
1972          a class is used in exception handling.  */
1973       && flag_rtti)
1974     {
1975       DECL_NOT_REALLY_EXTERN (decl) = !CLASSTYPE_INTERFACE_ONLY (type);
1976       DECL_COMDAT (decl) = 0;
1977     }
1978   else
1979     {
1980       DECL_NOT_REALLY_EXTERN (decl) = 1;
1981       DECL_COMDAT (decl) = 1;
1982     }
1983
1984   /* Now override some cases. */
1985   if (flag_weak)
1986     DECL_COMDAT (decl) = 1;
1987   else if (is_in_library)
1988     DECL_COMDAT (decl) = 0;
1989   
1990   DECL_INTERFACE_KNOWN (decl) = 1;
1991 }
1992
1993 tree
1994 build_cleanup (decl)
1995      tree decl;
1996 {
1997   tree temp;
1998   tree type = TREE_TYPE (decl);
1999
2000   if (TREE_CODE (type) == ARRAY_TYPE)
2001     temp = decl;
2002   else
2003     {
2004       cxx_mark_addressable (decl);
2005       temp = build1 (ADDR_EXPR, build_pointer_type (type), decl);
2006     }
2007   temp = build_delete (TREE_TYPE (temp), temp,
2008                        sfk_complete_destructor,
2009                        LOOKUP_NORMAL|LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR, 0);
2010   return temp;
2011 }
2012
2013 /* Returns the initialization guard variable for the variable DECL,
2014    which has static storage duration.  */
2015
2016 tree
2017 get_guard (decl)
2018      tree decl;
2019 {
2020   tree sname;
2021   tree guard;
2022
2023   sname = mangle_guard_variable (decl);
2024   guard = IDENTIFIER_GLOBAL_VALUE (sname);
2025   if (! guard)
2026     {
2027       tree guard_type;
2028
2029       /* We use a type that is big enough to contain a mutex as well
2030          as an integer counter.  */
2031       guard_type = long_long_integer_type_node;
2032       guard = build_decl (VAR_DECL, sname, guard_type);
2033       
2034       /* The guard should have the same linkage as what it guards. */
2035       TREE_PUBLIC (guard) = TREE_PUBLIC (decl);
2036       TREE_STATIC (guard) = TREE_STATIC (decl);
2037       DECL_COMMON (guard) = DECL_COMMON (decl);
2038       DECL_ONE_ONLY (guard) = DECL_ONE_ONLY (decl);
2039       if (TREE_PUBLIC (decl))
2040         DECL_WEAK (guard) = DECL_WEAK (decl);
2041       
2042       DECL_ARTIFICIAL (guard) = 1;
2043       TREE_USED (guard) = 1;
2044       pushdecl_top_level (guard);
2045       cp_finish_decl (guard, NULL_TREE, NULL_TREE, 0);
2046     }
2047   return guard;
2048 }
2049
2050 /* Return those bits of the GUARD variable that should be set when the
2051    guarded entity is actually initialized.  */
2052
2053 static tree
2054 get_guard_bits (guard)
2055      tree guard;
2056 {
2057   /* We only set the first byte of the guard, in order to leave room
2058      for a mutex in the high-order bits.  */
2059   guard = build1 (ADDR_EXPR, 
2060                   build_pointer_type (TREE_TYPE (guard)),
2061                   guard);
2062   guard = build1 (NOP_EXPR, 
2063                   build_pointer_type (char_type_node), 
2064                   guard);
2065   guard = build1 (INDIRECT_REF, char_type_node, guard);
2066
2067   return guard;
2068 }
2069
2070 /* Return an expression which determines whether or not the GUARD
2071    variable has already been initialized.  */
2072
2073 tree
2074 get_guard_cond (guard)
2075      tree guard;
2076 {
2077   tree guard_value;
2078
2079   /* Check to see if the GUARD is zero.  */
2080   guard = get_guard_bits (guard);
2081   guard_value = integer_zero_node;
2082   if (!same_type_p (TREE_TYPE (guard_value), TREE_TYPE (guard)))
2083     guard_value = convert (TREE_TYPE (guard), guard_value);
2084   return cp_build_binary_op (EQ_EXPR, guard, guard_value);
2085 }
2086
2087 /* Return an expression which sets the GUARD variable, indicating that
2088    the variable being guarded has been initialized.  */
2089
2090 tree
2091 set_guard (guard)
2092      tree guard;
2093 {
2094   tree guard_init;
2095
2096   /* Set the GUARD to one.  */
2097   guard = get_guard_bits (guard);
2098   guard_init = integer_one_node;
2099   if (!same_type_p (TREE_TYPE (guard_init), TREE_TYPE (guard)))
2100     guard_init = convert (TREE_TYPE (guard), guard_init);
2101   return build_modify_expr (guard, NOP_EXPR, guard_init);
2102 }
2103
2104 /* Start the process of running a particular set of global constructors
2105    or destructors.  Subroutine of do_[cd]tors.  */
2106
2107 static tree
2108 start_objects (method_type, initp)
2109      int method_type, initp;
2110 {
2111   tree fnname;
2112   tree body;
2113   char type[10];
2114
2115   /* Make ctor or dtor function.  METHOD_TYPE may be 'I' or 'D'.  */
2116
2117   if (initp != DEFAULT_INIT_PRIORITY)
2118     {
2119       char joiner;
2120
2121 #ifdef JOINER
2122       joiner = JOINER;
2123 #else
2124       joiner = '_';
2125 #endif
2126
2127       sprintf (type, "%c%c%.5u", method_type, joiner, initp);
2128     }
2129   else
2130     sprintf (type, "%c", method_type);
2131
2132   fnname = get_file_function_name_long (type);
2133
2134   start_function (void_list_node,
2135                   make_call_declarator (fnname, void_list_node, NULL_TREE,
2136                                         NULL_TREE),
2137                   NULL_TREE, SF_DEFAULT);
2138
2139   /* It can be a static function as long as collect2 does not have
2140      to scan the object file to find its ctor/dtor routine.  */
2141   TREE_PUBLIC (current_function_decl) = ! targetm.have_ctors_dtors;
2142
2143   /* Mark this declaration as used to avoid spurious warnings.  */
2144   TREE_USED (current_function_decl) = 1;
2145
2146   /* Mark this function as a global constructor or destructor.  */
2147   if (method_type == 'I')
2148     DECL_GLOBAL_CTOR_P (current_function_decl) = 1;
2149   else
2150     DECL_GLOBAL_DTOR_P (current_function_decl) = 1;
2151   DECL_LANG_SPECIFIC (current_function_decl)->decl_flags.u2sel = 1;
2152   GLOBAL_INIT_PRIORITY (current_function_decl) = initp;
2153
2154   body = begin_compound_stmt (/*has_no_scope=*/0);
2155
2156   /* We cannot allow these functions to be elided, even if they do not
2157      have external linkage.  And, there's no point in deferring
2158      copmilation of thes functions; they're all going to have to be
2159      out anyhow.  */
2160   current_function_cannot_inline
2161     = "static constructors and destructors cannot be inlined";
2162
2163   return body;
2164 }
2165
2166 /* Finish the process of running a particular set of global constructors
2167    or destructors.  Subroutine of do_[cd]tors.  */
2168
2169 static void
2170 finish_objects (method_type, initp, body)
2171      int method_type, initp;
2172      tree body;
2173 {
2174   tree fn;
2175
2176   /* Finish up.  */
2177   finish_compound_stmt (/*has_no_scope=*/0, body);
2178   fn = finish_function (0);
2179   expand_body (fn);
2180
2181   /* When only doing semantic analysis, and no RTL generation, we
2182      can't call functions that directly emit assembly code; there is
2183      no assembly file in which to put the code.  */
2184   if (flag_syntax_only)
2185     return;
2186
2187   if (targetm.have_ctors_dtors)
2188     {
2189       rtx fnsym = XEXP (DECL_RTL (fn), 0);
2190       if (method_type == 'I')
2191         (* targetm.asm_out.constructor) (fnsym, initp);
2192       else
2193         (* targetm.asm_out.destructor) (fnsym, initp);
2194     }
2195 }
2196
2197 /* The names of the parameters to the function created to handle
2198    initializations and destructions for objects with static storage
2199    duration.  */
2200 #define INITIALIZE_P_IDENTIFIER "__initialize_p"
2201 #define PRIORITY_IDENTIFIER "__priority"
2202
2203 /* The name of the function we create to handle initializations and
2204    destructions for objects with static storage duration.  */
2205 #define SSDF_IDENTIFIER "__static_initialization_and_destruction"
2206
2207 /* The declaration for the __INITIALIZE_P argument.  */
2208 static GTY(()) tree initialize_p_decl;
2209
2210 /* The declaration for the __PRIORITY argument.  */
2211 static GTY(()) tree priority_decl;
2212
2213 /* The declaration for the static storage duration function.  */
2214 static GTY(()) tree ssdf_decl;
2215
2216 /* All the static storage duration functions created in this
2217    translation unit.  */
2218 static GTY(()) varray_type ssdf_decls;
2219
2220 /* A map from priority levels to information about that priority
2221    level.  There may be many such levels, so efficient lookup is
2222    important.  */
2223 static splay_tree priority_info_map;
2224
2225 /* Begins the generation of the function that will handle all
2226    initialization and destruction of objects with static storage
2227    duration.  The function generated takes two parameters of type
2228    `int': __INITIALIZE_P and __PRIORITY.  If __INITIALIZE_P is
2229    non-zero, it performs initializations.  Otherwise, it performs
2230    destructions.  It only performs those initializations or
2231    destructions with the indicated __PRIORITY.  The generated function
2232    returns no value.  
2233
2234    It is assumed that this function will only be called once per
2235    translation unit.  */
2236
2237 static tree
2238 start_static_storage_duration_function ()
2239 {
2240   static unsigned ssdf_number;
2241
2242   tree parm_types;
2243   tree type;
2244   tree body;
2245   char id[sizeof (SSDF_IDENTIFIER) + 1 /* '\0' */ + 32];
2246
2247   /* Create the identifier for this function.  It will be of the form
2248      SSDF_IDENTIFIER_<number>.  */
2249   sprintf (id, "%s_%u", SSDF_IDENTIFIER, ssdf_number++);
2250   if (ssdf_number == 0)
2251     {
2252       /* Overflow occurred.  That means there are at least 4 billion
2253          initialization functions.  */
2254       sorry ("too many initialization functions required");
2255       abort ();
2256     }
2257
2258   /* Create the parameters.  */
2259   parm_types = void_list_node;
2260   parm_types = tree_cons (NULL_TREE, integer_type_node, parm_types);
2261   parm_types = tree_cons (NULL_TREE, integer_type_node, parm_types);
2262   type = build_function_type (void_type_node, parm_types);
2263
2264   /* Create the FUNCTION_DECL itself.  */
2265   ssdf_decl = build_lang_decl (FUNCTION_DECL, 
2266                                get_identifier (id),
2267                                type);
2268   TREE_PUBLIC (ssdf_decl) = 0;
2269   DECL_ARTIFICIAL (ssdf_decl) = 1;
2270
2271   /* Put this function in the list of functions to be called from the
2272      static constructors and destructors.  */
2273   if (!ssdf_decls)
2274     {
2275       VARRAY_TREE_INIT (ssdf_decls, 32, "ssdf_decls");
2276
2277       /* Take this opportunity to initialize the map from priority
2278          numbers to information about that priority level. */
2279       priority_info_map = splay_tree_new (splay_tree_compare_ints,
2280                                           /*delete_key_fn=*/0,
2281                                           /*delete_value_fn=*/
2282                                           (splay_tree_delete_value_fn) &free);
2283
2284       /* We always need to generate functions for the
2285          DEFAULT_INIT_PRIORITY so enter it now.  That way when we walk
2286          priorities later, we'll be sure to find the
2287          DEFAULT_INIT_PRIORITY.  */
2288       get_priority_info (DEFAULT_INIT_PRIORITY);
2289     }
2290
2291   VARRAY_PUSH_TREE (ssdf_decls, ssdf_decl);
2292
2293   /* Create the argument list.  */
2294   initialize_p_decl = cp_build_parm_decl
2295     (get_identifier (INITIALIZE_P_IDENTIFIER), integer_type_node);
2296   DECL_CONTEXT (initialize_p_decl) = ssdf_decl;
2297   TREE_USED (initialize_p_decl) = 1;
2298   priority_decl = cp_build_parm_decl
2299     (get_identifier (PRIORITY_IDENTIFIER), integer_type_node);
2300   DECL_CONTEXT (priority_decl) = ssdf_decl;
2301   TREE_USED (priority_decl) = 1;
2302
2303   TREE_CHAIN (initialize_p_decl) = priority_decl;
2304   DECL_ARGUMENTS (ssdf_decl) = initialize_p_decl;
2305
2306   /* Put the function in the global scope.  */
2307   pushdecl (ssdf_decl);
2308
2309   /* Start the function itself.  This is equivalent to declarating the
2310      function as:
2311
2312        static void __ssdf (int __initialize_p, init __priority_p);
2313        
2314      It is static because we only need to call this function from the
2315      various constructor and destructor functions for this module.  */
2316   start_function (/*specs=*/NULL_TREE, 
2317                   ssdf_decl,
2318                   /*attrs=*/NULL_TREE,
2319                   SF_PRE_PARSED);
2320
2321   /* Set up the scope of the outermost block in the function.  */
2322   body = begin_compound_stmt (/*has_no_scope=*/0);
2323
2324   /* This function must not be deferred because we are depending on
2325      its compilation to tell us what is TREE_SYMBOL_REFERENCED.  */
2326   current_function_cannot_inline 
2327     = "static storage duration functions cannot be inlined";
2328
2329   return body;
2330 }
2331
2332 /* Finish the generation of the function which performs initialization
2333    and destruction of objects with static storage duration.  After
2334    this point, no more such objects can be created.  */
2335
2336 static void
2337 finish_static_storage_duration_function (body)
2338      tree body;
2339 {
2340   /* Close out the function.  */
2341   finish_compound_stmt (/*has_no_scope=*/0, body);
2342   expand_body (finish_function (0));
2343 }
2344
2345 /* Return the information about the indicated PRIORITY level.  If no
2346    code to handle this level has yet been generated, generate the
2347    appropriate prologue.  */
2348
2349 static priority_info
2350 get_priority_info (priority)
2351      int priority;
2352 {
2353   priority_info pi;
2354   splay_tree_node n;
2355
2356   n = splay_tree_lookup (priority_info_map, 
2357                          (splay_tree_key) priority);
2358   if (!n)
2359     {
2360       /* Create a new priority information structure, and insert it
2361          into the map.  */
2362       pi = (priority_info) xmalloc (sizeof (struct priority_info_s));
2363       pi->initializations_p = 0;
2364       pi->destructions_p = 0;
2365       splay_tree_insert (priority_info_map,
2366                          (splay_tree_key) priority,
2367                          (splay_tree_value) pi);
2368     }
2369   else
2370     pi = (priority_info) n->value;
2371
2372   return pi;
2373 }
2374
2375 /* Set up to handle the initialization or destruction of DECL.  If
2376    INITP is non-zero, we are initializing the variable.  Otherwise, we
2377    are destroying it.  */
2378
2379 static tree
2380 start_static_initialization_or_destruction (decl, initp)
2381      tree decl;
2382      int initp;
2383 {
2384   tree guard_if_stmt = NULL_TREE;
2385   int priority;
2386   tree cond;
2387   tree guard;
2388   tree init_cond;
2389   priority_info pi;
2390
2391   /* Figure out the priority for this declaration.  */
2392   priority = DECL_INIT_PRIORITY (decl);
2393   if (!priority)
2394     priority = DEFAULT_INIT_PRIORITY;
2395
2396   /* Remember that we had an initialization or finalization at this
2397      priority.  */
2398   pi = get_priority_info (priority);
2399   if (initp)
2400     pi->initializations_p = 1;
2401   else
2402     pi->destructions_p = 1;
2403
2404   /* Trick the compiler into thinking we are at the file and line
2405      where DECL was declared so that error-messages make sense, and so
2406      that the debugger will show somewhat sensible file and line
2407      information.  */
2408   input_filename = DECL_SOURCE_FILE (decl);
2409   lineno = DECL_SOURCE_LINE (decl);
2410
2411   /* Because of:
2412
2413        [class.access.spec]
2414
2415        Access control for implicit calls to the constructors,
2416        the conversion functions, or the destructor called to
2417        create and destroy a static data member is performed as
2418        if these calls appeared in the scope of the member's
2419        class.  
2420
2421      we pretend we are in a static member function of the class of
2422      which the DECL is a member.  */
2423   if (member_p (decl))
2424     {
2425       DECL_CONTEXT (current_function_decl) = DECL_CONTEXT (decl);
2426       DECL_STATIC_FUNCTION_P (current_function_decl) = 1;
2427     }
2428   
2429   /* Conditionalize this initialization on being in the right priority
2430      and being initializing/finalizing appropriately.  */
2431   guard_if_stmt = begin_if_stmt ();
2432   cond = cp_build_binary_op (EQ_EXPR,
2433                              priority_decl,
2434                              build_int_2 (priority, 0));
2435   init_cond = initp ? integer_one_node : integer_zero_node;
2436   init_cond = cp_build_binary_op (EQ_EXPR,
2437                                   initialize_p_decl,
2438                                   init_cond);
2439   cond = cp_build_binary_op (TRUTH_ANDIF_EXPR, cond, init_cond);
2440
2441   /* Assume we don't need a guard.  */
2442   guard = NULL_TREE;
2443   /* We need a guard if this is an object with external linkage that
2444      might be initialized in more than one place.  (For example, a
2445      static data member of a template, when the data member requires
2446      construction.)  */
2447   if (TREE_PUBLIC (decl) && (DECL_COMMON (decl) 
2448                              || DECL_ONE_ONLY (decl)
2449                              || DECL_WEAK (decl)))
2450     {
2451       tree guard_cond;
2452
2453       guard = get_guard (decl);
2454
2455       /* When using __cxa_atexit, we just check the GUARD as we would
2456          for a local static.  */
2457       if (flag_use_cxa_atexit)
2458         {
2459           /* When using __cxa_atexit, we never try to destroy
2460              anything from a static destructor.  */
2461           my_friendly_assert (initp, 20000629);
2462           guard_cond = get_guard_cond (guard);
2463         }
2464       /* If we don't have __cxa_atexit, then we will be running
2465          destructors from .fini sections, or their equivalents.  So,
2466          we need to know how many times we've tried to initialize this
2467          object.  We do initializations only if the GUARD is zero,
2468          i.e., if we are the first to initialize the variable.  We do
2469          destructions only if the GUARD is one, i.e., if we are the
2470          last to destroy the variable.  */
2471       else if (initp)
2472         guard_cond 
2473           = cp_build_binary_op (EQ_EXPR,
2474                                 build_unary_op (PREINCREMENT_EXPR,
2475                                                 guard,
2476                                                 /*noconvert=*/1),
2477                                 integer_one_node);
2478       else
2479         guard_cond 
2480           = cp_build_binary_op (EQ_EXPR,
2481                                 build_unary_op (PREDECREMENT_EXPR,
2482                                                 guard,
2483                                                 /*noconvert=*/1),
2484                                 integer_zero_node);
2485
2486       cond = cp_build_binary_op (TRUTH_ANDIF_EXPR, cond, guard_cond);
2487     }
2488
2489   finish_if_stmt_cond (cond, guard_if_stmt);
2490
2491   /* If we're using __cxa_atexit, we have not already set the GUARD,
2492      so we must do so now.  */
2493   if (guard && initp && flag_use_cxa_atexit)
2494     finish_expr_stmt (set_guard (guard));
2495
2496   return guard_if_stmt;
2497 }
2498
2499 /* We've just finished generating code to do an initialization or
2500    finalization.  GUARD_IF_STMT is the if-statement we used to guard
2501    the initialization.  */
2502
2503 static void
2504 finish_static_initialization_or_destruction (guard_if_stmt)
2505      tree guard_if_stmt;
2506 {
2507   finish_then_clause (guard_if_stmt);
2508   finish_if_stmt ();
2509
2510   /* Now that we're done with DECL we don't need to pretend to be a
2511      member of its class any longer.  */
2512   DECL_CONTEXT (current_function_decl) = NULL_TREE;
2513   DECL_STATIC_FUNCTION_P (current_function_decl) = 0;
2514 }
2515
2516 /* Generate code to do the static initialization of DECL.  The
2517    initialization is INIT.  If DECL may be initialized more than once
2518    in different object files, GUARD is the guard variable to 
2519    check.  PRIORITY is the priority for the initialization.  */
2520
2521 static void
2522 do_static_initialization (decl, init)
2523      tree decl;
2524      tree init;
2525 {
2526   tree expr;
2527   tree guard_if_stmt;
2528
2529   /* Set up for the initialization.  */
2530   guard_if_stmt
2531     = start_static_initialization_or_destruction (decl,
2532                                                   /*initp=*/1);
2533   
2534   /* Do the initialization itself.  */
2535   if (IS_AGGR_TYPE (TREE_TYPE (decl))
2536       || TREE_CODE (TREE_TYPE (decl)) == ARRAY_TYPE)
2537     expr = build_aggr_init (decl, init, 0);
2538   else
2539     {
2540       expr = build (INIT_EXPR, TREE_TYPE (decl), decl, init);
2541       TREE_SIDE_EFFECTS (expr) = 1;
2542     }
2543   finish_expr_stmt (expr);
2544
2545   /* If we're using __cxa_atexit, register a a function that calls the
2546      destructor for the object.  */
2547   if (flag_use_cxa_atexit)
2548     register_dtor_fn (decl);
2549
2550   /* Finsh up.  */
2551   finish_static_initialization_or_destruction (guard_if_stmt);
2552 }
2553
2554 /* Generate code to do the static destruction of DECL.  If DECL may be
2555    initialized more than once in different object files, GUARD is the
2556    guard variable to check.  PRIORITY is the priority for the
2557    destruction.  */
2558
2559 static void
2560 do_static_destruction (decl)
2561      tree decl;
2562 {
2563   tree guard_if_stmt;
2564
2565   /* If we're using __cxa_atexit, then destructors are registered
2566      immediately after objects are initialized.  */
2567   my_friendly_assert (!flag_use_cxa_atexit, 20000121);
2568
2569   /* If we don't need a destructor, there's nothing to do.  */
2570   if (TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl)))
2571     return;
2572
2573   /* Actually do the destruction.  */
2574   guard_if_stmt = start_static_initialization_or_destruction (decl,
2575                                                                /*initp=*/0);
2576   finish_expr_stmt (build_cleanup (decl));
2577   finish_static_initialization_or_destruction (guard_if_stmt);
2578 }
2579
2580 /* VARS is a list of variables with static storage duration which may
2581    need initialization and/or finalization.  Remove those variables
2582    that don't really need to be initialized or finalized, and return
2583    the resulting list.  The order in which the variables appear in
2584    VARS is in reverse order of the order in which they should actually
2585    be initialized.  The list we return is in the unreversed order;
2586    i.e., the first variable should be initialized first.  */
2587
2588 static tree
2589 prune_vars_needing_no_initialization (vars)
2590      tree vars;
2591 {
2592   tree var;
2593   tree result;
2594
2595   for (var = vars, result = NULL_TREE;
2596        var;
2597        var = TREE_CHAIN (var))
2598     {
2599       tree decl = TREE_VALUE (var);
2600       tree init = TREE_PURPOSE (var);
2601
2602       /* Deal gracefully with error.  */
2603       if (decl == error_mark_node)
2604         continue;
2605
2606       /* The only things that can be initialized are variables.  */
2607       my_friendly_assert (TREE_CODE (decl) == VAR_DECL, 19990420);
2608
2609       /* If this object is not defined, we don't need to do anything
2610          here.  */
2611       if (DECL_EXTERNAL (decl))
2612         continue;
2613
2614       /* Also, if the initializer already contains errors, we can bail
2615          out now.  */
2616       if (init && TREE_CODE (init) == TREE_LIST 
2617           && value_member (error_mark_node, init))
2618         continue;
2619
2620       /* This variable is going to need initialization and/or
2621          finalization, so we add it to the list.  */
2622       result = tree_cons (init, decl, result);
2623     }
2624
2625   return result;
2626 }
2627
2628 /* Make sure we have told the back end about all the variables in
2629    VARS.  */
2630
2631 static void
2632 write_out_vars (vars)
2633      tree vars;
2634 {
2635   tree v;
2636
2637   for (v = vars; v; v = TREE_CHAIN (v))
2638     if (! TREE_ASM_WRITTEN (TREE_VALUE (v)))
2639       rest_of_decl_compilation (TREE_VALUE (v), 0, 1, 1);
2640 }
2641
2642 /* Generate a static constructor (if CONSTRUCTOR_P) or destructor
2643    (otherwise) that will initialize all gobal objects with static
2644    storage duration having the indicated PRIORITY.  */
2645
2646 static void
2647 generate_ctor_or_dtor_function (constructor_p, priority)
2648      int constructor_p;
2649      int priority;
2650 {
2651   char function_key;
2652   tree arguments;
2653   tree body;
2654   size_t i;
2655
2656   /* We use `I' to indicate initialization and `D' to indicate
2657      destruction.  */
2658   if (constructor_p)
2659     function_key = 'I';
2660   else
2661     function_key = 'D';
2662
2663   /* Begin the function.  */
2664   body = start_objects (function_key, priority);
2665
2666   /* Call the static storage duration function with appropriate
2667      arguments.  */
2668   for (i = 0; i < ssdf_decls->elements_used; ++i) 
2669     {
2670       arguments = tree_cons (NULL_TREE, build_int_2 (priority, 0), 
2671                              NULL_TREE);
2672       arguments = tree_cons (NULL_TREE, build_int_2 (constructor_p, 0),
2673                              arguments);
2674       finish_expr_stmt (build_function_call (VARRAY_TREE (ssdf_decls, i),
2675                                              arguments));
2676     }
2677
2678   /* If we're generating code for the DEFAULT_INIT_PRIORITY, throw in
2679      calls to any functions marked with attributes indicating that
2680      they should be called at initialization- or destruction-time.  */
2681   if (priority == DEFAULT_INIT_PRIORITY)
2682     {
2683       tree fns;
2684       
2685       for (fns = constructor_p ? static_ctors : static_dtors; 
2686            fns;
2687            fns = TREE_CHAIN (fns))
2688         finish_expr_stmt (build_function_call (TREE_VALUE (fns), NULL_TREE));
2689     }
2690
2691   /* Close out the function.  */
2692   finish_objects (function_key, priority, body);
2693 }
2694
2695 /* Generate constructor and destructor functions for the priority
2696    indicated by N.  */
2697
2698 static int
2699 generate_ctor_and_dtor_functions_for_priority (n, data)
2700      splay_tree_node n;
2701      void *data ATTRIBUTE_UNUSED;
2702 {
2703   int priority = (int) n->key;
2704   priority_info pi = (priority_info) n->value;
2705
2706   /* Generate the functions themselves, but only if they are really
2707      needed.  */
2708   if (pi->initializations_p
2709       || (priority == DEFAULT_INIT_PRIORITY && static_ctors))
2710     generate_ctor_or_dtor_function (/*constructor_p=*/1,
2711                                     priority);
2712   if (pi->destructions_p
2713       || (priority == DEFAULT_INIT_PRIORITY && static_dtors))
2714     generate_ctor_or_dtor_function (/*constructor_p=*/0,
2715                                     priority);
2716
2717   /* Keep iterating.  */
2718   return 0;
2719 }
2720
2721 /* This routine is called from the last rule in yyparse ().
2722    Its job is to create all the code needed to initialize and
2723    destroy the global aggregates.  We do the destruction
2724    first, since that way we only need to reverse the decls once.  */
2725
2726 void
2727 finish_file ()
2728 {
2729   tree vars;
2730   int reconsider;
2731   size_t i;
2732
2733   at_eof = 1;
2734
2735   /* Bad parse errors.  Just forget about it.  */
2736   if (! global_bindings_p () || current_class_type || decl_namespace_list)
2737     return;
2738
2739   /* Otherwise, GDB can get confused, because in only knows
2740      about source for LINENO-1 lines.  */
2741   lineno -= 1;
2742
2743   interface_unknown = 1;
2744   interface_only = 0;
2745
2746   /* We now have to write out all the stuff we put off writing out.
2747      These include:
2748
2749        o Template specializations that we have not yet instantiated,
2750          but which are needed.
2751        o Initialization and destruction for non-local objects with
2752          static storage duration.  (Local objects with static storage
2753          duration are initialized when their scope is first entered,
2754          and are cleaned up via atexit.)
2755        o Virtual function tables.  
2756
2757      All of these may cause others to be needed.  For example,
2758      instantiating one function may cause another to be needed, and
2759      generating the intiailzer for an object may cause templates to be
2760      instantiated, etc., etc.  */
2761
2762   timevar_push (TV_VARCONST);
2763
2764   emit_support_tinfos ();
2765   
2766   do 
2767     {
2768       reconsider = 0;
2769
2770       /* If there are templates that we've put off instantiating, do
2771          them now.  */
2772       instantiate_pending_templates ();
2773
2774       /* Write out virtual tables as required.  Note that writing out
2775          the virtual table for a template class may cause the
2776          instantiation of members of that class.  */
2777       if (walk_globals (vtable_decl_p,
2778                         finish_vtable_vardecl,
2779                         /*data=*/0))
2780         reconsider = 1;
2781       
2782       /* Write out needed type info variables. Writing out one variable
2783          might cause others to be needed.  */
2784       if (walk_globals (unemitted_tinfo_decl_p, emit_tinfo_decl, /*data=*/0))
2785         reconsider = 1;
2786
2787       /* The list of objects with static storage duration is built up
2788          in reverse order.  We clear STATIC_AGGREGATES so that any new
2789          aggregates added during the initialization of these will be
2790          initialized in the correct order when we next come around the
2791          loop.  */
2792       vars = prune_vars_needing_no_initialization (static_aggregates);
2793       static_aggregates = NULL_TREE;
2794
2795       if (vars)
2796         {
2797           tree v;
2798
2799           /* We need to start a new initialization function each time
2800              through the loop.  That's because we need to know which
2801              vtables have been referenced, and TREE_SYMBOL_REFERENCED
2802              isn't computed until a function is finished, and written
2803              out.  That's a deficiency in the back-end.  When this is
2804              fixed, these initialization functions could all become
2805              inline, with resulting performance improvements.  */
2806           tree ssdf_body = start_static_storage_duration_function ();
2807
2808           /* Make sure the back end knows about all the variables.  */
2809           write_out_vars (vars);
2810
2811           /* First generate code to do all the initializations.  */
2812           for (v = vars; v; v = TREE_CHAIN (v))
2813             do_static_initialization (TREE_VALUE (v),
2814                                       TREE_PURPOSE (v));
2815
2816           /* Then, generate code to do all the destructions.  Do these
2817              in reverse order so that the most recently constructed
2818              variable is the first destroyed.  If we're using
2819              __cxa_atexit, then we don't need to do this; functions
2820              were registered at initialization time to destroy the
2821              local statics.  */
2822           if (!flag_use_cxa_atexit)
2823             {
2824               vars = nreverse (vars);
2825               for (v = vars; v; v = TREE_CHAIN (v))
2826                 do_static_destruction (TREE_VALUE (v));
2827             }
2828           else
2829             vars = NULL_TREE;
2830
2831           /* Finish up the static storage duration function for this
2832              round.  */
2833           finish_static_storage_duration_function (ssdf_body);
2834
2835           /* All those initializations and finalizations might cause
2836              us to need more inline functions, more template
2837              instantiations, etc.  */
2838           reconsider = 1;
2839         }
2840       
2841       /* Go through the various inline functions, and see if any need
2842          synthesizing.  */
2843       for (i = 0; i < deferred_fns_used; ++i)
2844         {
2845           tree decl = VARRAY_TREE (deferred_fns, i);
2846           import_export_decl (decl);
2847           if (DECL_ARTIFICIAL (decl) && ! DECL_INITIAL (decl)
2848               && TREE_USED (decl)
2849               && (! DECL_REALLY_EXTERN (decl) || DECL_INLINE (decl)))
2850             {
2851               /* Even though we're already at the top-level, we push
2852                  there again.  That way, when we pop back a few lines
2853                  hence, all of our state is restored.  Otherwise,
2854                  finish_function doesn't clean things up, and we end
2855                  up with CURRENT_FUNCTION_DECL set.  */
2856               push_to_top_level ();
2857               synthesize_method (decl);
2858               pop_from_top_level ();
2859               reconsider = 1;
2860             }
2861         }
2862
2863       /* We lie to the back-end, pretending that some functions are
2864          not defined when they really are.  This keeps these functions
2865          from being put out unnecessarily.  But, we must stop lying
2866          when the functions are referenced, or if they are not comdat
2867          since they need to be put out now.
2868          This is done in a separate for cycle, because if some deferred
2869          function is contained in another deferred function later in
2870          deferred_fns varray, rest_of_compilation would skip this
2871          function and we really cannot expand the same function twice. */
2872       for (i = 0; i < deferred_fns_used; ++i)
2873         {
2874           tree decl = VARRAY_TREE (deferred_fns, i);
2875       
2876           if (DECL_NOT_REALLY_EXTERN (decl)
2877               && DECL_INITIAL (decl)
2878               && DECL_NEEDED_P (decl))
2879             DECL_EXTERNAL (decl) = 0;
2880         }
2881
2882       for (i = 0; i < deferred_fns_used; ++i)
2883         {
2884           tree decl = VARRAY_TREE (deferred_fns, i);
2885
2886           /* If we're going to need to write this function out, and
2887              there's already a body for it, create RTL for it now.
2888              (There might be no body if this is a method we haven't
2889              gotten around to synthesizing yet.)  */
2890           if (!DECL_EXTERNAL (decl)
2891               && DECL_NEEDED_P (decl)
2892               && DECL_SAVED_TREE (decl)
2893               && !TREE_ASM_WRITTEN (decl))
2894             {
2895               int saved_not_really_extern;
2896
2897               /* When we call finish_function in expand_body, it will
2898                  try to reset DECL_NOT_REALLY_EXTERN so we save and
2899                  restore it here.  */
2900               saved_not_really_extern = DECL_NOT_REALLY_EXTERN (decl);
2901               /* Generate RTL for this function now that we know we
2902                  need it.  */
2903               expand_body (decl);
2904               /* Undo the damage done by finish_function.  */
2905               DECL_EXTERNAL (decl) = 0;
2906               DECL_NOT_REALLY_EXTERN (decl) = saved_not_really_extern;
2907               /* If we're compiling -fsyntax-only pretend that this
2908                  function has been written out so that we don't try to
2909                  expand it again.  */
2910               if (flag_syntax_only)
2911                 TREE_ASM_WRITTEN (decl) = 1;
2912               reconsider = 1;
2913             }
2914         }
2915
2916       if (deferred_fns_used
2917           && wrapup_global_declarations (&VARRAY_TREE (deferred_fns, 0),
2918                                          deferred_fns_used))
2919         reconsider = 1;
2920       if (walk_namespaces (wrapup_globals_for_namespace, /*data=*/0))
2921         reconsider = 1;
2922
2923       /* Static data members are just like namespace-scope globals.  */
2924       for (i = 0; i < pending_statics_used; ++i) 
2925         {
2926           tree decl = VARRAY_TREE (pending_statics, i);
2927           if (TREE_ASM_WRITTEN (decl))
2928             continue;
2929           import_export_decl (decl);
2930           if (DECL_NOT_REALLY_EXTERN (decl) && ! DECL_IN_AGGR_P (decl))
2931             DECL_EXTERNAL (decl) = 0;
2932         }
2933       if (pending_statics
2934           && wrapup_global_declarations (&VARRAY_TREE (pending_statics, 0),
2935                                          pending_statics_used))
2936         reconsider = 1;
2937     } 
2938   while (reconsider);
2939
2940   /* We give C linkage to static constructors and destructors.  */
2941   push_lang_context (lang_name_c);
2942
2943   /* Generate initialization and destruction functions for all
2944      priorities for which they are required.  */
2945   if (priority_info_map)
2946     splay_tree_foreach (priority_info_map, 
2947                         generate_ctor_and_dtor_functions_for_priority,
2948                         /*data=*/0);
2949
2950   /* We're done with the splay-tree now.  */
2951   if (priority_info_map)
2952     splay_tree_delete (priority_info_map);
2953
2954   /* We're done with static constructors, so we can go back to "C++"
2955      linkage now.  */
2956   pop_lang_context ();
2957
2958   /* Now delete from the chain of variables all virtual function tables.
2959      We output them all ourselves, because each will be treated
2960      specially.  We don't do this if we're just doing semantic
2961      analysis, and not code-generation.  */
2962   if (!flag_syntax_only)
2963     walk_globals (vtable_decl_p, prune_vtable_vardecl, /*data=*/0);
2964
2965   /* Now, issue warnings about static, but not defined, functions,
2966      etc., and emit debugging information.  */
2967   walk_namespaces (wrapup_globals_for_namespace, /*data=*/&reconsider);
2968   if (pending_statics)
2969     check_global_declarations (&VARRAY_TREE (pending_statics, 0),
2970                                pending_statics_used);
2971
2972   finish_repo ();
2973
2974   /* The entire file is now complete.  If requested, dump everything
2975      to a file.   */
2976   {
2977     int flags;
2978     FILE *stream = dump_begin (TDI_all, &flags);
2979
2980     if (stream)
2981       {
2982         dump_node (global_namespace, flags & ~TDF_SLIM, stream);
2983         dump_end (TDI_all, stream);
2984       }
2985   }
2986   
2987   timevar_pop (TV_VARCONST);
2988
2989   if (flag_detailed_statistics)
2990     {
2991       dump_tree_statistics ();
2992       dump_time_statistics ();
2993     }
2994 }
2995
2996 /* This is something of the form 'A()()()()()+1' that has turned out to be an
2997    expr.  Since it was parsed like a type, we need to wade through and fix
2998    that.  Unfortunately, since operator() is left-associative, we can't use
2999    tail recursion.  In the above example, TYPE is `A', and DECL is
3000    `()()()()()'.
3001
3002    Maybe this shouldn't be recursive, but how often will it actually be
3003    used?  (jason) */
3004
3005 tree
3006 reparse_absdcl_as_expr (type, decl)
3007      tree type, decl;
3008 {
3009   /* do build_functional_cast (type, NULL_TREE) at bottom */
3010   if (TREE_OPERAND (decl, 0) == NULL_TREE)
3011     return build_functional_cast (type, NULL_TREE);
3012
3013   /* recurse */
3014   decl = reparse_absdcl_as_expr (type, TREE_OPERAND (decl, 0));
3015
3016   return finish_call_expr (decl, NULL_TREE, /*disallow_virtual=*/false);
3017 }
3018
3019 /* This is something of the form `int ((int)(int)(int)1)' that has turned
3020    out to be an expr.  Since it was parsed like a type, we need to wade
3021    through and fix that.  Since casts are right-associative, we are
3022    reversing the order, so we don't have to recurse.
3023
3024    In the above example, DECL is the `(int)(int)(int)', and EXPR is the
3025    `1'.  */
3026
3027 tree
3028 reparse_absdcl_as_casts (decl, expr)
3029      tree decl, expr;
3030 {
3031   tree type;
3032   int non_void_p = 0;
3033   
3034   if (TREE_CODE (expr) == CONSTRUCTOR
3035       && TREE_TYPE (expr) == 0)
3036     {
3037       type = groktypename (TREE_VALUE (CALL_DECLARATOR_PARMS (decl)));
3038       decl = TREE_OPERAND (decl, 0);
3039
3040       if (processing_template_decl)
3041         TREE_TYPE (expr) = type;
3042       else
3043         {
3044           expr = digest_init (type, expr, (tree *) 0);
3045           if (TREE_CODE (type) == ARRAY_TYPE && !COMPLETE_TYPE_P (type))
3046             {
3047               int failure = complete_array_type (type, expr, 1);
3048               my_friendly_assert (!failure, 78);
3049             }
3050         }
3051     }
3052
3053   while (decl)
3054     {
3055       type = groktypename (TREE_VALUE (CALL_DECLARATOR_PARMS (decl)));
3056       decl = TREE_OPERAND (decl, 0);
3057       if (!VOID_TYPE_P (type))
3058         non_void_p = 1;
3059       expr = build_c_cast (type, expr);
3060     }
3061
3062   if (warn_old_style_cast && ! in_system_header
3063       && non_void_p && current_lang_name != lang_name_c)
3064     warning ("use of old-style cast");
3065
3066   return expr;
3067 }
3068
3069 /* T is the parse tree for an expression.  Return the expression after
3070    performing semantic analysis.  */
3071
3072 tree
3073 build_expr_from_tree (t)
3074      tree t;
3075 {
3076   if (t == NULL_TREE || t == error_mark_node)
3077     return t;
3078
3079   switch (TREE_CODE (t))
3080     {
3081     case IDENTIFIER_NODE:
3082       return do_identifier (t, 0, NULL_TREE);
3083
3084     case LOOKUP_EXPR:
3085       if (LOOKUP_EXPR_GLOBAL (t))
3086         {
3087           tree token = TREE_OPERAND (t, 0);
3088           return do_scoped_id (token, IDENTIFIER_GLOBAL_VALUE (token));
3089         }
3090       else
3091         return do_identifier (TREE_OPERAND (t, 0), 0, NULL_TREE);
3092
3093     case TEMPLATE_ID_EXPR:
3094       {
3095         tree template;
3096         tree args;
3097         tree object;
3098
3099         template = build_expr_from_tree (TREE_OPERAND (t, 0));
3100         args = build_expr_from_tree (TREE_OPERAND (t, 1));
3101         
3102         if (TREE_CODE (template) == COMPONENT_REF)
3103           {
3104             object = TREE_OPERAND (template, 0);
3105             template = TREE_OPERAND (template, 1);
3106           }
3107         else
3108           object = NULL_TREE;
3109
3110         template = lookup_template_function (template, args);
3111         if (object)
3112           return build (COMPONENT_REF, TREE_TYPE (template), 
3113                         object, template);
3114         else
3115           return template;
3116       }
3117
3118     case INDIRECT_REF:
3119       return build_x_indirect_ref
3120         (build_expr_from_tree (TREE_OPERAND (t, 0)), "unary *");
3121
3122     case CAST_EXPR:
3123       return build_functional_cast
3124         (TREE_TYPE (t), build_expr_from_tree (TREE_OPERAND (t, 0)));
3125
3126     case REINTERPRET_CAST_EXPR:
3127       return build_reinterpret_cast
3128         (TREE_TYPE (t), build_expr_from_tree (TREE_OPERAND (t, 0)));
3129
3130     case CONST_CAST_EXPR:
3131       return build_const_cast
3132         (TREE_TYPE (t), build_expr_from_tree (TREE_OPERAND (t, 0)));
3133
3134     case DYNAMIC_CAST_EXPR:
3135       return build_dynamic_cast
3136         (TREE_TYPE (t), build_expr_from_tree (TREE_OPERAND (t, 0)));
3137
3138     case STATIC_CAST_EXPR:
3139       return build_static_cast
3140         (TREE_TYPE (t), build_expr_from_tree (TREE_OPERAND (t, 0)));
3141
3142     case PREDECREMENT_EXPR:
3143     case PREINCREMENT_EXPR:
3144     case POSTDECREMENT_EXPR:
3145     case POSTINCREMENT_EXPR:
3146     case NEGATE_EXPR:
3147     case BIT_NOT_EXPR:
3148     case ABS_EXPR:
3149     case TRUTH_NOT_EXPR:
3150     case ADDR_EXPR:
3151     case CONVERT_EXPR:      /* Unary + */
3152     case REALPART_EXPR:
3153     case IMAGPART_EXPR:
3154       if (TREE_TYPE (t))
3155         return t;
3156       return build_x_unary_op (TREE_CODE (t),
3157                                build_expr_from_tree (TREE_OPERAND (t, 0)));
3158
3159     case PLUS_EXPR:
3160     case MINUS_EXPR:
3161     case MULT_EXPR:
3162     case TRUNC_DIV_EXPR:
3163     case CEIL_DIV_EXPR:
3164     case FLOOR_DIV_EXPR:
3165     case ROUND_DIV_EXPR:
3166     case EXACT_DIV_EXPR:
3167     case BIT_AND_EXPR:
3168     case BIT_ANDTC_EXPR:
3169     case BIT_IOR_EXPR:
3170     case BIT_XOR_EXPR:
3171     case TRUNC_MOD_EXPR:
3172     case FLOOR_MOD_EXPR:
3173     case TRUTH_ANDIF_EXPR:
3174     case TRUTH_ORIF_EXPR:
3175     case TRUTH_AND_EXPR:
3176     case TRUTH_OR_EXPR:
3177     case RSHIFT_EXPR:
3178     case LSHIFT_EXPR:
3179     case RROTATE_EXPR:
3180     case LROTATE_EXPR:
3181     case EQ_EXPR:
3182     case NE_EXPR:
3183     case MAX_EXPR:
3184     case MIN_EXPR:
3185     case LE_EXPR:
3186     case GE_EXPR:
3187     case LT_EXPR:
3188     case GT_EXPR:
3189     case MEMBER_REF:
3190       return build_x_binary_op
3191         (TREE_CODE (t), 
3192          build_expr_from_tree (TREE_OPERAND (t, 0)),
3193          build_expr_from_tree (TREE_OPERAND (t, 1)));
3194
3195     case DOTSTAR_EXPR:
3196       return build_m_component_ref
3197         (build_expr_from_tree (TREE_OPERAND (t, 0)),
3198          build_expr_from_tree (TREE_OPERAND (t, 1)));
3199
3200     case SCOPE_REF:
3201       return build_offset_ref (TREE_OPERAND (t, 0), TREE_OPERAND (t, 1));
3202
3203     case ARRAY_REF:
3204       if (TREE_OPERAND (t, 0) == NULL_TREE)
3205         /* new-type-id */
3206         return build_nt (ARRAY_REF, NULL_TREE,
3207                          build_expr_from_tree (TREE_OPERAND (t, 1)));
3208       return grok_array_decl (build_expr_from_tree (TREE_OPERAND (t, 0)),
3209                               build_expr_from_tree (TREE_OPERAND (t, 1)));
3210
3211     case SIZEOF_EXPR:
3212     case ALIGNOF_EXPR:
3213       {
3214         tree r = build_expr_from_tree (TREE_OPERAND (t, 0));
3215         if (!TYPE_P (r))
3216           return TREE_CODE (t) == SIZEOF_EXPR ? expr_sizeof (r) : c_alignof_expr (r);
3217         else
3218           return cxx_sizeof_or_alignof_type (r, TREE_CODE (t), true);
3219       }
3220
3221     case MODOP_EXPR:
3222       return build_x_modify_expr
3223         (build_expr_from_tree (TREE_OPERAND (t, 0)),
3224          TREE_CODE (TREE_OPERAND (t, 1)),
3225          build_expr_from_tree (TREE_OPERAND (t, 2)));
3226
3227     case ARROW_EXPR:
3228       return build_x_arrow
3229         (build_expr_from_tree (TREE_OPERAND (t, 0)));
3230
3231     case NEW_EXPR:
3232       return build_new
3233         (build_expr_from_tree (TREE_OPERAND (t, 0)),
3234          build_expr_from_tree (TREE_OPERAND (t, 1)),
3235          build_expr_from_tree (TREE_OPERAND (t, 2)),
3236          NEW_EXPR_USE_GLOBAL (t));
3237
3238     case DELETE_EXPR:
3239       return delete_sanity
3240         (build_expr_from_tree (TREE_OPERAND (t, 0)),
3241          build_expr_from_tree (TREE_OPERAND (t, 1)),
3242          DELETE_EXPR_USE_VEC (t), DELETE_EXPR_USE_GLOBAL (t));
3243
3244     case COMPOUND_EXPR:
3245       if (TREE_OPERAND (t, 1) == NULL_TREE)
3246         return build_x_compound_expr
3247           (build_expr_from_tree (TREE_OPERAND (t, 0)));
3248       else
3249         abort ();
3250
3251     case METHOD_CALL_EXPR:
3252       if (TREE_CODE (TREE_OPERAND (t, 0)) == SCOPE_REF)
3253         {
3254           tree ref = TREE_OPERAND (t, 0);
3255           tree name = TREE_OPERAND (ref, 1);
3256           
3257           if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
3258             name = build_nt (TEMPLATE_ID_EXPR,
3259                              TREE_OPERAND (name, 0),
3260                              build_expr_from_tree (TREE_OPERAND (name, 1)));
3261             
3262           return build_scoped_method_call
3263             (build_expr_from_tree (TREE_OPERAND (t, 1)),
3264              build_expr_from_tree (TREE_OPERAND (ref, 0)),
3265              name,
3266              build_expr_from_tree (TREE_OPERAND (t, 2)));
3267         }
3268       else 
3269         {
3270           tree fn = TREE_OPERAND (t, 0);
3271
3272           /* We can get a TEMPLATE_ID_EXPR here on code like:
3273
3274                x->f<2>();
3275               
3276              so we must resolve that.  However, we can also get things
3277              like a BIT_NOT_EXPR here, when referring to a destructor,
3278              and things like that are not correctly resolved by
3279              build_expr_from_tree.  So, just use build_expr_from_tree
3280              when we really need it.  */
3281           if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
3282             fn = lookup_template_function
3283               (TREE_OPERAND (fn, 0),
3284                build_expr_from_tree (TREE_OPERAND (fn, 1)));
3285
3286           return build_method_call
3287             (build_expr_from_tree (TREE_OPERAND (t, 1)),
3288              fn,
3289              build_expr_from_tree (TREE_OPERAND (t, 2)),
3290              NULL_TREE, LOOKUP_NORMAL);
3291         }
3292
3293     case CALL_EXPR:
3294       if (TREE_CODE (TREE_OPERAND (t, 0)) == SCOPE_REF)
3295         {
3296           tree ref = TREE_OPERAND (t, 0);
3297           tree name = TREE_OPERAND (ref, 1);
3298           
3299           if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
3300             name = build_nt (TEMPLATE_ID_EXPR,
3301                              TREE_OPERAND (name, 0),
3302                              build_expr_from_tree (TREE_OPERAND (name, 1)));
3303             
3304           return build_member_call
3305             (build_expr_from_tree (TREE_OPERAND (ref, 0)),
3306              name,
3307              build_expr_from_tree (TREE_OPERAND (t, 1)));
3308         }
3309       else
3310         {
3311           tree name = TREE_OPERAND (t, 0);
3312           tree id;
3313           tree args = build_expr_from_tree (TREE_OPERAND (t, 1));
3314           if (args != NULL_TREE && TREE_CODE (name) == LOOKUP_EXPR
3315               && !LOOKUP_EXPR_GLOBAL (name)
3316               && TREE_CODE ((id = TREE_OPERAND (name, 0))) == IDENTIFIER_NODE
3317               && (!current_class_type
3318                   || !lookup_member (current_class_type, id, 0, 0)))
3319             {
3320               /* Do Koenig lookup if there are no class members. */
3321               name = do_identifier (id, 0, args);
3322             }
3323           else if (TREE_CODE (name) == TEMPLATE_ID_EXPR
3324                    || ! really_overloaded_fn (name))
3325             name = build_expr_from_tree (name);
3326
3327           if (TREE_CODE (name) == OFFSET_REF)
3328             return build_offset_ref_call_from_tree (name, args);
3329           if (TREE_CODE (name) == COMPONENT_REF)
3330             return finish_object_call_expr (TREE_OPERAND (name, 1),
3331                                             TREE_OPERAND (name, 0),
3332                                             args);
3333           name = convert_from_reference (name);
3334           return build_call_from_tree (name, args, 
3335                                        /*disallow_virtual=*/false);
3336         }
3337
3338     case COND_EXPR:
3339       return build_x_conditional_expr
3340         (build_expr_from_tree (TREE_OPERAND (t, 0)),
3341          build_expr_from_tree (TREE_OPERAND (t, 1)),
3342          build_expr_from_tree (TREE_OPERAND (t, 2)));
3343
3344     case PSEUDO_DTOR_EXPR:
3345       return (finish_pseudo_destructor_call_expr 
3346               (build_expr_from_tree (TREE_OPERAND (t, 0)),
3347                build_expr_from_tree (TREE_OPERAND (t, 1)),
3348                build_expr_from_tree (TREE_OPERAND (t, 2))));
3349
3350     case TREE_LIST:
3351       {
3352         tree purpose, value, chain;
3353
3354         if (t == void_list_node)
3355           return t;
3356
3357         purpose = TREE_PURPOSE (t);
3358         if (purpose)
3359           purpose = build_expr_from_tree (purpose);
3360         value = TREE_VALUE (t);
3361         if (value)
3362           value = build_expr_from_tree (value);
3363         chain = TREE_CHAIN (t);
3364         if (chain && chain != void_type_node)
3365           chain = build_expr_from_tree (chain);
3366         return tree_cons (purpose, value, chain);
3367       }
3368
3369     case COMPONENT_REF:
3370       {
3371         tree object = build_expr_from_tree (TREE_OPERAND (t, 0));
3372         return finish_class_member_access_expr (object, 
3373                                                 TREE_OPERAND (t, 1));
3374       }
3375
3376     case THROW_EXPR:
3377       return build_throw (build_expr_from_tree (TREE_OPERAND (t, 0)));
3378
3379     case CONSTRUCTOR:
3380       {
3381         tree r;
3382         tree elts;
3383         tree type = TREE_TYPE (t);
3384         bool purpose_p;
3385
3386         /* digest_init will do the wrong thing if we let it.  */
3387         if (type && TYPE_PTRMEMFUNC_P (type))
3388           return t;
3389
3390         r = NULL_TREE;
3391         /* We do not want to process the purpose of aggregate
3392            initializers as they are identifier nodes which will be
3393            looked up by digest_init.  */
3394         purpose_p = !(type && IS_AGGR_TYPE (type));
3395         for (elts = CONSTRUCTOR_ELTS (t); elts; elts = TREE_CHAIN (elts))
3396           {
3397             tree purpose = TREE_PURPOSE (elts);
3398             tree value = TREE_VALUE (elts);
3399             
3400             if (purpose && purpose_p)
3401               purpose = build_expr_from_tree (purpose);
3402             value = build_expr_from_tree (value);
3403             r = tree_cons (purpose, value, r);
3404           }
3405         
3406         r = build_nt (CONSTRUCTOR, NULL_TREE, nreverse (r));
3407         TREE_HAS_CONSTRUCTOR (r) = TREE_HAS_CONSTRUCTOR (t);
3408
3409         if (type)
3410           return digest_init (type, r, 0);
3411         return r;
3412       }
3413
3414     case TYPEID_EXPR:
3415       if (TYPE_P (TREE_OPERAND (t, 0)))
3416         return get_typeid (TREE_OPERAND (t, 0));
3417       return build_typeid (build_expr_from_tree (TREE_OPERAND (t, 0)));
3418
3419     case VAR_DECL:
3420       return convert_from_reference (t);
3421
3422     case VA_ARG_EXPR:
3423       return build_va_arg (build_expr_from_tree (TREE_OPERAND (t, 0)),
3424                            TREE_TYPE (t));
3425
3426     default:
3427       return t;
3428     }
3429 }
3430
3431 /* FN is an OFFSET_REF indicating the function to call in parse-tree
3432    form; it has not yet been semantically analyzed.  ARGS are the
3433    arguments to the function.  They have already been semantically
3434    analzyed.  */
3435
3436 tree
3437 build_offset_ref_call_from_tree (tree fn, tree args)
3438 {
3439   tree object_addr;
3440
3441   my_friendly_assert (TREE_CODE (fn) == OFFSET_REF, 20020725);
3442
3443   /* A qualified name corresponding to a non-static member
3444      function or a pointer-to-member is represented as an 
3445      OFFSET_REF.  
3446
3447      For both of these function calls, FN will be an OFFSET_REF.
3448
3449         struct A { void f(); };
3450         void A::f() { (A::f) (); } 
3451
3452         struct B { void g(); };
3453         void (B::*p)();
3454         void B::g() { (this->*p)(); }  */
3455
3456   /* This code is not really correct (for example, it does not
3457      handle the case that `A::f' is overloaded), but it is
3458      historically how we have handled this situation.  */
3459   object_addr = build_unary_op (ADDR_EXPR, TREE_OPERAND (fn, 0), 0);
3460   if (TREE_CODE (TREE_OPERAND (fn, 1)) == FIELD_DECL)
3461     fn = resolve_offset_ref (fn);
3462   else
3463     {
3464       fn = TREE_OPERAND (fn, 1);
3465       fn = get_member_function_from_ptrfunc (&object_addr, fn);
3466     }
3467   args = tree_cons (NULL_TREE, object_addr, args);
3468   return build_function_call (fn, args);
3469 }
3470
3471 /* FN indicates the function to call.  Name resolution has been
3472    performed on FN.  ARGS are the arguments to the function.  They
3473    have already been semantically analyzed.  DISALLOW_VIRTUAL is true
3474    if the function call should be determined at compile time, even if
3475    FN is virtual.  */
3476
3477 tree
3478 build_call_from_tree (tree fn, tree args, bool disallow_virtual)
3479 {
3480   tree template_args;
3481   tree template_id;
3482   tree f;
3483   
3484   /* Check to see that name lookup has already been performed.  */
3485   my_friendly_assert (TREE_CODE (fn) != OFFSET_REF, 20020725);
3486   my_friendly_assert (TREE_CODE (fn) != SCOPE_REF, 20020725);
3487
3488   /* In the future all of this should be eliminated.  Instead,
3489      name-lookup for a member function should simply return a
3490      baselink, instead of a FUNCTION_DECL, TEMPLATE_DECL, or
3491      TEMPLATE_ID_EXPR.  */
3492
3493   if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
3494     {
3495       template_id = fn;
3496       template_args = TREE_OPERAND (fn, 1);
3497       fn = TREE_OPERAND (fn, 0);
3498     }
3499   else
3500     {
3501       template_id = NULL_TREE;
3502       template_args = NULL_TREE;
3503     }
3504
3505   f = (TREE_CODE (fn) == OVERLOAD) ? get_first_fn (fn) : fn;
3506   /* Make sure we have a baselink (rather than simply a
3507      FUNCTION_DECL) for a member function.  */
3508   if (current_class_type
3509       && ((TREE_CODE (f) == FUNCTION_DECL
3510            && DECL_FUNCTION_MEMBER_P (f))
3511           || (DECL_FUNCTION_TEMPLATE_P (f) 
3512               && DECL_FUNCTION_MEMBER_P (f))))
3513     {
3514       f = lookup_member (current_class_type, DECL_NAME (f), 
3515                          /*protect=*/1, /*want_type=*/0);
3516       if (f)
3517         fn = f;
3518     }
3519
3520   if (template_id)
3521     {
3522       if (BASELINK_P (fn))
3523           BASELINK_FUNCTIONS (fn) = build_nt (TEMPLATE_ID_EXPR, 
3524                                               BASELINK_FUNCTIONS (fn),
3525                                               template_args);
3526       else
3527         fn = template_id;
3528     }
3529
3530   return finish_call_expr (fn, args, disallow_virtual);
3531 }
3532
3533 /* This is something of the form `int (*a)++' that has turned out to be an
3534    expr.  It was only converted into parse nodes, so we need to go through
3535    and build up the semantics.  Most of the work is done by
3536    build_expr_from_tree, above.
3537
3538    In the above example, TYPE is `int' and DECL is `*a'.  */
3539
3540 tree
3541 reparse_decl_as_expr (type, decl)
3542      tree type, decl;
3543 {
3544   decl = build_expr_from_tree (decl);
3545   if (type)
3546     return build_functional_cast (type, build_tree_list (NULL_TREE, decl));
3547   else
3548     return decl;
3549 }
3550
3551 /* This is something of the form `int (*a)' that has turned out to be a
3552    decl.  It was only converted into parse nodes, so we need to do the
3553    checking that make_{pointer,reference}_declarator do.  */
3554
3555 tree
3556 finish_decl_parsing (decl)
3557      tree decl;
3558 {
3559   switch (TREE_CODE (decl))
3560     {
3561     case IDENTIFIER_NODE:
3562       return decl;
3563     case INDIRECT_REF:
3564       return make_pointer_declarator
3565         (NULL_TREE, finish_decl_parsing (TREE_OPERAND (decl, 0)));
3566     case ADDR_EXPR:
3567       return make_reference_declarator
3568         (NULL_TREE, finish_decl_parsing (TREE_OPERAND (decl, 0)));
3569     case BIT_NOT_EXPR:
3570       TREE_OPERAND (decl, 0) = finish_decl_parsing (TREE_OPERAND (decl, 0));
3571       return decl;
3572     case SCOPE_REF:
3573       push_nested_class (TREE_TYPE (TREE_OPERAND (decl, 0)), 3);
3574       TREE_COMPLEXITY (decl) = current_class_depth;
3575       return decl;
3576     case ARRAY_REF:
3577       TREE_OPERAND (decl, 0) = finish_decl_parsing (TREE_OPERAND (decl, 0));
3578       return decl;
3579     case TREE_LIST:
3580       /* For attribute handling.  */
3581       TREE_VALUE (decl) = finish_decl_parsing (TREE_VALUE (decl));
3582       return decl;
3583     case TEMPLATE_ID_EXPR:
3584       return decl;
3585     default:
3586       abort ();
3587       return NULL_TREE;
3588     }
3589 }
3590
3591 /* Return 1 if root encloses child. */
3592
3593 static int
3594 is_namespace_ancestor (root, child)
3595      tree root, child;
3596 {
3597   if (root == child)
3598     return 1;
3599   if (root == global_namespace)
3600     return 1;
3601   if (child == global_namespace)
3602     return 0;
3603   return is_namespace_ancestor (root, CP_DECL_CONTEXT (child));
3604 }
3605   
3606
3607 /* Return the namespace that is the common ancestor 
3608    of two given namespaces. */
3609
3610 tree
3611 namespace_ancestor (ns1, ns2)
3612      tree ns1, ns2;
3613 {
3614   if (is_namespace_ancestor (ns1, ns2))
3615     return ns1;
3616   return namespace_ancestor (CP_DECL_CONTEXT (ns1), ns2);
3617 }
3618
3619 /* Insert used into the using list of user. Set indirect_flag if this
3620    directive is not directly from the source. Also find the common
3621    ancestor and let our users know about the new namespace */
3622 static void 
3623 add_using_namespace (user, used, indirect)
3624      tree user;
3625      tree used;
3626      int indirect;
3627 {
3628   tree t;
3629   /* Using oneself is a no-op. */
3630   if (user == used)
3631     return;
3632   my_friendly_assert (TREE_CODE (user) == NAMESPACE_DECL, 380);
3633   my_friendly_assert (TREE_CODE (used) == NAMESPACE_DECL, 380);
3634   /* Check if we already have this. */
3635   t = purpose_member (used, DECL_NAMESPACE_USING (user));
3636   if (t != NULL_TREE)
3637     {
3638       if (!indirect)
3639         /* Promote to direct usage. */
3640         TREE_INDIRECT_USING (t) = 0;
3641       return;
3642     }
3643
3644   /* Add used to the user's using list. */
3645   DECL_NAMESPACE_USING (user) 
3646     = tree_cons (used, namespace_ancestor (user, used), 
3647                  DECL_NAMESPACE_USING (user));
3648
3649   TREE_INDIRECT_USING (DECL_NAMESPACE_USING (user)) = indirect;
3650
3651   /* Add user to the used's users list. */
3652   DECL_NAMESPACE_USERS (used)
3653     = tree_cons (user, 0, DECL_NAMESPACE_USERS (used));
3654
3655   /* Recursively add all namespaces used. */
3656   for (t = DECL_NAMESPACE_USING (used); t; t = TREE_CHAIN (t))
3657     /* indirect usage */
3658     add_using_namespace (user, TREE_PURPOSE (t), 1);
3659
3660   /* Tell everyone using us about the new used namespaces. */
3661   for (t = DECL_NAMESPACE_USERS (user); t; t = TREE_CHAIN (t))
3662     add_using_namespace (TREE_PURPOSE (t), used, 1);
3663 }
3664
3665 /* Combines two sets of overloaded functions into an OVERLOAD chain, removing
3666    duplicates.  The first list becomes the tail of the result.
3667
3668    The algorithm is O(n^2).  We could get this down to O(n log n) by
3669    doing a sort on the addresses of the functions, if that becomes
3670    necessary.  */
3671
3672 static tree
3673 merge_functions (s1, s2)
3674      tree s1;
3675      tree s2;
3676 {
3677   for (; s2; s2 = OVL_NEXT (s2))
3678     {
3679       tree fn2 = OVL_CURRENT (s2);
3680       tree fns1;
3681
3682       for (fns1 = s1; fns1; fns1 = OVL_NEXT (fns1))
3683         {
3684           tree fn1 = OVL_CURRENT (fns1);
3685
3686           /* If the function from S2 is already in S1, there is no
3687              need to add it again.  For `extern "C"' functions, we
3688              might have two FUNCTION_DECLs for the same function, in
3689              different namespaces; again, we only need one of them.  */
3690           if (fn1 == fn2 
3691               || (DECL_EXTERN_C_P (fn1) && DECL_EXTERN_C_P (fn2)
3692                   && DECL_NAME (fn1) == DECL_NAME (fn2)))
3693             break;
3694         }
3695       
3696       /* If we exhausted all of the functions in S1, FN2 is new.  */
3697       if (!fns1)
3698         s1 = build_overload (fn2, s1);
3699     }
3700   return s1;
3701 }
3702
3703 /* This should return an error not all definitions define functions.
3704    It is not an error if we find two functions with exactly the
3705    same signature, only if these are selected in overload resolution.
3706    old is the current set of bindings, new the freshly-found binding.
3707    XXX Do we want to give *all* candidates in case of ambiguity?
3708    XXX In what way should I treat extern declarations?
3709    XXX I don't want to repeat the entire duplicate_decls here */
3710
3711 static tree
3712 ambiguous_decl (name, old, new, flags)
3713      tree name;
3714      tree old;
3715      tree new;
3716      int flags;
3717 {
3718   tree val, type;
3719   my_friendly_assert (old != NULL_TREE, 393);
3720   /* Copy the value. */
3721   val = BINDING_VALUE (new);
3722   if (val)
3723     switch (TREE_CODE (val))
3724       {
3725       case TEMPLATE_DECL:
3726         /* If we expect types or namespaces, and not templates,
3727            or this is not a template class. */
3728         if (LOOKUP_QUALIFIERS_ONLY (flags)
3729             && !DECL_CLASS_TEMPLATE_P (val))
3730           val = NULL_TREE;
3731         break;
3732       case TYPE_DECL:
3733         if (LOOKUP_NAMESPACES_ONLY (flags))
3734           val = NULL_TREE;
3735         break;
3736       case NAMESPACE_DECL:
3737         if (LOOKUP_TYPES_ONLY (flags))
3738           val = NULL_TREE;
3739         break;
3740       case FUNCTION_DECL:
3741         /* Ignore built-in functions that are still anticipated.  */
3742         if (LOOKUP_QUALIFIERS_ONLY (flags) || DECL_ANTICIPATED (val))
3743           val = NULL_TREE;
3744         break;
3745       default:
3746         if (LOOKUP_QUALIFIERS_ONLY (flags))
3747           val = NULL_TREE;
3748       }
3749         
3750   if (!BINDING_VALUE (old))
3751     BINDING_VALUE (old) = val;
3752   else if (val && val != BINDING_VALUE (old))
3753     {
3754       if (is_overloaded_fn (BINDING_VALUE (old)) 
3755           && is_overloaded_fn (val))
3756         {
3757           BINDING_VALUE (old) = merge_functions (BINDING_VALUE (old),
3758                                                  val);
3759         }
3760       else
3761         {
3762           /* Some declarations are functions, some are not. */
3763           if (flags & LOOKUP_COMPLAIN)
3764             {
3765               /* If we've already given this error for this lookup,
3766                  BINDING_VALUE (old) is error_mark_node, so let's not
3767                  repeat ourselves.  */
3768               if (BINDING_VALUE (old) != error_mark_node)
3769                 {
3770                   error ("use of `%D' is ambiguous", name);
3771                   cp_error_at ("  first declared as `%#D' here",
3772                                BINDING_VALUE (old));
3773                 }
3774               cp_error_at ("  also declared as `%#D' here", val);
3775             }
3776           BINDING_VALUE (old) = error_mark_node;
3777         }
3778     }
3779   /* ... and copy the type. */
3780   type = BINDING_TYPE (new);
3781   if (LOOKUP_NAMESPACES_ONLY (flags))
3782     type = NULL_TREE;
3783   if (!BINDING_TYPE (old))
3784     BINDING_TYPE (old) = type;
3785   else if (type && BINDING_TYPE (old) != type)
3786     {
3787       if (flags & LOOKUP_COMPLAIN)
3788         {
3789           error ("`%D' denotes an ambiguous type",name);
3790           cp_error_at ("  first type here", BINDING_TYPE (old));
3791           cp_error_at ("  other type here", type);
3792         }
3793     }
3794   return old;
3795 }
3796
3797 /* Subroutine of unualified_namespace_lookup:
3798    Add the bindings of NAME in used namespaces to VAL.
3799    We are currently looking for names in namespace SCOPE, so we
3800    look through USINGS for using-directives of namespaces
3801    which have SCOPE as a common ancestor with the current scope.
3802    Returns zero on errors. */
3803
3804 int
3805 lookup_using_namespace (name, val, usings, scope, flags, spacesp)
3806      tree name, val, usings, scope;
3807      int flags;
3808      tree *spacesp;
3809 {
3810   tree iter;
3811   tree val1;
3812   /* Iterate over all used namespaces in current, searching for using
3813      directives of scope. */
3814   for (iter = usings; iter; iter = TREE_CHAIN (iter))
3815     if (TREE_VALUE (iter) == scope)
3816       {
3817         if (spacesp)
3818           *spacesp = tree_cons (TREE_PURPOSE (iter), NULL_TREE,
3819                                 *spacesp);
3820         val1 = binding_for_name (name, TREE_PURPOSE (iter));
3821         /* Resolve ambiguities. */
3822         val = ambiguous_decl (name, val, val1, flags);
3823       }
3824   return BINDING_VALUE (val) != error_mark_node;
3825 }
3826
3827 /* [namespace.qual]
3828    Accepts the NAME to lookup and its qualifying SCOPE.
3829    Returns the name/type pair found into the CPLUS_BINDING RESULT,
3830    or 0 on error. */
3831
3832 int
3833 qualified_lookup_using_namespace (name, scope, result, flags)
3834      tree name;
3835      tree scope;
3836      tree result;
3837      int flags;
3838 {
3839   /* Maintain a list of namespaces visited... */
3840   tree seen = NULL_TREE;
3841   /* ... and a list of namespace yet to see. */
3842   tree todo = NULL_TREE;
3843   tree usings;
3844   /* Look through namespace aliases.  */
3845   scope = ORIGINAL_NAMESPACE (scope);
3846   while (scope && (result != error_mark_node))
3847     {
3848       seen = tree_cons (scope, NULL_TREE, seen);
3849       result = ambiguous_decl (name, result,
3850                                binding_for_name (name, scope), flags);
3851       if (!BINDING_VALUE (result) && !BINDING_TYPE (result))
3852         /* Consider using directives. */
3853         for (usings = DECL_NAMESPACE_USING (scope); usings;
3854              usings = TREE_CHAIN (usings))
3855           /* If this was a real directive, and we have not seen it. */
3856           if (!TREE_INDIRECT_USING (usings)
3857               && !purpose_member (TREE_PURPOSE (usings), seen))
3858             todo = tree_cons (TREE_PURPOSE (usings), NULL_TREE, todo);
3859       if (todo)
3860         {
3861           scope = TREE_PURPOSE (todo);
3862           todo = TREE_CHAIN (todo);
3863         }
3864       else
3865         scope = NULL_TREE; /* If there never was a todo list. */
3866     }
3867   return result != error_mark_node;
3868 }
3869
3870 /* [namespace.memdef]/2 */
3871
3872 /* Set the context of a declaration to scope. Complain if we are not
3873    outside scope. */
3874
3875 void
3876 set_decl_namespace (decl, scope, friendp)
3877      tree decl;
3878      tree scope;
3879      int friendp;
3880 {
3881   tree old;
3882   
3883   /* Get rid of namespace aliases. */
3884   scope = ORIGINAL_NAMESPACE (scope);
3885   
3886   /* It is ok for friends to be qualified in parallel space.  */
3887   if (!friendp && !is_namespace_ancestor (current_namespace, scope))
3888     error ("declaration of `%D' not in a namespace surrounding `%D'",
3889               decl, scope);
3890   DECL_CONTEXT (decl) = FROB_CONTEXT (scope);
3891   if (scope != current_namespace)
3892     {
3893       /* See whether this has been declared in the namespace. */
3894       old = namespace_binding (DECL_NAME (decl), scope);
3895       if (!old)
3896         /* No old declaration at all. */
3897         goto complain;
3898       /* A template can be explicitly specialized in any namespace.  */
3899       if (processing_explicit_instantiation)
3900         return;
3901       if (!is_overloaded_fn (decl))
3902         /* Don't compare non-function decls with decls_match here,
3903            since it can't check for the correct constness at this
3904            point. pushdecl will find those errors later.  */
3905         return;
3906       /* Since decl is a function, old should contain a function decl. */
3907       if (!is_overloaded_fn (old))
3908         goto complain;
3909       if (processing_template_decl || processing_specialization)
3910         /* We have not yet called push_template_decl to turn the
3911            FUNCTION_DECL into a TEMPLATE_DECL, so the declarations
3912            won't match.  But, we'll check later, when we construct the
3913            template.  */
3914         return;
3915       for (; old; old = OVL_NEXT (old))
3916         if (decls_match (decl, OVL_CURRENT (old)))
3917           return;
3918     }
3919   else
3920     return;
3921  complain:
3922   error ("`%D' should have been declared inside `%D'",
3923             decl, scope);
3924
3925
3926 /* Compute the namespace where a declaration is defined. */
3927
3928 static tree
3929 decl_namespace (decl)
3930      tree decl;
3931 {
3932   if (TYPE_P (decl))
3933     decl = TYPE_STUB_DECL (decl);
3934   while (DECL_CONTEXT (decl))
3935     {
3936       decl = DECL_CONTEXT (decl);
3937       if (TREE_CODE (decl) == NAMESPACE_DECL)
3938         return decl;
3939       if (TYPE_P (decl))
3940         decl = TYPE_STUB_DECL (decl);
3941       my_friendly_assert (DECL_P (decl), 390);
3942     }
3943
3944   return global_namespace;
3945 }
3946
3947 /* Return the namespace where the current declaration is declared. */
3948
3949 tree
3950 current_decl_namespace ()
3951 {
3952   tree result;
3953   /* If we have been pushed into a different namespace, use it. */
3954   if (decl_namespace_list)
3955     return TREE_PURPOSE (decl_namespace_list);
3956
3957   if (current_class_type)
3958     result = decl_namespace (TYPE_STUB_DECL (current_class_type));
3959   else if (current_function_decl)
3960     result = decl_namespace (current_function_decl);
3961   else 
3962     result = current_namespace;
3963   return result;
3964 }
3965
3966 /* Temporarily set the namespace for the current declaration. */
3967
3968 void
3969 push_decl_namespace (decl)
3970      tree decl;
3971 {
3972   if (TREE_CODE (decl) != NAMESPACE_DECL)
3973     decl = decl_namespace (decl);
3974   decl_namespace_list = tree_cons (ORIGINAL_NAMESPACE (decl),
3975                                    NULL_TREE, decl_namespace_list);
3976 }
3977
3978 void
3979 pop_decl_namespace ()
3980 {
3981   decl_namespace_list = TREE_CHAIN (decl_namespace_list);
3982 }
3983
3984 /* Enter a class or namespace scope. */
3985
3986 void
3987 push_scope (t)
3988      tree t;
3989 {
3990   if (TREE_CODE (t) == NAMESPACE_DECL)
3991     push_decl_namespace (t);
3992   else
3993     pushclass (t, 2);
3994 }
3995
3996 /* Leave scope pushed by push_scope. */
3997
3998 void
3999 pop_scope (t)
4000      tree t;
4001 {
4002   if (TREE_CODE (t) == NAMESPACE_DECL)
4003     pop_decl_namespace ();
4004   else
4005     popclass ();
4006 }
4007
4008 /* [basic.lookup.koenig] */
4009 /* A non-zero return value in the functions below indicates an error.  */
4010
4011 struct arg_lookup
4012 {
4013   tree name;
4014   tree namespaces;
4015   tree classes;
4016   tree functions;
4017 };
4018
4019 static int arg_assoc         PARAMS ((struct arg_lookup*, tree));
4020 static int arg_assoc_args    PARAMS ((struct arg_lookup*, tree));
4021 static int arg_assoc_type    PARAMS ((struct arg_lookup*, tree));
4022 static int add_function      PARAMS ((struct arg_lookup *, tree));
4023 static int arg_assoc_namespace PARAMS ((struct arg_lookup *, tree));
4024 static int arg_assoc_class   PARAMS ((struct arg_lookup *, tree));
4025 static int arg_assoc_template_arg PARAMS ((struct arg_lookup*, tree));
4026
4027 /* Add a function to the lookup structure.
4028    Returns 1 on error.  */
4029
4030 static int
4031 add_function (k, fn)
4032      struct arg_lookup *k;
4033      tree fn;
4034 {
4035   /* We used to check here to see if the function was already in the list,
4036      but that's O(n^2), which is just too expensive for function lookup.
4037      Now we deal with the occasional duplicate in joust.  In doing this, we
4038      assume that the number of duplicates will be small compared to the
4039      total number of functions being compared, which should usually be the
4040      case.  */
4041
4042   /* We must find only functions, or exactly one non-function. */
4043   if (!k->functions) 
4044     k->functions = fn;
4045   else if (is_overloaded_fn (k->functions) && is_overloaded_fn (fn))
4046     k->functions = build_overload (fn, k->functions);
4047   else
4048     {
4049       tree f1 = OVL_CURRENT (k->functions);
4050       tree f2 = fn;
4051       if (is_overloaded_fn (f1))
4052         {
4053           fn = f1; f1 = f2; f2 = fn;
4054         }
4055       cp_error_at ("`%D' is not a function,", f1);
4056       cp_error_at ("  conflict with `%D'", f2);
4057       error ("  in call to `%D'", k->name);
4058       return 1;
4059     }
4060
4061   return 0;
4062 }
4063
4064 /* Add functions of a namespace to the lookup structure.
4065    Returns 1 on error.  */
4066
4067 static int
4068 arg_assoc_namespace (k, scope)
4069      struct arg_lookup *k;
4070      tree scope;
4071 {
4072   tree value;
4073
4074   if (purpose_member (scope, k->namespaces))
4075     return 0;
4076   k->namespaces = tree_cons (scope, NULL_TREE, k->namespaces);
4077   
4078   value = namespace_binding (k->name, scope);
4079   if (!value)
4080     return 0;
4081
4082   for (; value; value = OVL_NEXT (value))
4083     if (add_function (k, OVL_CURRENT (value)))
4084       return 1;
4085   
4086   return 0;
4087 }
4088
4089 /* Adds everything associated with a template argument to the lookup
4090    structure.  Returns 1 on error.  */
4091
4092 static int
4093 arg_assoc_template_arg (k, arg)
4094      struct arg_lookup* k;
4095      tree arg;
4096 {
4097   /* [basic.lookup.koenig]
4098
4099      If T is a template-id, its associated namespaces and classes are
4100      ... the namespaces and classes associated with the types of the
4101      template arguments provided for template type parameters
4102      (excluding template template parameters); the namespaces in which
4103      any template template arguments are defined; and the classes in
4104      which any member templates used as template template arguments
4105      are defined.  [Note: non-type template arguments do not
4106      contribute to the set of associated namespaces.  ]  */
4107
4108   /* Consider first template template arguments.  */
4109   if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4110       || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
4111     return 0;
4112   else if (TREE_CODE (arg) == TEMPLATE_DECL)
4113     {
4114       tree ctx = CP_DECL_CONTEXT (arg);
4115
4116       /* It's not a member template.  */
4117       if (TREE_CODE (ctx) == NAMESPACE_DECL)
4118         return arg_assoc_namespace (k, ctx);
4119       /* Otherwise, it must be member template.  */
4120       else 
4121         return arg_assoc_class (k, ctx);
4122     }
4123   /* It's not a template template argument, but it is a type template
4124      argument.  */
4125   else if (TYPE_P (arg))
4126     return arg_assoc_type (k, arg);
4127   /* It's a non-type template argument.  */
4128   else
4129     return 0;
4130 }
4131
4132 /* Adds everything associated with class to the lookup structure.
4133    Returns 1 on error.  */
4134
4135 static int
4136 arg_assoc_class (k, type)
4137      struct arg_lookup* k;
4138      tree type;
4139 {
4140   tree list, friends, context;
4141   int i;
4142   
4143   /* Backend build structures, such as __builtin_va_list, aren't
4144      affected by all this.  */
4145   if (!CLASS_TYPE_P (type))
4146     return 0;
4147
4148   if (purpose_member (type, k->classes))
4149     return 0;
4150   k->classes = tree_cons (type, NULL_TREE, k->classes);
4151   
4152   context = decl_namespace (TYPE_MAIN_DECL (type));
4153   if (arg_assoc_namespace (k, context))
4154     return 1;
4155   
4156   /* Process baseclasses. */
4157   for (i = 0; i < CLASSTYPE_N_BASECLASSES (type); i++)
4158     if (arg_assoc_class (k, TYPE_BINFO_BASETYPE (type, i)))
4159       return 1;
4160   
4161   /* Process friends. */
4162   for (list = DECL_FRIENDLIST (TYPE_MAIN_DECL (type)); list; 
4163        list = TREE_CHAIN (list))
4164     if (k->name == TREE_PURPOSE (list))
4165       for (friends = TREE_VALUE (list); friends; 
4166            friends = TREE_CHAIN (friends))
4167         /* Only interested in global functions with potentially hidden
4168            (i.e. unqualified) declarations. */
4169         if (TREE_PURPOSE (friends) == error_mark_node && TREE_VALUE (friends)
4170             && decl_namespace (TREE_VALUE (friends)) == context)
4171           if (add_function (k, TREE_VALUE (friends)))
4172             return 1;
4173
4174   /* Process template arguments.  */
4175   if (CLASSTYPE_TEMPLATE_INFO (type))
4176     {
4177       list = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
4178       for (i = 0; i < TREE_VEC_LENGTH (list); ++i) 
4179         arg_assoc_template_arg (k, TREE_VEC_ELT (list, i));
4180     }
4181
4182   return 0;
4183 }
4184
4185 /* Adds everything associated with a given type.
4186    Returns 1 on error.  */
4187
4188 static int
4189 arg_assoc_type (k, type)
4190      struct arg_lookup *k;
4191      tree type;
4192 {
4193   switch (TREE_CODE (type))
4194     {
4195     case VOID_TYPE:
4196     case INTEGER_TYPE:
4197     case REAL_TYPE:
4198     case COMPLEX_TYPE:
4199     case VECTOR_TYPE:
4200     case CHAR_TYPE:
4201     case BOOLEAN_TYPE:
4202       return 0;
4203     case RECORD_TYPE:
4204       if (TYPE_PTRMEMFUNC_P (type))
4205         return arg_assoc_type (k, TYPE_PTRMEMFUNC_FN_TYPE (type));
4206       return arg_assoc_class (k, type);
4207     case POINTER_TYPE:
4208     case REFERENCE_TYPE:
4209     case ARRAY_TYPE:
4210       return arg_assoc_type (k, TREE_TYPE (type));
4211     case UNION_TYPE:
4212     case ENUMERAL_TYPE:
4213       return arg_assoc_namespace (k, decl_namespace (TYPE_MAIN_DECL (type)));
4214     case OFFSET_TYPE:
4215       /* Pointer to member: associate class type and value type. */
4216       if (arg_assoc_type (k, TYPE_OFFSET_BASETYPE (type)))
4217         return 1;
4218       return arg_assoc_type (k, TREE_TYPE (type));
4219     case METHOD_TYPE:
4220       /* The basetype is referenced in the first arg type, so just
4221          fall through.  */
4222     case FUNCTION_TYPE:
4223       /* Associate the parameter types. */
4224       if (arg_assoc_args (k, TYPE_ARG_TYPES (type)))
4225         return 1;
4226       /* Associate the return type. */
4227       return arg_assoc_type (k, TREE_TYPE (type));
4228     case TEMPLATE_TYPE_PARM:
4229     case BOUND_TEMPLATE_TEMPLATE_PARM:
4230       return 0;
4231     case TYPENAME_TYPE:
4232       return 0;
4233     case LANG_TYPE:
4234       if (type == unknown_type_node)
4235         return 0;
4236       /* else fall through */
4237     default:
4238       abort ();
4239     }
4240   return 0;
4241 }
4242
4243 /* Adds everything associated with arguments.  Returns 1 on error.  */
4244
4245 static int
4246 arg_assoc_args (k, args)
4247      struct arg_lookup* k;
4248      tree args;
4249 {
4250   for (; args; args = TREE_CHAIN (args))
4251     if (arg_assoc (k, TREE_VALUE (args)))
4252       return 1;
4253   return 0;
4254 }
4255
4256 /* Adds everything associated with a given tree_node.  Returns 1 on error.  */
4257
4258 static int
4259 arg_assoc (k, n)
4260      struct arg_lookup* k;
4261      tree n;
4262 {
4263   if (n == error_mark_node)
4264     return 0;
4265
4266   if (TYPE_P (n))
4267     return arg_assoc_type (k, n);
4268
4269   if (! type_unknown_p (n))
4270     return arg_assoc_type (k, TREE_TYPE (n));
4271
4272   if (TREE_CODE (n) == ADDR_EXPR)
4273     n = TREE_OPERAND (n, 0);
4274   if (TREE_CODE (n) == COMPONENT_REF)
4275     n = TREE_OPERAND (n, 1);
4276   if (TREE_CODE (n) == OFFSET_REF)
4277     n = TREE_OPERAND (n, 1);
4278   while (TREE_CODE (n) == TREE_LIST)
4279     n = TREE_VALUE (n);
4280   if (TREE_CODE (n) == BASELINK)
4281     n = BASELINK_FUNCTIONS (n);
4282
4283   if (TREE_CODE (n) == FUNCTION_DECL)
4284     return arg_assoc_type (k, TREE_TYPE (n));
4285   if (TREE_CODE (n) == TEMPLATE_ID_EXPR)
4286     {
4287       /* [basic.lookup.koenig]
4288
4289          If T is a template-id, its associated namespaces and classes
4290          are the namespace in which the template is defined; for
4291          member templates, the member template's class...  */
4292       tree template = TREE_OPERAND (n, 0);
4293       tree args = TREE_OPERAND (n, 1);
4294       tree ctx;
4295       tree arg;
4296
4297       if (TREE_CODE (template) == COMPONENT_REF)
4298         template = TREE_OPERAND (template, 1);
4299       
4300       /* First, the template.  There may actually be more than one if
4301          this is an overloaded function template.  But, in that case,
4302          we only need the first; all the functions will be in the same
4303          namespace.  */
4304       template = OVL_CURRENT (template);
4305
4306       ctx = CP_DECL_CONTEXT (template);
4307        
4308       if (TREE_CODE (ctx) == NAMESPACE_DECL)
4309         {
4310           if (arg_assoc_namespace (k, ctx) == 1)
4311             return 1;
4312         }
4313       /* It must be a member template.  */
4314       else if (arg_assoc_class (k, ctx) == 1)
4315         return 1;
4316
4317       /* Now the arguments.  */
4318       for (arg = args; arg != NULL_TREE; arg = TREE_CHAIN (arg))
4319         if (arg_assoc_template_arg (k, TREE_VALUE (arg)) == 1)
4320           return 1;
4321     }
4322   else
4323     {
4324       my_friendly_assert (TREE_CODE (n) == OVERLOAD, 980715);
4325       
4326       for (; n; n = OVL_CHAIN (n))
4327         if (arg_assoc_type (k, TREE_TYPE (OVL_FUNCTION (n))))
4328           return 1;
4329     }
4330
4331   return 0;
4332 }
4333
4334 /* Performs Koenig lookup depending on arguments, where fns
4335    are the functions found in normal lookup. */
4336
4337 tree
4338 lookup_arg_dependent (name, fns, args)
4339      tree name;
4340      tree fns;
4341      tree args;
4342 {
4343   struct arg_lookup k;
4344   tree fn = NULL_TREE;
4345
4346   k.name = name;
4347   k.functions = fns;
4348   k.classes = NULL_TREE;
4349
4350   /* Note that we've already looked at some namespaces during normal
4351      unqualified lookup, unless we found a decl in function scope.  */
4352   if (fns)
4353     fn = OVL_CURRENT (fns);
4354   if (fn && TREE_CODE (fn) == FUNCTION_DECL && DECL_LOCAL_FUNCTION_P (fn))
4355     k.namespaces = NULL_TREE;
4356   else
4357     unqualified_namespace_lookup (name, 0, &k.namespaces);
4358
4359   arg_assoc_args (&k, args);
4360   return k.functions;
4361 }
4362
4363 /* Process a namespace-alias declaration. */
4364
4365 void
4366 do_namespace_alias (alias, namespace)
4367      tree alias, namespace;
4368 {
4369   if (TREE_CODE (namespace) != NAMESPACE_DECL)
4370     {
4371       /* The parser did not find it, so it's not there. */
4372       error ("unknown namespace `%D'", namespace);
4373       return;
4374     }
4375
4376   namespace = ORIGINAL_NAMESPACE (namespace);
4377
4378   /* Build the alias. */
4379   alias = build_lang_decl (NAMESPACE_DECL, alias, void_type_node);     
4380   DECL_NAMESPACE_ALIAS (alias) = namespace;
4381   pushdecl (alias);
4382 }
4383
4384 /* Check a non-member using-declaration. Return the name and scope
4385    being used, and the USING_DECL, or NULL_TREE on failure. */
4386
4387 static tree
4388 validate_nonmember_using_decl (decl, scope, name)
4389      tree decl;
4390      tree *scope;
4391      tree *name;
4392 {
4393   if (TREE_CODE (decl) == SCOPE_REF)
4394     {
4395       *scope = TREE_OPERAND (decl, 0);
4396       *name = TREE_OPERAND (decl, 1);
4397
4398       if (!processing_template_decl)
4399         {
4400           /* [namespace.udecl]
4401              A using-declaration for a class member shall be a
4402              member-declaration.  */
4403           if(TREE_CODE (*scope) != NAMESPACE_DECL)
4404             {
4405               if (TYPE_P (*scope))
4406                 error ("`%T' is not a namespace", *scope);
4407               else
4408                 error ("`%D' is not a namespace", *scope);
4409               return NULL_TREE;
4410             }
4411           
4412           /* 7.3.3/5
4413              A using-declaration shall not name a template-id.  */
4414           if (TREE_CODE (*name) == TEMPLATE_ID_EXPR)
4415             {
4416               *name = TREE_OPERAND (*name, 0);
4417               error ("a using-declaration cannot specify a template-id.  Try `using %D'", *name);
4418               return NULL_TREE;
4419             }
4420         }
4421     }
4422   else if (TREE_CODE (decl) == IDENTIFIER_NODE
4423            || TREE_CODE (decl) == TYPE_DECL
4424            || TREE_CODE (decl) == TEMPLATE_DECL)
4425     {
4426       *scope = global_namespace;
4427       *name = decl;
4428     }
4429   else if (TREE_CODE (decl) == NAMESPACE_DECL)
4430     {
4431       error ("namespace `%D' not allowed in using-declaration", decl);
4432       return NULL_TREE;
4433     }
4434   else
4435     abort ();
4436   if (DECL_P (*name))
4437     *name = DECL_NAME (*name);
4438   /* Make a USING_DECL. */
4439   return push_using_decl (*scope, *name);
4440 }
4441
4442 /* Process local and global using-declarations. */
4443
4444 static void
4445 do_nonmember_using_decl (scope, name, oldval, oldtype, newval, newtype)
4446      tree scope, name;
4447      tree oldval, oldtype;
4448      tree *newval, *newtype;
4449 {
4450   tree decls;
4451
4452   *newval = *newtype = NULL_TREE;
4453   decls = make_node (CPLUS_BINDING);
4454   if (!qualified_lookup_using_namespace (name, scope, decls, 0))
4455     /* Lookup error */
4456     return;
4457
4458   if (!BINDING_VALUE (decls) && !BINDING_TYPE (decls))
4459     {
4460       error ("`%D' not declared", name);
4461       return;
4462     }
4463
4464   /* Check for using functions. */
4465   if (BINDING_VALUE (decls) && is_overloaded_fn (BINDING_VALUE (decls)))
4466     {
4467       tree tmp, tmp1;
4468
4469       if (oldval && !is_overloaded_fn (oldval))
4470         {
4471           duplicate_decls (OVL_CURRENT (BINDING_VALUE (decls)), oldval);
4472           oldval = NULL_TREE;
4473         }
4474
4475       *newval = oldval;
4476       for (tmp = BINDING_VALUE (decls); tmp; tmp = OVL_NEXT (tmp))
4477         {
4478           tree new_fn = OVL_CURRENT (tmp);
4479
4480           /* [namespace.udecl]
4481
4482              If a function declaration in namespace scope or block
4483              scope has the same name and the same parameter types as a
4484              function introduced by a using declaration the program is
4485              ill-formed.  */
4486           for (tmp1 = oldval; tmp1; tmp1 = OVL_NEXT (tmp1))
4487             {
4488               tree old_fn = OVL_CURRENT (tmp1);
4489
4490               if (new_fn == old_fn)
4491                 /* The function already exists in the current namespace.  */
4492                 break;
4493               else if (OVL_USED (tmp1))
4494                 continue; /* this is a using decl */
4495               else if (compparms (TYPE_ARG_TYPES (TREE_TYPE (new_fn)),
4496                                   TYPE_ARG_TYPES (TREE_TYPE (old_fn))))
4497                 {
4498                   /* If this using declaration introduces a function
4499                      recognized as a built-in, no longer mark it as
4500                      anticipated in this scope.  */
4501                   if (DECL_ANTICIPATED (old_fn))
4502                     {
4503                       DECL_ANTICIPATED (old_fn) = 0;
4504                       break;
4505                     }
4506
4507                   /* There was already a non-using declaration in
4508                      this scope with the same parameter types. If both
4509                      are the same extern "C" functions, that's ok.  */
4510                   if (!decls_match (new_fn, old_fn))
4511                     error ("`%D' is already declared in this scope", name);
4512                   break;
4513                 }
4514             }
4515
4516           /* If we broke out of the loop, there's no reason to add
4517              this function to the using declarations for this
4518              scope.  */
4519           if (tmp1)
4520             continue;
4521             
4522           *newval = build_overload (OVL_CURRENT (tmp), *newval);
4523           if (TREE_CODE (*newval) != OVERLOAD)
4524             *newval = ovl_cons (*newval, NULL_TREE);
4525           OVL_USED (*newval) = 1;
4526         }
4527     }
4528   else 
4529     {
4530       *newval = BINDING_VALUE (decls);
4531       if (oldval)
4532         duplicate_decls (*newval, oldval);
4533     } 
4534
4535   *newtype = BINDING_TYPE (decls);
4536   if (oldtype && *newtype && oldtype != *newtype)
4537     {
4538       error ("using declaration `%D' introduced ambiguous type `%T'",
4539                 name, oldtype);
4540       return;
4541     }
4542 }
4543
4544 /* Process a using-declaration not appearing in class or local scope. */
4545
4546 void
4547 do_toplevel_using_decl (decl)
4548      tree decl;
4549 {
4550   tree scope, name, binding;
4551   tree oldval, oldtype, newval, newtype;
4552
4553   decl = validate_nonmember_using_decl (decl, &scope, &name);
4554   if (decl == NULL_TREE)
4555     return;
4556   
4557   binding = binding_for_name (name, current_namespace);
4558
4559   oldval = BINDING_VALUE (binding);
4560   oldtype = BINDING_TYPE (binding);
4561
4562   do_nonmember_using_decl (scope, name, oldval, oldtype, &newval, &newtype);
4563
4564   /* Copy declarations found. */
4565   if (newval)
4566     BINDING_VALUE (binding) = newval;
4567   if (newtype)
4568     BINDING_TYPE (binding) = newtype;
4569   return;
4570 }
4571
4572 /* Process a using-declaration at function scope.  */
4573
4574 void
4575 do_local_using_decl (decl)
4576      tree decl;
4577 {
4578   tree scope, name;
4579   tree oldval, oldtype, newval, newtype;
4580
4581   decl = validate_nonmember_using_decl (decl, &scope, &name);
4582   if (decl == NULL_TREE)
4583     return;
4584
4585   if (building_stmt_tree ()
4586       && at_function_scope_p ())
4587     add_decl_stmt (decl);
4588
4589   oldval = lookup_name_current_level (name);
4590   oldtype = lookup_type_current_level (name);
4591
4592   do_nonmember_using_decl (scope, name, oldval, oldtype, &newval, &newtype);
4593
4594   if (newval)
4595     {
4596       if (is_overloaded_fn (newval))
4597         {
4598           tree fn, term;
4599
4600           /* We only need to push declarations for those functions
4601              that were not already bound in the current level.
4602              The old value might be NULL_TREE, it might be a single
4603              function, or an OVERLOAD.  */
4604           if (oldval && TREE_CODE (oldval) == OVERLOAD)
4605             term = OVL_FUNCTION (oldval);
4606           else
4607             term = oldval;
4608           for (fn = newval; fn && OVL_CURRENT (fn) != term; 
4609                fn = OVL_NEXT (fn))
4610             push_overloaded_decl (OVL_CURRENT (fn), 
4611                                   PUSH_LOCAL | PUSH_USING);
4612         }
4613       else
4614         push_local_binding (name, newval, PUSH_USING);
4615     }
4616   if (newtype)
4617     set_identifier_type_value (name, newtype);
4618 }
4619
4620 tree
4621 do_class_using_decl (decl)
4622      tree decl;
4623 {
4624   tree name, value;
4625
4626   if (TREE_CODE (decl) != SCOPE_REF
4627       || !TYPE_P (TREE_OPERAND (decl, 0)))
4628     {
4629       error ("using-declaration for non-member at class scope");
4630       return NULL_TREE;
4631     }
4632   name = TREE_OPERAND (decl, 1);
4633   if (TREE_CODE (name) == BIT_NOT_EXPR)
4634     {
4635       error ("using-declaration for destructor");
4636       return NULL_TREE;
4637     }
4638   else if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
4639     {
4640       name = TREE_OPERAND (name, 0);
4641       error ("a using-declaration cannot specify a template-id.  Try  `using %T::%D'", TREE_OPERAND (decl, 0), name);
4642       return NULL_TREE;
4643     }
4644   if (TREE_CODE (name) == TYPE_DECL || TREE_CODE (name) == TEMPLATE_DECL)
4645     name = DECL_NAME (name);
4646   else if (BASELINK_P (name))
4647     {
4648       name = BASELINK_FUNCTIONS (name);
4649       if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
4650         name = TREE_OPERAND (name, 0);
4651       name = DECL_NAME (get_first_fn (name));
4652     }
4653
4654   my_friendly_assert (TREE_CODE (name) == IDENTIFIER_NODE, 980716);
4655
4656   value = build_lang_decl (USING_DECL, name, void_type_node);
4657   DECL_INITIAL (value) = TREE_OPERAND (decl, 0);
4658   return value;
4659 }
4660
4661 /* Process a using-directive. */
4662
4663 void
4664 do_using_directive (namespace)
4665      tree namespace;
4666 {
4667   if (building_stmt_tree ())
4668     add_stmt (build_stmt (USING_STMT, namespace));
4669   
4670   /* using namespace A::B::C; */
4671   if (TREE_CODE (namespace) == SCOPE_REF)
4672       namespace = TREE_OPERAND (namespace, 1);
4673   if (TREE_CODE (namespace) == IDENTIFIER_NODE)
4674     {
4675       /* Lookup in lexer did not find a namespace. */
4676       if (!processing_template_decl)
4677         error ("namespace `%T' undeclared", namespace);
4678       return;
4679     }
4680   if (TREE_CODE (namespace) != NAMESPACE_DECL)
4681     {
4682       if (!processing_template_decl)
4683         error ("`%T' is not a namespace", namespace);
4684       return;
4685     }
4686   namespace = ORIGINAL_NAMESPACE (namespace);
4687   if (!toplevel_bindings_p ())
4688     push_using_directive (namespace);
4689   else
4690     /* direct usage */
4691     add_using_namespace (current_namespace, namespace, 0);
4692 }
4693
4694 void
4695 check_default_args (x)
4696      tree x;
4697 {
4698   tree arg = TYPE_ARG_TYPES (TREE_TYPE (x));
4699   int saw_def = 0, i = 0 - (TREE_CODE (TREE_TYPE (x)) == METHOD_TYPE);
4700   for (; arg && arg != void_list_node; arg = TREE_CHAIN (arg), ++i)
4701     {
4702       if (TREE_PURPOSE (arg))
4703         saw_def = 1;
4704       else if (saw_def)
4705         {
4706           cp_error_at ("default argument missing for parameter %P of `%+#D'",
4707                        i, x);
4708           break;
4709         }
4710     }
4711 }
4712
4713 void
4714 mark_used (decl)
4715      tree decl;
4716 {
4717   TREE_USED (decl) = 1;
4718   if (processing_template_decl)
4719     return;
4720   if (!skip_evaluation)
4721     assemble_external (decl);
4722
4723   /* Is it a synthesized method that needs to be synthesized?  */
4724   if (TREE_CODE (decl) == FUNCTION_DECL
4725       && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl)
4726       && DECL_ARTIFICIAL (decl) 
4727       && ! DECL_INITIAL (decl)
4728       /* Kludge: don't synthesize for default args.  */
4729       && current_function_decl)
4730     {
4731       synthesize_method (decl);
4732       /* If we've already synthesized the method we don't need to
4733          instantiate it, so we can return right away.  */
4734       return;
4735     }
4736
4737   /* If this is a function or variable that is an instance of some
4738      template, we now know that we will need to actually do the
4739      instantiation. We check that DECL is not an explicit
4740      instantiation because that is not checked in instantiate_decl.  */
4741   if ((DECL_NON_THUNK_FUNCTION_P (decl) || TREE_CODE (decl) == VAR_DECL)
4742       && DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
4743       && (!DECL_EXPLICIT_INSTANTIATION (decl)
4744           || (TREE_CODE (decl) == FUNCTION_DECL && DECL_INLINE (decl))))
4745     instantiate_decl (decl, /*defer_ok=*/1);
4746 }
4747
4748 /* Helper function for class_head_decl and class_head_defn
4749    nonterminals. AGGR is the class, union or struct tag. SCOPE is the
4750    explicit scope used (NULL for no scope resolution). ID is the
4751    name. DEFN_P is true, if this is a definition of the class and
4752    NEW_TYPE_P is set to non-zero, if we push into the scope containing
4753    the to be defined aggregate.
4754    
4755    Return a TYPE_DECL for the type declared by ID in SCOPE.  */
4756
4757 tree
4758 handle_class_head (tag_kind, scope, id, attributes, defn_p, new_type_p)
4759      enum tag_types tag_kind;
4760      tree scope, id, attributes;
4761      int defn_p;
4762      int *new_type_p;
4763 {
4764   tree decl = NULL_TREE;
4765   tree current = current_scope ();
4766   bool xrefd_p = false;
4767   
4768   if (current == NULL_TREE)
4769     current = current_namespace;
4770
4771   *new_type_p = 0;
4772   
4773   if (scope)
4774     {
4775       if (TREE_CODE (id) == TYPE_DECL)
4776         /* We must bash typedefs back to the main decl of the
4777            type. Otherwise we become confused about scopes.  */
4778         decl = TYPE_MAIN_DECL (TREE_TYPE (id));
4779       else if (DECL_CLASS_TEMPLATE_P (id))
4780         decl = DECL_TEMPLATE_RESULT (id);
4781       else
4782         {
4783           if (TYPE_P (scope))
4784             {
4785               /* According to the suggested resolution of core issue
4786                  180, 'typename' is assumed after a class-key.  */
4787               decl = make_typename_type (scope, id, tf_error);
4788               if (decl != error_mark_node)
4789                 decl = TYPE_MAIN_DECL (decl);
4790               else
4791                 decl = NULL_TREE;
4792             }
4793           else if (scope == current)
4794             {
4795               /* We've been given AGGR SCOPE::ID, when we're already
4796                  inside SCOPE.  Be nice about it.  */
4797               if (pedantic)
4798                 pedwarn ("extra qualification `%T::' on member `%D' ignored",
4799                          scope, id);
4800             }
4801           else
4802             error ("`%T' does not have a class or union named `%D'",
4803                    scope, id);
4804         }
4805     }
4806   
4807   if (!decl)
4808     {
4809       decl = TYPE_MAIN_DECL (xref_tag (tag_kind, id, attributes, !defn_p));
4810       xrefd_p = true;
4811     }
4812
4813   if (!TYPE_BINFO (TREE_TYPE (decl)))
4814     {
4815       error ("`%T' is not a class or union type", decl);
4816       return error_mark_node;
4817     }
4818   
4819   if (defn_p)
4820     {
4821       /* For a definition, we want to enter the containing scope
4822          before looking up any base classes etc. Only do so, if this
4823          is different to the current scope.  */
4824       tree context = CP_DECL_CONTEXT (decl);
4825
4826       *new_type_p = (current != context
4827                      && TREE_CODE (context) != TEMPLATE_TYPE_PARM
4828                      && TREE_CODE (context) != BOUND_TEMPLATE_TEMPLATE_PARM);
4829       if (*new_type_p)
4830         push_scope (context);
4831
4832       if (TREE_CODE (TREE_TYPE (decl)) == RECORD_TYPE)
4833         /* It is valid to define a class with a different class key,
4834            and this changes the default member access.  */
4835         CLASSTYPE_DECLARED_CLASS (TREE_TYPE (decl))
4836           = (tag_kind == class_type);
4837         
4838       if (!xrefd_p && PROCESSING_REAL_TEMPLATE_DECL_P ())
4839         decl = push_template_decl (decl);
4840     }
4841
4842   return decl;
4843 }
4844
4845 #include "gt-cp-decl2.h"