OSDN Git Service

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