OSDN Git Service

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