OSDN Git Service

PR c++/25811
[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, 2007, 2008, 2009
4    Free Software Foundation, Inc.
5    Hacked by Michael Tiemann (tiemann@cygnus.com)
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3, or (at your option)
12 any later version.
13
14 GCC is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.  */
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 #include "gimple.h"
55 #include "pointer-set.h"
56
57 extern cpp_reader *parse_in;
58
59 /* This structure contains information about the initializations
60    and/or destructions required for a particular priority level.  */
61 typedef struct priority_info_s {
62   /* Nonzero if there have been any initializations at this priority
63      throughout the translation unit.  */
64   int initializations_p;
65   /* Nonzero if there have been any destructions at this priority
66      throughout the translation unit.  */
67   int destructions_p;
68 } *priority_info;
69
70 static void mark_vtable_entries (tree);
71 static bool maybe_emit_vtables (tree);
72 static bool acceptable_java_type (tree);
73 static tree start_objects (int, int);
74 static void finish_objects (int, int, tree);
75 static tree start_static_storage_duration_function (unsigned);
76 static void finish_static_storage_duration_function (tree);
77 static priority_info get_priority_info (int);
78 static void do_static_initialization_or_destruction (tree, bool);
79 static void one_static_initialization_or_destruction (tree, tree, bool);
80 static void generate_ctor_or_dtor_function (bool, int, location_t *);
81 static int generate_ctor_and_dtor_functions_for_priority (splay_tree_node,
82                                                           void *);
83 static tree prune_vars_needing_no_initialization (tree *);
84 static void write_out_vars (tree);
85 static void import_export_class (tree);
86 static tree get_guard_bits (tree);
87 static void determine_visibility_from_class (tree, tree);
88 static bool decl_defined_p (tree);
89
90 /* A list of static class variables.  This is needed, because a
91    static class variable can be declared inside the class without
92    an initializer, and then initialized, statically, outside the class.  */
93 static GTY(()) VEC(tree,gc) *pending_statics;
94
95 /* A list of functions which were declared inline, but which we
96    may need to emit outline anyway.  */
97 static GTY(()) VEC(tree,gc) *deferred_fns;
98
99 /* A list of decls that use types with no linkage, which we need to make
100    sure are defined.  */
101 static GTY(()) VEC(tree,gc) *no_linkage_decls;
102
103 /* Nonzero if we're done parsing and into end-of-file activities.  */
104
105 int at_eof;
106
107 \f
108
109 /* Return a member function type (a METHOD_TYPE), given FNTYPE (a
110    FUNCTION_TYPE), CTYPE (class type), and QUALS (the cv-qualifiers
111    that apply to the function).  */
112
113 tree
114 build_memfn_type (tree fntype, tree ctype, cp_cv_quals quals)
115 {
116   tree raises;
117   tree attrs;
118   int type_quals;
119
120   if (fntype == error_mark_node || ctype == error_mark_node)
121     return error_mark_node;
122
123   gcc_assert (TREE_CODE (fntype) == FUNCTION_TYPE
124               || TREE_CODE (fntype) == METHOD_TYPE);
125
126   type_quals = quals & ~TYPE_QUAL_RESTRICT;
127   ctype = cp_build_qualified_type (ctype, type_quals);
128   raises = TYPE_RAISES_EXCEPTIONS (fntype);
129   attrs = TYPE_ATTRIBUTES (fntype);
130   fntype = build_method_type_directly (ctype, TREE_TYPE (fntype),
131                                        (TREE_CODE (fntype) == METHOD_TYPE
132                                         ? TREE_CHAIN (TYPE_ARG_TYPES (fntype))
133                                         : TYPE_ARG_TYPES (fntype)));
134   if (raises)
135     fntype = build_exception_variant (fntype, raises);
136   if (attrs)
137     fntype = cp_build_type_attribute_variant (fntype, attrs);
138
139   return fntype;
140 }
141
142 /* Return a variant of FNTYPE, a FUNCTION_TYPE or METHOD_TYPE, with its
143    return type changed to NEW_RET.  */
144
145 tree
146 change_return_type (tree new_ret, tree fntype)
147 {
148   tree newtype;
149   tree args = TYPE_ARG_TYPES (fntype);
150   tree raises = TYPE_RAISES_EXCEPTIONS (fntype);
151   tree attrs = TYPE_ATTRIBUTES (fntype);
152
153   if (same_type_p (new_ret, TREE_TYPE (fntype)))
154     return fntype;
155
156   if (TREE_CODE (fntype) == FUNCTION_TYPE)
157     newtype = build_function_type (new_ret, args);
158   else
159     newtype = build_method_type_directly
160       (TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (fntype))),
161        new_ret, TREE_CHAIN (args));
162   if (raises)
163     newtype = build_exception_variant (newtype, raises);
164   if (attrs)
165     newtype = cp_build_type_attribute_variant (newtype, attrs);
166
167   return newtype;
168 }
169
170 /* Build a PARM_DECL with NAME and TYPE, and set DECL_ARG_TYPE
171    appropriately.  */
172
173 tree
174 cp_build_parm_decl (tree name, tree type)
175 {
176   tree parm = build_decl (input_location,
177                           PARM_DECL, name, type);
178   /* DECL_ARG_TYPE is only used by the back end and the back end never
179      sees templates.  */
180   if (!processing_template_decl)
181     DECL_ARG_TYPE (parm) = type_passed_as (type);
182
183   /* If the type is a pack expansion, then we have a function
184      parameter pack. */
185   if (type && TREE_CODE (type) == TYPE_PACK_EXPANSION)
186     FUNCTION_PARAMETER_PACK_P (parm) = 1;
187
188   return parm;
189 }
190
191 /* Returns a PARM_DECL for a parameter of the indicated TYPE, with the
192    indicated NAME.  */
193
194 tree
195 build_artificial_parm (tree name, tree type)
196 {
197   tree parm = cp_build_parm_decl (name, type);
198   DECL_ARTIFICIAL (parm) = 1;
199   /* All our artificial parms are implicitly `const'; they cannot be
200      assigned to.  */
201   TREE_READONLY (parm) = 1;
202   return parm;
203 }
204
205 /* Constructors for types with virtual baseclasses need an "in-charge" flag
206    saying whether this constructor is responsible for initialization of
207    virtual baseclasses or not.  All destructors also need this "in-charge"
208    flag, which additionally determines whether or not the destructor should
209    free the memory for the object.
210
211    This function adds the "in-charge" flag to member function FN if
212    appropriate.  It is called from grokclassfn and tsubst.
213    FN must be either a constructor or destructor.
214
215    The in-charge flag follows the 'this' parameter, and is followed by the
216    VTT parm (if any), then the user-written parms.  */
217
218 void
219 maybe_retrofit_in_chrg (tree fn)
220 {
221   tree basetype, arg_types, parms, parm, fntype;
222
223   /* If we've already add the in-charge parameter don't do it again.  */
224   if (DECL_HAS_IN_CHARGE_PARM_P (fn))
225     return;
226
227   /* When processing templates we can't know, in general, whether or
228      not we're going to have virtual baseclasses.  */
229   if (processing_template_decl)
230     return;
231
232   /* We don't need an in-charge parameter for constructors that don't
233      have virtual bases.  */
234   if (DECL_CONSTRUCTOR_P (fn)
235       && !CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fn)))
236     return;
237
238   arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
239   basetype = TREE_TYPE (TREE_VALUE (arg_types));
240   arg_types = TREE_CHAIN (arg_types);
241
242   parms = TREE_CHAIN (DECL_ARGUMENTS (fn));
243
244   /* If this is a subobject constructor or destructor, our caller will
245      pass us a pointer to our VTT.  */
246   if (CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fn)))
247     {
248       parm = build_artificial_parm (vtt_parm_identifier, vtt_parm_type);
249
250       /* First add it to DECL_ARGUMENTS between 'this' and the real args...  */
251       TREE_CHAIN (parm) = parms;
252       parms = parm;
253
254       /* ...and then to TYPE_ARG_TYPES.  */
255       arg_types = hash_tree_chain (vtt_parm_type, arg_types);
256
257       DECL_HAS_VTT_PARM_P (fn) = 1;
258     }
259
260   /* Then add the in-charge parm (before the VTT parm).  */
261   parm = build_artificial_parm (in_charge_identifier, integer_type_node);
262   TREE_CHAIN (parm) = parms;
263   parms = parm;
264   arg_types = hash_tree_chain (integer_type_node, arg_types);
265
266   /* Insert our new parameter(s) into the list.  */
267   TREE_CHAIN (DECL_ARGUMENTS (fn)) = parms;
268
269   /* And rebuild the function type.  */
270   fntype = build_method_type_directly (basetype, TREE_TYPE (TREE_TYPE (fn)),
271                                        arg_types);
272   if (TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn)))
273     fntype = build_exception_variant (fntype,
274                                       TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn)));
275   if (TYPE_ATTRIBUTES (TREE_TYPE (fn)))
276     fntype = (cp_build_type_attribute_variant
277               (fntype, TYPE_ATTRIBUTES (TREE_TYPE (fn))));
278   TREE_TYPE (fn) = fntype;
279
280   /* Now we've got the in-charge parameter.  */
281   DECL_HAS_IN_CHARGE_PARM_P (fn) = 1;
282 }
283
284 /* Classes overload their constituent function names automatically.
285    When a function name is declared in a record structure,
286    its name is changed to it overloaded name.  Since names for
287    constructors and destructors can conflict, we place a leading
288    '$' for destructors.
289
290    CNAME is the name of the class we are grokking for.
291
292    FUNCTION is a FUNCTION_DECL.  It was created by `grokdeclarator'.
293
294    FLAGS contains bits saying what's special about today's
295    arguments.  DTOR_FLAG == DESTRUCTOR.
296
297    If FUNCTION is a destructor, then we must add the `auto-delete' field
298    as a second parameter.  There is some hair associated with the fact
299    that we must "declare" this variable in the manner consistent with the
300    way the rest of the arguments were declared.
301
302    QUALS are the qualifiers for the this pointer.  */
303
304 void
305 grokclassfn (tree ctype, tree function, enum overload_flags flags)
306 {
307   tree fn_name = DECL_NAME (function);
308
309   /* Even within an `extern "C"' block, members get C++ linkage.  See
310      [dcl.link] for details.  */
311   SET_DECL_LANGUAGE (function, lang_cplusplus);
312
313   if (fn_name == NULL_TREE)
314     {
315       error ("name missing for member function");
316       fn_name = get_identifier ("<anonymous>");
317       DECL_NAME (function) = fn_name;
318     }
319
320   DECL_CONTEXT (function) = ctype;
321
322   if (flags == DTOR_FLAG)
323     DECL_DESTRUCTOR_P (function) = 1;
324
325   if (flags == DTOR_FLAG || DECL_CONSTRUCTOR_P (function))
326     maybe_retrofit_in_chrg (function);
327 }
328
329 /* Create an ARRAY_REF, checking for the user doing things backwards
330    along the way.  */
331
332 tree
333 grok_array_decl (tree array_expr, tree index_exp)
334 {
335   tree type;
336   tree expr;
337   tree orig_array_expr = array_expr;
338   tree orig_index_exp = index_exp;
339
340   if (error_operand_p (array_expr) || error_operand_p (index_exp))
341     return error_mark_node;
342
343   if (processing_template_decl)
344     {
345       if (type_dependent_expression_p (array_expr)
346           || type_dependent_expression_p (index_exp))
347         return build_min_nt (ARRAY_REF, array_expr, index_exp,
348                              NULL_TREE, NULL_TREE);
349       array_expr = build_non_dependent_expr (array_expr);
350       index_exp = build_non_dependent_expr (index_exp);
351     }
352
353   type = TREE_TYPE (array_expr);
354   gcc_assert (type);
355   type = non_reference (type);
356
357   /* If they have an `operator[]', use that.  */
358   if (MAYBE_CLASS_TYPE_P (type) || MAYBE_CLASS_TYPE_P (TREE_TYPE (index_exp)))
359     expr = build_new_op (ARRAY_REF, LOOKUP_NORMAL,
360                          array_expr, index_exp, NULL_TREE,
361                          /*overloaded_p=*/NULL, tf_warning_or_error);
362   else
363     {
364       tree p1, p2, i1, i2;
365
366       /* Otherwise, create an ARRAY_REF for a pointer or array type.
367          It is a little-known fact that, if `a' is an array and `i' is
368          an int, you can write `i[a]', which means the same thing as
369          `a[i]'.  */
370       if (TREE_CODE (type) == ARRAY_TYPE)
371         p1 = array_expr;
372       else
373         p1 = build_expr_type_conversion (WANT_POINTER, array_expr, false);
374
375       if (TREE_CODE (TREE_TYPE (index_exp)) == ARRAY_TYPE)
376         p2 = index_exp;
377       else
378         p2 = build_expr_type_conversion (WANT_POINTER, index_exp, false);
379
380       i1 = build_expr_type_conversion (WANT_INT | WANT_ENUM, array_expr,
381                                        false);
382       i2 = build_expr_type_conversion (WANT_INT | WANT_ENUM, index_exp,
383                                        false);
384
385       if ((p1 && i2) && (i1 && p2))
386         error ("ambiguous conversion for array subscript");
387
388       if (p1 && i2)
389         array_expr = p1, index_exp = i2;
390       else if (i1 && p2)
391         array_expr = p2, index_exp = i1;
392       else
393         {
394           error ("invalid types %<%T[%T]%> for array subscript",
395                  type, TREE_TYPE (index_exp));
396           return error_mark_node;
397         }
398
399       if (array_expr == error_mark_node || index_exp == error_mark_node)
400         error ("ambiguous conversion for array subscript");
401
402       expr = build_array_ref (input_location, array_expr, index_exp);
403     }
404   if (processing_template_decl && expr != error_mark_node)
405     return build_min_non_dep (ARRAY_REF, expr, orig_array_expr, orig_index_exp,
406                               NULL_TREE, NULL_TREE);
407   return expr;
408 }
409
410 /* Given the cast expression EXP, checking out its validity.   Either return
411    an error_mark_node if there was an unavoidable error, return a cast to
412    void for trying to delete a pointer w/ the value 0, or return the
413    call to delete.  If DOING_VEC is true, we handle things differently
414    for doing an array delete.
415    Implements ARM $5.3.4.  This is called from the parser.  */
416
417 tree
418 delete_sanity (tree exp, tree size, bool doing_vec, int use_global_delete)
419 {
420   tree t, type;
421
422   if (exp == error_mark_node)
423     return exp;
424
425   if (processing_template_decl)
426     {
427       t = build_min (DELETE_EXPR, void_type_node, exp, size);
428       DELETE_EXPR_USE_GLOBAL (t) = use_global_delete;
429       DELETE_EXPR_USE_VEC (t) = doing_vec;
430       TREE_SIDE_EFFECTS (t) = 1;
431       return t;
432     }
433
434   /* An array can't have been allocated by new, so complain.  */
435   if (TREE_CODE (exp) == VAR_DECL
436       && TREE_CODE (TREE_TYPE (exp)) == ARRAY_TYPE)
437     warning (0, "deleting array %q#D", exp);
438
439   t = build_expr_type_conversion (WANT_POINTER, exp, true);
440
441   if (t == NULL_TREE || t == error_mark_node)
442     {
443       error ("type %q#T argument given to %<delete%>, expected pointer",
444              TREE_TYPE (exp));
445       return error_mark_node;
446     }
447
448   type = TREE_TYPE (t);
449
450   /* As of Valley Forge, you can delete a pointer to const.  */
451
452   /* You can't delete functions.  */
453   if (TREE_CODE (TREE_TYPE (type)) == FUNCTION_TYPE)
454     {
455       error ("cannot delete a function.  Only pointer-to-objects are "
456              "valid arguments to %<delete%>");
457       return error_mark_node;
458     }
459
460   /* Deleting ptr to void is undefined behavior [expr.delete/3].  */
461   if (TREE_CODE (TREE_TYPE (type)) == VOID_TYPE)
462     {
463       warning (0, "deleting %qT is undefined", type);
464       doing_vec = 0;
465     }
466
467   /* Deleting a pointer with the value zero is valid and has no effect.  */
468   if (integer_zerop (t))
469     return build1 (NOP_EXPR, void_type_node, t);
470
471   if (doing_vec)
472     return build_vec_delete (t, /*maxindex=*/NULL_TREE,
473                              sfk_deleting_destructor,
474                              use_global_delete);
475   else
476     return build_delete (type, t, sfk_deleting_destructor,
477                          LOOKUP_NORMAL, use_global_delete);
478 }
479
480 /* Report an error if the indicated template declaration is not the
481    sort of thing that should be a member template.  */
482
483 void
484 check_member_template (tree tmpl)
485 {
486   tree decl;
487
488   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
489   decl = DECL_TEMPLATE_RESULT (tmpl);
490
491   if (TREE_CODE (decl) == FUNCTION_DECL
492       || (TREE_CODE (decl) == TYPE_DECL
493           && MAYBE_CLASS_TYPE_P (TREE_TYPE (decl))))
494     {
495       /* The parser rejects template declarations in local classes.  */
496       gcc_assert (!current_function_decl);
497       /* The parser rejects any use of virtual in a function template.  */
498       gcc_assert (!(TREE_CODE (decl) == FUNCTION_DECL
499                     && DECL_VIRTUAL_P (decl)));
500
501       /* The debug-information generating code doesn't know what to do
502          with member templates.  */
503       DECL_IGNORED_P (tmpl) = 1;
504     }
505   else
506     error ("template declaration of %q#D", decl);
507 }
508
509 /* Return true iff TYPE is a valid Java parameter or return type.  */
510
511 static bool
512 acceptable_java_type (tree type)
513 {
514   if (type == error_mark_node)
515     return false;
516
517   if (TREE_CODE (type) == VOID_TYPE || TYPE_FOR_JAVA (type))
518     return true;
519   if (TREE_CODE (type) == POINTER_TYPE || TREE_CODE (type) == REFERENCE_TYPE)
520     {
521       type = TREE_TYPE (type);
522       if (TREE_CODE (type) == RECORD_TYPE)
523         {
524           tree args;  int i;
525           if (! TYPE_FOR_JAVA (type))
526             return false;
527           if (! CLASSTYPE_TEMPLATE_INFO (type))
528             return true;
529           args = CLASSTYPE_TI_ARGS (type);
530           i = TREE_VEC_LENGTH (args);
531           while (--i >= 0)
532             {
533               type = TREE_VEC_ELT (args, i);
534               if (TREE_CODE (type) == POINTER_TYPE)
535                 type = TREE_TYPE (type);
536               if (! TYPE_FOR_JAVA (type))
537                 return false;
538             }
539           return true;
540         }
541     }
542   return false;
543 }
544
545 /* For a METHOD in a Java class CTYPE, return true if
546    the parameter and return types are valid Java types.
547    Otherwise, print appropriate error messages, and return false.  */
548
549 bool
550 check_java_method (tree method)
551 {
552   bool jerr = false;
553   tree arg_types = TYPE_ARG_TYPES (TREE_TYPE (method));
554   tree ret_type = TREE_TYPE (TREE_TYPE (method));
555
556   if (!acceptable_java_type (ret_type))
557     {
558       error ("Java method %qD has non-Java return type %qT",
559              method, ret_type);
560       jerr = true;
561     }
562
563   arg_types = TREE_CHAIN (arg_types);
564   if (DECL_HAS_IN_CHARGE_PARM_P (method))
565     arg_types = TREE_CHAIN (arg_types);
566   if (DECL_HAS_VTT_PARM_P (method))
567     arg_types = TREE_CHAIN (arg_types);
568
569   for (; arg_types != NULL_TREE; arg_types = TREE_CHAIN (arg_types))
570     {
571       tree type = TREE_VALUE (arg_types);
572       if (!acceptable_java_type (type))
573         {
574           if (type != error_mark_node)
575             error ("Java method %qD has non-Java parameter type %qT",
576                    method, type);
577           jerr = true;
578         }
579     }
580   return !jerr;
581 }
582
583 /* Sanity check: report error if this function FUNCTION is not
584    really a member of the class (CTYPE) it is supposed to belong to.
585    TEMPLATE_PARMS is used to specify the template parameters of a member
586    template passed as FUNCTION_DECL. If the member template is passed as a
587    TEMPLATE_DECL, it can be NULL since the parameters can be extracted
588    from the declaration. If the function is not a function template, it
589    must be NULL.
590    It returns the original declaration for the function, NULL_TREE if
591    no declaration was found, error_mark_node if an error was emitted.  */
592
593 tree
594 check_classfn (tree ctype, tree function, tree template_parms)
595 {
596   int ix;
597   bool is_template;
598   tree pushed_scope;
599   
600   if (DECL_USE_TEMPLATE (function)
601       && !(TREE_CODE (function) == TEMPLATE_DECL
602            && DECL_TEMPLATE_SPECIALIZATION (function))
603       && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (function)))
604     /* Since this is a specialization of a member template,
605        we're not going to find the declaration in the class.
606        For example, in:
607
608          struct S { template <typename T> void f(T); };
609          template <> void S::f(int);
610
611        we're not going to find `S::f(int)', but there's no
612        reason we should, either.  We let our callers know we didn't
613        find the method, but we don't complain.  */
614     return NULL_TREE;
615
616   /* Basic sanity check: for a template function, the template parameters
617      either were not passed, or they are the same of DECL_TEMPLATE_PARMS.  */
618   if (TREE_CODE (function) == TEMPLATE_DECL)
619     {
620       if (template_parms
621           && !comp_template_parms (template_parms,
622                                    DECL_TEMPLATE_PARMS (function)))
623         {
624           error ("template parameter lists provided don't match the "
625                  "template parameters of %qD", function);
626           return error_mark_node;
627         }
628       template_parms = DECL_TEMPLATE_PARMS (function);
629     }
630
631   /* OK, is this a definition of a member template?  */
632   is_template = (template_parms != NULL_TREE);
633
634   /* We must enter the scope here, because conversion operators are
635      named by target type, and type equivalence relies on typenames
636      resolving within the scope of CTYPE.  */
637   pushed_scope = push_scope (ctype);
638   ix = class_method_index_for_fn (complete_type (ctype), function);
639   if (ix >= 0)
640     {
641       VEC(tree,gc) *methods = CLASSTYPE_METHOD_VEC (ctype);
642       tree fndecls, fndecl = 0;
643       bool is_conv_op;
644       const char *format = NULL;
645
646       for (fndecls = VEC_index (tree, methods, ix);
647            fndecls; fndecls = OVL_NEXT (fndecls))
648         {
649           tree p1, p2;
650
651           fndecl = OVL_CURRENT (fndecls);
652           p1 = TYPE_ARG_TYPES (TREE_TYPE (function));
653           p2 = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
654
655           /* We cannot simply call decls_match because this doesn't
656              work for static member functions that are pretending to
657              be methods, and because the name may have been changed by
658              asm("new_name").  */
659
660            /* Get rid of the this parameter on functions that become
661               static.  */
662           if (DECL_STATIC_FUNCTION_P (fndecl)
663               && TREE_CODE (TREE_TYPE (function)) == METHOD_TYPE)
664             p1 = TREE_CHAIN (p1);
665
666           /* A member template definition only matches a member template
667              declaration.  */
668           if (is_template != (TREE_CODE (fndecl) == TEMPLATE_DECL))
669             continue;
670
671           if (same_type_p (TREE_TYPE (TREE_TYPE (function)),
672                            TREE_TYPE (TREE_TYPE (fndecl)))
673               && compparms (p1, p2)
674               && (!is_template
675                   || comp_template_parms (template_parms,
676                                           DECL_TEMPLATE_PARMS (fndecl)))
677               && (DECL_TEMPLATE_SPECIALIZATION (function)
678                   == DECL_TEMPLATE_SPECIALIZATION (fndecl))
679               && (!DECL_TEMPLATE_SPECIALIZATION (function)
680                   || (DECL_TI_TEMPLATE (function)
681                       == DECL_TI_TEMPLATE (fndecl))))
682             break;
683         }
684       if (fndecls)
685         {
686           if (pushed_scope)
687             pop_scope (pushed_scope);
688           return OVL_CURRENT (fndecls);
689         }
690       
691       error_at (DECL_SOURCE_LOCATION (function),
692                 "prototype for %q#D does not match any in class %qT",
693                 function, ctype);
694       is_conv_op = DECL_CONV_FN_P (fndecl);
695
696       if (is_conv_op)
697         ix = CLASSTYPE_FIRST_CONVERSION_SLOT;
698       fndecls = VEC_index (tree, methods, ix);
699       while (fndecls)
700         {
701           fndecl = OVL_CURRENT (fndecls);
702           fndecls = OVL_NEXT (fndecls);
703
704           if (!fndecls && is_conv_op)
705             {
706               if (VEC_length (tree, methods) > (size_t) ++ix)
707                 {
708                   fndecls = VEC_index (tree, methods, ix);
709                   if (!DECL_CONV_FN_P (OVL_CURRENT (fndecls)))
710                     {
711                       fndecls = NULL_TREE;
712                       is_conv_op = false;
713                     }
714                 }
715               else
716                 is_conv_op = false;
717             }
718           if (format)
719             format = "                %+#D";
720           else if (fndecls)
721             format = N_("candidates are: %+#D");
722           else
723             format = N_("candidate is: %+#D");
724           error (format, fndecl);
725         }
726     }
727   else if (!COMPLETE_TYPE_P (ctype))
728     cxx_incomplete_type_error (function, ctype);
729   else
730     error ("no %q#D member function declared in class %qT",
731            function, ctype);
732
733   if (pushed_scope)
734     pop_scope (pushed_scope);
735   return error_mark_node;
736 }
737
738 /* DECL is a function with vague linkage.  Remember it so that at the
739    end of the translation unit we can decide whether or not to emit
740    it.  */
741
742 void
743 note_vague_linkage_fn (tree decl)
744 {
745   DECL_DEFER_OUTPUT (decl) = 1;
746   VEC_safe_push (tree, gc, deferred_fns, decl);
747 }
748
749 /* We have just processed the DECL, which is a static data member.
750    The other parameters are as for cp_finish_decl.  */
751
752 void
753 finish_static_data_member_decl (tree decl,
754                                 tree init, bool init_const_expr_p,
755                                 tree asmspec_tree,
756                                 int flags)
757 {
758   DECL_CONTEXT (decl) = current_class_type;
759
760   /* We cannot call pushdecl here, because that would fill in the
761      TREE_CHAIN of our decl.  Instead, we modify cp_finish_decl to do
762      the right thing, namely, to put this decl out straight away.  */
763
764   if (! processing_template_decl)
765     VEC_safe_push (tree, gc, pending_statics, decl);
766
767   if (LOCAL_CLASS_P (current_class_type))
768     permerror (input_location, "local class %q#T shall not have static data member %q#D",
769                current_class_type, decl);
770
771   /* Static consts need not be initialized in the class definition.  */
772   if (init != NULL_TREE && TYPE_NEEDS_CONSTRUCTING (TREE_TYPE (decl)))
773     {
774       static int explained = 0;
775
776       error ("initializer invalid for static member with constructor");
777       if (!explained)
778         {
779           error ("(an out of class initialization is required)");
780           explained = 1;
781         }
782       init = NULL_TREE;
783     }
784
785   DECL_INITIAL (decl) = init;
786   DECL_IN_AGGR_P (decl) = 1;
787
788   if (TREE_CODE (TREE_TYPE (decl)) == ARRAY_TYPE
789       && TYPE_DOMAIN (TREE_TYPE (decl)) == NULL_TREE)
790     SET_VAR_HAD_UNKNOWN_BOUND (decl);
791
792   cp_finish_decl (decl, init, init_const_expr_p, asmspec_tree, flags);
793 }
794
795 /* DECLARATOR and DECLSPECS correspond to a class member.  The other
796    parameters are as for cp_finish_decl.  Return the DECL for the
797    class member declared.  */
798
799 tree
800 grokfield (const cp_declarator *declarator,
801            cp_decl_specifier_seq *declspecs,
802            tree init, bool init_const_expr_p,
803            tree asmspec_tree,
804            tree attrlist)
805 {
806   tree value;
807   const char *asmspec = 0;
808   int flags = LOOKUP_ONLYCONVERTING;
809   tree name;
810
811   if (init
812       && TREE_CODE (init) == TREE_LIST
813       && TREE_VALUE (init) == error_mark_node
814       && TREE_CHAIN (init) == NULL_TREE)
815     init = NULL_TREE;
816
817   value = grokdeclarator (declarator, declspecs, FIELD, init != 0, &attrlist);
818   if (! value || error_operand_p (value))
819     /* friend or constructor went bad.  */
820     return error_mark_node;
821
822   if (TREE_CODE (value) == TYPE_DECL && init)
823     {
824       error ("typedef %qD is initialized (use decltype instead)", value);
825       init = NULL_TREE;
826     }
827
828   /* Pass friendly classes back.  */
829   if (value == void_type_node)
830     return value;
831
832   /* Pass friend decls back.  */
833   if ((TREE_CODE (value) == FUNCTION_DECL
834        || TREE_CODE (value) == TEMPLATE_DECL)
835       && DECL_CONTEXT (value) != current_class_type)
836     return value;
837
838   name = DECL_NAME (value);
839
840   if (name != NULL_TREE)
841     {
842       if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
843         {
844           error ("explicit template argument list not allowed");
845           return error_mark_node;
846         }
847
848       if (IDENTIFIER_POINTER (name)[0] == '_'
849           && ! strcmp (IDENTIFIER_POINTER (name), "_vptr"))
850         error ("member %qD conflicts with virtual function table field name",
851                value);
852     }
853
854   /* Stash away type declarations.  */
855   if (TREE_CODE (value) == TYPE_DECL)
856     {
857       DECL_NONLOCAL (value) = 1;
858       DECL_CONTEXT (value) = current_class_type;
859
860       if (processing_template_decl)
861         value = push_template_decl (value);
862
863       if (attrlist)
864         {
865           int attrflags = 0;
866
867           /* If this is a typedef that names the class for linkage purposes
868              (7.1.3p8), apply any attributes directly to the type.  */
869           if (TAGGED_TYPE_P (TREE_TYPE (value))
870               && value == TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (value))))
871             attrflags = ATTR_FLAG_TYPE_IN_PLACE;
872
873           cplus_decl_attributes (&value, attrlist, attrflags);
874         }
875
876       if (declspecs->specs[(int)ds_typedef]
877           && TREE_TYPE (value) != error_mark_node
878           && TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (value))) != value)
879         cp_set_underlying_type (value);
880
881       return value;
882     }
883
884   if (DECL_IN_AGGR_P (value))
885     {
886       error ("%qD is already defined in %qT", value, DECL_CONTEXT (value));
887       return void_type_node;
888     }
889
890   if (asmspec_tree && asmspec_tree != error_mark_node)
891     asmspec = TREE_STRING_POINTER (asmspec_tree);
892
893   if (init)
894     {
895       if (TREE_CODE (value) == FUNCTION_DECL)
896         {
897           /* Initializers for functions are rejected early in the parser.
898              If we get here, it must be a pure specifier for a method.  */
899           if (init == ridpointers[(int)RID_DELETE])
900             {
901               DECL_DELETED_FN (value) = 1;
902               DECL_DECLARED_INLINE_P (value) = 1;
903               DECL_INITIAL (value) = error_mark_node;
904             }
905           else if (init == ridpointers[(int)RID_DEFAULT])
906             {
907               if (defaultable_fn_check (value))
908                 {
909                   DECL_DEFAULTED_FN (value) = 1;
910                   DECL_INITIALIZED_IN_CLASS_P (value) = 1;
911                   DECL_DECLARED_INLINE_P (value) = 1;
912                 }
913             }
914           else if (TREE_CODE (TREE_TYPE (value)) == METHOD_TYPE)
915             {
916               if (integer_zerop (init))
917                 DECL_PURE_VIRTUAL_P (value) = 1;
918               else if (error_operand_p (init))
919                 ; /* An error has already been reported.  */
920               else
921                 error ("invalid initializer for member function %qD",
922                        value);
923             }
924           else
925             {
926               gcc_assert (TREE_CODE (TREE_TYPE (value)) == FUNCTION_TYPE);
927               error ("initializer specified for static member function %qD",
928                      value);
929             }
930         }
931       else if (pedantic && TREE_CODE (value) != VAR_DECL)
932         /* Already complained in grokdeclarator.  */
933         init = NULL_TREE;
934       else if (!processing_template_decl)
935         {
936           if (TREE_CODE (init) == CONSTRUCTOR)
937             init = digest_init (TREE_TYPE (value), init);
938           else
939             init = integral_constant_value (init);
940
941           if (init != error_mark_node && !TREE_CONSTANT (init))
942             {
943               /* We can allow references to things that are effectively
944                  static, since references are initialized with the
945                  address.  */
946               if (TREE_CODE (TREE_TYPE (value)) != REFERENCE_TYPE
947                   || (TREE_STATIC (init) == 0
948                       && (!DECL_P (init) || DECL_EXTERNAL (init) == 0)))
949                 {
950                   error ("field initializer is not constant");
951                   init = error_mark_node;
952                 }
953             }
954         }
955     }
956
957   if (processing_template_decl
958       && (TREE_CODE (value) == VAR_DECL || TREE_CODE (value) == FUNCTION_DECL))
959     {
960       value = push_template_decl (value);
961       if (error_operand_p (value))
962         return error_mark_node;
963     }
964
965   if (attrlist)
966     cplus_decl_attributes (&value, attrlist, 0);
967
968   switch (TREE_CODE (value))
969     {
970     case VAR_DECL:
971       finish_static_data_member_decl (value, init, init_const_expr_p,
972                                       asmspec_tree, flags);
973       return value;
974
975     case FIELD_DECL:
976       if (asmspec)
977         error ("%<asm%> specifiers are not permitted on non-static data members");
978       if (DECL_INITIAL (value) == error_mark_node)
979         init = error_mark_node;
980       cp_finish_decl (value, init, /*init_const_expr_p=*/false,
981                       NULL_TREE, flags);
982       DECL_INITIAL (value) = init;
983       DECL_IN_AGGR_P (value) = 1;
984       return value;
985
986     case  FUNCTION_DECL:
987       if (asmspec)
988         set_user_assembler_name (value, asmspec);
989
990       cp_finish_decl (value,
991                       /*init=*/NULL_TREE,
992                       /*init_const_expr_p=*/false,
993                       asmspec_tree, flags);
994
995       /* Pass friends back this way.  */
996       if (DECL_FRIEND_P (value))
997         return void_type_node;
998
999       DECL_IN_AGGR_P (value) = 1;
1000       return value;
1001
1002     default:
1003       gcc_unreachable ();
1004     }
1005   return NULL_TREE;
1006 }
1007
1008 /* Like `grokfield', but for bitfields.
1009    WIDTH is non-NULL for bit fields only, and is an INTEGER_CST node.  */
1010
1011 tree
1012 grokbitfield (const cp_declarator *declarator,
1013               cp_decl_specifier_seq *declspecs, tree width,
1014               tree attrlist)
1015 {
1016   tree value = grokdeclarator (declarator, declspecs, BITFIELD, 0, &attrlist);
1017
1018   if (value == error_mark_node) 
1019     return NULL_TREE; /* friends went bad.  */
1020
1021   /* Pass friendly classes back.  */
1022   if (TREE_CODE (value) == VOID_TYPE)
1023     return void_type_node;
1024
1025   if (!INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (value))
1026       && (POINTER_TYPE_P (value)
1027           || !dependent_type_p (TREE_TYPE (value))))
1028     {
1029       error ("bit-field %qD with non-integral type", value);
1030       return error_mark_node;
1031     }
1032
1033   if (TREE_CODE (value) == TYPE_DECL)
1034     {
1035       error ("cannot declare %qD to be a bit-field type", value);
1036       return NULL_TREE;
1037     }
1038
1039   /* Usually, finish_struct_1 catches bitfields with invalid types.
1040      But, in the case of bitfields with function type, we confuse
1041      ourselves into thinking they are member functions, so we must
1042      check here.  */
1043   if (TREE_CODE (value) == FUNCTION_DECL)
1044     {
1045       error ("cannot declare bit-field %qD with function type",
1046              DECL_NAME (value));
1047       return NULL_TREE;
1048     }
1049
1050   if (DECL_IN_AGGR_P (value))
1051     {
1052       error ("%qD is already defined in the class %qT", value,
1053              DECL_CONTEXT (value));
1054       return void_type_node;
1055     }
1056
1057   if (TREE_STATIC (value))
1058     {
1059       error ("static member %qD cannot be a bit-field", value);
1060       return NULL_TREE;
1061     }
1062   cp_finish_decl (value, NULL_TREE, false, NULL_TREE, 0);
1063
1064   if (width != error_mark_node)
1065     {
1066       constant_expression_warning (width);
1067       DECL_INITIAL (value) = width;
1068       SET_DECL_C_BIT_FIELD (value);
1069     }
1070
1071   DECL_IN_AGGR_P (value) = 1;
1072
1073   if (attrlist)
1074     cplus_decl_attributes (&value, attrlist, /*flags=*/0);
1075
1076   return value;
1077 }
1078
1079 \f
1080 /* Returns true iff ATTR is an attribute which needs to be applied at
1081    instantiation time rather than template definition time.  */
1082
1083 static bool
1084 is_late_template_attribute (tree attr, tree decl)
1085 {
1086   tree name = TREE_PURPOSE (attr);
1087   tree args = TREE_VALUE (attr);
1088   const struct attribute_spec *spec = lookup_attribute_spec (name);
1089   tree arg;
1090
1091   if (!spec)
1092     /* Unknown attribute.  */
1093     return false;
1094
1095   /* Attribute weak handling wants to write out assembly right away.  */
1096   if (is_attribute_p ("weak", name))
1097     return true;
1098
1099   /* If any of the arguments are dependent expressions, we can't evaluate
1100      the attribute until instantiation time.  */
1101   for (arg = args; arg; arg = TREE_CHAIN (arg))
1102     {
1103       tree t = TREE_VALUE (arg);
1104
1105       /* If the first attribute argument is an identifier, only consider
1106          second and following arguments.  Attributes like mode, format,
1107          cleanup and several target specific attributes aren't late
1108          just because they have an IDENTIFIER_NODE as first argument.  */
1109       if (arg == args && TREE_CODE (t) == IDENTIFIER_NODE)
1110         continue;
1111
1112       if (value_dependent_expression_p (t)
1113           || type_dependent_expression_p (t))
1114         return true;
1115     }
1116
1117   if (TREE_CODE (decl) == TYPE_DECL
1118       || TYPE_P (decl)
1119       || spec->type_required)
1120     {
1121       tree type = TYPE_P (decl) ? decl : TREE_TYPE (decl);
1122
1123       /* We can't apply any attributes to a completely unknown type until
1124          instantiation time.  */
1125       enum tree_code code = TREE_CODE (type);
1126       if (code == TEMPLATE_TYPE_PARM
1127           || code == BOUND_TEMPLATE_TEMPLATE_PARM
1128           || code == TYPENAME_TYPE)
1129         return true;
1130       /* Also defer most attributes on dependent types.  This is not
1131          necessary in all cases, but is the better default.  */
1132       else if (dependent_type_p (type)
1133                /* But attribute visibility specifically works on
1134                   templates.  */
1135                && !is_attribute_p ("visibility", name))
1136         return true;
1137       else
1138         return false;
1139     }
1140   else
1141     return false;
1142 }
1143
1144 /* ATTR_P is a list of attributes.  Remove any attributes which need to be
1145    applied at instantiation time and return them.  If IS_DEPENDENT is true,
1146    the declaration itself is dependent, so all attributes should be applied
1147    at instantiation time.  */
1148
1149 static tree
1150 splice_template_attributes (tree *attr_p, tree decl)
1151 {
1152   tree *p = attr_p;
1153   tree late_attrs = NULL_TREE;
1154   tree *q = &late_attrs;
1155
1156   if (!p)
1157     return NULL_TREE;
1158
1159   for (; *p; )
1160     {
1161       if (is_late_template_attribute (*p, decl))
1162         {
1163           ATTR_IS_DEPENDENT (*p) = 1;
1164           *q = *p;
1165           *p = TREE_CHAIN (*p);
1166           q = &TREE_CHAIN (*q);
1167           *q = NULL_TREE;
1168         }
1169       else
1170         p = &TREE_CHAIN (*p);
1171     }
1172
1173   return late_attrs;
1174 }
1175
1176 /* Remove any late attributes from the list in ATTR_P and attach them to
1177    DECL_P.  */
1178
1179 static void
1180 save_template_attributes (tree *attr_p, tree *decl_p)
1181 {
1182   tree late_attrs = splice_template_attributes (attr_p, *decl_p);
1183   tree *q;
1184   tree old_attrs = NULL_TREE;
1185
1186   if (!late_attrs)
1187     return;
1188
1189   if (DECL_P (*decl_p))
1190     q = &DECL_ATTRIBUTES (*decl_p);
1191   else
1192     q = &TYPE_ATTRIBUTES (*decl_p);
1193
1194   old_attrs = *q;
1195
1196   /* Place the late attributes at the beginning of the attribute
1197      list.  */
1198   TREE_CHAIN (tree_last (late_attrs)) = *q;
1199   *q = late_attrs;
1200
1201   if (!DECL_P (*decl_p) && *decl_p == TYPE_MAIN_VARIANT (*decl_p))
1202     {
1203       /* We've added new attributes directly to the main variant, so
1204          now we need to update all of the other variants to include
1205          these new attributes.  */
1206       tree variant;
1207       for (variant = TYPE_NEXT_VARIANT (*decl_p); variant;
1208            variant = TYPE_NEXT_VARIANT (variant))
1209         {
1210           gcc_assert (TYPE_ATTRIBUTES (variant) == old_attrs);
1211           TYPE_ATTRIBUTES (variant) = TYPE_ATTRIBUTES (*decl_p);
1212         }
1213     }
1214 }
1215
1216 /* Like reconstruct_complex_type, but handle also template trees.  */
1217
1218 tree
1219 cp_reconstruct_complex_type (tree type, tree bottom)
1220 {
1221   tree inner, outer;
1222
1223   if (TREE_CODE (type) == POINTER_TYPE)
1224     {
1225       inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1226       outer = build_pointer_type_for_mode (inner, TYPE_MODE (type),
1227                                            TYPE_REF_CAN_ALIAS_ALL (type));
1228     }
1229   else if (TREE_CODE (type) == REFERENCE_TYPE)
1230     {
1231       inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1232       outer = build_reference_type_for_mode (inner, TYPE_MODE (type),
1233                                              TYPE_REF_CAN_ALIAS_ALL (type));
1234     }
1235   else if (TREE_CODE (type) == ARRAY_TYPE)
1236     {
1237       inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1238       outer = build_cplus_array_type (inner, TYPE_DOMAIN (type));
1239       /* Don't call cp_build_qualified_type on ARRAY_TYPEs, the
1240          element type qualification will be handled by the recursive
1241          cp_reconstruct_complex_type call and cp_build_qualified_type
1242          for ARRAY_TYPEs changes the element type.  */
1243       return outer;
1244     }
1245   else if (TREE_CODE (type) == FUNCTION_TYPE)
1246     {
1247       inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1248       outer = build_function_type (inner, TYPE_ARG_TYPES (type));
1249     }
1250   else if (TREE_CODE (type) == METHOD_TYPE)
1251     {
1252       inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1253       /* The build_method_type_directly() routine prepends 'this' to argument list,
1254          so we must compensate by getting rid of it.  */
1255       outer
1256         = build_method_type_directly
1257             (TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (type))),
1258              inner,
1259              TREE_CHAIN (TYPE_ARG_TYPES (type)));
1260     }
1261   else if (TREE_CODE (type) == OFFSET_TYPE)
1262     {
1263       inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1264       outer = build_offset_type (TYPE_OFFSET_BASETYPE (type), inner);
1265     }
1266   else
1267     return bottom;
1268
1269   if (TYPE_ATTRIBUTES (type))
1270     outer = cp_build_type_attribute_variant (outer, TYPE_ATTRIBUTES (type));
1271   return cp_build_qualified_type (outer, TYPE_QUALS (type));
1272 }
1273
1274 /* Like decl_attributes, but handle C++ complexity.  */
1275
1276 void
1277 cplus_decl_attributes (tree *decl, tree attributes, int flags)
1278 {
1279   if (*decl == NULL_TREE || *decl == void_type_node
1280       || *decl == error_mark_node
1281       || attributes == NULL_TREE)
1282     return;
1283
1284   if (processing_template_decl)
1285     {
1286       if (check_for_bare_parameter_packs (attributes))
1287         return;
1288
1289       save_template_attributes (&attributes, decl);
1290       if (attributes == NULL_TREE)
1291         return;
1292     }
1293
1294   if (TREE_CODE (*decl) == TEMPLATE_DECL)
1295     decl = &DECL_TEMPLATE_RESULT (*decl);
1296
1297   decl_attributes (decl, attributes, flags);
1298
1299   if (TREE_CODE (*decl) == TYPE_DECL)
1300     SET_IDENTIFIER_TYPE_VALUE (DECL_NAME (*decl), TREE_TYPE (*decl));
1301 }
1302 \f
1303 /* Walks through the namespace- or function-scope anonymous union
1304    OBJECT, with the indicated TYPE, building appropriate VAR_DECLs.
1305    Returns one of the fields for use in the mangled name.  */
1306
1307 static tree
1308 build_anon_union_vars (tree type, tree object)
1309 {
1310   tree main_decl = NULL_TREE;
1311   tree field;
1312
1313   /* Rather than write the code to handle the non-union case,
1314      just give an error.  */
1315   if (TREE_CODE (type) != UNION_TYPE)
1316     error ("anonymous struct not inside named type");
1317
1318   for (field = TYPE_FIELDS (type);
1319        field != NULL_TREE;
1320        field = TREE_CHAIN (field))
1321     {
1322       tree decl;
1323       tree ref;
1324
1325       if (DECL_ARTIFICIAL (field))
1326         continue;
1327       if (TREE_CODE (field) != FIELD_DECL)
1328         {
1329           permerror (input_location, "%q+#D invalid; an anonymous union can only "
1330                      "have non-static data members", field);
1331           continue;
1332         }
1333
1334       if (TREE_PRIVATE (field))
1335         permerror (input_location, "private member %q+#D in anonymous union", field);
1336       else if (TREE_PROTECTED (field))
1337         permerror (input_location, "protected member %q+#D in anonymous union", field);
1338
1339       if (processing_template_decl)
1340         ref = build_min_nt (COMPONENT_REF, object,
1341                             DECL_NAME (field), NULL_TREE);
1342       else
1343         ref = build_class_member_access_expr (object, field, NULL_TREE,
1344                                               false, tf_warning_or_error);
1345
1346       if (DECL_NAME (field))
1347         {
1348           tree base;
1349
1350           decl = build_decl (input_location,
1351                              VAR_DECL, DECL_NAME (field), TREE_TYPE (field));
1352           DECL_ANON_UNION_VAR_P (decl) = 1;
1353           DECL_ARTIFICIAL (decl) = 1;
1354
1355           base = get_base_address (object);
1356           TREE_PUBLIC (decl) = TREE_PUBLIC (base);
1357           TREE_STATIC (decl) = TREE_STATIC (base);
1358           DECL_EXTERNAL (decl) = DECL_EXTERNAL (base);
1359
1360           SET_DECL_VALUE_EXPR (decl, ref);
1361           DECL_HAS_VALUE_EXPR_P (decl) = 1;
1362
1363           decl = pushdecl (decl);
1364         }
1365       else if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1366         decl = build_anon_union_vars (TREE_TYPE (field), ref);
1367       else
1368         decl = 0;
1369
1370       if (main_decl == NULL_TREE)
1371         main_decl = decl;
1372     }
1373
1374   return main_decl;
1375 }
1376
1377 /* Finish off the processing of a UNION_TYPE structure.  If the union is an
1378    anonymous union, then all members must be laid out together.  PUBLIC_P
1379    is nonzero if this union is not declared static.  */
1380
1381 void
1382 finish_anon_union (tree anon_union_decl)
1383 {
1384   tree type;
1385   tree main_decl;
1386   bool public_p;
1387
1388   if (anon_union_decl == error_mark_node)
1389     return;
1390
1391   type = TREE_TYPE (anon_union_decl);
1392   public_p = TREE_PUBLIC (anon_union_decl);
1393
1394   /* The VAR_DECL's context is the same as the TYPE's context.  */
1395   DECL_CONTEXT (anon_union_decl) = DECL_CONTEXT (TYPE_NAME (type));
1396
1397   if (TYPE_FIELDS (type) == NULL_TREE)
1398     return;
1399
1400   if (public_p)
1401     {
1402       error ("namespace-scope anonymous aggregates must be static");
1403       return;
1404     }
1405
1406   main_decl = build_anon_union_vars (type, anon_union_decl);
1407   if (main_decl == error_mark_node)
1408     return;
1409   if (main_decl == NULL_TREE)
1410     {
1411       warning (0, "anonymous union with no members");
1412       return;
1413     }
1414
1415   if (!processing_template_decl)
1416     {
1417       /* Use main_decl to set the mangled name.  */
1418       DECL_NAME (anon_union_decl) = DECL_NAME (main_decl);
1419       maybe_commonize_var (anon_union_decl);
1420       mangle_decl (anon_union_decl);
1421       DECL_NAME (anon_union_decl) = NULL_TREE;
1422     }
1423
1424   pushdecl (anon_union_decl);
1425   if (building_stmt_tree ()
1426       && at_function_scope_p ())
1427     add_decl_expr (anon_union_decl);
1428   else if (!processing_template_decl)
1429     rest_of_decl_compilation (anon_union_decl,
1430                               toplevel_bindings_p (), at_eof);
1431 }
1432 \f
1433 /* Auxiliary functions to make type signatures for
1434    `operator new' and `operator delete' correspond to
1435    what compiler will be expecting.  */
1436
1437 tree
1438 coerce_new_type (tree type)
1439 {
1440   int e = 0;
1441   tree args = TYPE_ARG_TYPES (type);
1442
1443   gcc_assert (TREE_CODE (type) == FUNCTION_TYPE);
1444
1445   if (!same_type_p (TREE_TYPE (type), ptr_type_node))
1446     {
1447       e = 1;
1448       error ("%<operator new%> must return type %qT", ptr_type_node);
1449     }
1450
1451   if (args && args != void_list_node)
1452     {
1453       if (TREE_PURPOSE (args))
1454         {
1455           /* [basic.stc.dynamic.allocation]
1456              
1457              The first parameter shall not have an associated default
1458              argument.  */
1459           error ("the first parameter of %<operator new%> cannot "
1460                  "have a default argument");
1461           /* Throw away the default argument.  */
1462           TREE_PURPOSE (args) = NULL_TREE;
1463         }
1464
1465       if (!same_type_p (TREE_VALUE (args), size_type_node))
1466         {
1467           e = 2;
1468           args = TREE_CHAIN (args);
1469         }
1470     }
1471   else
1472     e = 2;
1473
1474   if (e == 2)
1475     permerror (input_location, "%<operator new%> takes type %<size_t%> (%qT) "
1476                "as first parameter", size_type_node);
1477
1478   switch (e)
1479   {
1480     case 2:
1481       args = tree_cons (NULL_TREE, size_type_node, args);
1482       /* Fall through.  */
1483     case 1:
1484       type = build_exception_variant
1485               (build_function_type (ptr_type_node, args),
1486                TYPE_RAISES_EXCEPTIONS (type));
1487       /* Fall through.  */
1488     default:;
1489   }
1490   return type;
1491 }
1492
1493 tree
1494 coerce_delete_type (tree type)
1495 {
1496   int e = 0;
1497   tree args = TYPE_ARG_TYPES (type);
1498
1499   gcc_assert (TREE_CODE (type) == FUNCTION_TYPE);
1500
1501   if (!same_type_p (TREE_TYPE (type), void_type_node))
1502     {
1503       e = 1;
1504       error ("%<operator delete%> must return type %qT", void_type_node);
1505     }
1506
1507   if (!args || args == void_list_node
1508       || !same_type_p (TREE_VALUE (args), ptr_type_node))
1509     {
1510       e = 2;
1511       if (args && args != void_list_node)
1512         args = TREE_CHAIN (args);
1513       error ("%<operator delete%> takes type %qT as first parameter",
1514              ptr_type_node);
1515     }
1516   switch (e)
1517   {
1518     case 2:
1519       args = tree_cons (NULL_TREE, ptr_type_node, args);
1520       /* Fall through.  */
1521     case 1:
1522       type = build_exception_variant
1523               (build_function_type (void_type_node, args),
1524                TYPE_RAISES_EXCEPTIONS (type));
1525       /* Fall through.  */
1526     default:;
1527   }
1528
1529   return type;
1530 }
1531 \f
1532 /* DECL is a VAR_DECL for a vtable: walk through the entries in the vtable
1533    and mark them as needed.  */
1534
1535 static void
1536 mark_vtable_entries (tree decl)
1537 {
1538   tree fnaddr;
1539   unsigned HOST_WIDE_INT idx;
1540
1541   FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (DECL_INITIAL (decl)),
1542                               idx, fnaddr)
1543     {
1544       tree fn;
1545
1546       STRIP_NOPS (fnaddr);
1547
1548       if (TREE_CODE (fnaddr) != ADDR_EXPR
1549           && TREE_CODE (fnaddr) != FDESC_EXPR)
1550         /* This entry is an offset: a virtual base class offset, a
1551            virtual call offset, an RTTI offset, etc.  */
1552         continue;
1553
1554       fn = TREE_OPERAND (fnaddr, 0);
1555       TREE_ADDRESSABLE (fn) = 1;
1556       /* When we don't have vcall offsets, we output thunks whenever
1557          we output the vtables that contain them.  With vcall offsets,
1558          we know all the thunks we'll need when we emit a virtual
1559          function, so we emit the thunks there instead.  */
1560       if (DECL_THUNK_P (fn))
1561         use_thunk (fn, /*emit_p=*/0);
1562       mark_used (fn);
1563     }
1564 }
1565
1566 /* Set DECL up to have the closest approximation of "initialized common"
1567    linkage available.  */
1568
1569 void
1570 comdat_linkage (tree decl)
1571 {
1572   if (flag_weak)
1573     make_decl_one_only (decl, cxx_comdat_group (decl));
1574   else if (TREE_CODE (decl) == FUNCTION_DECL
1575            || (TREE_CODE (decl) == VAR_DECL && DECL_ARTIFICIAL (decl)))
1576     /* We can just emit function and compiler-generated variables
1577        statically; having multiple copies is (for the most part) only
1578        a waste of space.
1579
1580        There are two correctness issues, however: the address of a
1581        template instantiation with external linkage should be the
1582        same, independent of what translation unit asks for the
1583        address, and this will not hold when we emit multiple copies of
1584        the function.  However, there's little else we can do.
1585
1586        Also, by default, the typeinfo implementation assumes that
1587        there will be only one copy of the string used as the name for
1588        each type.  Therefore, if weak symbols are unavailable, the
1589        run-time library should perform a more conservative check; it
1590        should perform a string comparison, rather than an address
1591        comparison.  */
1592     TREE_PUBLIC (decl) = 0;
1593   else
1594     {
1595       /* Static data member template instantiations, however, cannot
1596          have multiple copies.  */
1597       if (DECL_INITIAL (decl) == 0
1598           || DECL_INITIAL (decl) == error_mark_node)
1599         DECL_COMMON (decl) = 1;
1600       else if (EMPTY_CONSTRUCTOR_P (DECL_INITIAL (decl)))
1601         {
1602           DECL_COMMON (decl) = 1;
1603           DECL_INITIAL (decl) = error_mark_node;
1604         }
1605       else if (!DECL_EXPLICIT_INSTANTIATION (decl))
1606         {
1607           /* We can't do anything useful; leave vars for explicit
1608              instantiation.  */
1609           DECL_EXTERNAL (decl) = 1;
1610           DECL_NOT_REALLY_EXTERN (decl) = 0;
1611         }
1612     }
1613
1614   DECL_COMDAT (decl) = 1;
1615 }
1616
1617 /* For win32 we also want to put explicit instantiations in
1618    linkonce sections, so that they will be merged with implicit
1619    instantiations; otherwise we get duplicate symbol errors.
1620    For Darwin we do not want explicit instantiations to be
1621    linkonce.  */
1622
1623 void
1624 maybe_make_one_only (tree decl)
1625 {
1626   /* We used to say that this was not necessary on targets that support weak
1627      symbols, because the implicit instantiations will defer to the explicit
1628      one.  However, that's not actually the case in SVR4; a strong definition
1629      after a weak one is an error.  Also, not making explicit
1630      instantiations one_only means that we can end up with two copies of
1631      some template instantiations.  */
1632   if (! flag_weak)
1633     return;
1634
1635   /* We can't set DECL_COMDAT on functions, or cp_finish_file will think
1636      we can get away with not emitting them if they aren't used.  We need
1637      to for variables so that cp_finish_decl will update their linkage,
1638      because their DECL_INITIAL may not have been set properly yet.  */
1639
1640   if (!TARGET_WEAK_NOT_IN_ARCHIVE_TOC
1641       || (! DECL_EXPLICIT_INSTANTIATION (decl)
1642           && ! DECL_TEMPLATE_SPECIALIZATION (decl)))
1643     {
1644       make_decl_one_only (decl, cxx_comdat_group (decl));
1645
1646       if (TREE_CODE (decl) == VAR_DECL)
1647         {
1648           DECL_COMDAT (decl) = 1;
1649           /* Mark it needed so we don't forget to emit it.  */
1650           mark_decl_referenced (decl);
1651         }
1652     }
1653 }
1654
1655 /* Returns true iff DECL, a FUNCTION_DECL or VAR_DECL, has vague linkage.
1656    This predicate will give the right answer during parsing of the
1657    function, which other tests may not.  */
1658
1659 bool
1660 vague_linkage_p (tree decl)
1661 {
1662   /* Unfortunately, import_export_decl has not always been called
1663      before the function is processed, so we cannot simply check
1664      DECL_COMDAT.  */
1665   return (DECL_COMDAT (decl)
1666           || (((TREE_CODE (decl) == FUNCTION_DECL
1667                 && DECL_DECLARED_INLINE_P (decl))
1668                || (DECL_LANG_SPECIFIC (decl)
1669                    && DECL_TEMPLATE_INSTANTIATION (decl)))
1670               && TREE_PUBLIC (decl)));
1671 }
1672
1673 /* Determine whether or not we want to specifically import or export CTYPE,
1674    using various heuristics.  */
1675
1676 static void
1677 import_export_class (tree ctype)
1678 {
1679   /* -1 for imported, 1 for exported.  */
1680   int import_export = 0;
1681
1682   /* It only makes sense to call this function at EOF.  The reason is
1683      that this function looks at whether or not the first non-inline
1684      non-abstract virtual member function has been defined in this
1685      translation unit.  But, we can't possibly know that until we've
1686      seen the entire translation unit.  */
1687   gcc_assert (at_eof);
1688
1689   if (CLASSTYPE_INTERFACE_KNOWN (ctype))
1690     return;
1691
1692   /* If MULTIPLE_SYMBOL_SPACES is set and we saw a #pragma interface,
1693      we will have CLASSTYPE_INTERFACE_ONLY set but not
1694      CLASSTYPE_INTERFACE_KNOWN.  In that case, we don't want to use this
1695      heuristic because someone will supply a #pragma implementation
1696      elsewhere, and deducing it here would produce a conflict.  */
1697   if (CLASSTYPE_INTERFACE_ONLY (ctype))
1698     return;
1699
1700   if (lookup_attribute ("dllimport", TYPE_ATTRIBUTES (ctype)))
1701     import_export = -1;
1702   else if (lookup_attribute ("dllexport", TYPE_ATTRIBUTES (ctype)))
1703     import_export = 1;
1704   else if (CLASSTYPE_IMPLICIT_INSTANTIATION (ctype)
1705            && !flag_implicit_templates)
1706     /* For a template class, without -fimplicit-templates, check the
1707        repository.  If the virtual table is assigned to this
1708        translation unit, then export the class; otherwise, import
1709        it.  */
1710       import_export = repo_export_class_p (ctype) ? 1 : -1;
1711   else if (TYPE_POLYMORPHIC_P (ctype))
1712     {
1713       /* The ABI specifies that the virtual table and associated
1714          information are emitted with the key method, if any.  */
1715       tree method = CLASSTYPE_KEY_METHOD (ctype);
1716       /* If weak symbol support is not available, then we must be
1717          careful not to emit the vtable when the key function is
1718          inline.  An inline function can be defined in multiple
1719          translation units.  If we were to emit the vtable in each
1720          translation unit containing a definition, we would get
1721          multiple definition errors at link-time.  */
1722       if (method && (flag_weak || ! DECL_DECLARED_INLINE_P (method)))
1723         import_export = (DECL_REALLY_EXTERN (method) ? -1 : 1);
1724     }
1725
1726   /* When MULTIPLE_SYMBOL_SPACES is set, we cannot count on seeing
1727      a definition anywhere else.  */
1728   if (MULTIPLE_SYMBOL_SPACES && import_export == -1)
1729     import_export = 0;
1730
1731   /* Allow back ends the chance to overrule the decision.  */
1732   if (targetm.cxx.import_export_class)
1733     import_export = targetm.cxx.import_export_class (ctype, import_export);
1734
1735   if (import_export)
1736     {
1737       SET_CLASSTYPE_INTERFACE_KNOWN (ctype);
1738       CLASSTYPE_INTERFACE_ONLY (ctype) = (import_export < 0);
1739     }
1740 }
1741
1742 /* Return true if VAR has already been provided to the back end; in that
1743    case VAR should not be modified further by the front end.  */
1744 static bool
1745 var_finalized_p (tree var)
1746 {
1747   return varpool_node (var)->finalized;
1748 }
1749
1750 /* DECL is a VAR_DECL or FUNCTION_DECL which, for whatever reason,
1751    must be emitted in this translation unit.  Mark it as such.  */
1752
1753 void
1754 mark_needed (tree decl)
1755 {
1756   /* It's possible that we no longer need to set
1757      TREE_SYMBOL_REFERENCED here directly, but doing so is
1758      harmless.  */
1759   TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (decl)) = 1;
1760   mark_decl_referenced (decl);
1761 }
1762
1763 /* DECL is either a FUNCTION_DECL or a VAR_DECL.  This function
1764    returns true if a definition of this entity should be provided in
1765    this object file.  Callers use this function to determine whether
1766    or not to let the back end know that a definition of DECL is
1767    available in this translation unit.  */
1768
1769 bool
1770 decl_needed_p (tree decl)
1771 {
1772   gcc_assert (TREE_CODE (decl) == VAR_DECL
1773               || TREE_CODE (decl) == FUNCTION_DECL);
1774   /* This function should only be called at the end of the translation
1775      unit.  We cannot be sure of whether or not something will be
1776      COMDAT until that point.  */
1777   gcc_assert (at_eof);
1778
1779   /* All entities with external linkage that are not COMDAT should be
1780      emitted; they may be referred to from other object files.  */
1781   if (TREE_PUBLIC (decl) && !DECL_COMDAT (decl))
1782     return true;
1783   /* If this entity was used, let the back end see it; it will decide
1784      whether or not to emit it into the object file.  */
1785   if (TREE_USED (decl)
1786       || (DECL_ASSEMBLER_NAME_SET_P (decl)
1787           && TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (decl))))
1788       return true;
1789   /* Functions marked "dllexport" must be emitted so that they are
1790      visible to other DLLs.  */
1791   if (lookup_attribute ("dllexport", DECL_ATTRIBUTES (decl)))
1792     return true;
1793   /* Otherwise, DECL does not need to be emitted -- yet.  A subsequent
1794      reference to DECL might cause it to be emitted later.  */
1795   return false;
1796 }
1797
1798 /* If necessary, write out the vtables for the dynamic class CTYPE.
1799    Returns true if any vtables were emitted.  */
1800
1801 static bool
1802 maybe_emit_vtables (tree ctype)
1803 {
1804   tree vtbl;
1805   tree primary_vtbl;
1806   int needed = 0;
1807
1808   /* If the vtables for this class have already been emitted there is
1809      nothing more to do.  */
1810   primary_vtbl = CLASSTYPE_VTABLES (ctype);
1811   if (var_finalized_p (primary_vtbl))
1812     return false;
1813   /* Ignore dummy vtables made by get_vtable_decl.  */
1814   if (TREE_TYPE (primary_vtbl) == void_type_node)
1815     return false;
1816
1817   /* On some targets, we cannot determine the key method until the end
1818      of the translation unit -- which is when this function is
1819      called.  */
1820   if (!targetm.cxx.key_method_may_be_inline ())
1821     determine_key_method (ctype);
1822
1823   /* See if any of the vtables are needed.  */
1824   for (vtbl = CLASSTYPE_VTABLES (ctype); vtbl; vtbl = TREE_CHAIN (vtbl))
1825     {
1826       import_export_decl (vtbl);
1827       if (DECL_NOT_REALLY_EXTERN (vtbl) && decl_needed_p (vtbl))
1828         needed = 1;
1829     }
1830   if (!needed)
1831     {
1832       /* If the references to this class' vtables are optimized away,
1833          still emit the appropriate debugging information.  See
1834          dfs_debug_mark.  */
1835       if (DECL_COMDAT (primary_vtbl)
1836           && CLASSTYPE_DEBUG_REQUESTED (ctype))
1837         note_debug_info_needed (ctype);
1838       return false;
1839     }
1840
1841   /* The ABI requires that we emit all of the vtables if we emit any
1842      of them.  */
1843   for (vtbl = CLASSTYPE_VTABLES (ctype); vtbl; vtbl = TREE_CHAIN (vtbl))
1844     {
1845       /* Mark entities references from the virtual table as used.  */
1846       mark_vtable_entries (vtbl);
1847
1848       if (TREE_TYPE (DECL_INITIAL (vtbl)) == 0)
1849         {
1850           tree expr = store_init_value (vtbl, DECL_INITIAL (vtbl), LOOKUP_NORMAL);
1851
1852           /* It had better be all done at compile-time.  */
1853           gcc_assert (!expr);
1854         }
1855
1856       /* Write it out.  */
1857       DECL_EXTERNAL (vtbl) = 0;
1858       rest_of_decl_compilation (vtbl, 1, 1);
1859
1860       /* Because we're only doing syntax-checking, we'll never end up
1861          actually marking the variable as written.  */
1862       if (flag_syntax_only)
1863         TREE_ASM_WRITTEN (vtbl) = 1;
1864     }
1865
1866   /* Since we're writing out the vtable here, also write the debug
1867      info.  */
1868   note_debug_info_needed (ctype);
1869
1870   return true;
1871 }
1872
1873 /* A special return value from type_visibility meaning internal
1874    linkage.  */
1875
1876 enum { VISIBILITY_ANON = VISIBILITY_INTERNAL+1 };
1877
1878 /* walk_tree helper function for type_visibility.  */
1879
1880 static tree
1881 min_vis_r (tree *tp, int *walk_subtrees, void *data)
1882 {
1883   int *vis_p = (int *)data;
1884   if (! TYPE_P (*tp))
1885     {
1886       *walk_subtrees = 0;
1887     }
1888   else if (CLASS_TYPE_P (*tp))
1889     {
1890       if (!TREE_PUBLIC (TYPE_MAIN_DECL (*tp)))
1891         {
1892           *vis_p = VISIBILITY_ANON;
1893           return *tp;
1894         }
1895       else if (CLASSTYPE_VISIBILITY (*tp) > *vis_p)
1896         *vis_p = CLASSTYPE_VISIBILITY (*tp);
1897     }
1898   return NULL;
1899 }
1900
1901 /* Returns the visibility of TYPE, which is the minimum visibility of its
1902    component types.  */
1903
1904 static int
1905 type_visibility (tree type)
1906 {
1907   int vis = VISIBILITY_DEFAULT;
1908   cp_walk_tree_without_duplicates (&type, min_vis_r, &vis);
1909   return vis;
1910 }
1911
1912 /* Limit the visibility of DECL to VISIBILITY, if not explicitly
1913    specified (or if VISIBILITY is static).  */
1914
1915 static bool
1916 constrain_visibility (tree decl, int visibility)
1917 {
1918   if (visibility == VISIBILITY_ANON)
1919     {
1920       /* extern "C" declarations aren't affected by the anonymous
1921          namespace.  */
1922       if (!DECL_EXTERN_C_P (decl))
1923         {
1924           TREE_PUBLIC (decl) = 0;
1925           DECL_WEAK (decl) = 0;
1926           DECL_COMMON (decl) = 0;
1927           DECL_COMDAT_GROUP (decl) = NULL_TREE;
1928           DECL_INTERFACE_KNOWN (decl) = 1;
1929           if (DECL_LANG_SPECIFIC (decl))
1930             DECL_NOT_REALLY_EXTERN (decl) = 1;
1931         }
1932     }
1933   else if (visibility > DECL_VISIBILITY (decl)
1934            && !DECL_VISIBILITY_SPECIFIED (decl))
1935     {
1936       DECL_VISIBILITY (decl) = (enum symbol_visibility) visibility;
1937       return true;
1938     }
1939   return false;
1940 }
1941
1942 /* Constrain the visibility of DECL based on the visibility of its template
1943    arguments.  */
1944
1945 static void
1946 constrain_visibility_for_template (tree decl, tree targs)
1947 {
1948   /* If this is a template instantiation, check the innermost
1949      template args for visibility constraints.  The outer template
1950      args are covered by the class check.  */
1951   tree args = INNERMOST_TEMPLATE_ARGS (targs);
1952   int i;
1953   for (i = TREE_VEC_LENGTH (args); i > 0; --i)
1954     {
1955       int vis = 0;
1956
1957       tree arg = TREE_VEC_ELT (args, i-1);
1958       if (TYPE_P (arg))
1959         vis = type_visibility (arg);
1960       else if (TREE_TYPE (arg) && POINTER_TYPE_P (TREE_TYPE (arg)))
1961         {
1962           STRIP_NOPS (arg);
1963           if (TREE_CODE (arg) == ADDR_EXPR)
1964             arg = TREE_OPERAND (arg, 0);
1965           if (TREE_CODE (arg) == VAR_DECL
1966               || TREE_CODE (arg) == FUNCTION_DECL)
1967             {
1968               if (! TREE_PUBLIC (arg))
1969                 vis = VISIBILITY_ANON;
1970               else
1971                 vis = DECL_VISIBILITY (arg);
1972             }
1973         }
1974       if (vis)
1975         constrain_visibility (decl, vis);
1976     }
1977 }
1978
1979 /* Like c_determine_visibility, but with additional C++-specific
1980    behavior.
1981
1982    Function-scope entities can rely on the function's visibility because
1983    it is set in start_preparsed_function.
1984
1985    Class-scope entities cannot rely on the class's visibility until the end
1986    of the enclosing class definition.
1987
1988    Note that because namespaces have multiple independent definitions,
1989    namespace visibility is handled elsewhere using the #pragma visibility
1990    machinery rather than by decorating the namespace declaration.
1991
1992    The goal is for constraints from the type to give a diagnostic, and
1993    other constraints to be applied silently.  */
1994
1995 void
1996 determine_visibility (tree decl)
1997 {
1998   tree class_type = NULL_TREE;
1999   bool use_template;
2000   bool orig_visibility_specified;
2001   enum symbol_visibility orig_visibility;
2002
2003   /* Remember that all decls get VISIBILITY_DEFAULT when built.  */
2004
2005   /* Only relevant for names with external linkage.  */
2006   if (!TREE_PUBLIC (decl))
2007     return;
2008
2009   /* Cloned constructors and destructors get the same visibility as
2010      the underlying function.  That should be set up in
2011      maybe_clone_body.  */
2012   gcc_assert (!DECL_CLONED_FUNCTION_P (decl));
2013
2014   orig_visibility_specified = DECL_VISIBILITY_SPECIFIED (decl);
2015   orig_visibility = DECL_VISIBILITY (decl);
2016
2017   if (TREE_CODE (decl) == TYPE_DECL)
2018     {
2019       if (CLASS_TYPE_P (TREE_TYPE (decl)))
2020         use_template = CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl));
2021       else if (TYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
2022         use_template = 1;
2023       else
2024         use_template = 0;
2025     }
2026   else if (DECL_LANG_SPECIFIC (decl))
2027     use_template = DECL_USE_TEMPLATE (decl);
2028   else
2029     use_template = 0;
2030
2031   /* If DECL is a member of a class, visibility specifiers on the
2032      class can influence the visibility of the DECL.  */
2033   if (DECL_CLASS_SCOPE_P (decl))
2034     class_type = DECL_CONTEXT (decl);
2035   else
2036     {
2037       /* Not a class member.  */
2038
2039       /* Virtual tables have DECL_CONTEXT set to their associated class,
2040          so they are automatically handled above.  */
2041       gcc_assert (TREE_CODE (decl) != VAR_DECL
2042                   || !DECL_VTABLE_OR_VTT_P (decl));
2043
2044       if (DECL_FUNCTION_SCOPE_P (decl) && ! DECL_VISIBILITY_SPECIFIED (decl))
2045         {
2046           /* Local statics and classes get the visibility of their
2047              containing function by default, except that
2048              -fvisibility-inlines-hidden doesn't affect them.  */
2049           tree fn = DECL_CONTEXT (decl);
2050           if (DECL_VISIBILITY_SPECIFIED (fn) || ! DECL_CLASS_SCOPE_P (fn))
2051             {
2052               DECL_VISIBILITY (decl) = DECL_VISIBILITY (fn);
2053               DECL_VISIBILITY_SPECIFIED (decl) = 
2054                 DECL_VISIBILITY_SPECIFIED (fn);
2055             }
2056           else
2057             determine_visibility_from_class (decl, DECL_CONTEXT (fn));
2058
2059           /* Local classes in templates have CLASSTYPE_USE_TEMPLATE set,
2060              but have no TEMPLATE_INFO, so don't try to check it.  */
2061           use_template = 0;
2062         }
2063       else if (TREE_CODE (decl) == VAR_DECL && DECL_TINFO_P (decl)
2064                && flag_visibility_ms_compat)
2065         {
2066           /* Under -fvisibility-ms-compat, types are visible by default,
2067              even though their contents aren't.  */
2068           tree underlying_type = TREE_TYPE (DECL_NAME (decl));
2069           int underlying_vis = type_visibility (underlying_type);
2070           if (underlying_vis == VISIBILITY_ANON
2071               || CLASSTYPE_VISIBILITY_SPECIFIED (underlying_type))
2072             constrain_visibility (decl, underlying_vis);
2073           else
2074             DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
2075         }
2076       else if (TREE_CODE (decl) == VAR_DECL && DECL_TINFO_P (decl))
2077         {
2078           /* tinfo visibility is based on the type it's for.  */
2079           constrain_visibility
2080             (decl, type_visibility (TREE_TYPE (DECL_NAME (decl))));
2081
2082           /* Give the target a chance to override the visibility associated
2083              with DECL.  */
2084           if (TREE_PUBLIC (decl)
2085               && !DECL_REALLY_EXTERN (decl)
2086               && CLASS_TYPE_P (TREE_TYPE (DECL_NAME (decl)))
2087               && !CLASSTYPE_VISIBILITY_SPECIFIED (TREE_TYPE (DECL_NAME (decl))))
2088             targetm.cxx.determine_class_data_visibility (decl);
2089         }
2090       else if (use_template)
2091         /* Template instantiations and specializations get visibility based
2092            on their template unless they override it with an attribute.  */;
2093       else if (! DECL_VISIBILITY_SPECIFIED (decl))
2094         {
2095           /* Set default visibility to whatever the user supplied with
2096              #pragma GCC visibility or a namespace visibility attribute.  */
2097           DECL_VISIBILITY (decl) = default_visibility;
2098           DECL_VISIBILITY_SPECIFIED (decl) = visibility_options.inpragma;
2099         }
2100     }
2101
2102   if (use_template)
2103     {
2104       /* If the specialization doesn't specify visibility, use the
2105          visibility from the template.  */
2106       tree tinfo = (TREE_CODE (decl) == TYPE_DECL
2107                     ? TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
2108                     : DECL_TEMPLATE_INFO (decl));
2109       tree args = TI_ARGS (tinfo);
2110       
2111       if (args != error_mark_node)
2112         {
2113           int depth = TMPL_ARGS_DEPTH (args);
2114           tree pattern = DECL_TEMPLATE_RESULT (TI_TEMPLATE (tinfo));
2115
2116           if (!DECL_VISIBILITY_SPECIFIED (decl))
2117             {
2118               DECL_VISIBILITY (decl) = DECL_VISIBILITY (pattern);
2119               DECL_VISIBILITY_SPECIFIED (decl)
2120                 = DECL_VISIBILITY_SPECIFIED (pattern);
2121             }
2122
2123           /* FIXME should TMPL_ARGS_DEPTH really return 1 for null input? */
2124           if (args && depth > template_class_depth (class_type))
2125             /* Limit visibility based on its template arguments.  */
2126             constrain_visibility_for_template (decl, args);
2127         }
2128     }
2129
2130   if (class_type)
2131     determine_visibility_from_class (decl, class_type);
2132
2133   if (decl_anon_ns_mem_p (decl))
2134     /* Names in an anonymous namespace get internal linkage.
2135        This might change once we implement export.  */
2136     constrain_visibility (decl, VISIBILITY_ANON);
2137   else if (TREE_CODE (decl) != TYPE_DECL)
2138     {
2139       /* Propagate anonymity from type to decl.  */
2140       int tvis = type_visibility (TREE_TYPE (decl));
2141       if (tvis == VISIBILITY_ANON
2142           || ! DECL_VISIBILITY_SPECIFIED (decl))
2143         constrain_visibility (decl, tvis);
2144     }
2145   else if (no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/true))
2146     /* DR 757: A type without linkage shall not be used as the type of a
2147        variable or function with linkage, unless
2148        o the variable or function has extern "C" linkage (7.5 [dcl.link]), or
2149        o the variable or function is not used (3.2 [basic.def.odr]) or is
2150        defined in the same translation unit.
2151
2152        Since non-extern "C" decls need to be defined in the same
2153        translation unit, we can make the type internal.  */
2154     constrain_visibility (decl, VISIBILITY_ANON);
2155
2156   /* If visibility changed and DECL already has DECL_RTL, ensure
2157      symbol flags are updated.  */
2158   if ((DECL_VISIBILITY (decl) != orig_visibility
2159        || DECL_VISIBILITY_SPECIFIED (decl) != orig_visibility_specified)
2160       && ((TREE_CODE (decl) == VAR_DECL && TREE_STATIC (decl))
2161           || TREE_CODE (decl) == FUNCTION_DECL)
2162       && DECL_RTL_SET_P (decl))
2163     make_decl_rtl (decl);
2164 }
2165
2166 /* By default, static data members and function members receive
2167    the visibility of their containing class.  */
2168
2169 static void
2170 determine_visibility_from_class (tree decl, tree class_type)
2171 {
2172   if (DECL_VISIBILITY_SPECIFIED (decl))
2173     return;
2174
2175   if (visibility_options.inlines_hidden
2176       /* Don't do this for inline templates; specializations might not be
2177          inline, and we don't want them to inherit the hidden
2178          visibility.  We'll set it here for all inline instantiations.  */
2179       && !processing_template_decl
2180       && TREE_CODE (decl) == FUNCTION_DECL
2181       && DECL_DECLARED_INLINE_P (decl)
2182       && (! DECL_LANG_SPECIFIC (decl)
2183           || ! DECL_EXPLICIT_INSTANTIATION (decl)))
2184     DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
2185   else
2186     {
2187       /* Default to the class visibility.  */
2188       DECL_VISIBILITY (decl) = CLASSTYPE_VISIBILITY (class_type);
2189       DECL_VISIBILITY_SPECIFIED (decl)
2190         = CLASSTYPE_VISIBILITY_SPECIFIED (class_type);
2191     }
2192
2193   /* Give the target a chance to override the visibility associated
2194      with DECL.  */
2195   if (TREE_CODE (decl) == VAR_DECL
2196       && (DECL_TINFO_P (decl)
2197           || (DECL_VTABLE_OR_VTT_P (decl)
2198               /* Construction virtual tables are not exported because
2199                  they cannot be referred to from other object files;
2200                  their name is not standardized by the ABI.  */
2201               && !DECL_CONSTRUCTION_VTABLE_P (decl)))
2202       && TREE_PUBLIC (decl)
2203       && !DECL_REALLY_EXTERN (decl)
2204       && !CLASSTYPE_VISIBILITY_SPECIFIED (class_type))
2205     targetm.cxx.determine_class_data_visibility (decl);
2206 }
2207
2208 /* Constrain the visibility of a class TYPE based on the visibility of its
2209    field types.  Warn if any fields require lesser visibility.  */
2210
2211 void
2212 constrain_class_visibility (tree type)
2213 {
2214   tree binfo;
2215   tree t;
2216   int i;
2217
2218   int vis = type_visibility (type);
2219
2220   if (vis == VISIBILITY_ANON
2221       || DECL_IN_SYSTEM_HEADER (TYPE_MAIN_DECL (type)))
2222     return;
2223
2224   /* Don't warn about visibility if the class has explicit visibility.  */
2225   if (CLASSTYPE_VISIBILITY_SPECIFIED (type))
2226     vis = VISIBILITY_INTERNAL;
2227
2228   for (t = TYPE_FIELDS (type); t; t = TREE_CHAIN (t))
2229     if (TREE_CODE (t) == FIELD_DECL && TREE_TYPE (t) != error_mark_node)
2230       {
2231         tree ftype = strip_pointer_or_array_types (TREE_TYPE (t));
2232         int subvis = type_visibility (ftype);
2233
2234         if (subvis == VISIBILITY_ANON)
2235           {
2236             if (!in_main_input_context ())
2237               warning (0, "\
2238 %qT has a field %qD whose type uses the anonymous namespace",
2239                        type, t);
2240           }
2241         else if (MAYBE_CLASS_TYPE_P (ftype)
2242                  && vis < VISIBILITY_HIDDEN
2243                  && subvis >= VISIBILITY_HIDDEN)
2244           warning (OPT_Wattributes, "\
2245 %qT declared with greater visibility than the type of its field %qD",
2246                    type, t);
2247       }
2248
2249   binfo = TYPE_BINFO (type);
2250   for (i = 0; BINFO_BASE_ITERATE (binfo, i, t); ++i)
2251     {
2252       int subvis = type_visibility (TREE_TYPE (t));
2253
2254       if (subvis == VISIBILITY_ANON)
2255         {
2256           if (!in_main_input_context())
2257             warning (0, "\
2258 %qT has a base %qT whose type uses the anonymous namespace",
2259                      type, TREE_TYPE (t));
2260         }
2261       else if (vis < VISIBILITY_HIDDEN
2262                && subvis >= VISIBILITY_HIDDEN)
2263         warning (OPT_Wattributes, "\
2264 %qT declared with greater visibility than its base %qT",
2265                  type, TREE_TYPE (t));
2266     }
2267 }
2268
2269 /* DECL is a FUNCTION_DECL or VAR_DECL.  If the object file linkage
2270    for DECL has not already been determined, do so now by setting
2271    DECL_EXTERNAL, DECL_COMDAT and other related flags.  Until this
2272    function is called entities with vague linkage whose definitions
2273    are available must have TREE_PUBLIC set.
2274
2275    If this function decides to place DECL in COMDAT, it will set
2276    appropriate flags -- but will not clear DECL_EXTERNAL.  It is up to
2277    the caller to decide whether or not to clear DECL_EXTERNAL.  Some
2278    callers defer that decision until it is clear that DECL is actually
2279    required.  */
2280
2281 void
2282 import_export_decl (tree decl)
2283 {
2284   int emit_p;
2285   bool comdat_p;
2286   bool import_p;
2287   tree class_type = NULL_TREE;
2288
2289   if (DECL_INTERFACE_KNOWN (decl))
2290     return;
2291
2292   /* We cannot determine what linkage to give to an entity with vague
2293      linkage until the end of the file.  For example, a virtual table
2294      for a class will be defined if and only if the key method is
2295      defined in this translation unit.  As a further example, consider
2296      that when compiling a translation unit that uses PCH file with
2297      "-frepo" it would be incorrect to make decisions about what
2298      entities to emit when building the PCH; those decisions must be
2299      delayed until the repository information has been processed.  */
2300   gcc_assert (at_eof);
2301   /* Object file linkage for explicit instantiations is handled in
2302      mark_decl_instantiated.  For static variables in functions with
2303      vague linkage, maybe_commonize_var is used.
2304
2305      Therefore, the only declarations that should be provided to this
2306      function are those with external linkage that are:
2307
2308      * implicit instantiations of function templates
2309
2310      * inline function
2311
2312      * implicit instantiations of static data members of class
2313        templates
2314
2315      * virtual tables
2316
2317      * typeinfo objects
2318
2319      Furthermore, all entities that reach this point must have a
2320      definition available in this translation unit.
2321
2322      The following assertions check these conditions.  */
2323   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
2324               || TREE_CODE (decl) == VAR_DECL);
2325   /* Any code that creates entities with TREE_PUBLIC cleared should
2326      also set DECL_INTERFACE_KNOWN.  */
2327   gcc_assert (TREE_PUBLIC (decl));
2328   if (TREE_CODE (decl) == FUNCTION_DECL)
2329     gcc_assert (DECL_IMPLICIT_INSTANTIATION (decl)
2330                 || DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
2331                 || DECL_DECLARED_INLINE_P (decl));
2332   else
2333     gcc_assert (DECL_IMPLICIT_INSTANTIATION (decl)
2334                 || DECL_VTABLE_OR_VTT_P (decl)
2335                 || DECL_TINFO_P (decl));
2336   /* Check that a definition of DECL is available in this translation
2337      unit.  */
2338   gcc_assert (!DECL_REALLY_EXTERN (decl));
2339
2340   /* Assume that DECL will not have COMDAT linkage.  */
2341   comdat_p = false;
2342   /* Assume that DECL will not be imported into this translation
2343      unit.  */
2344   import_p = false;
2345
2346   /* See if the repository tells us whether or not to emit DECL in
2347      this translation unit.  */
2348   emit_p = repo_emit_p (decl);
2349   if (emit_p == 0)
2350     import_p = true;
2351   else if (emit_p == 1)
2352     {
2353       /* The repository indicates that this entity should be defined
2354          here.  Make sure the back end honors that request.  */
2355       if (TREE_CODE (decl) == VAR_DECL)
2356         mark_needed (decl);
2357       else if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (decl)
2358                || DECL_MAYBE_IN_CHARGE_DESTRUCTOR_P (decl))
2359         {
2360           tree clone;
2361           FOR_EACH_CLONE (clone, decl)
2362             mark_needed (clone);
2363         }
2364       else
2365         mark_needed (decl);
2366       /* Output the definition as an ordinary strong definition.  */
2367       DECL_EXTERNAL (decl) = 0;
2368       DECL_INTERFACE_KNOWN (decl) = 1;
2369       return;
2370     }
2371
2372   if (import_p)
2373     /* We have already decided what to do with this DECL; there is no
2374        need to check anything further.  */
2375     ;
2376   else if (TREE_CODE (decl) == VAR_DECL && DECL_VTABLE_OR_VTT_P (decl))
2377     {
2378       class_type = DECL_CONTEXT (decl);
2379       import_export_class (class_type);
2380       if (TYPE_FOR_JAVA (class_type))
2381         import_p = true;
2382       else if (CLASSTYPE_INTERFACE_KNOWN (class_type)
2383                && CLASSTYPE_INTERFACE_ONLY (class_type))
2384         import_p = true;
2385       else if ((!flag_weak || TARGET_WEAK_NOT_IN_ARCHIVE_TOC)
2386                && !CLASSTYPE_USE_TEMPLATE (class_type)
2387                && CLASSTYPE_KEY_METHOD (class_type)
2388                && !DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (class_type)))
2389         /* The ABI requires that all virtual tables be emitted with
2390            COMDAT linkage.  However, on systems where COMDAT symbols
2391            don't show up in the table of contents for a static
2392            archive, or on systems without weak symbols (where we
2393            approximate COMDAT linkage by using internal linkage), the
2394            linker will report errors about undefined symbols because
2395            it will not see the virtual table definition.  Therefore,
2396            in the case that we know that the virtual table will be
2397            emitted in only one translation unit, we make the virtual
2398            table an ordinary definition with external linkage.  */
2399         DECL_EXTERNAL (decl) = 0;
2400       else if (CLASSTYPE_INTERFACE_KNOWN (class_type))
2401         {
2402           /* CLASS_TYPE is being exported from this translation unit,
2403              so DECL should be defined here.  */
2404           if (!flag_weak && CLASSTYPE_EXPLICIT_INSTANTIATION (class_type))
2405             /* If a class is declared in a header with the "extern
2406                template" extension, then it will not be instantiated,
2407                even in translation units that would normally require
2408                it.  Often such classes are explicitly instantiated in
2409                one translation unit.  Therefore, the explicit
2410                instantiation must be made visible to other translation
2411                units.  */
2412             DECL_EXTERNAL (decl) = 0;
2413           else
2414             {
2415               /* The generic C++ ABI says that class data is always
2416                  COMDAT, even if there is a key function.  Some
2417                  variants (e.g., the ARM EABI) says that class data
2418                  only has COMDAT linkage if the class data might be
2419                  emitted in more than one translation unit.  When the
2420                  key method can be inline and is inline, we still have
2421                  to arrange for comdat even though
2422                  class_data_always_comdat is false.  */
2423               if (!CLASSTYPE_KEY_METHOD (class_type)
2424                   || DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (class_type))
2425                   || targetm.cxx.class_data_always_comdat ())
2426                 {
2427                   /* The ABI requires COMDAT linkage.  Normally, we
2428                      only emit COMDAT things when they are needed;
2429                      make sure that we realize that this entity is
2430                      indeed needed.  */
2431                   comdat_p = true;
2432                   mark_needed (decl);
2433                 }
2434             }
2435         }
2436       else if (!flag_implicit_templates
2437                && CLASSTYPE_IMPLICIT_INSTANTIATION (class_type))
2438         import_p = true;
2439       else
2440         comdat_p = true;
2441     }
2442   else if (TREE_CODE (decl) == VAR_DECL && DECL_TINFO_P (decl))
2443     {
2444       tree type = TREE_TYPE (DECL_NAME (decl));
2445       if (CLASS_TYPE_P (type))
2446         {
2447           class_type = type;
2448           import_export_class (type);
2449           if (CLASSTYPE_INTERFACE_KNOWN (type)
2450               && TYPE_POLYMORPHIC_P (type)
2451               && CLASSTYPE_INTERFACE_ONLY (type)
2452               /* If -fno-rtti was specified, then we cannot be sure
2453                  that RTTI information will be emitted with the
2454                  virtual table of the class, so we must emit it
2455                  wherever it is used.  */
2456               && flag_rtti)
2457             import_p = true;
2458           else
2459             {
2460               if (CLASSTYPE_INTERFACE_KNOWN (type)
2461                   && !CLASSTYPE_INTERFACE_ONLY (type))
2462                 {
2463                   comdat_p = (targetm.cxx.class_data_always_comdat ()
2464                               || (CLASSTYPE_KEY_METHOD (type)
2465                                   && DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (type))));
2466                   mark_needed (decl);
2467                   if (!flag_weak)
2468                     {
2469                       comdat_p = false;
2470                       DECL_EXTERNAL (decl) = 0;
2471                     }
2472                 }
2473               else
2474                 comdat_p = true;
2475             }
2476         }
2477       else
2478         comdat_p = true;
2479     }
2480   else if (DECL_TEMPLATE_INSTANTIATION (decl)
2481            || DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl))
2482     {
2483       /* DECL is an implicit instantiation of a function or static
2484          data member.  */
2485       if ((flag_implicit_templates
2486            && !flag_use_repository)
2487           || (flag_implicit_inline_templates
2488               && TREE_CODE (decl) == FUNCTION_DECL
2489               && DECL_DECLARED_INLINE_P (decl)))
2490         comdat_p = true;
2491       else
2492         /* If we are not implicitly generating templates, then mark
2493            this entity as undefined in this translation unit.  */
2494         import_p = true;
2495     }
2496   else if (DECL_FUNCTION_MEMBER_P (decl))
2497     {
2498       if (!DECL_DECLARED_INLINE_P (decl))
2499         {
2500           tree ctype = DECL_CONTEXT (decl);
2501           import_export_class (ctype);
2502           if (CLASSTYPE_INTERFACE_KNOWN (ctype))
2503             {
2504               DECL_NOT_REALLY_EXTERN (decl)
2505                 = ! (CLASSTYPE_INTERFACE_ONLY (ctype)
2506                      || (DECL_DECLARED_INLINE_P (decl)
2507                          && ! flag_implement_inlines
2508                          && !DECL_VINDEX (decl)));
2509
2510               if (!DECL_NOT_REALLY_EXTERN (decl))
2511                 DECL_EXTERNAL (decl) = 1;
2512
2513               /* Always make artificials weak.  */
2514               if (DECL_ARTIFICIAL (decl) && flag_weak)
2515                 comdat_p = true;
2516               else
2517                 maybe_make_one_only (decl);
2518             }
2519         }
2520       else
2521         comdat_p = true;
2522     }
2523   else
2524     comdat_p = true;
2525
2526   if (import_p)
2527     {
2528       /* If we are importing DECL into this translation unit, mark is
2529          an undefined here.  */
2530       DECL_EXTERNAL (decl) = 1;
2531       DECL_NOT_REALLY_EXTERN (decl) = 0;
2532     }
2533   else if (comdat_p)
2534     {
2535       /* If we decided to put DECL in COMDAT, mark it accordingly at
2536          this point.  */
2537       comdat_linkage (decl);
2538     }
2539
2540   DECL_INTERFACE_KNOWN (decl) = 1;
2541 }
2542
2543 /* Return an expression that performs the destruction of DECL, which
2544    must be a VAR_DECL whose type has a non-trivial destructor, or is
2545    an array whose (innermost) elements have a non-trivial destructor.  */
2546
2547 tree
2548 build_cleanup (tree decl)
2549 {
2550   tree temp;
2551   tree type = TREE_TYPE (decl);
2552
2553   /* This function should only be called for declarations that really
2554      require cleanups.  */
2555   gcc_assert (!TYPE_HAS_TRIVIAL_DESTRUCTOR (type));
2556
2557   /* Treat all objects with destructors as used; the destructor may do
2558      something substantive.  */
2559   mark_used (decl);
2560
2561   if (TREE_CODE (type) == ARRAY_TYPE)
2562     temp = decl;
2563   else
2564     temp = build_address (decl);
2565   temp = build_delete (TREE_TYPE (temp), temp,
2566                        sfk_complete_destructor,
2567                        LOOKUP_NORMAL|LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR, 0);
2568   return temp;
2569 }
2570
2571 /* Returns the initialization guard variable for the variable DECL,
2572    which has static storage duration.  */
2573
2574 tree
2575 get_guard (tree decl)
2576 {
2577   tree sname;
2578   tree guard;
2579
2580   sname = mangle_guard_variable (decl);
2581   guard = IDENTIFIER_GLOBAL_VALUE (sname);
2582   if (! guard)
2583     {
2584       tree guard_type;
2585
2586       /* We use a type that is big enough to contain a mutex as well
2587          as an integer counter.  */
2588       guard_type = targetm.cxx.guard_type ();
2589       guard = build_decl (DECL_SOURCE_LOCATION (decl),
2590                           VAR_DECL, sname, guard_type);
2591
2592       /* The guard should have the same linkage as what it guards.  */
2593       TREE_PUBLIC (guard) = TREE_PUBLIC (decl);
2594       TREE_STATIC (guard) = TREE_STATIC (decl);
2595       DECL_COMMON (guard) = DECL_COMMON (decl);
2596       DECL_COMDAT (guard) = DECL_COMDAT (decl);
2597       if (DECL_ONE_ONLY (decl))
2598         make_decl_one_only (guard, cxx_comdat_group (guard));
2599       if (TREE_PUBLIC (decl))
2600         DECL_WEAK (guard) = DECL_WEAK (decl);
2601       DECL_VISIBILITY (guard) = DECL_VISIBILITY (decl);
2602       DECL_VISIBILITY_SPECIFIED (guard) = DECL_VISIBILITY_SPECIFIED (decl);
2603
2604       DECL_ARTIFICIAL (guard) = 1;
2605       DECL_IGNORED_P (guard) = 1;
2606       TREE_USED (guard) = 1;
2607       pushdecl_top_level_and_finish (guard, NULL_TREE);
2608     }
2609   return guard;
2610 }
2611
2612 /* Return those bits of the GUARD variable that should be set when the
2613    guarded entity is actually initialized.  */
2614
2615 static tree
2616 get_guard_bits (tree guard)
2617 {
2618   if (!targetm.cxx.guard_mask_bit ())
2619     {
2620       /* We only set the first byte of the guard, in order to leave room
2621          for a mutex in the high-order bits.  */
2622       guard = build1 (ADDR_EXPR,
2623                       build_pointer_type (TREE_TYPE (guard)),
2624                       guard);
2625       guard = build1 (NOP_EXPR,
2626                       build_pointer_type (char_type_node),
2627                       guard);
2628       guard = build1 (INDIRECT_REF, char_type_node, guard);
2629     }
2630
2631   return guard;
2632 }
2633
2634 /* Return an expression which determines whether or not the GUARD
2635    variable has already been initialized.  */
2636
2637 tree
2638 get_guard_cond (tree guard)
2639 {
2640   tree guard_value;
2641
2642   /* Check to see if the GUARD is zero.  */
2643   guard = get_guard_bits (guard);
2644
2645   /* Mask off all but the low bit.  */
2646   if (targetm.cxx.guard_mask_bit ())
2647     {
2648       guard_value = integer_one_node;
2649       if (!same_type_p (TREE_TYPE (guard_value), TREE_TYPE (guard)))
2650         guard_value = convert (TREE_TYPE (guard), guard_value);
2651       guard = cp_build_binary_op (input_location,
2652                                   BIT_AND_EXPR, guard, guard_value,
2653                                   tf_warning_or_error);
2654     }
2655
2656   guard_value = integer_zero_node;
2657   if (!same_type_p (TREE_TYPE (guard_value), TREE_TYPE (guard)))
2658     guard_value = convert (TREE_TYPE (guard), guard_value);
2659   return cp_build_binary_op (input_location,
2660                              EQ_EXPR, guard, guard_value,
2661                              tf_warning_or_error);
2662 }
2663
2664 /* Return an expression which sets the GUARD variable, indicating that
2665    the variable being guarded has been initialized.  */
2666
2667 tree
2668 set_guard (tree guard)
2669 {
2670   tree guard_init;
2671
2672   /* Set the GUARD to one.  */
2673   guard = get_guard_bits (guard);
2674   guard_init = integer_one_node;
2675   if (!same_type_p (TREE_TYPE (guard_init), TREE_TYPE (guard)))
2676     guard_init = convert (TREE_TYPE (guard), guard_init);
2677   return cp_build_modify_expr (guard, NOP_EXPR, guard_init, 
2678                                tf_warning_or_error);
2679 }
2680
2681 /* Start the process of running a particular set of global constructors
2682    or destructors.  Subroutine of do_[cd]tors.  */
2683
2684 static tree
2685 start_objects (int method_type, int initp)
2686 {
2687   tree body;
2688   tree fndecl;
2689   char type[10];
2690
2691   /* Make ctor or dtor function.  METHOD_TYPE may be 'I' or 'D'.  */
2692
2693   if (initp != DEFAULT_INIT_PRIORITY)
2694     {
2695       char joiner;
2696
2697 #ifdef JOINER
2698       joiner = JOINER;
2699 #else
2700       joiner = '_';
2701 #endif
2702
2703       sprintf (type, "%c%c%.5u", method_type, joiner, initp);
2704     }
2705   else
2706     sprintf (type, "%c", method_type);
2707
2708   fndecl = build_lang_decl (FUNCTION_DECL,
2709                             get_file_function_name (type),
2710                             build_function_type (void_type_node,
2711                                                  void_list_node));
2712   start_preparsed_function (fndecl, /*attrs=*/NULL_TREE, SF_PRE_PARSED);
2713
2714   TREE_PUBLIC (current_function_decl) = 0;
2715
2716   /* Mark as artificial because it's not explicitly in the user's
2717      source code.  */
2718   DECL_ARTIFICIAL (current_function_decl) = 1;
2719
2720   /* Mark this declaration as used to avoid spurious warnings.  */
2721   TREE_USED (current_function_decl) = 1;
2722
2723   /* Mark this function as a global constructor or destructor.  */
2724   if (method_type == 'I')
2725     DECL_GLOBAL_CTOR_P (current_function_decl) = 1;
2726   else
2727     DECL_GLOBAL_DTOR_P (current_function_decl) = 1;
2728
2729   body = begin_compound_stmt (BCS_FN_BODY);
2730
2731   return body;
2732 }
2733
2734 /* Finish the process of running a particular set of global constructors
2735    or destructors.  Subroutine of do_[cd]tors.  */
2736
2737 static void
2738 finish_objects (int method_type, int initp, tree body)
2739 {
2740   tree fn;
2741
2742   /* Finish up.  */
2743   finish_compound_stmt (body);
2744   fn = finish_function (0);
2745
2746   if (method_type == 'I')
2747     {
2748       DECL_STATIC_CONSTRUCTOR (fn) = 1;
2749       decl_init_priority_insert (fn, initp);
2750     }
2751   else
2752     {
2753       DECL_STATIC_DESTRUCTOR (fn) = 1;
2754       decl_fini_priority_insert (fn, initp);
2755     }
2756
2757   expand_or_defer_fn (fn);
2758 }
2759
2760 /* The names of the parameters to the function created to handle
2761    initializations and destructions for objects with static storage
2762    duration.  */
2763 #define INITIALIZE_P_IDENTIFIER "__initialize_p"
2764 #define PRIORITY_IDENTIFIER "__priority"
2765
2766 /* The name of the function we create to handle initializations and
2767    destructions for objects with static storage duration.  */
2768 #define SSDF_IDENTIFIER "__static_initialization_and_destruction"
2769
2770 /* The declaration for the __INITIALIZE_P argument.  */
2771 static GTY(()) tree initialize_p_decl;
2772
2773 /* The declaration for the __PRIORITY argument.  */
2774 static GTY(()) tree priority_decl;
2775
2776 /* The declaration for the static storage duration function.  */
2777 static GTY(()) tree ssdf_decl;
2778
2779 /* All the static storage duration functions created in this
2780    translation unit.  */
2781 static GTY(()) VEC(tree,gc) *ssdf_decls;
2782
2783 /* A map from priority levels to information about that priority
2784    level.  There may be many such levels, so efficient lookup is
2785    important.  */
2786 static splay_tree priority_info_map;
2787
2788 /* Begins the generation of the function that will handle all
2789    initialization and destruction of objects with static storage
2790    duration.  The function generated takes two parameters of type
2791    `int': __INITIALIZE_P and __PRIORITY.  If __INITIALIZE_P is
2792    nonzero, it performs initializations.  Otherwise, it performs
2793    destructions.  It only performs those initializations or
2794    destructions with the indicated __PRIORITY.  The generated function
2795    returns no value.
2796
2797    It is assumed that this function will only be called once per
2798    translation unit.  */
2799
2800 static tree
2801 start_static_storage_duration_function (unsigned count)
2802 {
2803   tree parm_types;
2804   tree type;
2805   tree body;
2806   char id[sizeof (SSDF_IDENTIFIER) + 1 /* '\0' */ + 32];
2807
2808   /* Create the identifier for this function.  It will be of the form
2809      SSDF_IDENTIFIER_<number>.  */
2810   sprintf (id, "%s_%u", SSDF_IDENTIFIER, count);
2811
2812   /* Create the parameters.  */
2813   parm_types = void_list_node;
2814   parm_types = tree_cons (NULL_TREE, integer_type_node, parm_types);
2815   parm_types = tree_cons (NULL_TREE, integer_type_node, parm_types);
2816   type = build_function_type (void_type_node, parm_types);
2817
2818   /* Create the FUNCTION_DECL itself.  */
2819   ssdf_decl = build_lang_decl (FUNCTION_DECL,
2820                                get_identifier (id),
2821                                type);
2822   TREE_PUBLIC (ssdf_decl) = 0;
2823   DECL_ARTIFICIAL (ssdf_decl) = 1;
2824
2825   /* Put this function in the list of functions to be called from the
2826      static constructors and destructors.  */
2827   if (!ssdf_decls)
2828     {
2829       ssdf_decls = VEC_alloc (tree, gc, 32);
2830
2831       /* Take this opportunity to initialize the map from priority
2832          numbers to information about that priority level.  */
2833       priority_info_map = splay_tree_new (splay_tree_compare_ints,
2834                                           /*delete_key_fn=*/0,
2835                                           /*delete_value_fn=*/
2836                                           (splay_tree_delete_value_fn) &free);
2837
2838       /* We always need to generate functions for the
2839          DEFAULT_INIT_PRIORITY so enter it now.  That way when we walk
2840          priorities later, we'll be sure to find the
2841          DEFAULT_INIT_PRIORITY.  */
2842       get_priority_info (DEFAULT_INIT_PRIORITY);
2843     }
2844
2845   VEC_safe_push (tree, gc, ssdf_decls, ssdf_decl);
2846
2847   /* Create the argument list.  */
2848   initialize_p_decl = cp_build_parm_decl
2849     (get_identifier (INITIALIZE_P_IDENTIFIER), integer_type_node);
2850   DECL_CONTEXT (initialize_p_decl) = ssdf_decl;
2851   TREE_USED (initialize_p_decl) = 1;
2852   priority_decl = cp_build_parm_decl
2853     (get_identifier (PRIORITY_IDENTIFIER), integer_type_node);
2854   DECL_CONTEXT (priority_decl) = ssdf_decl;
2855   TREE_USED (priority_decl) = 1;
2856
2857   TREE_CHAIN (initialize_p_decl) = priority_decl;
2858   DECL_ARGUMENTS (ssdf_decl) = initialize_p_decl;
2859
2860   /* Put the function in the global scope.  */
2861   pushdecl (ssdf_decl);
2862
2863   /* Start the function itself.  This is equivalent to declaring the
2864      function as:
2865
2866        static void __ssdf (int __initialize_p, init __priority_p);
2867
2868      It is static because we only need to call this function from the
2869      various constructor and destructor functions for this module.  */
2870   start_preparsed_function (ssdf_decl,
2871                             /*attrs=*/NULL_TREE,
2872                             SF_PRE_PARSED);
2873
2874   /* Set up the scope of the outermost block in the function.  */
2875   body = begin_compound_stmt (BCS_FN_BODY);
2876
2877   return body;
2878 }
2879
2880 /* Finish the generation of the function which performs initialization
2881    and destruction of objects with static storage duration.  After
2882    this point, no more such objects can be created.  */
2883
2884 static void
2885 finish_static_storage_duration_function (tree body)
2886 {
2887   /* Close out the function.  */
2888   finish_compound_stmt (body);
2889   expand_or_defer_fn (finish_function (0));
2890 }
2891
2892 /* Return the information about the indicated PRIORITY level.  If no
2893    code to handle this level has yet been generated, generate the
2894    appropriate prologue.  */
2895
2896 static priority_info
2897 get_priority_info (int priority)
2898 {
2899   priority_info pi;
2900   splay_tree_node n;
2901
2902   n = splay_tree_lookup (priority_info_map,
2903                          (splay_tree_key) priority);
2904   if (!n)
2905     {
2906       /* Create a new priority information structure, and insert it
2907          into the map.  */
2908       pi = XNEW (struct priority_info_s);
2909       pi->initializations_p = 0;
2910       pi->destructions_p = 0;
2911       splay_tree_insert (priority_info_map,
2912                          (splay_tree_key) priority,
2913                          (splay_tree_value) pi);
2914     }
2915   else
2916     pi = (priority_info) n->value;
2917
2918   return pi;
2919 }
2920
2921 /* The effective initialization priority of a DECL.  */
2922
2923 #define DECL_EFFECTIVE_INIT_PRIORITY(decl)                                    \
2924         ((!DECL_HAS_INIT_PRIORITY_P (decl) || DECL_INIT_PRIORITY (decl) == 0) \
2925          ? DEFAULT_INIT_PRIORITY : DECL_INIT_PRIORITY (decl))
2926
2927 /* Whether a DECL needs a guard to protect it against multiple
2928    initialization.  */
2929
2930 #define NEEDS_GUARD_P(decl) (TREE_PUBLIC (decl) && (DECL_COMMON (decl)      \
2931                                                     || DECL_ONE_ONLY (decl) \
2932                                                     || DECL_WEAK (decl)))
2933
2934 /* Called from one_static_initialization_or_destruction(),
2935    via walk_tree.
2936    Walks the initializer list of a global variable and looks for
2937    temporary variables (DECL_NAME() == NULL and DECL_ARTIFICIAL != 0)
2938    and that have their DECL_CONTEXT() == NULL.
2939    For each such temporary variable, set their DECL_CONTEXT() to
2940    the current function. This is necessary because otherwise
2941    some optimizers (enabled by -O2 -fprofile-arcs) might crash
2942    when trying to refer to a temporary variable that does not have
2943    it's DECL_CONTECT() properly set.  */
2944 static tree 
2945 fix_temporary_vars_context_r (tree *node,
2946                               int  *unused ATTRIBUTE_UNUSED,
2947                               void *unused1 ATTRIBUTE_UNUSED)
2948 {
2949   gcc_assert (current_function_decl);
2950
2951   if (TREE_CODE (*node) == BIND_EXPR)
2952     {
2953       tree var;
2954
2955       for (var = BIND_EXPR_VARS (*node); var; var = TREE_CHAIN (var))
2956         if (TREE_CODE (var) == VAR_DECL
2957           && !DECL_NAME (var)
2958           && DECL_ARTIFICIAL (var)
2959           && !DECL_CONTEXT (var))
2960           DECL_CONTEXT (var) = current_function_decl;
2961     }
2962
2963   return NULL_TREE;
2964 }
2965
2966 /* Set up to handle the initialization or destruction of DECL.  If
2967    INITP is nonzero, we are initializing the variable.  Otherwise, we
2968    are destroying it.  */
2969
2970 static void
2971 one_static_initialization_or_destruction (tree decl, tree init, bool initp)
2972 {
2973   tree guard_if_stmt = NULL_TREE;
2974   tree guard;
2975
2976   /* If we are supposed to destruct and there's a trivial destructor,
2977      nothing has to be done.  */
2978   if (!initp
2979       && TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl)))
2980     return;
2981
2982   /* Trick the compiler into thinking we are at the file and line
2983      where DECL was declared so that error-messages make sense, and so
2984      that the debugger will show somewhat sensible file and line
2985      information.  */
2986   input_location = DECL_SOURCE_LOCATION (decl);
2987
2988   /* Make sure temporary variables in the initialiser all have
2989      their DECL_CONTEXT() set to a value different from NULL_TREE.
2990      This can happen when global variables initialisers are built.
2991      In that case, the DECL_CONTEXT() of the global variables _AND_ of all 
2992      the temporary variables that might have been generated in the
2993      accompagning initialisers is NULL_TREE, meaning the variables have been
2994      declared in the global namespace.
2995      What we want to do here is to fix that and make sure the DECL_CONTEXT()
2996      of the temporaries are set to the current function decl.  */
2997   cp_walk_tree_without_duplicates (&init,
2998                                    fix_temporary_vars_context_r,
2999                                    NULL);
3000
3001   /* Because of:
3002
3003        [class.access.spec]
3004
3005        Access control for implicit calls to the constructors,
3006        the conversion functions, or the destructor called to
3007        create and destroy a static data member is performed as
3008        if these calls appeared in the scope of the member's
3009        class.
3010
3011      we pretend we are in a static member function of the class of
3012      which the DECL is a member.  */
3013   if (member_p (decl))
3014     {
3015       DECL_CONTEXT (current_function_decl) = DECL_CONTEXT (decl);
3016       DECL_STATIC_FUNCTION_P (current_function_decl) = 1;
3017     }
3018
3019   /* Assume we don't need a guard.  */
3020   guard = NULL_TREE;
3021   /* We need a guard if this is an object with external linkage that
3022      might be initialized in more than one place.  (For example, a
3023      static data member of a template, when the data member requires
3024      construction.)  */
3025   if (NEEDS_GUARD_P (decl))
3026     {
3027       tree guard_cond;
3028
3029       guard = get_guard (decl);
3030
3031       /* When using __cxa_atexit, we just check the GUARD as we would
3032          for a local static.  */
3033       if (flag_use_cxa_atexit)
3034         {
3035           /* When using __cxa_atexit, we never try to destroy
3036              anything from a static destructor.  */
3037           gcc_assert (initp);
3038           guard_cond = get_guard_cond (guard);
3039         }
3040       /* If we don't have __cxa_atexit, then we will be running
3041          destructors from .fini sections, or their equivalents.  So,
3042          we need to know how many times we've tried to initialize this
3043          object.  We do initializations only if the GUARD is zero,
3044          i.e., if we are the first to initialize the variable.  We do
3045          destructions only if the GUARD is one, i.e., if we are the
3046          last to destroy the variable.  */
3047       else if (initp)
3048         guard_cond
3049           = cp_build_binary_op (input_location,
3050                                 EQ_EXPR,
3051                                 cp_build_unary_op (PREINCREMENT_EXPR,
3052                                                    guard,
3053                                                    /*noconvert=*/1,
3054                                                    tf_warning_or_error),
3055                                 integer_one_node,
3056                                 tf_warning_or_error);
3057       else
3058         guard_cond
3059           = cp_build_binary_op (input_location,
3060                                 EQ_EXPR,
3061                                 cp_build_unary_op (PREDECREMENT_EXPR,
3062                                                    guard,
3063                                                    /*noconvert=*/1,
3064                                                    tf_warning_or_error),
3065                                 integer_zero_node,
3066                                 tf_warning_or_error);
3067
3068       guard_if_stmt = begin_if_stmt ();
3069       finish_if_stmt_cond (guard_cond, guard_if_stmt);
3070     }
3071
3072
3073   /* If we're using __cxa_atexit, we have not already set the GUARD,
3074      so we must do so now.  */
3075   if (guard && initp && flag_use_cxa_atexit)
3076     finish_expr_stmt (set_guard (guard));
3077
3078   /* Perform the initialization or destruction.  */
3079   if (initp)
3080     {
3081       if (init)
3082         finish_expr_stmt (init);
3083
3084       /* If we're using __cxa_atexit, register a function that calls the
3085          destructor for the object.  */
3086       if (flag_use_cxa_atexit)
3087         finish_expr_stmt (register_dtor_fn (decl));
3088     }
3089   else
3090     finish_expr_stmt (build_cleanup (decl));
3091
3092   /* Finish the guard if-stmt, if necessary.  */
3093   if (guard)
3094     {
3095       finish_then_clause (guard_if_stmt);
3096       finish_if_stmt (guard_if_stmt);
3097     }
3098
3099   /* Now that we're done with DECL we don't need to pretend to be a
3100      member of its class any longer.  */
3101   DECL_CONTEXT (current_function_decl) = NULL_TREE;
3102   DECL_STATIC_FUNCTION_P (current_function_decl) = 0;
3103 }
3104
3105 /* Generate code to do the initialization or destruction of the decls in VARS,
3106    a TREE_LIST of VAR_DECL with static storage duration.
3107    Whether initialization or destruction is performed is specified by INITP.  */
3108
3109 static void
3110 do_static_initialization_or_destruction (tree vars, bool initp)
3111 {
3112   tree node, init_if_stmt, cond;
3113
3114   /* Build the outer if-stmt to check for initialization or destruction.  */
3115   init_if_stmt = begin_if_stmt ();
3116   cond = initp ? integer_one_node : integer_zero_node;
3117   cond = cp_build_binary_op (input_location,
3118                              EQ_EXPR,
3119                              initialize_p_decl,
3120                              cond,
3121                              tf_warning_or_error);
3122   finish_if_stmt_cond (cond, init_if_stmt);
3123
3124   node = vars;
3125   do {
3126     tree decl = TREE_VALUE (node);
3127     tree priority_if_stmt;
3128     int priority;
3129     priority_info pi;
3130
3131     /* If we don't need a destructor, there's nothing to do.  Avoid
3132        creating a possibly empty if-stmt.  */
3133     if (!initp && TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl)))
3134       {
3135         node = TREE_CHAIN (node);
3136         continue;
3137       }
3138
3139     /* Remember that we had an initialization or finalization at this
3140        priority.  */
3141     priority = DECL_EFFECTIVE_INIT_PRIORITY (decl);
3142     pi = get_priority_info (priority);
3143     if (initp)
3144       pi->initializations_p = 1;
3145     else
3146       pi->destructions_p = 1;
3147
3148     /* Conditionalize this initialization on being in the right priority
3149        and being initializing/finalizing appropriately.  */
3150     priority_if_stmt = begin_if_stmt ();
3151     cond = cp_build_binary_op (input_location,
3152                                EQ_EXPR,
3153                                priority_decl,
3154                                build_int_cst (NULL_TREE, priority),
3155                                tf_warning_or_error);
3156     finish_if_stmt_cond (cond, priority_if_stmt);
3157
3158     /* Process initializers with same priority.  */
3159     for (; node
3160            && DECL_EFFECTIVE_INIT_PRIORITY (TREE_VALUE (node)) == priority;
3161          node = TREE_CHAIN (node))
3162       /* Do one initialization or destruction.  */
3163       one_static_initialization_or_destruction (TREE_VALUE (node),
3164                                                 TREE_PURPOSE (node), initp);
3165
3166     /* Finish up the priority if-stmt body.  */
3167     finish_then_clause (priority_if_stmt);
3168     finish_if_stmt (priority_if_stmt);
3169
3170   } while (node);
3171
3172   /* Finish up the init/destruct if-stmt body.  */
3173   finish_then_clause (init_if_stmt);
3174   finish_if_stmt (init_if_stmt);
3175 }
3176
3177 /* VARS is a list of variables with static storage duration which may
3178    need initialization and/or finalization.  Remove those variables
3179    that don't really need to be initialized or finalized, and return
3180    the resulting list.  The order in which the variables appear in
3181    VARS is in reverse order of the order in which they should actually
3182    be initialized.  The list we return is in the unreversed order;
3183    i.e., the first variable should be initialized first.  */
3184
3185 static tree
3186 prune_vars_needing_no_initialization (tree *vars)
3187 {
3188   tree *var = vars;
3189   tree result = NULL_TREE;
3190
3191   while (*var)
3192     {
3193       tree t = *var;
3194       tree decl = TREE_VALUE (t);
3195       tree init = TREE_PURPOSE (t);
3196
3197       /* Deal gracefully with error.  */
3198       if (decl == error_mark_node)
3199         {
3200           var = &TREE_CHAIN (t);
3201           continue;
3202         }
3203
3204       /* The only things that can be initialized are variables.  */
3205       gcc_assert (TREE_CODE (decl) == VAR_DECL);
3206
3207       /* If this object is not defined, we don't need to do anything
3208          here.  */
3209       if (DECL_EXTERNAL (decl))
3210         {
3211           var = &TREE_CHAIN (t);
3212           continue;
3213         }
3214
3215       /* Also, if the initializer already contains errors, we can bail
3216          out now.  */
3217       if (init && TREE_CODE (init) == TREE_LIST
3218           && value_member (error_mark_node, init))
3219         {
3220           var = &TREE_CHAIN (t);
3221           continue;
3222         }
3223
3224       /* This variable is going to need initialization and/or
3225          finalization, so we add it to the list.  */
3226       *var = TREE_CHAIN (t);
3227       TREE_CHAIN (t) = result;
3228       result = t;
3229     }
3230
3231   return result;
3232 }
3233
3234 /* Make sure we have told the back end about all the variables in
3235    VARS.  */
3236
3237 static void
3238 write_out_vars (tree vars)
3239 {
3240   tree v;
3241
3242   for (v = vars; v; v = TREE_CHAIN (v))
3243     {
3244       tree var = TREE_VALUE (v);
3245       if (!var_finalized_p (var))
3246         {
3247           import_export_decl (var);
3248           rest_of_decl_compilation (var, 1, 1);
3249         }
3250     }
3251 }
3252
3253 /* Generate a static constructor (if CONSTRUCTOR_P) or destructor
3254    (otherwise) that will initialize all global objects with static
3255    storage duration having the indicated PRIORITY.  */
3256
3257 static void
3258 generate_ctor_or_dtor_function (bool constructor_p, int priority,
3259                                 location_t *locus)
3260 {
3261   char function_key;
3262   tree arguments;
3263   tree fndecl;
3264   tree body;
3265   size_t i;
3266
3267   input_location = *locus;
3268   /* ??? */
3269   /* Was: locus->line++; */
3270
3271   /* We use `I' to indicate initialization and `D' to indicate
3272      destruction.  */
3273   function_key = constructor_p ? 'I' : 'D';
3274
3275   /* We emit the function lazily, to avoid generating empty
3276      global constructors and destructors.  */
3277   body = NULL_TREE;
3278
3279   /* For Objective-C++, we may need to initialize metadata found in this module.
3280      This must be done _before_ any other static initializations.  */
3281   if (c_dialect_objc () && (priority == DEFAULT_INIT_PRIORITY)
3282       && constructor_p && objc_static_init_needed_p ())
3283     {
3284       body = start_objects (function_key, priority);
3285       objc_generate_static_init_call (NULL_TREE);
3286     }
3287
3288   /* Call the static storage duration function with appropriate
3289      arguments.  */
3290   for (i = 0; VEC_iterate (tree, ssdf_decls, i, fndecl); ++i)
3291     {
3292       /* Calls to pure or const functions will expand to nothing.  */
3293       if (! (flags_from_decl_or_type (fndecl) & (ECF_CONST | ECF_PURE)))
3294         {
3295           if (! body)
3296             body = start_objects (function_key, priority);
3297
3298           arguments = tree_cons (NULL_TREE,
3299                                  build_int_cst (NULL_TREE, priority),
3300                                  NULL_TREE);
3301           arguments = tree_cons (NULL_TREE,
3302                                  build_int_cst (NULL_TREE, constructor_p),
3303                                  arguments);
3304           finish_expr_stmt (cp_build_function_call (fndecl, arguments,
3305                                                     tf_warning_or_error));
3306         }
3307     }
3308
3309   /* Close out the function.  */
3310   if (body)
3311     finish_objects (function_key, priority, body);
3312 }
3313
3314 /* Generate constructor and destructor functions for the priority
3315    indicated by N.  */
3316
3317 static int
3318 generate_ctor_and_dtor_functions_for_priority (splay_tree_node n, void * data)
3319 {
3320   location_t *locus = (location_t *) data;
3321   int priority = (int) n->key;
3322   priority_info pi = (priority_info) n->value;
3323
3324   /* Generate the functions themselves, but only if they are really
3325      needed.  */
3326   if (pi->initializations_p)
3327     generate_ctor_or_dtor_function (/*constructor_p=*/true, priority, locus);
3328   if (pi->destructions_p)
3329     generate_ctor_or_dtor_function (/*constructor_p=*/false, priority, locus);
3330
3331   /* Keep iterating.  */
3332   return 0;
3333 }
3334
3335 /* Called via LANGHOOK_CALLGRAPH_ANALYZE_EXPR.  It is supposed to mark
3336    decls referenced from front-end specific constructs; it will be called
3337    only for language-specific tree nodes.
3338
3339    Here we must deal with member pointers.  */
3340
3341 tree
3342 cxx_callgraph_analyze_expr (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED)
3343 {
3344   tree t = *tp;
3345
3346   switch (TREE_CODE (t))
3347     {
3348     case PTRMEM_CST:
3349       if (TYPE_PTRMEMFUNC_P (TREE_TYPE (t)))
3350         cgraph_mark_address_taken_node (cgraph_node (PTRMEM_CST_MEMBER (t)));
3351       break;
3352     case BASELINK:
3353       if (TREE_CODE (BASELINK_FUNCTIONS (t)) == FUNCTION_DECL)
3354         cgraph_mark_address_taken_node (cgraph_node (BASELINK_FUNCTIONS (t)));
3355       break;
3356     case VAR_DECL:
3357       if (DECL_VTABLE_OR_VTT_P (t))
3358         {
3359           /* The ABI requires that all virtual tables be emitted
3360              whenever one of them is.  */
3361           tree vtbl;
3362           for (vtbl = CLASSTYPE_VTABLES (DECL_CONTEXT (t));
3363                vtbl;
3364                vtbl = TREE_CHAIN (vtbl))
3365             mark_decl_referenced (vtbl);
3366         }
3367       else if (DECL_CONTEXT (t)
3368                && flag_use_repository
3369                && TREE_CODE (DECL_CONTEXT (t)) == FUNCTION_DECL)
3370         /* If we need a static variable in a function, then we
3371            need the containing function.  */
3372         mark_decl_referenced (DECL_CONTEXT (t));
3373       break;
3374     default:
3375       break;
3376     }
3377
3378   return NULL;
3379 }
3380
3381 /* Java requires that we be able to reference a local address for a
3382    method, and not be confused by PLT entries.  If hidden aliases are
3383    supported, collect and return all the functions for which we should
3384    emit a hidden alias.  */
3385
3386 static struct pointer_set_t *
3387 collect_candidates_for_java_method_aliases (void)
3388 {
3389   struct cgraph_node *node;
3390   struct pointer_set_t *candidates = NULL;
3391
3392 #ifndef HAVE_GAS_HIDDEN
3393   return candidates;
3394 #endif
3395
3396   for (node = cgraph_nodes; node ; node = node->next)
3397     {
3398       tree fndecl = node->decl;
3399
3400       if (DECL_CONTEXT (fndecl)
3401           && TYPE_P (DECL_CONTEXT (fndecl))
3402           && TYPE_FOR_JAVA (DECL_CONTEXT (fndecl))
3403           && TARGET_USE_LOCAL_THUNK_ALIAS_P (fndecl))
3404         {
3405           if (candidates == NULL)
3406             candidates = pointer_set_create ();
3407           pointer_set_insert (candidates, fndecl);
3408         }
3409     }
3410
3411   return candidates;
3412 }
3413
3414
3415 /* Java requires that we be able to reference a local address for a
3416    method, and not be confused by PLT entries.  If hidden aliases are
3417    supported, emit one for each java function that we've emitted.
3418    CANDIDATES is the set of FUNCTION_DECLs that were gathered
3419    by collect_candidates_for_java_method_aliases.  */
3420
3421 static void
3422 build_java_method_aliases (struct pointer_set_t *candidates)
3423 {
3424   struct cgraph_node *node;
3425
3426 #ifndef HAVE_GAS_HIDDEN
3427   return;
3428 #endif
3429
3430   for (node = cgraph_nodes; node ; node = node->next)
3431     {
3432       tree fndecl = node->decl;
3433
3434       if (TREE_ASM_WRITTEN (fndecl)
3435           && pointer_set_contains (candidates, fndecl))
3436         {
3437           /* Mangle the name in a predictable way; we need to reference
3438              this from a java compiled object file.  */
3439           tree oid, nid, alias;
3440           const char *oname;
3441           char *nname;
3442
3443           oid = DECL_ASSEMBLER_NAME (fndecl);
3444           oname = IDENTIFIER_POINTER (oid);
3445           gcc_assert (oname[0] == '_' && oname[1] == 'Z');
3446           nname = ACONCAT (("_ZGA", oname+2, NULL));
3447           nid = get_identifier (nname);
3448
3449           alias = make_alias_for (fndecl, nid);
3450           TREE_PUBLIC (alias) = 1;
3451           DECL_VISIBILITY (alias) = VISIBILITY_HIDDEN;
3452
3453           assemble_alias (alias, oid);
3454         }
3455     }
3456 }
3457
3458 /* Returns true iff there is a definition available for variable or
3459    function DECL.  */
3460
3461 static bool
3462 decl_defined_p (tree decl)
3463 {
3464   if (TREE_CODE (decl) == FUNCTION_DECL)
3465     return (DECL_INITIAL (decl) != NULL_TREE);
3466   else
3467     {
3468       gcc_assert (TREE_CODE (decl) == VAR_DECL);
3469       return !DECL_EXTERNAL (decl);
3470     }
3471 }
3472
3473 /* Complain that DECL uses a type with no linkage but is never defined.  */
3474
3475 static void
3476 no_linkage_error (tree decl)
3477 {
3478   tree t = no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false);
3479   if (TYPE_ANONYMOUS_P (t))
3480     {
3481       permerror (0, "%q+#D, declared using anonymous type, "
3482                  "is used but never defined", decl);
3483       if (is_typedef_decl (TYPE_NAME (t)))
3484         permerror (0, "%q+#D does not refer to the unqualified type, "
3485                    "so it is not used for linkage", TYPE_NAME (t));
3486     }
3487   else
3488     permerror (0, "%q+#D, declared using local type %qT, "
3489                "is used but never defined", decl, t);
3490 }
3491
3492 /* This routine is called at the end of compilation.
3493    Its job is to create all the code needed to initialize and
3494    destroy the global aggregates.  We do the destruction
3495    first, since that way we only need to reverse the decls once.  */
3496
3497 void
3498 cp_write_global_declarations (void)
3499 {
3500   tree vars;
3501   bool reconsider;
3502   size_t i;
3503   location_t locus;
3504   unsigned ssdf_count = 0;
3505   int retries = 0;
3506   tree decl;
3507   struct pointer_set_t *candidates;
3508
3509   locus = input_location;
3510   at_eof = 1;
3511
3512   /* Bad parse errors.  Just forget about it.  */
3513   if (! global_bindings_p () || current_class_type || decl_namespace_list)
3514     return;
3515
3516   if (pch_file)
3517     c_common_write_pch ();
3518
3519   /* FIXME - huh?  was  input_line -= 1;*/
3520
3521   /* We now have to write out all the stuff we put off writing out.
3522      These include:
3523
3524        o Template specializations that we have not yet instantiated,
3525          but which are needed.
3526        o Initialization and destruction for non-local objects with
3527          static storage duration.  (Local objects with static storage
3528          duration are initialized when their scope is first entered,
3529          and are cleaned up via atexit.)
3530        o Virtual function tables.
3531
3532      All of these may cause others to be needed.  For example,
3533      instantiating one function may cause another to be needed, and
3534      generating the initializer for an object may cause templates to be
3535      instantiated, etc., etc.  */
3536
3537   timevar_push (TV_VARCONST);
3538
3539   emit_support_tinfos ();
3540
3541   do
3542     {
3543       tree t;
3544       tree decl;
3545
3546       reconsider = false;
3547
3548       /* If there are templates that we've put off instantiating, do
3549          them now.  */
3550       instantiate_pending_templates (retries);
3551       ggc_collect ();
3552
3553       /* Write out virtual tables as required.  Note that writing out
3554          the virtual table for a template class may cause the
3555          instantiation of members of that class.  If we write out
3556          vtables then we remove the class from our list so we don't
3557          have to look at it again.  */
3558
3559       while (keyed_classes != NULL_TREE
3560              && maybe_emit_vtables (TREE_VALUE (keyed_classes)))
3561         {
3562           reconsider = true;
3563           keyed_classes = TREE_CHAIN (keyed_classes);
3564         }
3565
3566       t = keyed_classes;
3567       if (t != NULL_TREE)
3568         {
3569           tree next = TREE_CHAIN (t);
3570
3571           while (next)
3572             {
3573               if (maybe_emit_vtables (TREE_VALUE (next)))
3574                 {
3575                   reconsider = true;
3576                   TREE_CHAIN (t) = TREE_CHAIN (next);
3577                 }
3578               else
3579                 t = next;
3580
3581               next = TREE_CHAIN (t);
3582             }
3583         }
3584
3585       /* Write out needed type info variables.  We have to be careful
3586          looping through unemitted decls, because emit_tinfo_decl may
3587          cause other variables to be needed. New elements will be
3588          appended, and we remove from the vector those that actually
3589          get emitted.  */
3590       for (i = VEC_length (tree, unemitted_tinfo_decls);
3591            VEC_iterate (tree, unemitted_tinfo_decls, --i, t);)
3592         if (emit_tinfo_decl (t))
3593           {
3594             reconsider = true;
3595             VEC_unordered_remove (tree, unemitted_tinfo_decls, i);
3596           }
3597
3598       /* The list of objects with static storage duration is built up
3599          in reverse order.  We clear STATIC_AGGREGATES so that any new
3600          aggregates added during the initialization of these will be
3601          initialized in the correct order when we next come around the
3602          loop.  */
3603       vars = prune_vars_needing_no_initialization (&static_aggregates);
3604
3605       if (vars)
3606         {
3607           /* We need to start a new initialization function each time
3608              through the loop.  That's because we need to know which
3609              vtables have been referenced, and TREE_SYMBOL_REFERENCED
3610              isn't computed until a function is finished, and written
3611              out.  That's a deficiency in the back end.  When this is
3612              fixed, these initialization functions could all become
3613              inline, with resulting performance improvements.  */
3614           tree ssdf_body;
3615
3616           /* Set the line and file, so that it is obviously not from
3617              the source file.  */
3618           input_location = locus;
3619           ssdf_body = start_static_storage_duration_function (ssdf_count);
3620
3621           /* Make sure the back end knows about all the variables.  */
3622           write_out_vars (vars);
3623
3624           /* First generate code to do all the initializations.  */
3625           if (vars)
3626             do_static_initialization_or_destruction (vars, /*initp=*/true);
3627
3628           /* Then, generate code to do all the destructions.  Do these
3629              in reverse order so that the most recently constructed
3630              variable is the first destroyed.  If we're using
3631              __cxa_atexit, then we don't need to do this; functions
3632              were registered at initialization time to destroy the
3633              local statics.  */
3634           if (!flag_use_cxa_atexit && vars)
3635             {
3636               vars = nreverse (vars);
3637               do_static_initialization_or_destruction (vars, /*initp=*/false);
3638             }
3639           else
3640             vars = NULL_TREE;
3641
3642           /* Finish up the static storage duration function for this
3643              round.  */
3644           input_location = locus;
3645           finish_static_storage_duration_function (ssdf_body);
3646
3647           /* All those initializations and finalizations might cause
3648              us to need more inline functions, more template
3649              instantiations, etc.  */
3650           reconsider = true;
3651           ssdf_count++;
3652           /* ??? was:  locus.line++; */
3653         }
3654
3655       /* Go through the set of inline functions whose bodies have not
3656          been emitted yet.  If out-of-line copies of these functions
3657          are required, emit them.  */
3658       for (i = 0; VEC_iterate (tree, deferred_fns, i, decl); ++i)
3659         {
3660           /* Does it need synthesizing?  */
3661           if (DECL_DEFAULTED_FN (decl) && ! DECL_INITIAL (decl)
3662               && (! DECL_REALLY_EXTERN (decl) || possibly_inlined_p (decl)))
3663             {
3664               /* Even though we're already at the top-level, we push
3665                  there again.  That way, when we pop back a few lines
3666                  hence, all of our state is restored.  Otherwise,
3667                  finish_function doesn't clean things up, and we end
3668                  up with CURRENT_FUNCTION_DECL set.  */
3669               push_to_top_level ();
3670               /* The decl's location will mark where it was first
3671                  needed.  Save that so synthesize method can indicate
3672                  where it was needed from, in case of error  */
3673               input_location = DECL_SOURCE_LOCATION (decl);
3674               synthesize_method (decl);
3675               pop_from_top_level ();
3676               reconsider = true;
3677             }
3678
3679           if (!DECL_SAVED_TREE (decl))
3680             continue;
3681
3682           /* We lie to the back end, pretending that some functions
3683              are not defined when they really are.  This keeps these
3684              functions from being put out unnecessarily.  But, we must
3685              stop lying when the functions are referenced, or if they
3686              are not comdat since they need to be put out now.  If
3687              DECL_INTERFACE_KNOWN, then we have already set
3688              DECL_EXTERNAL appropriately, so there's no need to check
3689              again, and we do not want to clear DECL_EXTERNAL if a
3690              previous call to import_export_decl set it.
3691
3692              This is done in a separate for cycle, because if some
3693              deferred function is contained in another deferred
3694              function later in deferred_fns varray,
3695              rest_of_compilation would skip this function and we
3696              really cannot expand the same function twice.  */
3697           import_export_decl (decl);
3698           if (DECL_NOT_REALLY_EXTERN (decl)
3699               && DECL_INITIAL (decl)
3700               && decl_needed_p (decl))
3701             {
3702               struct cgraph_node *node = cgraph_get_node (decl), *alias, *next;
3703
3704               DECL_EXTERNAL (decl) = 0;
3705               /* If we mark !DECL_EXTERNAL one of the same body aliases,
3706                  we need to mark all of them that way.  */
3707               if (node && node->same_body)
3708                 {
3709                   DECL_EXTERNAL (node->decl) = 0;
3710                   for (alias = node->same_body; alias; alias = alias->next)
3711                     DECL_EXTERNAL (alias->decl) = 0;
3712                 }
3713               /* If we mark !DECL_EXTERNAL one of the symbols in some comdat
3714                  group, we need to mark all symbols in the same comdat group
3715                  that way.  */
3716               if (node->same_comdat_group)
3717                 for (next = node->same_comdat_group;
3718                      next != node;
3719                      next = next->same_comdat_group)
3720                   {
3721                     DECL_EXTERNAL (next->decl) = 0;
3722                     if (next->same_body)
3723                       {
3724                         for (alias = next->same_body;
3725                              alias;
3726                              alias = alias->next)
3727                           DECL_EXTERNAL (alias->decl) = 0;
3728                       }
3729                   }
3730             }
3731
3732           /* If we're going to need to write this function out, and
3733              there's already a body for it, create RTL for it now.
3734              (There might be no body if this is a method we haven't
3735              gotten around to synthesizing yet.)  */
3736           if (!DECL_EXTERNAL (decl)
3737               && decl_needed_p (decl)
3738               && !TREE_ASM_WRITTEN (decl)
3739               && !cgraph_node (decl)->local.finalized)
3740             {
3741               /* We will output the function; no longer consider it in this
3742                  loop.  */
3743               DECL_DEFER_OUTPUT (decl) = 0;
3744               /* Generate RTL for this function now that we know we
3745                  need it.  */
3746               expand_or_defer_fn (decl);
3747               /* If we're compiling -fsyntax-only pretend that this
3748                  function has been written out so that we don't try to
3749                  expand it again.  */
3750               if (flag_syntax_only)
3751                 TREE_ASM_WRITTEN (decl) = 1;
3752               reconsider = true;
3753             }
3754         }
3755
3756       if (walk_namespaces (wrapup_globals_for_namespace, /*data=*/0))
3757         reconsider = true;
3758
3759       /* Static data members are just like namespace-scope globals.  */
3760       for (i = 0; VEC_iterate (tree, pending_statics, i, decl); ++i)
3761         {
3762           if (var_finalized_p (decl) || DECL_REALLY_EXTERN (decl)
3763               /* Don't write it out if we haven't seen a definition.  */
3764               || DECL_IN_AGGR_P (decl))
3765             continue;
3766           import_export_decl (decl);
3767           /* If this static data member is needed, provide it to the
3768              back end.  */
3769           if (DECL_NOT_REALLY_EXTERN (decl) && decl_needed_p (decl))
3770             DECL_EXTERNAL (decl) = 0;
3771         }
3772       if (VEC_length (tree, pending_statics) != 0
3773           && wrapup_global_declarations (VEC_address (tree, pending_statics),
3774                                          VEC_length (tree, pending_statics)))
3775         reconsider = true;
3776
3777       retries++;
3778     }
3779   while (reconsider);
3780
3781   /* All used inline functions must have a definition at this point.  */
3782   for (i = 0; VEC_iterate (tree, deferred_fns, i, decl); ++i)
3783     {
3784       if (/* Check online inline functions that were actually used.  */
3785           DECL_ODR_USED (decl) && DECL_DECLARED_INLINE_P (decl)
3786           /* If the definition actually was available here, then the
3787              fact that the function was not defined merely represents
3788              that for some reason (use of a template repository,
3789              #pragma interface, etc.) we decided not to emit the
3790              definition here.  */
3791           && !DECL_INITIAL (decl)
3792           /* An explicit instantiation can be used to specify
3793              that the body is in another unit. It will have
3794              already verified there was a definition.  */
3795           && !DECL_EXPLICIT_INSTANTIATION (decl))
3796         {
3797           warning (0, "inline function %q+D used but never defined", decl);
3798           /* Avoid a duplicate warning from check_global_declaration_1.  */
3799           TREE_NO_WARNING (decl) = 1;
3800         }
3801     }
3802
3803   /* So must decls that use a type with no linkage.  */
3804   for (i = 0; VEC_iterate (tree, no_linkage_decls, i, decl); ++i)
3805     if (!decl_defined_p (decl))
3806       no_linkage_error (decl);
3807
3808   /* We give C linkage to static constructors and destructors.  */
3809   push_lang_context (lang_name_c);
3810
3811   /* Generate initialization and destruction functions for all
3812      priorities for which they are required.  */
3813   if (priority_info_map)
3814     splay_tree_foreach (priority_info_map,
3815                         generate_ctor_and_dtor_functions_for_priority,
3816                         /*data=*/&locus);
3817   else if (c_dialect_objc () && objc_static_init_needed_p ())
3818     /* If this is obj-c++ and we need a static init, call
3819        generate_ctor_or_dtor_function.  */
3820     generate_ctor_or_dtor_function (/*constructor_p=*/true,
3821                                     DEFAULT_INIT_PRIORITY, &locus);
3822
3823   /* We're done with the splay-tree now.  */
3824   if (priority_info_map)
3825     splay_tree_delete (priority_info_map);
3826
3827   /* Generate any missing aliases.  */
3828   maybe_apply_pending_pragma_weaks ();
3829
3830   /* We're done with static constructors, so we can go back to "C++"
3831      linkage now.  */
3832   pop_lang_context ();
3833
3834   /* Collect candidates for Java hidden aliases.  */
3835   candidates = collect_candidates_for_java_method_aliases ();
3836
3837   cgraph_finalize_compilation_unit ();
3838
3839   /* Now, issue warnings about static, but not defined, functions,
3840      etc., and emit debugging information.  */
3841   walk_namespaces (wrapup_globals_for_namespace, /*data=*/&reconsider);
3842   if (VEC_length (tree, pending_statics) != 0)
3843     {
3844       check_global_declarations (VEC_address (tree, pending_statics),
3845                                  VEC_length (tree, pending_statics));
3846       emit_debug_global_declarations (VEC_address (tree, pending_statics),
3847                                       VEC_length (tree, pending_statics));
3848     }
3849
3850   /* Generate hidden aliases for Java.  */
3851   if (candidates)
3852     {
3853       build_java_method_aliases (candidates);
3854       pointer_set_destroy (candidates);
3855     }
3856
3857   finish_repo ();
3858
3859   /* The entire file is now complete.  If requested, dump everything
3860      to a file.  */
3861   {
3862     int flags;
3863     FILE *stream = dump_begin (TDI_tu, &flags);
3864
3865     if (stream)
3866       {
3867         dump_node (global_namespace, flags & ~TDF_SLIM, stream);
3868         dump_end (TDI_tu, stream);
3869       }
3870   }
3871
3872   timevar_pop (TV_VARCONST);
3873
3874   if (flag_detailed_statistics)
3875     {
3876       dump_tree_statistics ();
3877       dump_time_statistics ();
3878     }
3879   input_location = locus;
3880
3881 #ifdef ENABLE_CHECKING
3882   validate_conversion_obstack ();
3883 #endif /* ENABLE_CHECKING */
3884 }
3885
3886 /* FN is an OFFSET_REF, DOTSTAR_EXPR or MEMBER_REF indicating the
3887    function to call in parse-tree form; it has not yet been
3888    semantically analyzed.  ARGS are the arguments to the function.
3889    They have already been semantically analyzed.  This may change
3890    ARGS.  */
3891
3892 tree
3893 build_offset_ref_call_from_tree (tree fn, VEC(tree,gc) **args)
3894 {
3895   tree orig_fn;
3896   VEC(tree,gc) *orig_args = NULL;
3897   tree expr;
3898   tree object;
3899
3900   orig_fn = fn;
3901   object = TREE_OPERAND (fn, 0);
3902
3903   if (processing_template_decl)
3904     {
3905       gcc_assert (TREE_CODE (fn) == DOTSTAR_EXPR
3906                   || TREE_CODE (fn) == MEMBER_REF);
3907       if (type_dependent_expression_p (fn)
3908           || any_type_dependent_arguments_p (*args))
3909         return build_nt_call_vec (fn, *args);
3910
3911       orig_args = make_tree_vector_copy (*args);
3912
3913       /* Transform the arguments and add the implicit "this"
3914          parameter.  That must be done before the FN is transformed
3915          because we depend on the form of FN.  */
3916       make_args_non_dependent (*args);
3917       object = build_non_dependent_expr (object);
3918       if (TREE_CODE (fn) == DOTSTAR_EXPR)
3919         object = cp_build_unary_op (ADDR_EXPR, object, 0, tf_warning_or_error);
3920       VEC_safe_insert (tree, gc, *args, 0, object);
3921       /* Now that the arguments are done, transform FN.  */
3922       fn = build_non_dependent_expr (fn);
3923     }
3924
3925   /* A qualified name corresponding to a bound pointer-to-member is
3926      represented as an OFFSET_REF:
3927
3928         struct B { void g(); };
3929         void (B::*p)();
3930         void B::g() { (this->*p)(); }  */
3931   if (TREE_CODE (fn) == OFFSET_REF)
3932     {
3933       tree object_addr = cp_build_unary_op (ADDR_EXPR, object, 0,
3934                                          tf_warning_or_error);
3935       fn = TREE_OPERAND (fn, 1);
3936       fn = get_member_function_from_ptrfunc (&object_addr, fn);
3937       VEC_safe_insert (tree, gc, *args, 0, object_addr);
3938     }
3939
3940   expr = cp_build_function_call_vec (fn, args, tf_warning_or_error);
3941   if (processing_template_decl && expr != error_mark_node)
3942     expr = build_min_non_dep_call_vec (expr, orig_fn, orig_args);
3943
3944   if (orig_args != NULL)
3945     release_tree_vector (orig_args);
3946
3947   return expr;
3948 }
3949
3950
3951 void
3952 check_default_args (tree x)
3953 {
3954   tree arg = TYPE_ARG_TYPES (TREE_TYPE (x));
3955   bool saw_def = false;
3956   int i = 0 - (TREE_CODE (TREE_TYPE (x)) == METHOD_TYPE);
3957   for (; arg && arg != void_list_node; arg = TREE_CHAIN (arg), ++i)
3958     {
3959       if (TREE_PURPOSE (arg))
3960         saw_def = true;
3961       else if (saw_def)
3962         {
3963           error ("default argument missing for parameter %P of %q+#D", i, x);
3964           TREE_PURPOSE (arg) = error_mark_node;
3965         }
3966     }
3967 }
3968
3969 /* Return true if function DECL can be inlined.  This is used to force
3970    instantiation of methods that might be interesting for inlining.  */
3971 bool
3972 possibly_inlined_p (tree decl)
3973 {
3974   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL);
3975   if (DECL_UNINLINABLE (decl))
3976     return false;
3977   if (!optimize || pragma_java_exceptions)
3978     return DECL_DECLARED_INLINE_P (decl);
3979   /* When optimizing, we might inline everything when flatten
3980      attribute or heuristics inlining for size or autoinlining
3981      is used.  */
3982   return true;
3983 }
3984
3985 /* Mark DECL (either a _DECL or a BASELINK) as "used" in the program.
3986    If DECL is a specialization or implicitly declared class member,
3987    generate the actual definition.  */
3988
3989 void
3990 mark_used (tree decl)
3991 {
3992   HOST_WIDE_INT saved_processing_template_decl = 0;
3993
3994   /* If DECL is a BASELINK for a single function, then treat it just
3995      like the DECL for the function.  Otherwise, if the BASELINK is
3996      for an overloaded function, we don't know which function was
3997      actually used until after overload resolution.  */
3998   if (TREE_CODE (decl) == BASELINK)
3999     {
4000       decl = BASELINK_FUNCTIONS (decl);
4001       if (really_overloaded_fn (decl))
4002         return;
4003       decl = OVL_CURRENT (decl);
4004     }
4005
4006   /* Set TREE_USED for the benefit of -Wunused.  */
4007   TREE_USED (decl) = 1;
4008   if (DECL_CLONED_FUNCTION_P (decl))
4009     TREE_USED (DECL_CLONED_FUNCTION (decl)) = 1;
4010
4011   if (TREE_CODE (decl) == FUNCTION_DECL
4012       && DECL_DELETED_FN (decl))
4013     {
4014       if (DECL_ARTIFICIAL (decl))
4015         {
4016           if (DECL_OVERLOADED_OPERATOR_P (decl) == TYPE_EXPR
4017               && LAMBDA_TYPE_P (DECL_CONTEXT (decl)))
4018             {
4019               /* We mark a lambda conversion op as deleted if we can't
4020                  generate it properly; see maybe_add_lambda_conv_op.  */
4021               sorry ("converting lambda which uses %<...%> to "
4022                      "function pointer");
4023               return;
4024             }
4025         }
4026       error ("deleted function %q+D", decl);
4027       error ("used here");
4028       return;
4029     }
4030   /* If we don't need a value, then we don't need to synthesize DECL.  */
4031   if (cp_unevaluated_operand != 0)
4032     return;
4033
4034   /* We can only check DECL_ODR_USED on variables or functions with
4035      DECL_LANG_SPECIFIC set, and these are also the only decls that we
4036      might need special handling for.  */
4037   if ((TREE_CODE (decl) != VAR_DECL && TREE_CODE (decl) != FUNCTION_DECL)
4038       || DECL_LANG_SPECIFIC (decl) == NULL
4039       || DECL_THUNK_P (decl))
4040     return;
4041
4042   /* We only want to do this processing once.  We don't need to keep trying
4043      to instantiate inline templates, because unit-at-a-time will make sure
4044      we get them compiled before functions that want to inline them.  */
4045   if (DECL_ODR_USED (decl))
4046     return;
4047
4048   /* If within finish_function, defer the rest until that function
4049      finishes, otherwise it might recurse.  */
4050   if (defer_mark_used_calls)
4051     {
4052       VEC_safe_push (tree, gc, deferred_mark_used_calls, decl);
4053       return;
4054     }
4055
4056   /* Normally, we can wait until instantiation-time to synthesize
4057      DECL.  However, if DECL is a static data member initialized with
4058      a constant, we need the value right now because a reference to
4059      such a data member is not value-dependent.  */
4060   if (TREE_CODE (decl) == VAR_DECL
4061       && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl)
4062       && DECL_CLASS_SCOPE_P (decl))
4063     {
4064       /* Don't try to instantiate members of dependent types.  We
4065          cannot just use dependent_type_p here because this function
4066          may be called from fold_non_dependent_expr, and then we may
4067          see dependent types, even though processing_template_decl
4068          will not be set.  */
4069       if (CLASSTYPE_TEMPLATE_INFO ((DECL_CONTEXT (decl)))
4070           && uses_template_parms (CLASSTYPE_TI_ARGS (DECL_CONTEXT (decl))))
4071         return;
4072       /* Pretend that we are not in a template, even if we are, so
4073          that the static data member initializer will be processed.  */
4074       saved_processing_template_decl = processing_template_decl;
4075       processing_template_decl = 0;
4076     }
4077
4078   if (processing_template_decl)
4079     return;
4080
4081   DECL_ODR_USED (decl) = 1;
4082   if (DECL_CLONED_FUNCTION_P (decl))
4083     DECL_ODR_USED (DECL_CLONED_FUNCTION (decl)) = 1;
4084
4085   /* DR 757: A type without linkage shall not be used as the type of a
4086      variable or function with linkage, unless
4087    o the variable or function has extern "C" linkage (7.5 [dcl.link]), or
4088    o the variable or function is not used (3.2 [basic.def.odr]) or is
4089    defined in the same translation unit.  */
4090   if (cxx_dialect > cxx98
4091       && decl_linkage (decl) != lk_none
4092       && !DECL_EXTERN_C_P (decl)
4093       && !DECL_ARTIFICIAL (decl)
4094       && !decl_defined_p (decl)
4095       && no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false))
4096     {
4097       if (is_local_extern (decl))
4098         /* There's no way to define a local extern, and adding it to
4099            the vector interferes with GC, so give an error now.  */
4100         no_linkage_error (decl);
4101       else
4102         VEC_safe_push (tree, gc, no_linkage_decls, decl);
4103     }
4104
4105   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_DECLARED_INLINE_P (decl)
4106       && !DECL_INITIAL (decl) && !DECL_ARTIFICIAL (decl))
4107     /* Remember it, so we can check it was defined.  */
4108     note_vague_linkage_fn (decl);
4109
4110   /* Is it a synthesized method that needs to be synthesized?  */
4111   if (TREE_CODE (decl) == FUNCTION_DECL
4112       && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl)
4113       && DECL_DEFAULTED_FN (decl)
4114       && ! DECL_INITIAL (decl))
4115     {
4116       /* Remember the current location for a function we will end up
4117          synthesizing.  Then we can inform the user where it was
4118          required in the case of error.  */
4119       DECL_SOURCE_LOCATION (decl) = input_location;
4120
4121       /* Synthesizing an implicitly defined member function will result in
4122          garbage collection.  We must treat this situation as if we were
4123          within the body of a function so as to avoid collecting live data
4124          on the stack (such as overload resolution candidates).
4125
4126          We could just let cp_write_global_declarations handle synthesizing
4127          this function, since we just added it to deferred_fns, but doing
4128          it at the use site produces better error messages.  */
4129       ++function_depth;
4130       synthesize_method (decl);
4131       --function_depth;
4132       /* If this is a synthesized method we don't need to
4133          do the instantiation test below.  */
4134     }
4135   else if ((TREE_CODE (decl) == FUNCTION_DECL || TREE_CODE (decl) == VAR_DECL)
4136            && DECL_TEMPLATE_INFO (decl)
4137            && (!DECL_EXPLICIT_INSTANTIATION (decl)
4138                || always_instantiate_p (decl)))
4139     /* If this is a function or variable that is an instance of some
4140        template, we now know that we will need to actually do the
4141        instantiation. We check that DECL is not an explicit
4142        instantiation because that is not checked in instantiate_decl.
4143
4144        We put off instantiating functions in order to improve compile
4145        times.  Maintaining a stack of active functions is expensive,
4146        and the inliner knows to instantiate any functions it might
4147        need.  Therefore, we always try to defer instantiation.  */
4148     instantiate_decl (decl, /*defer_ok=*/true,
4149                       /*expl_inst_class_mem_p=*/false);
4150
4151   processing_template_decl = saved_processing_template_decl;
4152 }
4153
4154 #include "gt-cp-decl2.h"