OSDN Git Service

2004-08-04 Geoffrey Keating <geoffk@apple.com>
[pf3gnuchains/gcc-fork.git] / gcc / cp / decl2.c
1 /* Process declarations and variables for C++ compiler.
2    Copyright (C) 1988, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3    1999, 2000, 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
4    Hacked by Michael Tiemann (tiemann@cygnus.com)
5
6 This file is part of GCC.
7
8 GCC 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 GCC 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 GCC; 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 "coretypes.h"
34 #include "tm.h"
35 #include "tree.h"
36 #include "rtl.h"
37 #include "expr.h"
38 #include "flags.h"
39 #include "cp-tree.h"
40 #include "decl.h"
41 #include "output.h"
42 #include "except.h"
43 #include "toplev.h"
44 #include "timevar.h"
45 #include "cpplib.h"
46 #include "target.h"
47 #include "c-common.h"
48 #include "tree-mudflap.h"
49 #include "cgraph.h"
50 #include "tree-inline.h"
51
52 extern cpp_reader *parse_in;
53
54 /* This structure contains information about the initializations
55    and/or destructions required for a particular priority level.  */
56 typedef struct priority_info_s {
57   /* Nonzero if there have been any initializations at this priority
58      throughout the translation unit.  */
59   int initializations_p;
60   /* Nonzero if there have been any destructions at this priority
61      throughout the translation unit.  */
62   int destructions_p;
63 } *priority_info;
64
65 static void mark_vtable_entries (tree);
66 static void grok_function_init (tree, tree);
67 static bool maybe_emit_vtables (tree);
68 static tree build_anon_union_vars (tree);
69 static bool acceptable_java_type (tree);
70 static tree start_objects (int, int);
71 static void finish_objects (int, int, tree);
72 static tree start_static_storage_duration_function (unsigned);
73 static void finish_static_storage_duration_function (tree);
74 static priority_info get_priority_info (int);
75 static void do_static_initialization (tree, tree);
76 static void do_static_destruction (tree);
77 static tree start_static_initialization_or_destruction (tree, int);
78 static void finish_static_initialization_or_destruction (tree);
79 static void generate_ctor_or_dtor_function (bool, int, location_t *);
80 static int generate_ctor_and_dtor_functions_for_priority (splay_tree_node,
81                                                           void *);
82 static tree prune_vars_needing_no_initialization (tree *);
83 static void write_out_vars (tree);
84 static void import_export_class (tree);
85 static tree get_guard_bits (tree);
86
87 /* A list of static class variables.  This is needed, because a
88    static class variable can be declared inside the class without
89    an initializer, and then initialized, statically, outside the class.  */
90 static GTY(()) varray_type pending_statics;
91 #define pending_statics_used \
92   (pending_statics ? pending_statics->elements_used : 0)
93
94 /* A list of functions which were declared inline, but which we
95    may need to emit outline anyway.  */
96 static GTY(()) varray_type deferred_fns;
97 #define deferred_fns_used \
98   (deferred_fns ? deferred_fns->elements_used : 0)
99
100 /* Flag used when debugging spew.c */
101
102 extern int spew_debug;
103
104 /* Nonzero if we're done parsing and into end-of-file activities.  */
105
106 int at_eof;
107
108 /* Functions called along with real static constructors and destructors.  */
109
110 tree static_ctors;
111 tree static_dtors;
112
113 \f
114 /* Incorporate `const' and `volatile' qualifiers for member functions.
115    FUNCTION is a TYPE_DECL or a FUNCTION_DECL.
116    QUALS is a list of qualifiers.  Returns any explicit
117    top-level qualifiers of the method's this pointer, anything other than
118    TYPE_UNQUALIFIED will be an extension.  */
119
120 int
121 grok_method_quals (tree ctype, tree function, cp_cv_quals quals)
122 {
123   tree fntype = TREE_TYPE (function);
124   tree raises = TYPE_RAISES_EXCEPTIONS (fntype);
125   int type_quals = TYPE_UNQUALIFIED;
126   int this_quals = TYPE_UNQUALIFIED;
127
128   type_quals = quals & ~TYPE_QUAL_RESTRICT;
129   this_quals = quals & TYPE_QUAL_RESTRICT;
130
131   ctype = cp_build_qualified_type (ctype, type_quals);
132   fntype = build_method_type_directly (ctype, TREE_TYPE (fntype),
133                                        (TREE_CODE (fntype) == METHOD_TYPE
134                                         ? TREE_CHAIN (TYPE_ARG_TYPES (fntype))
135                                         : TYPE_ARG_TYPES (fntype)));
136   if (raises)
137     fntype = build_exception_variant (fntype, raises);
138
139   TREE_TYPE (function) = fntype;
140   return this_quals;
141 }
142
143 /* Build a PARM_DECL with NAME and TYPE, and set DECL_ARG_TYPE
144    appropriately.  */
145
146 tree
147 cp_build_parm_decl (tree name, tree type)
148 {
149   tree parm = build_decl (PARM_DECL, name, type);
150   /* DECL_ARG_TYPE is only used by the back end and the back end never
151      sees templates.  */
152   if (!processing_template_decl)
153     DECL_ARG_TYPE (parm) = type_passed_as (type);
154   return parm;
155 }
156
157 /* Returns a PARM_DECL for a parameter of the indicated TYPE, with the
158    indicated NAME.  */
159
160 tree
161 build_artificial_parm (tree name, tree type)
162 {
163   tree parm = cp_build_parm_decl (name, type);
164   DECL_ARTIFICIAL (parm) = 1;
165   /* All our artificial parms are implicitly `const'; they cannot be
166      assigned to.  */
167   TREE_READONLY (parm) = 1;
168   return parm;
169 }
170
171 /* Constructors for types with virtual baseclasses need an "in-charge" flag
172    saying whether this constructor is responsible for initialization of
173    virtual baseclasses or not.  All destructors also need this "in-charge"
174    flag, which additionally determines whether or not the destructor should
175    free the memory for the object.
176
177    This function adds the "in-charge" flag to member function FN if
178    appropriate.  It is called from grokclassfn and tsubst.
179    FN must be either a constructor or destructor.
180
181    The in-charge flag follows the 'this' parameter, and is followed by the
182    VTT parm (if any), then the user-written parms.  */
183
184 void
185 maybe_retrofit_in_chrg (tree fn)
186 {
187   tree basetype, arg_types, parms, parm, fntype;
188
189   /* If we've already add the in-charge parameter don't do it again.  */
190   if (DECL_HAS_IN_CHARGE_PARM_P (fn))
191     return;
192
193   /* When processing templates we can't know, in general, whether or
194      not we're going to have virtual baseclasses.  */
195   if (processing_template_decl)
196     return;
197
198   /* We don't need an in-charge parameter for constructors that don't
199      have virtual bases.  */
200   if (DECL_CONSTRUCTOR_P (fn)
201       && !TYPE_USES_VIRTUAL_BASECLASSES (DECL_CONTEXT (fn)))
202     return;
203
204   arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
205   basetype = TREE_TYPE (TREE_VALUE (arg_types));
206   arg_types = TREE_CHAIN (arg_types);
207
208   parms = TREE_CHAIN (DECL_ARGUMENTS (fn));
209
210   /* If this is a subobject constructor or destructor, our caller will
211      pass us a pointer to our VTT.  */
212   if (TYPE_USES_VIRTUAL_BASECLASSES (DECL_CONTEXT (fn)))
213     {
214       parm = build_artificial_parm (vtt_parm_identifier, vtt_parm_type);
215
216       /* First add it to DECL_ARGUMENTS between 'this' and the real args...  */
217       TREE_CHAIN (parm) = parms;
218       parms = parm;
219
220       /* ...and then to TYPE_ARG_TYPES.  */
221       arg_types = hash_tree_chain (vtt_parm_type, arg_types);
222
223       DECL_HAS_VTT_PARM_P (fn) = 1;
224     }
225
226   /* Then add the in-charge parm (before the VTT parm).  */
227   parm = build_artificial_parm (in_charge_identifier, integer_type_node);
228   TREE_CHAIN (parm) = parms;
229   parms = parm;
230   arg_types = hash_tree_chain (integer_type_node, arg_types);
231
232   /* Insert our new parameter(s) into the list.  */
233   TREE_CHAIN (DECL_ARGUMENTS (fn)) = parms;
234
235   /* And rebuild the function type.  */
236   fntype = build_method_type_directly (basetype, TREE_TYPE (TREE_TYPE (fn)),
237                                        arg_types);
238   if (TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn)))
239     fntype = build_exception_variant (fntype,
240                                       TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn)));
241   TREE_TYPE (fn) = fntype;
242
243   /* Now we've got the in-charge parameter.  */
244   DECL_HAS_IN_CHARGE_PARM_P (fn) = 1;
245 }
246
247 /* Classes overload their constituent function names automatically.
248    When a function name is declared in a record structure,
249    its name is changed to it overloaded name.  Since names for
250    constructors and destructors can conflict, we place a leading
251    '$' for destructors.
252
253    CNAME is the name of the class we are grokking for.
254
255    FUNCTION is a FUNCTION_DECL.  It was created by `grokdeclarator'.
256
257    FLAGS contains bits saying what's special about today's
258    arguments.  1 == DESTRUCTOR.  2 == OPERATOR.
259
260    If FUNCTION is a destructor, then we must add the `auto-delete' field
261    as a second parameter.  There is some hair associated with the fact
262    that we must "declare" this variable in the manner consistent with the
263    way the rest of the arguments were declared.
264
265    QUALS are the qualifiers for the this pointer.  */
266
267 void
268 grokclassfn (tree ctype, tree function, enum overload_flags flags, 
269              cp_cv_quals quals)
270 {
271   tree fn_name = DECL_NAME (function);
272   cp_cv_quals this_quals = TYPE_UNQUALIFIED;
273
274   /* Even within an `extern "C"' block, members get C++ linkage.  See
275      [dcl.link] for details.  */
276   SET_DECL_LANGUAGE (function, lang_cplusplus);
277
278   if (fn_name == NULL_TREE)
279     {
280       error ("name missing for member function");
281       fn_name = get_identifier ("<anonymous>");
282       DECL_NAME (function) = fn_name;
283     }
284
285   if (quals)
286     this_quals = grok_method_quals (ctype, function, quals);
287
288   if (TREE_CODE (TREE_TYPE (function)) == METHOD_TYPE)
289     {
290       /* Must add the class instance variable up front.  */
291       /* Right now we just make this a pointer.  But later
292          we may wish to make it special.  */
293       tree type = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (function)));
294       tree qual_type;
295       tree parm;
296
297       /* The `this' parameter is implicitly `const'; it cannot be
298          assigned to.  */
299       this_quals |= TYPE_QUAL_CONST;
300       qual_type = cp_build_qualified_type (type, this_quals);
301       parm = build_artificial_parm (this_identifier, qual_type);
302       c_apply_type_quals_to_decl (this_quals, parm);
303       TREE_CHAIN (parm) = DECL_ARGUMENTS (function);
304       DECL_ARGUMENTS (function) = parm;
305     }
306
307   DECL_CONTEXT (function) = ctype;
308
309   if (flags == DTOR_FLAG)
310     DECL_DESTRUCTOR_P (function) = 1;
311
312   if (flags == DTOR_FLAG || DECL_CONSTRUCTOR_P (function))
313     maybe_retrofit_in_chrg (function);
314 }
315
316 /* Create an ARRAY_REF, checking for the user doing things backwards
317    along the way.  */
318
319 tree
320 grok_array_decl (tree array_expr, tree index_exp)
321 {
322   tree type;
323   tree expr;
324   tree orig_array_expr = array_expr;
325   tree orig_index_exp = index_exp;
326
327   if (error_operand_p (array_expr) || error_operand_p (index_exp))
328     return error_mark_node;
329
330   if (processing_template_decl)
331     {
332       if (type_dependent_expression_p (array_expr)
333           || type_dependent_expression_p (index_exp))
334         return build_min_nt (ARRAY_REF, array_expr, index_exp,
335                              NULL_TREE, NULL_TREE);
336       array_expr = build_non_dependent_expr (array_expr);
337       index_exp = build_non_dependent_expr (index_exp);
338     }
339
340   type = TREE_TYPE (array_expr);
341   my_friendly_assert (type, 20030626);
342   type = non_reference (type);
343
344   /* If they have an `operator[]', use that.  */
345   if (IS_AGGR_TYPE (type) || IS_AGGR_TYPE (TREE_TYPE (index_exp)))
346     expr = build_new_op (ARRAY_REF, LOOKUP_NORMAL,
347                          array_expr, index_exp, NULL_TREE,
348                          /*overloaded_p=*/NULL);
349   else
350     {
351       tree p1, p2, i1, i2;
352
353       /* Otherwise, create an ARRAY_REF for a pointer or array type.
354          It is a little-known fact that, if `a' is an array and `i' is
355          an int, you can write `i[a]', which means the same thing as
356          `a[i]'.  */
357       if (TREE_CODE (type) == ARRAY_TYPE)
358         p1 = array_expr;
359       else
360         p1 = build_expr_type_conversion (WANT_POINTER, array_expr, false);
361
362       if (TREE_CODE (TREE_TYPE (index_exp)) == ARRAY_TYPE)
363         p2 = index_exp;
364       else
365         p2 = build_expr_type_conversion (WANT_POINTER, index_exp, false);
366
367       i1 = build_expr_type_conversion (WANT_INT | WANT_ENUM, array_expr, 
368                                        false);
369       i2 = build_expr_type_conversion (WANT_INT | WANT_ENUM, index_exp, 
370                                        false);
371
372       if ((p1 && i2) && (i1 && p2))
373         error ("ambiguous conversion for array subscript");
374
375       if (p1 && i2)
376         array_expr = p1, index_exp = i2;
377       else if (i1 && p2)
378         array_expr = p2, index_exp = i1;
379       else
380         {
381           error ("invalid types `%T[%T]' for array subscript",
382                     type, TREE_TYPE (index_exp));
383           return error_mark_node;
384         }
385
386       if (array_expr == error_mark_node || index_exp == error_mark_node)
387         error ("ambiguous conversion for array subscript");
388
389       expr = build_array_ref (array_expr, index_exp);
390     }
391   if (processing_template_decl && expr != error_mark_node)
392     return build_min_non_dep (ARRAY_REF, expr, orig_array_expr, orig_index_exp,
393                               NULL_TREE, NULL_TREE);
394   return expr;
395 }
396
397 /* Given the cast expression EXP, checking out its validity.   Either return
398    an error_mark_node if there was an unavoidable error, return a cast to
399    void for trying to delete a pointer w/ the value 0, or return the
400    call to delete.  If DOING_VEC is true, we handle things differently
401    for doing an array delete.
402    Implements ARM $5.3.4.  This is called from the parser.  */
403
404 tree
405 delete_sanity (tree exp, tree size, bool doing_vec, int use_global_delete)
406 {
407   tree t, type;
408
409   if (exp == error_mark_node)
410     return exp;
411
412   if (processing_template_decl)
413     {
414       t = build_min (DELETE_EXPR, void_type_node, exp, size);
415       DELETE_EXPR_USE_GLOBAL (t) = use_global_delete;
416       DELETE_EXPR_USE_VEC (t) = doing_vec;
417       TREE_SIDE_EFFECTS (t) = 1;
418       return t;
419     }
420
421   exp = convert_from_reference (exp);
422
423   /* An array can't have been allocated by new, so complain.  */
424   if (TREE_CODE (exp) == VAR_DECL
425       && TREE_CODE (TREE_TYPE (exp)) == ARRAY_TYPE)
426     warning ("deleting array `%#D'", exp);
427
428   t = build_expr_type_conversion (WANT_POINTER, exp, true);
429
430   if (t == NULL_TREE || t == error_mark_node)
431     {
432       error ("type `%#T' argument given to `delete', expected pointer",
433                 TREE_TYPE (exp));
434       return error_mark_node;
435     }
436
437   type = TREE_TYPE (t);
438
439   /* As of Valley Forge, you can delete a pointer to const.  */
440
441   /* You can't delete functions.  */
442   if (TREE_CODE (TREE_TYPE (type)) == FUNCTION_TYPE)
443     {
444       error ("cannot delete a function.  Only pointer-to-objects are valid arguments to `delete'");
445       return error_mark_node;
446     }
447
448   /* Deleting ptr to void is undefined behavior [expr.delete/3].  */
449   if (TREE_CODE (TREE_TYPE (type)) == VOID_TYPE)
450     {
451       warning ("deleting `%T' is undefined", type);
452       doing_vec = 0;
453     }
454
455   /* Deleting a pointer with the value zero is valid and has no effect.  */
456   if (integer_zerop (t))
457     return build1 (NOP_EXPR, void_type_node, t);
458
459   if (doing_vec)
460     return build_vec_delete (t, /*maxindex=*/NULL_TREE, 
461                              sfk_deleting_destructor,
462                              use_global_delete);
463   else
464     return build_delete (type, t, sfk_deleting_destructor,
465                          LOOKUP_NORMAL, use_global_delete);
466 }
467
468 /* Report an error if the indicated template declaration is not the
469    sort of thing that should be a member template.  */
470
471 void
472 check_member_template (tree tmpl)
473 {
474   tree decl;
475
476   my_friendly_assert (TREE_CODE (tmpl) == TEMPLATE_DECL, 0);
477   decl = DECL_TEMPLATE_RESULT (tmpl);
478
479   if (TREE_CODE (decl) == FUNCTION_DECL
480       || (TREE_CODE (decl) == TYPE_DECL
481           && IS_AGGR_TYPE (TREE_TYPE (decl))))
482     {
483       if (current_function_decl)
484         /* 14.5.2.2 [temp.mem]
485            
486            A local class shall not have member templates.  */
487         error ("invalid declaration of member template `%#D' in local class",
488                   decl);
489       
490       if (TREE_CODE (decl) == FUNCTION_DECL && DECL_VIRTUAL_P (decl))
491         {
492           /* 14.5.2.3 [temp.mem]
493
494              A member function template shall not be virtual.  */
495           error 
496             ("invalid use of `virtual' in template declaration of `%#D'",
497              decl);
498           DECL_VIRTUAL_P (decl) = 0;
499         }
500
501       /* The debug-information generating code doesn't know what to do
502          with member templates.  */ 
503       DECL_IGNORED_P (tmpl) = 1;
504     } 
505   else
506     error ("template declaration of `%#D'", decl);
507 }
508
509 /* Return true iff TYPE is a valid Java parameter or return type.  */
510
511 static bool
512 acceptable_java_type (tree type)
513 {
514   if (TREE_CODE (type) == VOID_TYPE || TYPE_FOR_JAVA (type))
515     return 1;
516   if (TREE_CODE (type) == POINTER_TYPE || TREE_CODE (type) == REFERENCE_TYPE)
517     {
518       type = TREE_TYPE (type);
519       if (TREE_CODE (type) == RECORD_TYPE)
520         {
521           tree args;  int i;
522           if (! TYPE_FOR_JAVA (type))
523             return false;
524           if (! CLASSTYPE_TEMPLATE_INFO (type))
525             return true;
526           args = CLASSTYPE_TI_ARGS (type);
527           i = TREE_VEC_LENGTH (args);
528           while (--i >= 0)
529             {
530               type = TREE_VEC_ELT (args, i);
531               if (TREE_CODE (type) == POINTER_TYPE)
532                 type = TREE_TYPE (type);
533               if (! TYPE_FOR_JAVA (type))
534                 return false;
535             }
536           return true;
537         }
538     }
539   return false;
540 }
541
542 /* For a METHOD in a Java class CTYPE, return true if
543    the parameter and return types are valid Java types.
544    Otherwise, print appropriate error messages, and return false.  */
545
546 bool
547 check_java_method (tree method)
548 {
549   bool jerr = false;
550   tree arg_types = TYPE_ARG_TYPES (TREE_TYPE (method));
551   tree ret_type = TREE_TYPE (TREE_TYPE (method));
552
553   if (!acceptable_java_type (ret_type))
554     {
555       error ("Java method '%D' has non-Java return type `%T'",
556                 method, ret_type);
557       jerr = true;
558     }
559
560   arg_types = TREE_CHAIN (arg_types);
561   if (DECL_HAS_IN_CHARGE_PARM_P (method))
562     arg_types = TREE_CHAIN (arg_types);
563   if (DECL_HAS_VTT_PARM_P (method))
564     arg_types = TREE_CHAIN (arg_types);
565   
566   for (; arg_types != NULL_TREE; arg_types = TREE_CHAIN (arg_types))
567     {
568       tree type = TREE_VALUE (arg_types);
569       if (!acceptable_java_type (type))
570         {
571           error ("Java method '%D' has non-Java parameter type `%T'",
572                     method, type);
573           jerr = true;
574         }
575     }
576   return !jerr;
577 }
578
579 /* Sanity check: report error if this function FUNCTION is not
580    really a member of the class (CTYPE) it is supposed to belong to.
581    TEMPLATE_PARMS is used to specifiy the template parameters of a member
582    template passed as FUNCTION_DECL. If the member template is passed as a 
583    TEMPLATE_DECL, it can be NULL since the parameters can be extracted
584    from the declaration. If the function is not a function template, it
585    must be NULL.
586    It returns the original declaration for the function, or NULL_TREE
587    if no declaration was found (and an error was emitted).  */
588
589 tree
590 check_classfn (tree ctype, tree function, tree template_parms)
591 {
592   int ix;
593   bool is_template;
594   
595   if (DECL_USE_TEMPLATE (function)
596       && !(TREE_CODE (function) == TEMPLATE_DECL
597            && DECL_TEMPLATE_SPECIALIZATION (function))
598       && is_member_template (DECL_TI_TEMPLATE (function)))
599     /* Since this is a specialization of a member template,
600        we're not going to find the declaration in the class.
601        For example, in:
602        
603          struct S { template <typename T> void f(T); };
604          template <> void S::f(int);
605        
606        we're not going to find `S::f(int)', but there's no
607        reason we should, either.  We let our callers know we didn't
608        find the method, but we don't complain.  */
609     return NULL_TREE;
610
611   /* Basic sanity check: for a template function, the template parameters
612      either were not passed, or they are the same of DECL_TEMPLATE_PARMS.  */
613   if (TREE_CODE (function) == TEMPLATE_DECL)
614     {
615       my_friendly_assert (!template_parms 
616                           || comp_template_parms 
617                               (template_parms, 
618                                DECL_TEMPLATE_PARMS (function)),
619                           20040303);
620       template_parms = DECL_TEMPLATE_PARMS (function);
621     }
622
623   /* OK, is this a definition of a member template?  */
624   is_template = (template_parms != NULL_TREE);
625
626   ix = lookup_fnfields_1 (complete_type (ctype),
627                           DECL_CONSTRUCTOR_P (function) ? ctor_identifier :
628                           DECL_DESTRUCTOR_P (function) ? dtor_identifier :
629                           DECL_NAME (function));
630
631   if (ix >= 0)
632     {
633       VEC(tree) *methods = CLASSTYPE_METHOD_VEC (ctype);
634       tree fndecls, fndecl = 0;
635       bool is_conv_op;
636       bool pop_p;
637       const char *format = NULL;
638       
639       pop_p = push_scope (ctype);
640       for (fndecls = VEC_index (tree, methods, ix);
641            fndecls; fndecls = OVL_NEXT (fndecls))
642         {
643           tree p1, p2;
644           
645           fndecl = OVL_CURRENT (fndecls);
646           p1 = TYPE_ARG_TYPES (TREE_TYPE (function));
647           p2 = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
648
649           /* We cannot simply call decls_match because this doesn't
650              work for static member functions that are pretending to
651              be methods, and because the name may have been changed by
652              asm("new_name").  */ 
653               
654            /* Get rid of the this parameter on functions that become
655               static.  */
656           if (DECL_STATIC_FUNCTION_P (fndecl)
657               && TREE_CODE (TREE_TYPE (function)) == METHOD_TYPE)
658             p1 = TREE_CHAIN (p1);
659
660           /* A member template definition only matches a member template
661              declaration.  */
662           if (is_template != (TREE_CODE (fndecl) == TEMPLATE_DECL))
663             continue;
664               
665           if (same_type_p (TREE_TYPE (TREE_TYPE (function)),
666                            TREE_TYPE (TREE_TYPE (fndecl)))
667               && compparms (p1, p2)
668               && (!is_template
669                   || comp_template_parms (template_parms, 
670                                           DECL_TEMPLATE_PARMS (fndecl)))
671               && (DECL_TEMPLATE_SPECIALIZATION (function)
672                   == DECL_TEMPLATE_SPECIALIZATION (fndecl))
673               && (!DECL_TEMPLATE_SPECIALIZATION (function)
674                   || (DECL_TI_TEMPLATE (function) 
675                       == DECL_TI_TEMPLATE (fndecl))))
676             break;
677         }
678       if (pop_p)
679         pop_scope (ctype);
680       if (fndecls)
681         return OVL_CURRENT (fndecls);
682       error ("prototype for `%#D' does not match any in class `%T'",
683              function, ctype);
684       is_conv_op = DECL_CONV_FN_P (fndecl);
685
686       if (is_conv_op)
687         ix = CLASSTYPE_FIRST_CONVERSION_SLOT;
688       fndecls = VEC_index (tree, methods, ix);
689       while (fndecls)
690         {
691           fndecl = OVL_CURRENT (fndecls);
692           fndecls = OVL_NEXT (fndecls);
693
694           if (!fndecls && is_conv_op)
695             {
696               if (VEC_length (tree, methods) > (size_t) ++ix)
697                 {
698                   fndecls = VEC_index (tree, methods, ix);
699                   if (!DECL_CONV_FN_P (OVL_CURRENT (fndecls)))
700                     {
701                       fndecls = NULL_TREE;
702                       is_conv_op = false;
703                     }
704                 }
705               else
706                 is_conv_op = false;
707             }
708           if (format)
709             format = "                %#D";
710           else if (fndecls)
711             format = "candidates are: %#D";
712           else
713             format = "candidate is: %#D";
714           cp_error_at (format, fndecl);
715         }
716     }
717   else if (!COMPLETE_TYPE_P (ctype))
718     cxx_incomplete_type_error (function, ctype);
719   else
720     error ("no `%#D' member function declared in class `%T'",
721            function, ctype);
722
723   /* If we did not find the method in the class, add it to avoid
724      spurious errors (unless the CTYPE is not yet defined, in which
725      case we'll only confuse ourselves when the function is declared
726      properly within the class.  */
727   if (COMPLETE_TYPE_P (ctype))
728     add_method (ctype, function);
729   return NULL_TREE;
730 }
731
732 /* DECL is a function with vague linkage.  Remember it so that at the
733    end of the translation unit we can decide whether or not to emit
734    it.  */
735
736 void
737 note_vague_linkage_fn (tree decl)
738 {
739   if (!DECL_DEFERRED_FN (decl))
740     {
741       DECL_DEFERRED_FN (decl) = 1;
742       DECL_DEFER_OUTPUT (decl) = 1;
743       if (!deferred_fns)
744         VARRAY_TREE_INIT (deferred_fns, 32, "deferred_fns");
745       VARRAY_PUSH_TREE (deferred_fns, decl);
746     }
747 }
748
749 /* Like note_vague_linkage_fn but for variables.  */
750
751 static void
752 note_vague_linkage_var (tree var)
753 {
754   if (!pending_statics)
755     VARRAY_TREE_INIT (pending_statics, 32, "pending_statics");
756   VARRAY_PUSH_TREE (pending_statics, var);
757 }
758
759 /* We have just processed the DECL, which is a static data member.
760    Its initializer, if present, is INIT.  The ASMSPEC_TREE, if
761    present, is the assembly-language name for the data member.
762    FLAGS is as for cp_finish_decl.  */
763
764 void
765 finish_static_data_member_decl (tree decl, tree init, tree asmspec_tree,
766                                 int flags)
767 {
768   my_friendly_assert (TREE_PUBLIC (decl), 0);
769
770   DECL_CONTEXT (decl) = current_class_type;
771
772   /* We cannot call pushdecl here, because that would fill in the
773      TREE_CHAIN of our decl.  Instead, we modify cp_finish_decl to do
774      the right thing, namely, to put this decl out straight away.  */
775   /* current_class_type can be NULL_TREE in case of error.  */
776   if (!asmspec_tree && current_class_type)
777     DECL_INITIAL (decl) = error_mark_node;
778
779   if (! processing_template_decl)
780     note_vague_linkage_var (decl);
781
782   if (LOCAL_CLASS_P (current_class_type))
783     pedwarn ("local class `%#T' shall not have static data member `%#D'",
784              current_class_type, decl);
785
786   /* Static consts need not be initialized in the class definition.  */
787   if (init != NULL_TREE && TYPE_NEEDS_CONSTRUCTING (TREE_TYPE (decl)))
788     {
789       static int explained = 0;
790           
791       error ("initializer invalid for static member with constructor");
792       if (!explained)
793         {
794           error ("(an out of class initialization is required)");
795           explained = 1;
796         }
797       init = NULL_TREE;
798     }
799   /* Force the compiler to know when an uninitialized static const
800      member is being used.  */
801   if (CP_TYPE_CONST_P (TREE_TYPE (decl)) && init == 0)
802     TREE_USED (decl) = 1;
803   DECL_INITIAL (decl) = init;
804   DECL_IN_AGGR_P (decl) = 1;
805
806   cp_finish_decl (decl, init, asmspec_tree, flags);
807 }
808
809 /* Process the specs, declarator (NULL if omitted) and width (NULL if omitted)
810    of a structure component, returning a _DECL node.
811    QUALS is a list of type qualifiers for this decl (such as for declaring
812    const member functions).
813
814    This is done during the parsing of the struct declaration.
815    The _DECL nodes are chained together and the lot of them
816    are ultimately passed to `build_struct' to make the RECORD_TYPE node.
817
818    If class A defines that certain functions in class B are friends, then
819    the way I have set things up, it is B who is interested in permission
820    granted by A.  However, it is in A's context that these declarations
821    are parsed.  By returning a void_type_node, class A does not attempt
822    to incorporate the declarations of the friends within its structure.
823
824    DO NOT MAKE ANY CHANGES TO THIS CODE WITHOUT MAKING CORRESPONDING
825    CHANGES TO CODE IN `start_method'.  */
826
827 tree
828 grokfield (const cp_declarator *declarator, 
829            cp_decl_specifier_seq *declspecs, 
830            tree init, tree asmspec_tree,
831            tree attrlist)
832 {
833   tree value;
834   const char *asmspec = 0;
835   int flags = LOOKUP_ONLYCONVERTING;
836
837   if (!declspecs->any_specifiers_p
838       && declarator->kind == cdk_id
839       && TREE_CODE (declarator->u.id.name) == SCOPE_REF
840       && (TREE_CODE (TREE_OPERAND (declarator->u.id.name, 1)) 
841           == IDENTIFIER_NODE))
842     /* Access declaration */
843     return do_class_using_decl (declarator->u.id.name);
844
845   if (init
846       && TREE_CODE (init) == TREE_LIST
847       && TREE_VALUE (init) == error_mark_node
848       && TREE_CHAIN (init) == NULL_TREE)
849     init = NULL_TREE;
850
851   value = grokdeclarator (declarator, declspecs, FIELD, init != 0, &attrlist);
852   if (! value || error_operand_p (value))
853     /* friend or constructor went bad.  */
854     return error_mark_node;
855
856   if (TREE_CODE (value) == TYPE_DECL && init)
857     {
858       error ("typedef `%D' is initialized (use __typeof__ instead)", value);
859       init = NULL_TREE;
860     }
861
862   /* Pass friendly classes back.  */
863   if (value == void_type_node)
864     return value;
865
866   /* Pass friend decls back.  */
867   if ((TREE_CODE (value) == FUNCTION_DECL
868        || TREE_CODE (value) == TEMPLATE_DECL)
869       && DECL_CONTEXT (value) != current_class_type)
870     return value;
871
872   if (DECL_NAME (value) != NULL_TREE
873       && IDENTIFIER_POINTER (DECL_NAME (value))[0] == '_'
874       && ! strcmp (IDENTIFIER_POINTER (DECL_NAME (value)), "_vptr"))
875     error ("member `%D' conflicts with virtual function table field name",
876               value);
877
878   /* Stash away type declarations.  */
879   if (TREE_CODE (value) == TYPE_DECL)
880     {
881       DECL_NONLOCAL (value) = 1;
882       DECL_CONTEXT (value) = current_class_type;
883
884       if (processing_template_decl)
885         value = push_template_decl (value);
886
887       return value;
888     }
889
890   if (DECL_IN_AGGR_P (value))
891     {
892       error ("`%D' is already defined in `%T'", value,
893                 DECL_CONTEXT (value));
894       return void_type_node;
895     }
896
897   if (asmspec_tree)
898     asmspec = TREE_STRING_POINTER (asmspec_tree);
899
900   if (init)
901     {
902       if (TREE_CODE (value) == FUNCTION_DECL)
903         {
904           grok_function_init (value, init);
905           init = NULL_TREE;
906         }
907       else if (pedantic && TREE_CODE (value) != VAR_DECL)
908         /* Already complained in grokdeclarator.  */
909         init = NULL_TREE;
910       else
911         {
912           /* We allow initializers to become parameters to base
913              initializers.  */
914           if (TREE_CODE (init) == TREE_LIST)
915             {
916               if (TREE_CHAIN (init) == NULL_TREE)
917                 init = TREE_VALUE (init);
918               else
919                 init = digest_init (TREE_TYPE (value), init, (tree *)0);
920             }
921
922           if (!processing_template_decl)
923             {
924               if (TREE_CODE (init) == CONST_DECL)
925                 init = DECL_INITIAL (init);
926               else if (TREE_READONLY_DECL_P (init))
927                 init = decl_constant_value (init);
928               else if (TREE_CODE (init) == CONSTRUCTOR)
929                 init = digest_init (TREE_TYPE (value), init, (tree *)0);
930               if (init != error_mark_node && ! TREE_CONSTANT (init))
931                 {
932                   /* We can allow references to things that are effectively
933                      static, since references are initialized with the
934                      address.  */
935                   if (TREE_CODE (TREE_TYPE (value)) != REFERENCE_TYPE
936                       || (TREE_STATIC (init) == 0
937                           && (!DECL_P (init) || DECL_EXTERNAL (init) == 0)))
938                     {
939                       error ("field initializer is not constant");
940                       init = error_mark_node;
941                     }
942                 }
943             }
944         }
945     }
946
947   if (processing_template_decl
948       && (TREE_CODE (value) == VAR_DECL || TREE_CODE (value) == FUNCTION_DECL))
949     {
950       value = push_template_decl (value);
951       if (error_operand_p (value))
952         return error_mark_node;
953     }
954
955   if (attrlist)
956     cplus_decl_attributes (&value, attrlist, 0);
957
958   if (TREE_CODE (value) == VAR_DECL)
959     {
960       finish_static_data_member_decl (value, init, asmspec_tree, 
961                                       flags);
962       return value;
963     }
964   if (TREE_CODE (value) == FIELD_DECL)
965     {
966       if (asmspec)
967         error ("`asm' specifiers are not permitted on non-static data members");
968       if (DECL_INITIAL (value) == error_mark_node)
969         init = error_mark_node;
970       cp_finish_decl (value, init, NULL_TREE, flags);
971       DECL_INITIAL (value) = init;
972       DECL_IN_AGGR_P (value) = 1;
973       return value;
974     }
975   if (TREE_CODE (value) == FUNCTION_DECL)
976     {
977       if (asmspec)
978         set_user_assembler_name (value, asmspec);
979       if (!DECL_FRIEND_P (value))
980         grok_special_member_properties (value);
981       
982       cp_finish_decl (value, init, asmspec_tree, flags);
983
984       /* Pass friends back this way.  */
985       if (DECL_FRIEND_P (value))
986         return void_type_node;
987
988       DECL_IN_AGGR_P (value) = 1;
989       return value;
990     }
991   abort ();
992   /* NOTREACHED */
993   return NULL_TREE;
994 }
995
996 /* Like `grokfield', but for bitfields.
997    WIDTH is non-NULL for bit fields only, and is an INTEGER_CST node.  */
998
999 tree
1000 grokbitfield (const cp_declarator *declarator, 
1001               cp_decl_specifier_seq *declspecs, tree width)
1002 {
1003   tree value = grokdeclarator (declarator, declspecs, BITFIELD, 0, NULL);
1004
1005   if (! value) return NULL_TREE; /* friends went bad.  */
1006
1007   /* Pass friendly classes back.  */
1008   if (TREE_CODE (value) == VOID_TYPE)
1009     return void_type_node;
1010
1011   if (TREE_CODE (value) == TYPE_DECL)
1012     {
1013       error ("cannot declare `%D' to be a bit-field type", value);
1014       return NULL_TREE;
1015     }
1016
1017   /* Usually, finish_struct_1 catches bitfields with invalid types.
1018      But, in the case of bitfields with function type, we confuse
1019      ourselves into thinking they are member functions, so we must
1020      check here.  */
1021   if (TREE_CODE (value) == FUNCTION_DECL)
1022     {
1023       error ("cannot declare bit-field `%D' with function type",
1024              DECL_NAME (value));
1025       return NULL_TREE;
1026     }
1027
1028   if (DECL_IN_AGGR_P (value))
1029     {
1030       error ("`%D' is already defined in the class %T", value,
1031                   DECL_CONTEXT (value));
1032       return void_type_node;
1033     }
1034
1035   if (TREE_STATIC (value))
1036     {
1037       error ("static member `%D' cannot be a bit-field", value);
1038       return NULL_TREE;
1039     }
1040   cp_finish_decl (value, NULL_TREE, NULL_TREE, 0);
1041
1042   if (width != error_mark_node)
1043     {
1044       constant_expression_warning (width);
1045       DECL_INITIAL (value) = width;
1046       SET_DECL_C_BIT_FIELD (value);
1047     }
1048
1049   DECL_IN_AGGR_P (value) = 1;
1050   return value;
1051 }
1052
1053 /* When a function is declared with an initializer,
1054    do the right thing.  Currently, there are two possibilities:
1055
1056    class B
1057    {
1058     public:
1059      // initialization possibility #1.
1060      virtual void f () = 0;
1061      int g ();
1062    };
1063    
1064    class D1 : B
1065    {
1066     public:
1067      int d1;
1068      // error, no f ();
1069    };
1070    
1071    class D2 : B
1072    {
1073     public:
1074      int d2;
1075      void f ();
1076    };
1077    
1078    class D3 : B
1079    {
1080     public:
1081      int d3;
1082      // initialization possibility #2
1083      void f () = B::f;
1084    };
1085
1086 */
1087
1088 static void
1089 grok_function_init (tree decl, tree init)
1090 {
1091   /* An initializer for a function tells how this function should
1092      be inherited.  */
1093   tree type = TREE_TYPE (decl);
1094
1095   if (TREE_CODE (type) == FUNCTION_TYPE)
1096     error ("initializer specified for non-member function `%D'", decl);
1097   else if (integer_zerop (init))
1098     DECL_PURE_VIRTUAL_P (decl) = 1;
1099   else
1100     error ("invalid initializer for virtual method `%D'", decl);
1101 }
1102 \f
1103 void
1104 cplus_decl_attributes (tree *decl, tree attributes, int flags)
1105 {
1106   if (*decl == NULL_TREE || *decl == void_type_node)
1107     return;
1108
1109   if (TREE_CODE (*decl) == TEMPLATE_DECL)
1110     decl = &DECL_TEMPLATE_RESULT (*decl);
1111
1112   decl_attributes (decl, attributes, flags);
1113
1114   if (TREE_CODE (*decl) == TYPE_DECL)
1115     SET_IDENTIFIER_TYPE_VALUE (DECL_NAME (*decl), TREE_TYPE (*decl));
1116 }
1117 \f
1118 /* Walks through the namespace- or function-scope anonymous union OBJECT,
1119    building appropriate ALIAS_DECLs.  Returns one of the fields for use in
1120    the mangled name.  */
1121
1122 static tree
1123 build_anon_union_vars (tree object)
1124 {
1125   tree type = TREE_TYPE (object);
1126   tree main_decl = NULL_TREE;
1127   tree field;
1128
1129   /* Rather than write the code to handle the non-union case,
1130      just give an error.  */
1131   if (TREE_CODE (type) != UNION_TYPE)
1132     error ("anonymous struct not inside named type");
1133
1134   for (field = TYPE_FIELDS (type); 
1135        field != NULL_TREE; 
1136        field = TREE_CHAIN (field))
1137     {
1138       tree decl;
1139       tree ref;
1140
1141       if (DECL_ARTIFICIAL (field))
1142         continue;
1143       if (TREE_CODE (field) != FIELD_DECL)
1144         {
1145           cp_pedwarn_at ("\
1146 `%#D' invalid; an anonymous union can only have non-static data members",
1147                          field);
1148           continue;
1149         }
1150
1151       if (TREE_PRIVATE (field))
1152         cp_pedwarn_at ("private member `%#D' in anonymous union", field);
1153       else if (TREE_PROTECTED (field))
1154         cp_pedwarn_at ("protected member `%#D' in anonymous union", field);
1155
1156       if (processing_template_decl)
1157         ref = build_min_nt (COMPONENT_REF, object,
1158                             DECL_NAME (field), NULL_TREE);
1159       else
1160         ref = build_class_member_access_expr (object, field, NULL_TREE,
1161                                               false);
1162
1163       if (DECL_NAME (field))
1164         {
1165           decl = build_decl (ALIAS_DECL, DECL_NAME (field), TREE_TYPE (field));
1166           DECL_INITIAL (decl) = ref;        
1167           TREE_PUBLIC (decl) = 0;
1168           TREE_STATIC (decl) = 0;
1169           DECL_EXTERNAL (decl) = 1;
1170           decl = pushdecl (decl);
1171         }
1172       else if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1173         decl = build_anon_union_vars (ref);
1174       else
1175         decl = 0;
1176
1177       if (main_decl == NULL_TREE)
1178         main_decl = decl;
1179     }
1180
1181   return main_decl;
1182 }
1183
1184 /* Finish off the processing of a UNION_TYPE structure.  If the union is an
1185    anonymous union, then all members must be laid out together.  PUBLIC_P
1186    is nonzero if this union is not declared static.  */
1187
1188 void
1189 finish_anon_union (tree anon_union_decl)
1190 {
1191   tree type = TREE_TYPE (anon_union_decl);
1192   tree main_decl;
1193   bool public_p = TREE_PUBLIC (anon_union_decl);
1194
1195   /* The VAR_DECL's context is the same as the TYPE's context.  */
1196   DECL_CONTEXT (anon_union_decl) = DECL_CONTEXT (TYPE_NAME (type));
1197   
1198   if (TYPE_FIELDS (type) == NULL_TREE)
1199     return;
1200
1201   if (public_p)
1202     {
1203       error ("namespace-scope anonymous aggregates must be static");
1204       return;
1205     }
1206
1207   main_decl = build_anon_union_vars (anon_union_decl);
1208   if (main_decl == NULL_TREE)
1209     {
1210       warning ("anonymous union with no members");
1211       return;
1212     }
1213
1214   if (!processing_template_decl)
1215     {
1216       /* Use main_decl to set the mangled name.  */
1217       DECL_NAME (anon_union_decl) = DECL_NAME (main_decl);
1218       mangle_decl (anon_union_decl);
1219       DECL_NAME (anon_union_decl) = NULL_TREE;
1220     }
1221
1222   pushdecl (anon_union_decl);
1223   if (building_stmt_tree ()
1224       && at_function_scope_p ())
1225     add_decl_expr (anon_union_decl);
1226   else if (!processing_template_decl)
1227     rest_of_decl_compilation (anon_union_decl,
1228                               toplevel_bindings_p (), at_eof);
1229 }
1230 \f
1231 /* Auxiliary functions to make type signatures for
1232    `operator new' and `operator delete' correspond to
1233    what compiler will be expecting.  */
1234
1235 tree
1236 coerce_new_type (tree type)
1237 {
1238   int e = 0;
1239   tree args = TYPE_ARG_TYPES (type);
1240
1241   my_friendly_assert (TREE_CODE (type) == FUNCTION_TYPE, 20001107);
1242   
1243   if (!same_type_p (TREE_TYPE (type), ptr_type_node))
1244     e = 1, error ("`operator new' must return type `%T'", ptr_type_node);
1245
1246   if (!args || args == void_list_node
1247       || !same_type_p (TREE_VALUE (args), size_type_node))
1248     {
1249       e = 2;
1250       if (args && args != void_list_node)
1251         args = TREE_CHAIN (args);
1252       pedwarn ("`operator new' takes type `size_t' (`%T') as first parameter", size_type_node);
1253     }
1254   switch (e)
1255   {
1256     case 2:
1257       args = tree_cons (NULL_TREE, size_type_node, args);
1258       /* Fall through.  */
1259     case 1:
1260       type = build_exception_variant
1261               (build_function_type (ptr_type_node, args),
1262                TYPE_RAISES_EXCEPTIONS (type));
1263       /* Fall through.  */
1264     default:;
1265   }
1266   return type;
1267 }
1268
1269 tree
1270 coerce_delete_type (tree type)
1271 {
1272   int e = 0;
1273   tree args = TYPE_ARG_TYPES (type);
1274   
1275   my_friendly_assert (TREE_CODE (type) == FUNCTION_TYPE, 20001107);
1276
1277   if (!same_type_p (TREE_TYPE (type), void_type_node))
1278     e = 1, error ("`operator delete' must return type `%T'", void_type_node);
1279
1280   if (!args || args == void_list_node
1281       || !same_type_p (TREE_VALUE (args), ptr_type_node))
1282     {
1283       e = 2;
1284       if (args && args != void_list_node)
1285         args = TREE_CHAIN (args);
1286       error ("`operator delete' takes type `%T' as first parameter", ptr_type_node);
1287     }
1288   switch (e)
1289   {
1290     case 2:
1291       args = tree_cons (NULL_TREE, ptr_type_node, args);
1292       /* Fall through.  */
1293     case 1:
1294       type = build_exception_variant
1295               (build_function_type (void_type_node, args),
1296                TYPE_RAISES_EXCEPTIONS (type));
1297       /* Fall through.  */
1298     default:;
1299   }
1300
1301   return type;
1302 }
1303 \f
1304 static void
1305 mark_vtable_entries (tree decl)
1306 {
1307   tree entries = CONSTRUCTOR_ELTS (DECL_INITIAL (decl));
1308
1309   for (; entries; entries = TREE_CHAIN (entries))
1310     {
1311       tree fnaddr = TREE_VALUE (entries);
1312       tree fn;
1313
1314       STRIP_NOPS (fnaddr);
1315
1316       if (TREE_CODE (fnaddr) != ADDR_EXPR
1317           && TREE_CODE (fnaddr) != FDESC_EXPR)
1318         /* This entry is an offset: a virtual base class offset, a
1319            virtual call offset, an RTTI offset, etc.  */
1320         continue;
1321
1322       fn = TREE_OPERAND (fnaddr, 0);
1323       TREE_ADDRESSABLE (fn) = 1;
1324       /* When we don't have vcall offsets, we output thunks whenever
1325          we output the vtables that contain them.  With vcall offsets,
1326          we know all the thunks we'll need when we emit a virtual
1327          function, so we emit the thunks there instead.  */
1328       if (DECL_THUNK_P (fn)) 
1329         use_thunk (fn, /*emit_p=*/0);
1330       mark_used (fn);
1331     }
1332 }
1333
1334 /* Set DECL up to have the closest approximation of "initialized common"
1335    linkage available.  */
1336
1337 void
1338 comdat_linkage (tree decl)
1339 {
1340   if (flag_weak)
1341     make_decl_one_only (decl);
1342   else if (TREE_CODE (decl) == FUNCTION_DECL 
1343            || (TREE_CODE (decl) == VAR_DECL && DECL_ARTIFICIAL (decl)))
1344     /* We can just emit function and compiler-generated variables
1345        statically; having multiple copies is (for the most part) only
1346        a waste of space.  
1347
1348        There are two correctness issues, however: the address of a
1349        template instantiation with external linkage should be the
1350        same, independent of what translation unit asks for the
1351        address, and this will not hold when we emit multiple copies of
1352        the function.  However, there's little else we can do.  
1353
1354        Also, by default, the typeinfo implementation assumes that
1355        there will be only one copy of the string used as the name for
1356        each type.  Therefore, if weak symbols are unavailable, the
1357        run-time library should perform a more conservative check; it
1358        should perform a string comparison, rather than an address
1359        comparison.  */
1360     TREE_PUBLIC (decl) = 0;
1361   else
1362     {
1363       /* Static data member template instantiations, however, cannot
1364          have multiple copies.  */
1365       if (DECL_INITIAL (decl) == 0
1366           || DECL_INITIAL (decl) == error_mark_node)
1367         DECL_COMMON (decl) = 1;
1368       else if (EMPTY_CONSTRUCTOR_P (DECL_INITIAL (decl)))
1369         {
1370           DECL_COMMON (decl) = 1;
1371           DECL_INITIAL (decl) = error_mark_node;
1372         }
1373       else if (!DECL_EXPLICIT_INSTANTIATION (decl))
1374         {
1375           /* We can't do anything useful; leave vars for explicit
1376              instantiation.  */
1377           DECL_EXTERNAL (decl) = 1;
1378           DECL_NOT_REALLY_EXTERN (decl) = 0;
1379         }
1380     }
1381
1382   if (DECL_LANG_SPECIFIC (decl))
1383     DECL_COMDAT (decl) = 1;
1384 }
1385
1386 /* For win32 we also want to put explicit instantiations in
1387    linkonce sections, so that they will be merged with implicit
1388    instantiations; otherwise we get duplicate symbol errors.  
1389    For Darwin we do not want explicit instantiations to be 
1390    linkonce.  */
1391
1392 void
1393 maybe_make_one_only (tree decl)
1394 {
1395   /* We used to say that this was not necessary on targets that support weak
1396      symbols, because the implicit instantiations will defer to the explicit
1397      one.  However, that's not actually the case in SVR4; a strong definition
1398      after a weak one is an error.  Also, not making explicit
1399      instantiations one_only means that we can end up with two copies of
1400      some template instantiations.  */
1401   if (! flag_weak)
1402     return;
1403
1404   /* We can't set DECL_COMDAT on functions, or finish_file will think
1405      we can get away with not emitting them if they aren't used.  We need
1406      to for variables so that cp_finish_decl will update their linkage,
1407      because their DECL_INITIAL may not have been set properly yet.  */
1408
1409   if (!TARGET_WEAK_NOT_IN_ARCHIVE_TOC
1410       || (! DECL_EXPLICIT_INSTANTIATION (decl)
1411           && ! DECL_TEMPLATE_SPECIALIZATION (decl)))
1412     {
1413       make_decl_one_only (decl);
1414
1415       if (TREE_CODE (decl) == VAR_DECL)
1416         {
1417           DECL_COMDAT (decl) = 1;
1418           /* Mark it needed so we don't forget to emit it.  */
1419           mark_decl_referenced (decl);
1420         }
1421     }
1422 }
1423
1424 /* Determine whether or not we want to specifically import or export CTYPE,
1425    using various heuristics.  */
1426
1427 static void
1428 import_export_class (tree ctype)
1429 {
1430   /* -1 for imported, 1 for exported.  */
1431   int import_export = 0;
1432
1433   /* It only makes sense to call this function at EOF.  The reason is
1434      that this function looks at whether or not the first non-inline
1435      non-abstract virtual member function has been defined in this
1436      translation unit.  But, we can't possibly know that until we've
1437      seen the entire translation unit.  */
1438   my_friendly_assert (at_eof, 20000226);
1439
1440   if (CLASSTYPE_INTERFACE_KNOWN (ctype))
1441     return;
1442
1443   /* If MULTIPLE_SYMBOL_SPACES is defined and we saw a #pragma interface,
1444      we will have CLASSTYPE_INTERFACE_ONLY set but not
1445      CLASSTYPE_INTERFACE_KNOWN.  In that case, we don't want to use this
1446      heuristic because someone will supply a #pragma implementation
1447      elsewhere, and deducing it here would produce a conflict.  */
1448   if (CLASSTYPE_INTERFACE_ONLY (ctype))
1449     return;
1450
1451   if (lookup_attribute ("dllimport", TYPE_ATTRIBUTES (ctype)))
1452     import_export = -1;
1453   else if (lookup_attribute ("dllexport", TYPE_ATTRIBUTES (ctype)))
1454     import_export = 1;
1455   else if (CLASSTYPE_IMPLICIT_INSTANTIATION (ctype)
1456            && !flag_implicit_templates)
1457     /* For a template class, without -fimplicit-templates, check the
1458        repository.  If the virtual table is assigned to this
1459        translation unit, then export the class; otherwise, import
1460        it.  */
1461       import_export = repo_export_class_p (ctype) ? 1 : -1;
1462   else if (TYPE_POLYMORPHIC_P (ctype))
1463     {
1464       /* The ABI specifies that the virtual table and associated
1465          information are emitted with the key method, if any.  */
1466       tree method = CLASSTYPE_KEY_METHOD (ctype);
1467       /* If weak symbol support is not available, then we must be
1468          careful not to emit the vtable when the key function is
1469          inline.  An inline function can be defined in multiple
1470          translation units.  If we were to emit the vtable in each
1471          translation unit containing a definition, we would get
1472          multiple definition errors at link-time.  */
1473       if (method && (flag_weak || ! DECL_DECLARED_INLINE_P (method)))
1474         import_export = (DECL_REALLY_EXTERN (method) ? -1 : 1);
1475     }
1476
1477 #ifdef MULTIPLE_SYMBOL_SPACES
1478   if (import_export == -1)
1479     import_export = 0;
1480 #endif
1481
1482   /* Allow backends the chance to overrule the decision.  */
1483   if (targetm.cxx.import_export_class)
1484     import_export = targetm.cxx.import_export_class (ctype, import_export);
1485
1486   if (import_export)
1487     {
1488       SET_CLASSTYPE_INTERFACE_KNOWN (ctype);
1489       CLASSTYPE_INTERFACE_ONLY (ctype) = (import_export < 0);
1490     }
1491 }
1492
1493 /* Return true if VAR has already been provided to the back end; in that
1494    case VAR should not be modified further by the front end.  */
1495 static bool
1496 var_finalized_p (tree var)
1497 {
1498   return cgraph_varpool_node (var)->finalized;
1499 }
1500
1501 /* DECL is a VAR_DECL or FUNCTION_DECL which, for whatever reason,
1502    must be emitted in this translation unit.  Mark it as such.  */
1503
1504 void
1505 mark_needed (tree decl)
1506 {
1507   /* It's possible that we no longer need to set
1508      TREE_SYMBOL_REFERENCED here directly, but doing so is
1509      harmless.  */
1510   TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (decl)) = 1;
1511   mark_decl_referenced (decl);
1512 }
1513
1514 /* DECL is either a FUNCTION_DECL or a VAR_DECL.  This function
1515    returns true if a definition of this entity should be provided in
1516    this object file.  Callers use this function to determine whether
1517    or not to let the back end know that a definition of DECL is
1518    available in this translation unit.  */
1519
1520 bool
1521 decl_needed_p (tree decl)
1522 {
1523   my_friendly_assert (TREE_CODE (decl) == VAR_DECL
1524                       || TREE_CODE (decl) == FUNCTION_DECL,
1525                       20040726);
1526   /* This function should only be called at the end of the translation
1527      unit.  We cannot be sure of whether or not something will be
1528      COMDAT until that point.  */
1529   my_friendly_assert (at_eof, 20040726);
1530
1531   /* All entities with external linkage that are not COMDAT should be
1532      emitted; they may be referred to from other object files.  */
1533   if (TREE_PUBLIC (decl) && !DECL_COMDAT (decl))
1534     return true;
1535   /* If this entity was used, let the back-end see it; it will decide
1536      whether or not to emit it into the object file.  */
1537   if (TREE_USED (decl) 
1538       || (DECL_ASSEMBLER_NAME_SET_P (decl)
1539           && TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (decl))))
1540       return true;
1541   /* Otherwise, DECL does not need to be emitted -- yet.  A subsequent
1542      reference to DECL might cause it to be emitted later.  */
1543   return false;
1544 }
1545
1546 /* If necessary, write out the vtables for the dynamic class CTYPE.
1547    Returns true if any vtables were emitted.  */
1548
1549 static bool
1550 maybe_emit_vtables (tree ctype)
1551 {
1552   tree vtbl;
1553   tree primary_vtbl;
1554   int needed = 0;
1555
1556   /* If the vtables for this class have already been emitted there is
1557      nothing more to do.  */
1558   primary_vtbl = CLASSTYPE_VTABLES (ctype);
1559   if (var_finalized_p (primary_vtbl))
1560     return false;
1561   /* Ignore dummy vtables made by get_vtable_decl.  */
1562   if (TREE_TYPE (primary_vtbl) == void_type_node)
1563     return false;
1564
1565   /* See if any of the vtables are needed.  */
1566   for (vtbl = CLASSTYPE_VTABLES (ctype); vtbl; vtbl = TREE_CHAIN (vtbl))
1567     {
1568       import_export_decl (vtbl);
1569       if (DECL_NOT_REALLY_EXTERN (vtbl) && decl_needed_p (vtbl))
1570         needed = 1;
1571     }
1572   if (!needed)
1573     {
1574       /* If the references to this class' vtables are optimized away,
1575          still emit the appropriate debugging information.  See
1576          dfs_debug_mark.  */
1577       if (DECL_COMDAT (primary_vtbl) 
1578           && CLASSTYPE_DEBUG_REQUESTED (ctype))
1579         note_debug_info_needed (ctype);
1580       return false;
1581     }
1582
1583   /* The ABI requires that we emit all of the vtables if we emit any
1584      of them.  */
1585   for (vtbl = CLASSTYPE_VTABLES (ctype); vtbl; vtbl = TREE_CHAIN (vtbl))
1586     {
1587       /* Mark entities references from the virtual table as used.  */
1588       mark_vtable_entries (vtbl);
1589
1590       if (TREE_TYPE (DECL_INITIAL (vtbl)) == 0)
1591         {
1592           /* It had better be all done at compile-time.  */
1593           if (store_init_value (vtbl, DECL_INITIAL (vtbl)))
1594             abort ();
1595         }
1596
1597       /* Write it out.  */
1598       DECL_EXTERNAL (vtbl) = 0;
1599       rest_of_decl_compilation (vtbl, 1, 1);
1600
1601       /* Because we're only doing syntax-checking, we'll never end up
1602          actually marking the variable as written.  */
1603       if (flag_syntax_only)
1604         TREE_ASM_WRITTEN (vtbl) = 1;
1605     }
1606
1607   /* Since we're writing out the vtable here, also write the debug
1608      info.  */
1609   note_debug_info_needed (ctype);
1610
1611   return true;
1612 }
1613
1614 /* Determine the ELF symbol visibility for DECL.  */
1615
1616 void
1617 determine_visibility (tree decl)
1618 {
1619   tree class_type;
1620
1621   /* Cloned constructors and destructors get the same visibility as
1622      the underlying function.  That should be set up in
1623      maybe_clone_body.  */
1624   if (DECL_CLONED_FUNCTION_P (decl))
1625     return;
1626
1627   if (DECL_CLASS_SCOPE_P (decl))
1628     class_type = DECL_CONTEXT (decl);
1629   else if (TREE_CODE (decl) == VAR_DECL
1630            && DECL_TINFO_P (decl)
1631            && CLASS_TYPE_P (TREE_TYPE (DECL_NAME (decl))))
1632     class_type = TREE_TYPE (DECL_NAME (decl));
1633   else
1634     {
1635       /* Virtual tables have DECL_CONTEXT set to their associated class,
1636          so they are automatically handled above.  */
1637       my_friendly_assert (!(TREE_CODE (decl) == VAR_DECL
1638                             && DECL_VTABLE_OR_VTT_P (decl)), 20040803);
1639       /* Entities not associated with any class just get the
1640          visibility specified by their attributes.  */
1641       return;
1642     }
1643
1644   /* By default, static data members and function members receive
1645      the visibility of their containing class.  */
1646   if (class_type
1647       && (TREE_CODE (decl) == VAR_DECL 
1648           || TREE_CODE (decl) == FUNCTION_DECL)
1649       && !lookup_attribute ("visibility", DECL_ATTRIBUTES (decl)))
1650     {
1651       if (TREE_CODE (decl) == FUNCTION_DECL
1652           && DECL_DECLARED_INLINE_P (decl)
1653           && visibility_options.inlines_hidden)
1654         {
1655           DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
1656           DECL_VISIBILITY_SPECIFIED (decl) = 1;
1657         }
1658       else
1659         {
1660           DECL_VISIBILITY (decl) = CLASSTYPE_VISIBILITY (class_type);
1661           DECL_VISIBILITY_SPECIFIED (decl)
1662             = CLASSTYPE_VISIBILITY_SPECIFIED (class_type);
1663         }
1664     }
1665 }
1666
1667 /* DECL is a FUNCTION_DECL or VAR_DECL.  If the object file linkage
1668    for DECL has not already been determined, do so now by setting
1669    DECL_EXTERNAL, DECL_COMDAT and other related flags.  Until this
1670    function is called entities with vague linkage whose definitions
1671    are available must have TREE_PUBLIC set.
1672
1673    If this function decides to place DECL in COMDAT, it will set
1674    appropriate flags -- but will not clear DECL_EXTERNAL.  It is up to
1675    the caller to decide whether or not to clear DECL_EXTERNAL.  Some
1676    callers defer that decision until it is clear that DECL is actually
1677    required.  */
1678
1679 void
1680 import_export_decl (tree decl)
1681 {
1682   int emit_p;
1683   bool comdat_p;
1684   bool import_p;
1685
1686   if (DECL_INTERFACE_KNOWN (decl))
1687     return;
1688
1689   /* We cannot determine what linkage to give to an entity with vague
1690      linkage until the end of the file.  For example, a virtual table
1691      for a class will be defined if and only if the key method is
1692      defined in this translation unit.  As a further example, consider
1693      that when compiling a translation unit that uses PCH file with
1694      "-frepo" it would be incorrect to make decisions about what
1695      entities to emit when building the PCH; those decisions must be
1696      delayed until the repository information has been processed.  */
1697   my_friendly_assert (at_eof, 20040727);
1698   /* Object file linkage for explicit instantiations is handled in
1699      mark_decl_instantiated.  For static variables in functions with
1700      vague linkage, maybe_commonize_var is used.
1701
1702      Therefore, the only declarations that should be provided to this
1703      function are those with external linkage that:
1704
1705      * implicit instantiations of function templates
1706
1707      * inline function
1708
1709      * implicit instantiations of static data members of class
1710        templates
1711
1712      * virtual tables
1713
1714      * typeinfo objects
1715
1716      Furthermore, all entities that reach this point must have a
1717      definition available in this translation unit.
1718
1719      The following assertions check these conditions.  */
1720   my_friendly_assert (TREE_CODE (decl) == FUNCTION_DECL
1721                       || TREE_CODE (decl) == VAR_DECL,
1722                       2004725);
1723   /* Any code that creates entities with TREE_PUBLIC cleared should
1724      also set DECL_INTERFACE_KNOWN.  */
1725   my_friendly_assert (TREE_PUBLIC (decl), 20040725);
1726   if (TREE_CODE (decl) == FUNCTION_DECL)
1727     my_friendly_assert (DECL_IMPLICIT_INSTANTIATION (decl)
1728                         || DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
1729                         || DECL_DECLARED_INLINE_P (decl),
1730                         20040725);
1731   else
1732     my_friendly_assert (DECL_IMPLICIT_INSTANTIATION (decl)
1733                         || DECL_VTABLE_OR_VTT_P (decl)
1734                         || DECL_TINFO_P (decl),
1735                         20040725);
1736   /* Check that a definition of DECL is available in this translation
1737      unit.  */
1738   my_friendly_assert (!DECL_REALLY_EXTERN (decl), 20040725);
1739
1740   /* Assume that DECL will not have COMDAT linkage.  */
1741   comdat_p = false;
1742   /* Assume that DECL will not be imported into this translation
1743      unit.  */
1744   import_p = false;
1745
1746   /* See if the repository tells us whether or not to emit DECL in
1747      this translation unit.  */
1748   emit_p = repo_emit_p (decl);
1749   if (emit_p == 0)
1750     import_p = true;
1751   else if (emit_p == 1)
1752     {
1753       /* The repository indicates that this entity should be defined
1754          here.  Make sure the back end honors that request.  */
1755       if (TREE_CODE (decl) == VAR_DECL)
1756         mark_needed (decl);
1757       else if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (decl)
1758                || DECL_MAYBE_IN_CHARGE_DESTRUCTOR_P (decl))
1759         {
1760           tree clone;
1761           FOR_EACH_CLONE (clone, decl)
1762             mark_needed (clone);
1763         }
1764       else
1765         mark_needed (decl);
1766       /* Output the definition as an ordinary strong definition.  */
1767       DECL_EXTERNAL (decl) = 0;
1768       DECL_INTERFACE_KNOWN (decl) = 1;
1769       return;
1770     }
1771
1772   if (import_p)
1773     /* We have already decided what to do with this DECL; there is no
1774        need to check anything further.  */
1775     ;
1776   else if (TREE_CODE (decl) == VAR_DECL && DECL_VTABLE_OR_VTT_P (decl))
1777     {
1778       tree type = DECL_CONTEXT (decl);
1779       import_export_class (type);
1780       if (TYPE_FOR_JAVA (type))
1781         import_p = true;
1782       else if (CLASSTYPE_INTERFACE_KNOWN (type)
1783                && CLASSTYPE_INTERFACE_ONLY (type))
1784         import_p = true;
1785       else if (TARGET_WEAK_NOT_IN_ARCHIVE_TOC
1786                && !CLASSTYPE_USE_TEMPLATE (type)
1787                && CLASSTYPE_KEY_METHOD (type)
1788                && !DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (type)))
1789         /* The ABI requires that all virtual tables be emitted with
1790            COMDAT linkage.  However, on systems where COMDAT symbols
1791            don't show up in the table of contents for a static
1792            archive, the linker will report errors about undefined
1793            symbols because it will not see the virtual table
1794            definition.  Therefore, in the case that we know that the
1795            virtual table will be emitted in only one translation
1796            unit, we make the virtual table an ordinary definition
1797            with external linkage.  */
1798         DECL_EXTERNAL (decl) = 0;
1799       else if (CLASSTYPE_INTERFACE_KNOWN (type))
1800         {
1801           /* TYPE is being exported from this translation unit, so DECL
1802              should be defined here.  The ABI requires COMDAT
1803              linkage.  Normally, we only emit COMDAT things when they
1804              are needed; make sure that we realize that this entity is
1805              indeed needed.  */
1806           comdat_p = true;
1807           mark_needed (decl);
1808         }
1809       else if (!flag_implicit_templates
1810                && CLASSTYPE_IMPLICIT_INSTANTIATION (type))
1811         import_p = true;
1812       else
1813         comdat_p = true;
1814     }
1815   else if (TREE_CODE (decl) == VAR_DECL && DECL_TINFO_P (decl))
1816     {
1817       tree type = TREE_TYPE (DECL_NAME (decl));
1818       if (CLASS_TYPE_P (type))
1819         {
1820           import_export_class (type);
1821           if (CLASSTYPE_INTERFACE_KNOWN (type)
1822               && TYPE_POLYMORPHIC_P (type)
1823               && CLASSTYPE_INTERFACE_ONLY (type)
1824               /* If -fno-rtti was specified, then we cannot be sure
1825                  that RTTI information will be emitted with the
1826                  virtual table of the class, so we must emit it
1827                  wherever it is used.  */
1828               && flag_rtti)
1829             import_p = true;
1830           else 
1831             {
1832               comdat_p = true;
1833               if (CLASSTYPE_INTERFACE_KNOWN (type)
1834                   && !CLASSTYPE_INTERFACE_ONLY (type))
1835                 mark_needed (decl);
1836             }
1837         }
1838       else
1839         comdat_p = true;
1840     }
1841   else if (DECL_TEMPLATE_INSTANTIATION (decl)
1842            || DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl))
1843     {
1844       /* DECL is an implicit instantiation of a function or static
1845          data member.  */
1846       if (flag_implicit_templates
1847           || (flag_implicit_inline_templates
1848               && TREE_CODE (decl) == FUNCTION_DECL 
1849               && DECL_DECLARED_INLINE_P (decl)))
1850         comdat_p = true;
1851       else
1852         /* If we are not implicitly generating templates, then mark
1853            this entity as undefined in this translation unit.  */
1854         import_p = true;
1855     }
1856   else if (DECL_FUNCTION_MEMBER_P (decl))
1857     {
1858       if (!DECL_DECLARED_INLINE_P (decl))
1859         {
1860           tree ctype = DECL_CONTEXT (decl);
1861           import_export_class (ctype);
1862           if (CLASSTYPE_INTERFACE_KNOWN (ctype))
1863             {
1864               DECL_NOT_REALLY_EXTERN (decl)
1865                 = ! (CLASSTYPE_INTERFACE_ONLY (ctype)
1866                      || (DECL_DECLARED_INLINE_P (decl) 
1867                          && ! flag_implement_inlines
1868                          && !DECL_VINDEX (decl)));
1869
1870               if (!DECL_NOT_REALLY_EXTERN (decl))
1871                 DECL_EXTERNAL (decl) = 1;
1872
1873               /* Always make artificials weak.  */
1874               if (DECL_ARTIFICIAL (decl) && flag_weak)
1875                 comdat_p = true;
1876               else
1877                 maybe_make_one_only (decl);
1878             }
1879         }
1880       else
1881         comdat_p = true;
1882     }
1883   else
1884     comdat_p = true;
1885
1886   if (import_p)
1887     {
1888       /* If we are importing DECL into this translation unit, mark is
1889          an undefined here.  */
1890       DECL_EXTERNAL (decl) = 1;
1891       DECL_NOT_REALLY_EXTERN (decl) = 0;
1892     }
1893   else if (comdat_p)
1894     {
1895       /* If we decided to put DECL in COMDAT, mark it accordingly at
1896          this point.  */
1897       comdat_linkage (decl);
1898     }
1899
1900   DECL_INTERFACE_KNOWN (decl) = 1;
1901 }
1902
1903 /* Return an expression that performs the destruction of DECL, which
1904    must be a VAR_DECL whose type has a non-trivial destructor, or is
1905    an array whose (innermost) elements have a non-trivial destructor.  */
1906
1907 tree
1908 build_cleanup (tree decl)
1909 {
1910   tree temp;
1911   tree type = TREE_TYPE (decl);
1912
1913   /* This function should only be called for declarations that really
1914      require cleanups.  */
1915   my_friendly_assert (!TYPE_HAS_TRIVIAL_DESTRUCTOR (type), 20030106);
1916
1917   /* Treat all objects with destructors as used; the destructor may do
1918      something substantive.  */
1919   mark_used (decl);
1920
1921   if (TREE_CODE (type) == ARRAY_TYPE)
1922     temp = decl;
1923   else
1924     {
1925       cxx_mark_addressable (decl);
1926       temp = build1 (ADDR_EXPR, build_pointer_type (type), decl);
1927     }
1928   temp = build_delete (TREE_TYPE (temp), temp,
1929                        sfk_complete_destructor,
1930                        LOOKUP_NORMAL|LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR, 0);
1931   return temp;
1932 }
1933
1934 /* Returns the initialization guard variable for the variable DECL,
1935    which has static storage duration.  */
1936
1937 tree
1938 get_guard (tree decl)
1939 {
1940   tree sname;
1941   tree guard;
1942
1943   sname = mangle_guard_variable (decl);
1944   guard = IDENTIFIER_GLOBAL_VALUE (sname);
1945   if (! guard)
1946     {
1947       tree guard_type;
1948
1949       /* We use a type that is big enough to contain a mutex as well
1950          as an integer counter.  */
1951       guard_type = targetm.cxx.guard_type ();
1952       guard = build_decl (VAR_DECL, sname, guard_type);
1953       
1954       /* The guard should have the same linkage as what it guards.  */
1955       TREE_PUBLIC (guard) = TREE_PUBLIC (decl);
1956       TREE_STATIC (guard) = TREE_STATIC (decl);
1957       DECL_COMMON (guard) = DECL_COMMON (decl);
1958       DECL_ONE_ONLY (guard) = DECL_ONE_ONLY (decl);
1959       if (TREE_PUBLIC (decl))
1960         DECL_WEAK (guard) = DECL_WEAK (decl);
1961       
1962       DECL_ARTIFICIAL (guard) = 1;
1963       TREE_USED (guard) = 1;
1964       pushdecl_top_level_and_finish (guard, NULL_TREE);
1965     }
1966   return guard;
1967 }
1968
1969 /* Return those bits of the GUARD variable that should be set when the
1970    guarded entity is actually initialized.  */
1971
1972 static tree
1973 get_guard_bits (tree guard)
1974 {
1975   if (!targetm.cxx.guard_mask_bit ())
1976     {
1977       /* We only set the first byte of the guard, in order to leave room
1978          for a mutex in the high-order bits.  */
1979       guard = build1 (ADDR_EXPR, 
1980                       build_pointer_type (TREE_TYPE (guard)),
1981                       guard);
1982       guard = build1 (NOP_EXPR, 
1983                       build_pointer_type (char_type_node), 
1984                       guard);
1985       guard = build1 (INDIRECT_REF, char_type_node, guard);
1986     }
1987
1988   return guard;
1989 }
1990
1991 /* Return an expression which determines whether or not the GUARD
1992    variable has already been initialized.  */
1993
1994 tree
1995 get_guard_cond (tree guard)
1996 {
1997   tree guard_value;
1998
1999   /* Check to see if the GUARD is zero.  */
2000   guard = get_guard_bits (guard);
2001
2002   /* Mask off all but the low bit.  */
2003   if (targetm.cxx.guard_mask_bit ())
2004     {
2005       guard_value = integer_one_node;
2006       if (!same_type_p (TREE_TYPE (guard_value), TREE_TYPE (guard)))
2007         guard_value = convert (TREE_TYPE (guard), guard_value);
2008         guard = cp_build_binary_op (BIT_AND_EXPR, guard, guard_value);
2009     }
2010
2011   guard_value = integer_zero_node;
2012   if (!same_type_p (TREE_TYPE (guard_value), TREE_TYPE (guard)))
2013     guard_value = convert (TREE_TYPE (guard), guard_value);
2014   return cp_build_binary_op (EQ_EXPR, guard, guard_value);
2015 }
2016
2017 /* Return an expression which sets the GUARD variable, indicating that
2018    the variable being guarded has been initialized.  */
2019
2020 tree
2021 set_guard (tree guard)
2022 {
2023   tree guard_init;
2024
2025   /* Set the GUARD to one.  */
2026   guard = get_guard_bits (guard);
2027   guard_init = integer_one_node;
2028   if (!same_type_p (TREE_TYPE (guard_init), TREE_TYPE (guard)))
2029     guard_init = convert (TREE_TYPE (guard), guard_init);
2030   return build_modify_expr (guard, NOP_EXPR, guard_init);
2031 }
2032
2033 /* Start the process of running a particular set of global constructors
2034    or destructors.  Subroutine of do_[cd]tors.  */
2035
2036 static tree
2037 start_objects (int method_type, int initp)
2038 {
2039   tree body;
2040   tree fndecl;
2041   char type[10];
2042
2043   /* Make ctor or dtor function.  METHOD_TYPE may be 'I' or 'D'.  */
2044
2045   if (initp != DEFAULT_INIT_PRIORITY)
2046     {
2047       char joiner;
2048
2049 #ifdef JOINER
2050       joiner = JOINER;
2051 #else
2052       joiner = '_';
2053 #endif
2054
2055       sprintf (type, "%c%c%.5u", method_type, joiner, initp);
2056     }
2057   else
2058     sprintf (type, "%c", method_type);
2059
2060   fndecl = build_lang_decl (FUNCTION_DECL, 
2061                             get_file_function_name_long (type),
2062                             build_function_type (void_type_node,
2063                                                  void_list_node));
2064   start_preparsed_function (fndecl, /*attrs=*/NULL_TREE, SF_PRE_PARSED);
2065
2066   /* It can be a static function as long as collect2 does not have
2067      to scan the object file to find its ctor/dtor routine.  */
2068   TREE_PUBLIC (current_function_decl) = ! targetm.have_ctors_dtors;
2069
2070   /* Mark this declaration as used to avoid spurious warnings.  */
2071   TREE_USED (current_function_decl) = 1;
2072
2073   /* Mark this function as a global constructor or destructor.  */
2074   if (method_type == 'I')
2075     DECL_GLOBAL_CTOR_P (current_function_decl) = 1;
2076   else
2077     DECL_GLOBAL_DTOR_P (current_function_decl) = 1;
2078   DECL_LANG_SPECIFIC (current_function_decl)->decl_flags.u2sel = 1;
2079
2080   body = begin_compound_stmt (BCS_FN_BODY);
2081
2082   /* We cannot allow these functions to be elided, even if they do not
2083      have external linkage.  And, there's no point in deferring
2084      compilation of thes functions; they're all going to have to be
2085      out anyhow.  */
2086   DECL_INLINE (current_function_decl) = 0;
2087   DECL_UNINLINABLE (current_function_decl) = 1;
2088
2089   return body;
2090 }
2091
2092 /* Finish the process of running a particular set of global constructors
2093    or destructors.  Subroutine of do_[cd]tors.  */
2094
2095 static void
2096 finish_objects (int method_type, int initp, tree body)
2097 {
2098   tree fn;
2099
2100   /* Finish up.  */
2101   finish_compound_stmt (body);
2102   fn = finish_function (0);
2103   expand_or_defer_fn (fn);
2104
2105   /* When only doing semantic analysis, and no RTL generation, we
2106      can't call functions that directly emit assembly code; there is
2107      no assembly file in which to put the code.  */
2108   if (flag_syntax_only)
2109     return;
2110
2111   if (targetm.have_ctors_dtors)
2112     {
2113       rtx fnsym = XEXP (DECL_RTL (fn), 0);
2114       if (method_type == 'I')
2115         (* targetm.asm_out.constructor) (fnsym, initp);
2116       else
2117         (* targetm.asm_out.destructor) (fnsym, initp);
2118     }
2119 }
2120
2121 /* The names of the parameters to the function created to handle
2122    initializations and destructions for objects with static storage
2123    duration.  */
2124 #define INITIALIZE_P_IDENTIFIER "__initialize_p"
2125 #define PRIORITY_IDENTIFIER "__priority"
2126
2127 /* The name of the function we create to handle initializations and
2128    destructions for objects with static storage duration.  */
2129 #define SSDF_IDENTIFIER "__static_initialization_and_destruction"
2130
2131 /* The declaration for the __INITIALIZE_P argument.  */
2132 static GTY(()) tree initialize_p_decl;
2133
2134 /* The declaration for the __PRIORITY argument.  */
2135 static GTY(()) tree priority_decl;
2136
2137 /* The declaration for the static storage duration function.  */
2138 static GTY(()) tree ssdf_decl;
2139
2140 /* All the static storage duration functions created in this
2141    translation unit.  */
2142 static GTY(()) varray_type ssdf_decls;
2143
2144 /* A map from priority levels to information about that priority
2145    level.  There may be many such levels, so efficient lookup is
2146    important.  */
2147 static splay_tree priority_info_map;
2148
2149 /* Begins the generation of the function that will handle all
2150    initialization and destruction of objects with static storage
2151    duration.  The function generated takes two parameters of type
2152    `int': __INITIALIZE_P and __PRIORITY.  If __INITIALIZE_P is
2153    nonzero, it performs initializations.  Otherwise, it performs
2154    destructions.  It only performs those initializations or
2155    destructions with the indicated __PRIORITY.  The generated function
2156    returns no value.  
2157
2158    It is assumed that this function will only be called once per
2159    translation unit.  */
2160
2161 static tree
2162 start_static_storage_duration_function (unsigned count)
2163 {
2164   tree parm_types;
2165   tree type;
2166   tree body;
2167   char id[sizeof (SSDF_IDENTIFIER) + 1 /* '\0' */ + 32];
2168
2169   /* Create the identifier for this function.  It will be of the form
2170      SSDF_IDENTIFIER_<number>.  */
2171   sprintf (id, "%s_%u", SSDF_IDENTIFIER, count);
2172
2173   /* Create the parameters.  */
2174   parm_types = void_list_node;
2175   parm_types = tree_cons (NULL_TREE, integer_type_node, parm_types);
2176   parm_types = tree_cons (NULL_TREE, integer_type_node, parm_types);
2177   type = build_function_type (void_type_node, parm_types);
2178
2179   /* Create the FUNCTION_DECL itself.  */
2180   ssdf_decl = build_lang_decl (FUNCTION_DECL, 
2181                                get_identifier (id),
2182                                type);
2183   TREE_PUBLIC (ssdf_decl) = 0;
2184   DECL_ARTIFICIAL (ssdf_decl) = 1;
2185
2186   /* Put this function in the list of functions to be called from the
2187      static constructors and destructors.  */
2188   if (!ssdf_decls)
2189     {
2190       VARRAY_TREE_INIT (ssdf_decls, 32, "ssdf_decls");
2191
2192       /* Take this opportunity to initialize the map from priority
2193          numbers to information about that priority level.  */
2194       priority_info_map = splay_tree_new (splay_tree_compare_ints,
2195                                           /*delete_key_fn=*/0,
2196                                           /*delete_value_fn=*/
2197                                           (splay_tree_delete_value_fn) &free);
2198
2199       /* We always need to generate functions for the
2200          DEFAULT_INIT_PRIORITY so enter it now.  That way when we walk
2201          priorities later, we'll be sure to find the
2202          DEFAULT_INIT_PRIORITY.  */
2203       get_priority_info (DEFAULT_INIT_PRIORITY);
2204     }
2205
2206   VARRAY_PUSH_TREE (ssdf_decls, ssdf_decl);
2207
2208   /* Create the argument list.  */
2209   initialize_p_decl = cp_build_parm_decl
2210     (get_identifier (INITIALIZE_P_IDENTIFIER), integer_type_node);
2211   DECL_CONTEXT (initialize_p_decl) = ssdf_decl;
2212   TREE_USED (initialize_p_decl) = 1;
2213   priority_decl = cp_build_parm_decl
2214     (get_identifier (PRIORITY_IDENTIFIER), integer_type_node);
2215   DECL_CONTEXT (priority_decl) = ssdf_decl;
2216   TREE_USED (priority_decl) = 1;
2217
2218   TREE_CHAIN (initialize_p_decl) = priority_decl;
2219   DECL_ARGUMENTS (ssdf_decl) = initialize_p_decl;
2220
2221   /* Put the function in the global scope.  */
2222   pushdecl (ssdf_decl);
2223
2224   /* Start the function itself.  This is equivalent to declaring the
2225      function as:
2226
2227        static void __ssdf (int __initialize_p, init __priority_p);
2228        
2229      It is static because we only need to call this function from the
2230      various constructor and destructor functions for this module.  */
2231   start_preparsed_function (ssdf_decl,
2232                             /*attrs=*/NULL_TREE,
2233                             SF_PRE_PARSED);
2234
2235   /* Set up the scope of the outermost block in the function.  */
2236   body = begin_compound_stmt (BCS_FN_BODY);
2237
2238   /* This function must not be deferred because we are depending on
2239      its compilation to tell us what is TREE_SYMBOL_REFERENCED.  */
2240   DECL_INLINE (ssdf_decl) = 0;
2241   DECL_UNINLINABLE (ssdf_decl) = 1;
2242
2243   return body;
2244 }
2245
2246 /* Finish the generation of the function which performs initialization
2247    and destruction of objects with static storage duration.  After
2248    this point, no more such objects can be created.  */
2249
2250 static void
2251 finish_static_storage_duration_function (tree body)
2252 {
2253   /* Close out the function.  */
2254   finish_compound_stmt (body);
2255   expand_or_defer_fn (finish_function (0));
2256 }
2257
2258 /* Return the information about the indicated PRIORITY level.  If no
2259    code to handle this level has yet been generated, generate the
2260    appropriate prologue.  */
2261
2262 static priority_info
2263 get_priority_info (int priority)
2264 {
2265   priority_info pi;
2266   splay_tree_node n;
2267
2268   n = splay_tree_lookup (priority_info_map, 
2269                          (splay_tree_key) priority);
2270   if (!n)
2271     {
2272       /* Create a new priority information structure, and insert it
2273          into the map.  */
2274       pi = xmalloc (sizeof (struct priority_info_s));
2275       pi->initializations_p = 0;
2276       pi->destructions_p = 0;
2277       splay_tree_insert (priority_info_map,
2278                          (splay_tree_key) priority,
2279                          (splay_tree_value) pi);
2280     }
2281   else
2282     pi = (priority_info) n->value;
2283
2284   return pi;
2285 }
2286
2287 /* Set up to handle the initialization or destruction of DECL.  If
2288    INITP is nonzero, we are initializing the variable.  Otherwise, we
2289    are destroying it.  */
2290
2291 static tree
2292 start_static_initialization_or_destruction (tree decl, int initp)
2293 {
2294   tree guard_if_stmt = NULL_TREE;
2295   int priority;
2296   tree cond;
2297   tree guard;
2298   tree init_cond;
2299   priority_info pi;
2300
2301   /* Figure out the priority for this declaration.  */
2302   priority = DECL_INIT_PRIORITY (decl);
2303   if (!priority)
2304     priority = DEFAULT_INIT_PRIORITY;
2305
2306   /* Remember that we had an initialization or finalization at this
2307      priority.  */
2308   pi = get_priority_info (priority);
2309   if (initp)
2310     pi->initializations_p = 1;
2311   else
2312     pi->destructions_p = 1;
2313
2314   /* Trick the compiler into thinking we are at the file and line
2315      where DECL was declared so that error-messages make sense, and so
2316      that the debugger will show somewhat sensible file and line
2317      information.  */
2318   input_location = DECL_SOURCE_LOCATION (decl);
2319
2320   /* Because of:
2321
2322        [class.access.spec]
2323
2324        Access control for implicit calls to the constructors,
2325        the conversion functions, or the destructor called to
2326        create and destroy a static data member is performed as
2327        if these calls appeared in the scope of the member's
2328        class.  
2329
2330      we pretend we are in a static member function of the class of
2331      which the DECL is a member.  */
2332   if (member_p (decl))
2333     {
2334       DECL_CONTEXT (current_function_decl) = DECL_CONTEXT (decl);
2335       DECL_STATIC_FUNCTION_P (current_function_decl) = 1;
2336     }
2337   
2338   /* Conditionalize this initialization on being in the right priority
2339      and being initializing/finalizing appropriately.  */
2340   guard_if_stmt = begin_if_stmt ();
2341   cond = cp_build_binary_op (EQ_EXPR,
2342                              priority_decl,
2343                              build_int_2 (priority, 0));
2344   init_cond = initp ? integer_one_node : integer_zero_node;
2345   init_cond = cp_build_binary_op (EQ_EXPR,
2346                                   initialize_p_decl,
2347                                   init_cond);
2348   cond = cp_build_binary_op (TRUTH_ANDIF_EXPR, cond, init_cond);
2349
2350   /* Assume we don't need a guard.  */
2351   guard = NULL_TREE;
2352   /* We need a guard if this is an object with external linkage that
2353      might be initialized in more than one place.  (For example, a
2354      static data member of a template, when the data member requires
2355      construction.)  */
2356   if (TREE_PUBLIC (decl) && (DECL_COMMON (decl) 
2357                              || DECL_ONE_ONLY (decl)
2358                              || DECL_WEAK (decl)))
2359     {
2360       tree guard_cond;
2361
2362       guard = get_guard (decl);
2363
2364       /* When using __cxa_atexit, we just check the GUARD as we would
2365          for a local static.  */
2366       if (flag_use_cxa_atexit)
2367         {
2368           /* When using __cxa_atexit, we never try to destroy
2369              anything from a static destructor.  */
2370           my_friendly_assert (initp, 20000629);
2371           guard_cond = get_guard_cond (guard);
2372         }
2373       /* If we don't have __cxa_atexit, then we will be running
2374          destructors from .fini sections, or their equivalents.  So,
2375          we need to know how many times we've tried to initialize this
2376          object.  We do initializations only if the GUARD is zero,
2377          i.e., if we are the first to initialize the variable.  We do
2378          destructions only if the GUARD is one, i.e., if we are the
2379          last to destroy the variable.  */
2380       else if (initp)
2381         guard_cond 
2382           = cp_build_binary_op (EQ_EXPR,
2383                                 build_unary_op (PREINCREMENT_EXPR,
2384                                                 guard,
2385                                                 /*noconvert=*/1),
2386                                 integer_one_node);
2387       else
2388         guard_cond 
2389           = cp_build_binary_op (EQ_EXPR,
2390                                 build_unary_op (PREDECREMENT_EXPR,
2391                                                 guard,
2392                                                 /*noconvert=*/1),
2393                                 integer_zero_node);
2394
2395       cond = cp_build_binary_op (TRUTH_ANDIF_EXPR, cond, guard_cond);
2396     }
2397
2398   finish_if_stmt_cond (cond, guard_if_stmt);
2399
2400   /* If we're using __cxa_atexit, we have not already set the GUARD,
2401      so we must do so now.  */
2402   if (guard && initp && flag_use_cxa_atexit)
2403     finish_expr_stmt (set_guard (guard));
2404
2405   return guard_if_stmt;
2406 }
2407
2408 /* We've just finished generating code to do an initialization or
2409    finalization.  GUARD_IF_STMT is the if-statement we used to guard
2410    the initialization.  */
2411
2412 static void
2413 finish_static_initialization_or_destruction (tree guard_if_stmt)
2414 {
2415   finish_then_clause (guard_if_stmt);
2416   finish_if_stmt (guard_if_stmt);
2417
2418   /* Now that we're done with DECL we don't need to pretend to be a
2419      member of its class any longer.  */
2420   DECL_CONTEXT (current_function_decl) = NULL_TREE;
2421   DECL_STATIC_FUNCTION_P (current_function_decl) = 0;
2422 }
2423
2424 /* Generate code to do the initialization of DECL, a VAR_DECL with
2425    static storage duration.  The initialization is INIT.  */
2426
2427 static void
2428 do_static_initialization (tree decl, tree init)
2429 {
2430   tree guard_if_stmt;
2431
2432   /* Set up for the initialization.  */
2433   guard_if_stmt
2434     = start_static_initialization_or_destruction (decl,
2435                                                   /*initp=*/1);
2436
2437   /* Perform the initialization.  */
2438   if (init)
2439     finish_expr_stmt (init);
2440
2441   /* If we're using __cxa_atexit, register a a function that calls the
2442      destructor for the object.  */
2443   if (flag_use_cxa_atexit)
2444     register_dtor_fn (decl);
2445
2446   /* Finish up.  */
2447   finish_static_initialization_or_destruction (guard_if_stmt);
2448 }
2449
2450 /* Generate code to do the static destruction of DECL.  If DECL may be
2451    initialized more than once in different object files, GUARD is the
2452    guard variable to check.  PRIORITY is the priority for the
2453    destruction.  */
2454
2455 static void
2456 do_static_destruction (tree decl)
2457 {
2458   tree guard_if_stmt;
2459
2460   /* If we're using __cxa_atexit, then destructors are registered
2461      immediately after objects are initialized.  */
2462   my_friendly_assert (!flag_use_cxa_atexit, 20000121);
2463
2464   /* If we don't need a destructor, there's nothing to do.  */
2465   if (TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl)))
2466     return;
2467
2468   /* Actually do the destruction.  */
2469   guard_if_stmt = start_static_initialization_or_destruction (decl,
2470                                                               /*initp=*/0);
2471   finish_expr_stmt (build_cleanup (decl));
2472   finish_static_initialization_or_destruction (guard_if_stmt);
2473 }
2474
2475 /* VARS is a list of variables with static storage duration which may
2476    need initialization and/or finalization.  Remove those variables
2477    that don't really need to be initialized or finalized, and return
2478    the resulting list.  The order in which the variables appear in
2479    VARS is in reverse order of the order in which they should actually
2480    be initialized.  The list we return is in the unreversed order;
2481    i.e., the first variable should be initialized first.  */
2482
2483 static tree
2484 prune_vars_needing_no_initialization (tree *vars)
2485 {
2486   tree *var = vars;
2487   tree result = NULL_TREE;
2488
2489   while (*var)
2490     {
2491       tree t = *var;
2492       tree decl = TREE_VALUE (t);
2493       tree init = TREE_PURPOSE (t);
2494
2495       /* Deal gracefully with error.  */
2496       if (decl == error_mark_node)
2497         {
2498           var = &TREE_CHAIN (t);
2499           continue;
2500         }
2501
2502       /* The only things that can be initialized are variables.  */
2503       my_friendly_assert (TREE_CODE (decl) == VAR_DECL, 19990420);
2504
2505       /* If this object is not defined, we don't need to do anything
2506          here.  */
2507       if (DECL_EXTERNAL (decl))
2508         {
2509           var = &TREE_CHAIN (t);
2510           continue;
2511         }
2512
2513       /* Also, if the initializer already contains errors, we can bail
2514          out now.  */
2515       if (init && TREE_CODE (init) == TREE_LIST 
2516           && value_member (error_mark_node, init))
2517         {
2518           var = &TREE_CHAIN (t);
2519           continue;
2520         }
2521
2522       /* This variable is going to need initialization and/or
2523          finalization, so we add it to the list.  */
2524       *var = TREE_CHAIN (t);
2525       TREE_CHAIN (t) = result;
2526       result = t;
2527     }
2528
2529   return result;
2530 }
2531
2532 /* Make sure we have told the back end about all the variables in
2533    VARS.  */
2534
2535 static void
2536 write_out_vars (tree vars)
2537 {
2538   tree v;
2539
2540   for (v = vars; v; v = TREE_CHAIN (v))
2541     {
2542       tree var = TREE_VALUE (v);
2543       if (!var_finalized_p (var))
2544         {
2545           import_export_decl (var);
2546           rest_of_decl_compilation (var, 1, 1);
2547         }
2548     }
2549 }
2550
2551 /* Generate a static constructor (if CONSTRUCTOR_P) or destructor
2552    (otherwise) that will initialize all gobal objects with static
2553    storage duration having the indicated PRIORITY.  */
2554
2555 static void
2556 generate_ctor_or_dtor_function (bool constructor_p, int priority,
2557                                 location_t *locus)
2558 {
2559   char function_key;
2560   tree arguments;
2561   tree fndecl;
2562   tree body;
2563   size_t i;
2564
2565   input_location = *locus;
2566 #ifdef USE_MAPPED_LOCATION
2567   /* ??? */
2568 #else
2569   locus->line++;
2570 #endif
2571   
2572   /* We use `I' to indicate initialization and `D' to indicate
2573      destruction.  */
2574   function_key = constructor_p ? 'I' : 'D';
2575
2576   /* We emit the function lazily, to avoid generating empty
2577      global constructors and destructors.  */
2578   body = NULL_TREE;
2579
2580   /* Call the static storage duration function with appropriate
2581      arguments.  */
2582   if (ssdf_decls)
2583     for (i = 0; i < ssdf_decls->elements_used; ++i) 
2584       {
2585         fndecl = VARRAY_TREE (ssdf_decls, i);
2586
2587         /* Calls to pure or const functions will expand to nothing.  */
2588         if (! (flags_from_decl_or_type (fndecl) & (ECF_CONST | ECF_PURE)))
2589           {
2590             if (! body)
2591               body = start_objects (function_key, priority);
2592
2593             arguments = tree_cons (NULL_TREE, build_int_2 (priority, 0), 
2594                                    NULL_TREE);
2595             arguments = tree_cons (NULL_TREE, build_int_2 (constructor_p, 0),
2596                                    arguments);
2597             finish_expr_stmt (build_function_call (fndecl, arguments));
2598           }
2599       }
2600
2601   /* If we're generating code for the DEFAULT_INIT_PRIORITY, throw in
2602      calls to any functions marked with attributes indicating that
2603      they should be called at initialization- or destruction-time.  */
2604   if (priority == DEFAULT_INIT_PRIORITY)
2605     {
2606       tree fns;
2607
2608       for (fns = constructor_p ? static_ctors : static_dtors; 
2609            fns;
2610            fns = TREE_CHAIN (fns))
2611         {
2612           fndecl = TREE_VALUE (fns);
2613
2614           /* Calls to pure/const functions will expand to nothing.  */
2615           if (! (flags_from_decl_or_type (fndecl) & (ECF_CONST | ECF_PURE)))
2616             {
2617               if (! body)
2618                 body = start_objects (function_key, priority);
2619               finish_expr_stmt (build_function_call (fndecl, NULL_TREE));
2620             }
2621         }
2622     }
2623
2624   /* Close out the function.  */
2625   if (body)
2626     finish_objects (function_key, priority, body);
2627 }
2628
2629 /* Generate constructor and destructor functions for the priority
2630    indicated by N.  */
2631
2632 static int
2633 generate_ctor_and_dtor_functions_for_priority (splay_tree_node n, void * data)
2634 {
2635   location_t *locus = data;
2636   int priority = (int) n->key;
2637   priority_info pi = (priority_info) n->value;
2638
2639   /* Generate the functions themselves, but only if they are really
2640      needed.  */
2641   if (pi->initializations_p
2642       || (priority == DEFAULT_INIT_PRIORITY && static_ctors))
2643     generate_ctor_or_dtor_function (/*constructor_p=*/true, priority, locus);
2644   if (pi->destructions_p
2645       || (priority == DEFAULT_INIT_PRIORITY && static_dtors))
2646     generate_ctor_or_dtor_function (/*constructor_p=*/false, priority, locus);
2647
2648   /* Keep iterating.  */
2649   return 0;
2650 }
2651
2652 /* Called via LANGHOOK_CALLGRAPH_ANALYZE_EXPR.  It is supposed to mark
2653    decls referenced from frontend specific constructs; it will be called
2654    only for language-specific tree nodes.
2655
2656    Here we must deal with member pointers.  */
2657
2658 tree
2659 cxx_callgraph_analyze_expr (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
2660                             tree from ATTRIBUTE_UNUSED)
2661 {
2662   tree t = *tp;
2663
2664   switch (TREE_CODE (t))
2665     {
2666     case PTRMEM_CST:
2667       if (TYPE_PTRMEMFUNC_P (TREE_TYPE (t)))
2668         cgraph_mark_needed_node (cgraph_node (PTRMEM_CST_MEMBER (t)));
2669       break;
2670     case BASELINK:
2671       if (TREE_CODE (BASELINK_FUNCTIONS (t)) == FUNCTION_DECL)
2672         cgraph_mark_needed_node (cgraph_node (BASELINK_FUNCTIONS (t)));
2673       break;
2674     case VAR_DECL:
2675       if (DECL_VTABLE_OR_VTT_P (t))
2676         {
2677           /* The ABI requires that all virtual tables be emitted
2678              whenever one of them is.  */
2679           tree vtbl;
2680           for (vtbl = CLASSTYPE_VTABLES (DECL_CONTEXT (t));
2681                vtbl;
2682                vtbl = TREE_CHAIN (vtbl))
2683             mark_decl_referenced (vtbl);
2684         }
2685       else if (DECL_CONTEXT (t) 
2686                && TREE_CODE (DECL_CONTEXT (t)) == FUNCTION_DECL)
2687         /* If we need a static variable in a function, then we
2688            need the containing function.  */
2689         mark_decl_referenced (DECL_CONTEXT (t));
2690       break;
2691     default:
2692       break;
2693     }
2694
2695   return NULL;
2696 }
2697
2698 /* This routine is called from the last rule in yyparse ().
2699    Its job is to create all the code needed to initialize and
2700    destroy the global aggregates.  We do the destruction
2701    first, since that way we only need to reverse the decls once.  */
2702
2703 void
2704 finish_file (void)
2705 {
2706   tree vars;
2707   bool reconsider;
2708   size_t i;
2709   location_t locus;
2710   unsigned ssdf_count = 0;
2711
2712   locus = input_location;
2713   at_eof = 1;
2714
2715   /* Bad parse errors.  Just forget about it.  */
2716   if (! global_bindings_p () || current_class_type || decl_namespace_list)
2717     return;
2718
2719   if (pch_file)
2720     c_common_write_pch ();
2721
2722 #ifdef USE_MAPPED_LOCATION
2723   /* FIXME - huh? */
2724 #else
2725   /* Otherwise, GDB can get confused, because in only knows
2726      about source for LINENO-1 lines.  */
2727   input_line -= 1;
2728 #endif
2729
2730   interface_unknown = 1;
2731   interface_only = 0;
2732
2733   /* We now have to write out all the stuff we put off writing out.
2734      These include:
2735
2736        o Template specializations that we have not yet instantiated,
2737          but which are needed.
2738        o Initialization and destruction for non-local objects with
2739          static storage duration.  (Local objects with static storage
2740          duration are initialized when their scope is first entered,
2741          and are cleaned up via atexit.)
2742        o Virtual function tables.  
2743
2744      All of these may cause others to be needed.  For example,
2745      instantiating one function may cause another to be needed, and
2746      generating the initializer for an object may cause templates to be
2747      instantiated, etc., etc.  */
2748
2749   timevar_push (TV_VARCONST);
2750
2751   emit_support_tinfos ();
2752
2753   do 
2754     {
2755       tree t;
2756       size_t n_old, n_new;
2757
2758       reconsider = false;
2759
2760       /* If there are templates that we've put off instantiating, do
2761          them now.  */
2762       instantiate_pending_templates ();
2763       ggc_collect ();
2764
2765       /* Write out virtual tables as required.  Note that writing out
2766          the virtual table for a template class may cause the
2767          instantiation of members of that class.  If we write out
2768          vtables then we remove the class from our list so we don't
2769          have to look at it again.  */
2770  
2771       while (keyed_classes != NULL_TREE
2772              && maybe_emit_vtables (TREE_VALUE (keyed_classes)))
2773         {
2774           reconsider = true;
2775           keyed_classes = TREE_CHAIN (keyed_classes);
2776         }
2777  
2778       t = keyed_classes;
2779       if (t != NULL_TREE)
2780         {
2781           tree next = TREE_CHAIN (t);
2782  
2783           while (next)
2784             {
2785               if (maybe_emit_vtables (TREE_VALUE (next)))
2786                 {
2787                   reconsider = true;
2788                   TREE_CHAIN (t) = TREE_CHAIN (next);
2789                 }
2790               else
2791                 t = next;
2792  
2793               next = TREE_CHAIN (t);
2794             }
2795         }
2796        
2797       /* Write out needed type info variables.  We have to be careful
2798          looping through unemitted decls, because emit_tinfo_decl may
2799          cause other variables to be needed.  We stick new elements
2800          (and old elements that we may need to reconsider) at the end
2801          of the array, then shift them back to the beginning once we're
2802          done.  */
2803   
2804       n_old = VARRAY_ACTIVE_SIZE (unemitted_tinfo_decls);
2805       for (i = 0; i < n_old; ++i)
2806         {
2807           tree tinfo_decl = VARRAY_TREE (unemitted_tinfo_decls, i);
2808           if (emit_tinfo_decl (tinfo_decl))
2809             reconsider = true;
2810           else
2811             VARRAY_PUSH_TREE (unemitted_tinfo_decls, tinfo_decl);
2812         }
2813   
2814       /* The only elements we want to keep are the new ones.  Copy
2815          them to the beginning of the array, then get rid of the
2816          leftovers.  */
2817       n_new = VARRAY_ACTIVE_SIZE (unemitted_tinfo_decls) - n_old;
2818       if (n_new)
2819         memmove (&VARRAY_TREE (unemitted_tinfo_decls, 0),
2820                  &VARRAY_TREE (unemitted_tinfo_decls, n_old),
2821                  n_new * sizeof (tree));
2822       memset (&VARRAY_TREE (unemitted_tinfo_decls, n_new),
2823               0, n_old * sizeof (tree));
2824       VARRAY_ACTIVE_SIZE (unemitted_tinfo_decls) = n_new;
2825
2826       /* The list of objects with static storage duration is built up
2827          in reverse order.  We clear STATIC_AGGREGATES so that any new
2828          aggregates added during the initialization of these will be
2829          initialized in the correct order when we next come around the
2830          loop.  */
2831       vars = prune_vars_needing_no_initialization (&static_aggregates);
2832
2833       if (vars)
2834         {
2835           tree v;
2836
2837           /* We need to start a new initialization function each time
2838              through the loop.  That's because we need to know which
2839              vtables have been referenced, and TREE_SYMBOL_REFERENCED
2840              isn't computed until a function is finished, and written
2841              out.  That's a deficiency in the back-end.  When this is
2842              fixed, these initialization functions could all become
2843              inline, with resulting performance improvements.  */
2844           tree ssdf_body;
2845
2846           /* Set the line and file, so that it is obviously not from
2847              the source file.  */
2848           input_location = locus;
2849           ssdf_body = start_static_storage_duration_function (ssdf_count);
2850
2851           /* Make sure the back end knows about all the variables.  */
2852           write_out_vars (vars);
2853
2854           /* First generate code to do all the initializations.  */
2855           for (v = vars; v; v = TREE_CHAIN (v))
2856             do_static_initialization (TREE_VALUE (v),
2857                                       TREE_PURPOSE (v));
2858
2859           /* Then, generate code to do all the destructions.  Do these
2860              in reverse order so that the most recently constructed
2861              variable is the first destroyed.  If we're using
2862              __cxa_atexit, then we don't need to do this; functions
2863              were registered at initialization time to destroy the
2864              local statics.  */
2865           if (!flag_use_cxa_atexit)
2866             {
2867               vars = nreverse (vars);
2868               for (v = vars; v; v = TREE_CHAIN (v))
2869                 do_static_destruction (TREE_VALUE (v));
2870             }
2871           else
2872             vars = NULL_TREE;
2873
2874           /* Finish up the static storage duration function for this
2875              round.  */
2876           input_location = locus;
2877           finish_static_storage_duration_function (ssdf_body);
2878
2879           /* All those initializations and finalizations might cause
2880              us to need more inline functions, more template
2881              instantiations, etc.  */
2882           reconsider = true;
2883           ssdf_count++;
2884 #ifdef USE_MAPPED_LOCATION
2885           /* ??? */
2886 #else
2887           locus.line++;
2888 #endif
2889         }
2890       
2891       /* Go through the set of inline functions whose bodies have not
2892          been emitted yet.  If out-of-line copies of these functions
2893          are required, emit them.  */
2894       for (i = 0; i < deferred_fns_used; ++i)
2895         {
2896           tree decl = VARRAY_TREE (deferred_fns, i);
2897
2898           /* Does it need synthesizing?  */
2899           if (DECL_ARTIFICIAL (decl) && ! DECL_INITIAL (decl)
2900               && (! DECL_REALLY_EXTERN (decl) || DECL_INLINE (decl)))
2901             {
2902               /* Even though we're already at the top-level, we push
2903                  there again.  That way, when we pop back a few lines
2904                  hence, all of our state is restored.  Otherwise,
2905                  finish_function doesn't clean things up, and we end
2906                  up with CURRENT_FUNCTION_DECL set.  */
2907               push_to_top_level ();
2908               synthesize_method (decl);
2909               pop_from_top_level ();
2910               reconsider = true;
2911             }
2912
2913           if (!DECL_SAVED_TREE (decl))
2914             continue;
2915
2916           import_export_decl (decl);
2917
2918           /* We lie to the back-end, pretending that some functions
2919              are not defined when they really are.  This keeps these
2920              functions from being put out unnecessarily.  But, we must
2921              stop lying when the functions are referenced, or if they
2922              are not comdat since they need to be put out now.  This
2923              is done in a separate for cycle, because if some deferred
2924              function is contained in another deferred function later
2925              in deferred_fns varray, rest_of_compilation would skip
2926              this function and we really cannot expand the same
2927              function twice.  */
2928           if (DECL_NOT_REALLY_EXTERN (decl)
2929               && DECL_INITIAL (decl)
2930               && decl_needed_p (decl))
2931             DECL_EXTERNAL (decl) = 0;
2932
2933           /* If we're going to need to write this function out, and
2934              there's already a body for it, create RTL for it now.
2935              (There might be no body if this is a method we haven't
2936              gotten around to synthesizing yet.)  */
2937           if (!DECL_EXTERNAL (decl)
2938               && decl_needed_p (decl)
2939               && !TREE_ASM_WRITTEN (decl)
2940               && !cgraph_node (decl)->local.finalized)
2941             {
2942               /* We will output the function; no longer consider it in this
2943                  loop.  */
2944               DECL_DEFER_OUTPUT (decl) = 0;
2945               /* Generate RTL for this function now that we know we
2946                  need it.  */
2947               expand_or_defer_fn (decl);
2948               /* If we're compiling -fsyntax-only pretend that this
2949                  function has been written out so that we don't try to
2950                  expand it again.  */
2951               if (flag_syntax_only)
2952                 TREE_ASM_WRITTEN (decl) = 1;
2953               reconsider = true;
2954             }
2955         }
2956
2957       if (walk_namespaces (wrapup_globals_for_namespace, /*data=*/0))
2958         reconsider = true;
2959
2960       /* Static data members are just like namespace-scope globals.  */
2961       for (i = 0; i < pending_statics_used; ++i) 
2962         {
2963           tree decl = VARRAY_TREE (pending_statics, i);
2964           if (var_finalized_p (decl) || DECL_REALLY_EXTERN (decl))
2965             continue;
2966           import_export_decl (decl);
2967           /* If this static data member is needed, provide it to the
2968              back end.  */
2969           if (DECL_NOT_REALLY_EXTERN (decl) && decl_needed_p (decl))
2970             DECL_EXTERNAL (decl) = 0;
2971         }
2972       if (pending_statics
2973           && wrapup_global_declarations (&VARRAY_TREE (pending_statics, 0),
2974                                          pending_statics_used))
2975         reconsider = true;
2976
2977       /* Ask the back end to emit functions and variables that are
2978          enqued.  These emissions may result in marking more entities
2979          as needed.  */
2980       if (cgraph_assemble_pending_functions ())
2981         reconsider = true;
2982       if (cgraph_varpool_assemble_pending_decls ())
2983         reconsider = true;
2984     } 
2985   while (reconsider);
2986
2987   /* All used inline functions must have a definition at this point.  */
2988   for (i = 0; i < deferred_fns_used; ++i)
2989     {
2990       tree decl = VARRAY_TREE (deferred_fns, i);
2991
2992       if (/* Check online inline functions that were actually used.  */
2993           TREE_USED (decl) && DECL_DECLARED_INLINE_P (decl)
2994           /* But not defined.  */
2995           && DECL_REALLY_EXTERN (decl)
2996           /* If we decided to emit this function in another
2997              translation unit, the fact that the definition was
2998              missing here likely indicates only that the repository
2999              decided to place the function elsewhere.  With -Winline,
3000              we will still warn if we could not inline the
3001              function.  */
3002           && !flag_use_repository
3003           /* An explicit instantiation can be used to specify
3004              that the body is in another unit. It will have
3005              already verified there was a definition.  */
3006           && !DECL_EXPLICIT_INSTANTIATION (decl))
3007         {
3008           cp_warning_at ("inline function `%D' used but never defined", decl);
3009           /* This symbol is effectively an "extern" declaration now.
3010              This is not strictly necessary, but removes a duplicate
3011              warning.  */
3012           TREE_PUBLIC (decl) = 1;
3013         }
3014     }
3015   
3016   /* We give C linkage to static constructors and destructors.  */
3017   push_lang_context (lang_name_c);
3018
3019   /* Generate initialization and destruction functions for all
3020      priorities for which they are required.  */
3021   if (priority_info_map)
3022     splay_tree_foreach (priority_info_map, 
3023                         generate_ctor_and_dtor_functions_for_priority,
3024                         /*data=*/&locus);
3025   else
3026     {
3027       
3028       if (static_ctors)
3029         generate_ctor_or_dtor_function (/*constructor_p=*/true,
3030                                         DEFAULT_INIT_PRIORITY, &locus);
3031       if (static_dtors)
3032         generate_ctor_or_dtor_function (/*constructor_p=*/false,
3033                                         DEFAULT_INIT_PRIORITY, &locus);
3034     }
3035
3036   /* We're done with the splay-tree now.  */
3037   if (priority_info_map)
3038     splay_tree_delete (priority_info_map);
3039
3040   /* We're done with static constructors, so we can go back to "C++"
3041      linkage now.  */
3042   pop_lang_context ();
3043
3044   cgraph_finalize_compilation_unit ();
3045   cgraph_optimize ();
3046
3047   /* Emit mudflap static registration function.  This must be done
3048      after all the user functions have been expanded.  */
3049   if (flag_mudflap)
3050     mudflap_finish_file ();
3051
3052   /* Now, issue warnings about static, but not defined, functions,
3053      etc., and emit debugging information.  */
3054   walk_namespaces (wrapup_globals_for_namespace, /*data=*/&reconsider);
3055   if (pending_statics)
3056     check_global_declarations (&VARRAY_TREE (pending_statics, 0),
3057                                pending_statics_used);
3058
3059   finish_repo ();
3060
3061   /* The entire file is now complete.  If requested, dump everything
3062      to a file.  */
3063   {
3064     int flags;
3065     FILE *stream = dump_begin (TDI_tu, &flags);
3066
3067     if (stream)
3068       {
3069         dump_node (global_namespace, flags & ~TDF_SLIM, stream);
3070         dump_end (TDI_tu, stream);
3071       }
3072   }
3073   
3074   timevar_pop (TV_VARCONST);
3075
3076   if (flag_detailed_statistics)
3077     {
3078       dump_tree_statistics ();
3079       dump_time_statistics ();
3080     }
3081   input_location = locus;
3082
3083 #ifdef ENABLE_CHECKING
3084   validate_conversion_obstack ();
3085 #endif /* ENABLE_CHECKING */
3086 }
3087
3088 /* FN is an OFFSET_REF, DOTSTAR_EXPR or MEMBER_REF indicating the
3089    function to call in parse-tree form; it has not yet been
3090    semantically analyzed.  ARGS are the arguments to the function.
3091    They have already been semantically analyzed.  */
3092
3093 tree
3094 build_offset_ref_call_from_tree (tree fn, tree args)
3095 {
3096   tree orig_fn;
3097   tree orig_args;
3098   tree expr;
3099   tree object;
3100
3101   orig_fn = fn;
3102   orig_args = args;
3103   object = TREE_OPERAND (fn, 0);
3104
3105   if (processing_template_decl)
3106     {
3107       my_friendly_assert (TREE_CODE (fn) == DOTSTAR_EXPR
3108                           || TREE_CODE (fn) == MEMBER_REF,
3109                           20030708);
3110       if (type_dependent_expression_p (fn)
3111           || any_type_dependent_arguments_p (args))
3112         return build_min_nt (CALL_EXPR, fn, args, NULL_TREE);
3113
3114       /* Transform the arguments and add the implicit "this"
3115          parameter.  That must be done before the FN is transformed
3116          because we depend on the form of FN.  */
3117       args = build_non_dependent_args (args);
3118       if (TREE_CODE (fn) == DOTSTAR_EXPR)
3119         object = build_unary_op (ADDR_EXPR, object, 0);
3120       object = build_non_dependent_expr (object);
3121       args = tree_cons (NULL_TREE, object, args);
3122       /* Now that the arguments are done, transform FN.  */
3123       fn = build_non_dependent_expr (fn);
3124     }
3125
3126   /* A qualified name corresponding to a bound pointer-to-member is
3127      represented as an OFFSET_REF:
3128
3129         struct B { void g(); };
3130         void (B::*p)();
3131         void B::g() { (this->*p)(); }  */
3132   if (TREE_CODE (fn) == OFFSET_REF)
3133     {
3134       tree object_addr = build_unary_op (ADDR_EXPR, object, 0);
3135       fn = TREE_OPERAND (fn, 1);
3136       fn = get_member_function_from_ptrfunc (&object_addr, fn);
3137       args = tree_cons (NULL_TREE, object_addr, args);
3138     }
3139
3140   expr = build_function_call (fn, args);
3141   if (processing_template_decl && expr != error_mark_node)
3142     return build_min_non_dep (CALL_EXPR, expr, orig_fn, orig_args, NULL_TREE);
3143   return expr;
3144 }
3145   
3146
3147 void
3148 check_default_args (tree x)
3149 {
3150   tree arg = TYPE_ARG_TYPES (TREE_TYPE (x));
3151   bool saw_def = false;
3152   int i = 0 - (TREE_CODE (TREE_TYPE (x)) == METHOD_TYPE);
3153   for (; arg && arg != void_list_node; arg = TREE_CHAIN (arg), ++i)
3154     {
3155       if (TREE_PURPOSE (arg))
3156         saw_def = true;
3157       else if (saw_def)
3158         {
3159           cp_error_at ("default argument missing for parameter %P of `%+#D'",
3160                        i, x);
3161           break;
3162         }
3163     }
3164 }
3165
3166 void
3167 mark_used (tree decl)
3168 {
3169   TREE_USED (decl) = 1;
3170   if (processing_template_decl || skip_evaluation)
3171     return;
3172
3173   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_DECLARED_INLINE_P (decl)
3174       && !TREE_ASM_WRITTEN (decl))
3175     /* Remember it, so we can check it was defined.  */
3176     {
3177       if (DECL_DEFERRED_FN (decl))
3178         return;
3179       note_vague_linkage_fn (decl);
3180     }
3181   
3182   assemble_external (decl);
3183
3184   /* Is it a synthesized method that needs to be synthesized?  */
3185   if (TREE_CODE (decl) == FUNCTION_DECL
3186       && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl)
3187       && DECL_ARTIFICIAL (decl) 
3188       && !DECL_THUNK_P (decl)
3189       && ! DECL_INITIAL (decl)
3190       /* Kludge: don't synthesize for default args.  */
3191       && current_function_decl)
3192     {
3193       synthesize_method (decl);
3194       /* If we've already synthesized the method we don't need to
3195          instantiate it, so we can return right away.  */
3196       return;
3197     }
3198
3199   /* If this is a function or variable that is an instance of some
3200      template, we now know that we will need to actually do the
3201      instantiation. We check that DECL is not an explicit
3202      instantiation because that is not checked in instantiate_decl.  */
3203   if ((DECL_NON_THUNK_FUNCTION_P (decl) || TREE_CODE (decl) == VAR_DECL)
3204       && DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
3205       && (!DECL_EXPLICIT_INSTANTIATION (decl)
3206           || (TREE_CODE (decl) == FUNCTION_DECL 
3207               && DECL_INLINE (DECL_TEMPLATE_RESULT 
3208                               (template_for_substitution (decl))))))
3209     /* We put off instantiating functions in order to improve compile
3210        times.  Maintaining a stack of active functions is expensive,
3211        and the inliner knows to instantiate any functions it might
3212        need.  */
3213     instantiate_decl (decl, /*defer_ok=*/true, /*undefined_ok=*/0);
3214 }
3215
3216 #include "gt-cp-decl2.h"