OSDN Git Service

PR c++/28114
[pf3gnuchains/gcc-fork.git] / gcc / cp / name-lookup.c
1 /* Definitions for C++ name lookup routines.
2    Copyright (C) 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
3    Contributed by Gabriel Dos Reis <gdr@integrable-solutions.net>
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING.  If not, write to
19 the Free Software Foundation, 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, USA.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "flags.h"
27 #include "tree.h"
28 #include "cp-tree.h"
29 #include "name-lookup.h"
30 #include "timevar.h"
31 #include "toplev.h"
32 #include "diagnostic.h"
33 #include "debug.h"
34 #include "c-pragma.h"
35
36 /* The bindings for a particular name in a particular scope.  */
37
38 struct scope_binding {
39   tree value;
40   tree type;
41 };
42 #define EMPTY_SCOPE_BINDING { NULL_TREE, NULL_TREE }
43
44 static cxx_scope *innermost_nonclass_level (void);
45 static tree select_decl (const struct scope_binding *, int);
46 static cxx_binding *binding_for_name (cxx_scope *, tree);
47 static tree lookup_name_innermost_nonclass_level (tree);
48 static tree push_overloaded_decl (tree, int, bool);
49 static bool lookup_using_namespace (tree, struct scope_binding *, tree,
50                                     tree, int);
51 static bool qualified_lookup_using_namespace (tree, tree,
52                                               struct scope_binding *, int);
53 static tree lookup_type_current_level (tree);
54 static tree push_using_directive (tree);
55
56 /* The :: namespace.  */
57
58 tree global_namespace;
59
60 /* The name of the anonymous namespace, throughout this translation
61    unit.  */
62 static GTY(()) tree anonymous_namespace_name;
63
64
65 /* Compute the chain index of a binding_entry given the HASH value of its
66    name and the total COUNT of chains.  COUNT is assumed to be a power
67    of 2.  */
68
69 #define ENTRY_INDEX(HASH, COUNT) (((HASH) >> 3) & ((COUNT) - 1))
70
71 /* A free list of "binding_entry"s awaiting for re-use.  */
72
73 static GTY((deletable)) binding_entry free_binding_entry = NULL;
74
75 /* Create a binding_entry object for (NAME, TYPE).  */
76
77 static inline binding_entry
78 binding_entry_make (tree name, tree type)
79 {
80   binding_entry entry;
81
82   if (free_binding_entry)
83     {
84       entry = free_binding_entry;
85       free_binding_entry = entry->chain;
86     }
87   else
88     entry = GGC_NEW (struct binding_entry_s);
89
90   entry->name = name;
91   entry->type = type;
92   entry->chain = NULL;
93
94   return entry;
95 }
96
97 /* Put ENTRY back on the free list.  */
98 #if 0
99 static inline void
100 binding_entry_free (binding_entry entry)
101 {
102   entry->name = NULL;
103   entry->type = NULL;
104   entry->chain = free_binding_entry;
105   free_binding_entry = entry;
106 }
107 #endif
108
109 /* The datatype used to implement the mapping from names to types at
110    a given scope.  */
111 struct binding_table_s GTY(())
112 {
113   /* Array of chains of "binding_entry"s  */
114   binding_entry * GTY((length ("%h.chain_count"))) chain;
115
116   /* The number of chains in this table.  This is the length of the
117      the member "chain" considered as an array.  */
118   size_t chain_count;
119
120   /* Number of "binding_entry"s in this table.  */
121   size_t entry_count;
122 };
123
124 /* Construct TABLE with an initial CHAIN_COUNT.  */
125
126 static inline void
127 binding_table_construct (binding_table table, size_t chain_count)
128 {
129   table->chain_count = chain_count;
130   table->entry_count = 0;
131   table->chain = GGC_CNEWVEC (binding_entry, table->chain_count);
132 }
133
134 /* Make TABLE's entries ready for reuse.  */
135 #if 0
136 static void
137 binding_table_free (binding_table table)
138 {
139   size_t i;
140   size_t count;
141
142   if (table == NULL)
143     return;
144
145   for (i = 0, count = table->chain_count; i < count; ++i)
146     {
147       binding_entry temp = table->chain[i];
148       while (temp != NULL)
149         {
150           binding_entry entry = temp;
151           temp = entry->chain;
152           binding_entry_free (entry);
153         }
154       table->chain[i] = NULL;
155     }
156   table->entry_count = 0;
157 }
158 #endif
159
160 /* Allocate a table with CHAIN_COUNT, assumed to be a power of two.  */
161
162 static inline binding_table
163 binding_table_new (size_t chain_count)
164 {
165   binding_table table = GGC_NEW (struct binding_table_s);
166   table->chain = NULL;
167   binding_table_construct (table, chain_count);
168   return table;
169 }
170
171 /* Expand TABLE to twice its current chain_count.  */
172
173 static void
174 binding_table_expand (binding_table table)
175 {
176   const size_t old_chain_count = table->chain_count;
177   const size_t old_entry_count = table->entry_count;
178   const size_t new_chain_count = 2 * old_chain_count;
179   binding_entry *old_chains = table->chain;
180   size_t i;
181
182   binding_table_construct (table, new_chain_count);
183   for (i = 0; i < old_chain_count; ++i)
184     {
185       binding_entry entry = old_chains[i];
186       for (; entry != NULL; entry = old_chains[i])
187         {
188           const unsigned int hash = IDENTIFIER_HASH_VALUE (entry->name);
189           const size_t j = ENTRY_INDEX (hash, new_chain_count);
190
191           old_chains[i] = entry->chain;
192           entry->chain = table->chain[j];
193           table->chain[j] = entry;
194         }
195     }
196   table->entry_count = old_entry_count;
197 }
198
199 /* Insert a binding for NAME to TYPE into TABLE.  */
200
201 static void
202 binding_table_insert (binding_table table, tree name, tree type)
203 {
204   const unsigned int hash = IDENTIFIER_HASH_VALUE (name);
205   const size_t i = ENTRY_INDEX (hash, table->chain_count);
206   binding_entry entry = binding_entry_make (name, type);
207
208   entry->chain = table->chain[i];
209   table->chain[i] = entry;
210   ++table->entry_count;
211
212   if (3 * table->chain_count < 5 * table->entry_count)
213     binding_table_expand (table);
214 }
215
216 /* Return the binding_entry, if any, that maps NAME.  */
217
218 binding_entry
219 binding_table_find (binding_table table, tree name)
220 {
221   const unsigned int hash = IDENTIFIER_HASH_VALUE (name);
222   binding_entry entry = table->chain[ENTRY_INDEX (hash, table->chain_count)];
223
224   while (entry != NULL && entry->name != name)
225     entry = entry->chain;
226
227   return entry;
228 }
229
230 /* Apply PROC -- with DATA -- to all entries in TABLE.  */
231
232 void
233 binding_table_foreach (binding_table table, bt_foreach_proc proc, void *data)
234 {
235   const size_t chain_count = table->chain_count;
236   size_t i;
237
238   for (i = 0; i < chain_count; ++i)
239     {
240       binding_entry entry = table->chain[i];
241       for (; entry != NULL; entry = entry->chain)
242         proc (entry, data);
243     }
244 }
245 \f
246 #ifndef ENABLE_SCOPE_CHECKING
247 #  define ENABLE_SCOPE_CHECKING 0
248 #else
249 #  define ENABLE_SCOPE_CHECKING 1
250 #endif
251
252 /* A free list of "cxx_binding"s, connected by their PREVIOUS.  */
253
254 static GTY((deletable)) cxx_binding *free_bindings;
255
256 /* Initialize VALUE and TYPE field for BINDING, and set the PREVIOUS
257    field to NULL.  */
258
259 static inline void
260 cxx_binding_init (cxx_binding *binding, tree value, tree type)
261 {
262   binding->value = value;
263   binding->type = type;
264   binding->previous = NULL;
265 }
266
267 /* (GC)-allocate a binding object with VALUE and TYPE member initialized.  */
268
269 static cxx_binding *
270 cxx_binding_make (tree value, tree type)
271 {
272   cxx_binding *binding;
273   if (free_bindings)
274     {
275       binding = free_bindings;
276       free_bindings = binding->previous;
277     }
278   else
279     binding = GGC_NEW (cxx_binding);
280
281   cxx_binding_init (binding, value, type);
282
283   return binding;
284 }
285
286 /* Put BINDING back on the free list.  */
287
288 static inline void
289 cxx_binding_free (cxx_binding *binding)
290 {
291   binding->scope = NULL;
292   binding->previous = free_bindings;
293   free_bindings = binding;
294 }
295
296 /* Create a new binding for NAME (with the indicated VALUE and TYPE
297    bindings) in the class scope indicated by SCOPE.  */
298
299 static cxx_binding *
300 new_class_binding (tree name, tree value, tree type, cxx_scope *scope)
301 {
302   cp_class_binding *cb;
303   cxx_binding *binding;
304
305   if (VEC_length (cp_class_binding, scope->class_shadowed))
306     {
307       cp_class_binding *old_base;
308       old_base = VEC_index (cp_class_binding, scope->class_shadowed, 0);
309       if (VEC_reserve (cp_class_binding, gc, scope->class_shadowed, 1))
310         {
311           /* Fixup the current bindings, as they might have moved.  */
312           size_t i;
313
314           for (i = 0;
315                VEC_iterate (cp_class_binding, scope->class_shadowed, i, cb);
316                i++)
317             {
318               cxx_binding **b;
319               b = &IDENTIFIER_BINDING (cb->identifier);
320               while (*b != &old_base[i].base)
321                 b = &((*b)->previous);
322               *b = &cb->base;
323             }
324         }
325       cb = VEC_quick_push (cp_class_binding, scope->class_shadowed, NULL);
326     }
327   else
328     cb = VEC_safe_push (cp_class_binding, gc, scope->class_shadowed, NULL);
329
330   cb->identifier = name;
331   binding = &cb->base;
332   binding->scope = scope;
333   cxx_binding_init (binding, value, type);
334   return binding;
335 }
336
337 /* Make DECL the innermost binding for ID.  The LEVEL is the binding
338    level at which this declaration is being bound.  */
339
340 static void
341 push_binding (tree id, tree decl, cxx_scope* level)
342 {
343   cxx_binding *binding;
344
345   if (level != class_binding_level)
346     {
347       binding = cxx_binding_make (decl, NULL_TREE);
348       binding->scope = level;
349     }
350   else
351     binding = new_class_binding (id, decl, /*type=*/NULL_TREE, level);
352
353   /* Now, fill in the binding information.  */
354   binding->previous = IDENTIFIER_BINDING (id);
355   INHERITED_VALUE_BINDING_P (binding) = 0;
356   LOCAL_BINDING_P (binding) = (level != class_binding_level);
357
358   /* And put it on the front of the list of bindings for ID.  */
359   IDENTIFIER_BINDING (id) = binding;
360 }
361
362 /* Remove the binding for DECL which should be the innermost binding
363    for ID.  */
364
365 void
366 pop_binding (tree id, tree decl)
367 {
368   cxx_binding *binding;
369
370   if (id == NULL_TREE)
371     /* It's easiest to write the loops that call this function without
372        checking whether or not the entities involved have names.  We
373        get here for such an entity.  */
374     return;
375
376   /* Get the innermost binding for ID.  */
377   binding = IDENTIFIER_BINDING (id);
378
379   /* The name should be bound.  */
380   gcc_assert (binding != NULL);
381
382   /* The DECL will be either the ordinary binding or the type
383      binding for this identifier.  Remove that binding.  */
384   if (binding->value == decl)
385     binding->value = NULL_TREE;
386   else
387     {
388       gcc_assert (binding->type == decl);
389       binding->type = NULL_TREE;
390     }
391
392   if (!binding->value && !binding->type)
393     {
394       /* We're completely done with the innermost binding for this
395          identifier.  Unhook it from the list of bindings.  */
396       IDENTIFIER_BINDING (id) = binding->previous;
397
398       /* Add it to the free list.  */
399       cxx_binding_free (binding);
400     }
401 }
402
403 /* BINDING records an existing declaration for a name in the current scope.
404    But, DECL is another declaration for that same identifier in the
405    same scope.  This is the `struct stat' hack whereby a non-typedef
406    class name or enum-name can be bound at the same level as some other
407    kind of entity.
408    3.3.7/1
409
410      A class name (9.1) or enumeration name (7.2) can be hidden by the
411      name of an object, function, or enumerator declared in the same scope.
412      If a class or enumeration name and an object, function, or enumerator
413      are declared in the same scope (in any order) with the same name, the
414      class or enumeration name is hidden wherever the object, function, or
415      enumerator name is visible.
416
417    It's the responsibility of the caller to check that
418    inserting this name is valid here.  Returns nonzero if the new binding
419    was successful.  */
420
421 static bool
422 supplement_binding (cxx_binding *binding, tree decl)
423 {
424   tree bval = binding->value;
425   bool ok = true;
426
427   timevar_push (TV_NAME_LOOKUP);
428   if (TREE_CODE (decl) == TYPE_DECL && DECL_ARTIFICIAL (decl))
429     /* The new name is the type name.  */
430     binding->type = decl;
431   else if (/* BVAL is null when push_class_level_binding moves an
432               inherited type-binding out of the way to make room for a
433               new value binding.  */
434            !bval
435            /* BVAL is error_mark_node when DECL's name has been used
436               in a non-class scope prior declaration.  In that case,
437               we should have already issued a diagnostic; for graceful
438               error recovery purpose, pretend this was the intended
439               declaration for that name.  */
440            || bval == error_mark_node
441            /* If BVAL is anticipated but has not yet been declared,
442               pretend it is not there at all.  */
443            || (TREE_CODE (bval) == FUNCTION_DECL
444                && DECL_ANTICIPATED (bval)
445                && !DECL_HIDDEN_FRIEND_P (bval)))
446     binding->value = decl;
447   else if (TREE_CODE (bval) == TYPE_DECL && DECL_ARTIFICIAL (bval))
448     {
449       /* The old binding was a type name.  It was placed in
450          VALUE field because it was thought, at the point it was
451          declared, to be the only entity with such a name.  Move the
452          type name into the type slot; it is now hidden by the new
453          binding.  */
454       binding->type = bval;
455       binding->value = decl;
456       binding->value_is_inherited = false;
457     }
458   else if (TREE_CODE (bval) == TYPE_DECL
459            && TREE_CODE (decl) == TYPE_DECL
460            && DECL_NAME (decl) == DECL_NAME (bval)
461            && binding->scope->kind != sk_class
462            && (same_type_p (TREE_TYPE (decl), TREE_TYPE (bval))
463                /* If either type involves template parameters, we must
464                   wait until instantiation.  */
465                || uses_template_parms (TREE_TYPE (decl))
466                || uses_template_parms (TREE_TYPE (bval))))
467     /* We have two typedef-names, both naming the same type to have
468        the same name.  In general, this is OK because of:
469
470          [dcl.typedef]
471
472          In a given scope, a typedef specifier can be used to redefine
473          the name of any type declared in that scope to refer to the
474          type to which it already refers.
475
476        However, in class scopes, this rule does not apply due to the
477        stricter language in [class.mem] prohibiting redeclarations of
478        members.  */
479     ok = false;
480   /* There can be two block-scope declarations of the same variable,
481      so long as they are `extern' declarations.  However, there cannot
482      be two declarations of the same static data member:
483
484        [class.mem]
485
486        A member shall not be declared twice in the
487        member-specification.  */
488   else if (TREE_CODE (decl) == VAR_DECL && TREE_CODE (bval) == VAR_DECL
489            && DECL_EXTERNAL (decl) && DECL_EXTERNAL (bval)
490            && !DECL_CLASS_SCOPE_P (decl))
491     {
492       duplicate_decls (decl, binding->value, /*newdecl_is_friend=*/false);
493       ok = false;
494     }
495   else if (TREE_CODE (decl) == NAMESPACE_DECL
496            && TREE_CODE (bval) == NAMESPACE_DECL
497            && DECL_NAMESPACE_ALIAS (decl)
498            && DECL_NAMESPACE_ALIAS (bval)
499            && ORIGINAL_NAMESPACE (bval) == ORIGINAL_NAMESPACE (decl))
500     /* [namespace.alias]
501
502       In a declarative region, a namespace-alias-definition can be
503       used to redefine a namespace-alias declared in that declarative
504       region to refer only to the namespace to which it already
505       refers.  */
506     ok = false;
507   else
508     {
509       error ("declaration of %q#D", decl);
510       error ("conflicts with previous declaration %q+#D", bval);
511       ok = false;
512     }
513
514   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, ok);
515 }
516
517 /* Add DECL to the list of things declared in B.  */
518
519 static void
520 add_decl_to_level (tree decl, cxx_scope *b)
521 {
522   if (TREE_CODE (decl) == NAMESPACE_DECL
523       && !DECL_NAMESPACE_ALIAS (decl))
524     {
525       TREE_CHAIN (decl) = b->namespaces;
526       b->namespaces = decl;
527     }
528   else if (TREE_CODE (decl) == VAR_DECL && DECL_VIRTUAL_P (decl))
529     {
530       TREE_CHAIN (decl) = b->vtables;
531       b->vtables = decl;
532     }
533   else
534     {
535       /* We build up the list in reverse order, and reverse it later if
536          necessary.  */
537       TREE_CHAIN (decl) = b->names;
538       b->names = decl;
539       b->names_size++;
540
541       /* If appropriate, add decl to separate list of statics.  We
542          include extern variables because they might turn out to be
543          static later.  It's OK for this list to contain a few false
544          positives.  */
545       if (b->kind == sk_namespace)
546         if ((TREE_CODE (decl) == VAR_DECL
547              && (TREE_STATIC (decl) || DECL_EXTERNAL (decl)))
548             || (TREE_CODE (decl) == FUNCTION_DECL
549                 && (!TREE_PUBLIC (decl) || DECL_DECLARED_INLINE_P (decl))))
550           VEC_safe_push (tree, gc, b->static_decls, decl);
551     }
552 }
553
554 /* Record a decl-node X as belonging to the current lexical scope.
555    Check for errors (such as an incompatible declaration for the same
556    name already seen in the same scope).  IS_FRIEND is true if X is
557    declared as a friend.
558
559    Returns either X or an old decl for the same name.
560    If an old decl is returned, it may have been smashed
561    to agree with what X says.  */
562
563 tree
564 pushdecl_maybe_friend (tree x, bool is_friend)
565 {
566   tree t;
567   tree name;
568   int need_new_binding;
569
570   timevar_push (TV_NAME_LOOKUP);
571
572   need_new_binding = 1;
573
574   if (DECL_TEMPLATE_PARM_P (x))
575     /* Template parameters have no context; they are not X::T even
576        when declared within a class or namespace.  */
577     ;
578   else
579     {
580       if (current_function_decl && x != current_function_decl
581           /* A local declaration for a function doesn't constitute
582              nesting.  */
583           && TREE_CODE (x) != FUNCTION_DECL
584           /* A local declaration for an `extern' variable is in the
585              scope of the current namespace, not the current
586              function.  */
587           && !(TREE_CODE (x) == VAR_DECL && DECL_EXTERNAL (x))
588           && !DECL_CONTEXT (x))
589         DECL_CONTEXT (x) = current_function_decl;
590
591       /* If this is the declaration for a namespace-scope function,
592          but the declaration itself is in a local scope, mark the
593          declaration.  */
594       if (TREE_CODE (x) == FUNCTION_DECL
595           && DECL_NAMESPACE_SCOPE_P (x)
596           && current_function_decl
597           && x != current_function_decl)
598         DECL_LOCAL_FUNCTION_P (x) = 1;
599     }
600
601   name = DECL_NAME (x);
602   if (name)
603     {
604       int different_binding_level = 0;
605
606       if (TREE_CODE (x) == FUNCTION_DECL || DECL_FUNCTION_TEMPLATE_P (x))
607        check_default_args (x);
608
609       if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
610         name = TREE_OPERAND (name, 0);
611
612       /* In case this decl was explicitly namespace-qualified, look it
613          up in its namespace context.  */
614       if (DECL_NAMESPACE_SCOPE_P (x) && namespace_bindings_p ())
615         t = namespace_binding (name, DECL_CONTEXT (x));
616       else
617         t = lookup_name_innermost_nonclass_level (name);
618
619       /* [basic.link] If there is a visible declaration of an entity
620          with linkage having the same name and type, ignoring entities
621          declared outside the innermost enclosing namespace scope, the
622          block scope declaration declares that same entity and
623          receives the linkage of the previous declaration.  */
624       if (! t && current_function_decl && x != current_function_decl
625           && (TREE_CODE (x) == FUNCTION_DECL || TREE_CODE (x) == VAR_DECL)
626           && DECL_EXTERNAL (x))
627         {
628           /* Look in block scope.  */
629           t = innermost_non_namespace_value (name);
630           /* Or in the innermost namespace.  */
631           if (! t)
632             t = namespace_binding (name, DECL_CONTEXT (x));
633           /* Does it have linkage?  Note that if this isn't a DECL, it's an
634              OVERLOAD, which is OK.  */
635           if (t && DECL_P (t) && ! (TREE_STATIC (t) || DECL_EXTERNAL (t)))
636             t = NULL_TREE;
637           if (t)
638             different_binding_level = 1;
639         }
640
641       /* If we are declaring a function, and the result of name-lookup
642          was an OVERLOAD, look for an overloaded instance that is
643          actually the same as the function we are declaring.  (If
644          there is one, we have to merge our declaration with the
645          previous declaration.)  */
646       if (t && TREE_CODE (t) == OVERLOAD)
647         {
648           tree match;
649
650           if (TREE_CODE (x) == FUNCTION_DECL)
651             for (match = t; match; match = OVL_NEXT (match))
652               {
653                 if (decls_match (OVL_CURRENT (match), x))
654                   break;
655               }
656           else
657             /* Just choose one.  */
658             match = t;
659
660           if (match)
661             t = OVL_CURRENT (match);
662           else
663             t = NULL_TREE;
664         }
665
666       if (t && t != error_mark_node)
667         {
668           if (different_binding_level)
669             {
670               if (decls_match (x, t))
671                 /* The standard only says that the local extern
672                    inherits linkage from the previous decl; in
673                    particular, default args are not shared.  Add
674                    the decl into a hash table to make sure only
675                    the previous decl in this case is seen by the
676                    middle end.  */
677                 {
678                   struct cxx_int_tree_map *h;
679                   void **loc;
680
681                   TREE_PUBLIC (x) = TREE_PUBLIC (t);
682
683                   if (cp_function_chain->extern_decl_map == NULL)
684                     cp_function_chain->extern_decl_map
685                       = htab_create_ggc (20, cxx_int_tree_map_hash,
686                                          cxx_int_tree_map_eq, NULL);
687
688                   h = GGC_NEW (struct cxx_int_tree_map);
689                   h->uid = DECL_UID (x);
690                   h->to = t;
691                   loc = htab_find_slot_with_hash
692                           (cp_function_chain->extern_decl_map, h,
693                            h->uid, INSERT);
694                   *(struct cxx_int_tree_map **) loc = h;
695                 }
696             }
697           else if (TREE_CODE (t) == PARM_DECL)
698             {
699               gcc_assert (DECL_CONTEXT (t));
700
701               /* Check for duplicate params.  */
702               if (duplicate_decls (x, t, is_friend))
703                 POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
704             }
705           else if ((DECL_EXTERN_C_FUNCTION_P (x)
706                     || DECL_FUNCTION_TEMPLATE_P (x))
707                    && is_overloaded_fn (t))
708             /* Don't do anything just yet.  */;
709           else if (t == wchar_decl_node)
710             {
711               if (pedantic && ! DECL_IN_SYSTEM_HEADER (x))
712                 pedwarn ("redeclaration of %<wchar_t%> as %qT",
713                          TREE_TYPE (x));
714
715               /* Throw away the redeclaration.  */
716               POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
717             }
718           else
719             {
720               tree olddecl = duplicate_decls (x, t, is_friend);
721
722               /* If the redeclaration failed, we can stop at this
723                  point.  */
724               if (olddecl == error_mark_node)
725                 POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
726
727               if (olddecl)
728                 {
729                   if (TREE_CODE (t) == TYPE_DECL)
730                     SET_IDENTIFIER_TYPE_VALUE (name, TREE_TYPE (t));
731
732                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
733                 }
734               else if (DECL_MAIN_P (x) && TREE_CODE (t) == FUNCTION_DECL)
735                 {
736                   /* A redeclaration of main, but not a duplicate of the
737                      previous one.
738
739                      [basic.start.main]
740
741                      This function shall not be overloaded.  */
742                   error ("invalid redeclaration of %q+D", t);
743                   error ("as %qD", x);
744                   /* We don't try to push this declaration since that
745                      causes a crash.  */
746                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, x);
747                 }
748             }
749         }
750
751       check_template_shadow (x);
752
753       /* If this is a function conjured up by the backend, massage it
754          so it looks friendly.  */
755       if (DECL_NON_THUNK_FUNCTION_P (x) && ! DECL_LANG_SPECIFIC (x))
756         {
757           retrofit_lang_decl (x);
758           SET_DECL_LANGUAGE (x, lang_c);
759         }
760
761       if (DECL_NON_THUNK_FUNCTION_P (x) && ! DECL_FUNCTION_MEMBER_P (x))
762         {
763           t = push_overloaded_decl (x, PUSH_LOCAL, is_friend);
764           if (t != x)
765             POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
766           if (!namespace_bindings_p ())
767             /* We do not need to create a binding for this name;
768                push_overloaded_decl will have already done so if
769                necessary.  */
770             need_new_binding = 0;
771         }
772       else if (DECL_FUNCTION_TEMPLATE_P (x) && DECL_NAMESPACE_SCOPE_P (x))
773         {
774           t = push_overloaded_decl (x, PUSH_GLOBAL, is_friend);
775           if (t == x)
776             add_decl_to_level (x, NAMESPACE_LEVEL (CP_DECL_CONTEXT (t)));
777           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
778         }
779
780       /* If declaring a type as a typedef, copy the type (unless we're
781          at line 0), and install this TYPE_DECL as the new type's typedef
782          name.  See the extensive comment in ../c-decl.c (pushdecl).  */
783       if (TREE_CODE (x) == TYPE_DECL)
784         {
785           tree type = TREE_TYPE (x);
786           if (DECL_IS_BUILTIN (x))
787             {
788               if (TYPE_NAME (type) == 0)
789                 TYPE_NAME (type) = x;
790             }
791           else if (type != error_mark_node && TYPE_NAME (type) != x
792                    /* We don't want to copy the type when all we're
793                       doing is making a TYPE_DECL for the purposes of
794                       inlining.  */
795                    && (!TYPE_NAME (type)
796                        || TYPE_NAME (type) != DECL_ABSTRACT_ORIGIN (x)))
797             {
798               DECL_ORIGINAL_TYPE (x) = type;
799               type = build_variant_type_copy (type);
800               TYPE_STUB_DECL (type) = TYPE_STUB_DECL (DECL_ORIGINAL_TYPE (x));
801               TYPE_NAME (type) = x;
802               TREE_TYPE (x) = type;
803             }
804
805           if (type != error_mark_node
806               && TYPE_NAME (type)
807               && TYPE_IDENTIFIER (type))
808             set_identifier_type_value (DECL_NAME (x), x);
809         }
810
811       /* Multiple external decls of the same identifier ought to match.
812
813          We get warnings about inline functions where they are defined.
814          We get warnings about other functions from push_overloaded_decl.
815
816          Avoid duplicate warnings where they are used.  */
817       if (TREE_PUBLIC (x) && TREE_CODE (x) != FUNCTION_DECL)
818         {
819           tree decl;
820
821           decl = IDENTIFIER_NAMESPACE_VALUE (name);
822           if (decl && TREE_CODE (decl) == OVERLOAD)
823             decl = OVL_FUNCTION (decl);
824
825           if (decl && decl != error_mark_node
826               && (DECL_EXTERNAL (decl) || TREE_PUBLIC (decl))
827               /* If different sort of thing, we already gave an error.  */
828               && TREE_CODE (decl) == TREE_CODE (x)
829               && !same_type_p (TREE_TYPE (x), TREE_TYPE (decl)))
830             {
831               pedwarn ("type mismatch with previous external decl of %q#D", x);
832               pedwarn ("previous external decl of %q+#D", decl);
833             }
834         }
835
836       if (TREE_CODE (x) == FUNCTION_DECL
837           && is_friend
838           && !flag_friend_injection)
839         {
840           /* This is a new declaration of a friend function, so hide
841              it from ordinary function lookup.  */
842           DECL_ANTICIPATED (x) = 1;
843           DECL_HIDDEN_FRIEND_P (x) = 1;
844         }
845
846       /* This name is new in its binding level.
847          Install the new declaration and return it.  */
848       if (namespace_bindings_p ())
849         {
850           /* Install a global value.  */
851
852           /* If the first global decl has external linkage,
853              warn if we later see static one.  */
854           if (IDENTIFIER_GLOBAL_VALUE (name) == NULL_TREE && TREE_PUBLIC (x))
855             TREE_PUBLIC (name) = 1;
856
857           /* Bind the name for the entity.  */
858           if (!(TREE_CODE (x) == TYPE_DECL && DECL_ARTIFICIAL (x)
859                 && t != NULL_TREE)
860               && (TREE_CODE (x) == TYPE_DECL
861                   || TREE_CODE (x) == VAR_DECL
862                   || TREE_CODE (x) == NAMESPACE_DECL
863                   || TREE_CODE (x) == CONST_DECL
864                   || TREE_CODE (x) == TEMPLATE_DECL))
865             SET_IDENTIFIER_NAMESPACE_VALUE (name, x);
866
867           /* If new decl is `static' and an `extern' was seen previously,
868              warn about it.  */
869           if (x != NULL_TREE && t != NULL_TREE && decls_match (x, t))
870             warn_extern_redeclared_static (x, t);
871         }
872       else
873         {
874           /* Here to install a non-global value.  */
875           tree oldlocal = innermost_non_namespace_value (name);
876           tree oldglobal = IDENTIFIER_NAMESPACE_VALUE (name);
877
878           if (need_new_binding)
879             {
880               push_local_binding (name, x, 0);
881               /* Because push_local_binding will hook X on to the
882                  current_binding_level's name list, we don't want to
883                  do that again below.  */
884               need_new_binding = 0;
885             }
886
887           /* If this is a TYPE_DECL, push it into the type value slot.  */
888           if (TREE_CODE (x) == TYPE_DECL)
889             set_identifier_type_value (name, x);
890
891           /* Clear out any TYPE_DECL shadowed by a namespace so that
892              we won't think this is a type.  The C struct hack doesn't
893              go through namespaces.  */
894           if (TREE_CODE (x) == NAMESPACE_DECL)
895             set_identifier_type_value (name, NULL_TREE);
896
897           if (oldlocal)
898             {
899               tree d = oldlocal;
900
901               while (oldlocal
902                      && TREE_CODE (oldlocal) == VAR_DECL
903                      && DECL_DEAD_FOR_LOCAL (oldlocal))
904                 oldlocal = DECL_SHADOWED_FOR_VAR (oldlocal);
905
906               if (oldlocal == NULL_TREE)
907                 oldlocal = IDENTIFIER_NAMESPACE_VALUE (DECL_NAME (d));
908             }
909
910           /* If this is an extern function declaration, see if we
911              have a global definition or declaration for the function.  */
912           if (oldlocal == NULL_TREE
913               && DECL_EXTERNAL (x)
914               && oldglobal != NULL_TREE
915               && TREE_CODE (x) == FUNCTION_DECL
916               && TREE_CODE (oldglobal) == FUNCTION_DECL)
917             {
918               /* We have one.  Their types must agree.  */
919               if (decls_match (x, oldglobal))
920                 /* OK */;
921               else
922                 {
923                   warning (0, "extern declaration of %q#D doesn't match", x);
924                   warning (0, "global declaration %q+#D", oldglobal);
925                 }
926             }
927           /* If we have a local external declaration,
928              and no file-scope declaration has yet been seen,
929              then if we later have a file-scope decl it must not be static.  */
930           if (oldlocal == NULL_TREE
931               && oldglobal == NULL_TREE
932               && DECL_EXTERNAL (x)
933               && TREE_PUBLIC (x))
934             TREE_PUBLIC (name) = 1;
935
936           /* Warn if shadowing an argument at the top level of the body.  */
937           if (oldlocal != NULL_TREE && !DECL_EXTERNAL (x)
938               /* Inline decls shadow nothing.  */
939               && !DECL_FROM_INLINE (x)
940               && TREE_CODE (oldlocal) == PARM_DECL
941               /* Don't check the `this' parameter.  */
942               && !DECL_ARTIFICIAL (oldlocal))
943             {
944               bool err = false;
945
946               /* Don't complain if it's from an enclosing function.  */
947               if (DECL_CONTEXT (oldlocal) == current_function_decl
948                   && TREE_CODE (x) != PARM_DECL)
949                 {
950                   /* Go to where the parms should be and see if we find
951                      them there.  */
952                   struct cp_binding_level *b = current_binding_level->level_chain;
953
954                   if (FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
955                     /* Skip the ctor/dtor cleanup level.  */
956                     b = b->level_chain;
957
958                   /* ARM $8.3 */
959                   if (b->kind == sk_function_parms)
960                     {
961                       error ("declaration of %q#D shadows a parameter", x);
962                       err = true;
963                     }
964                 }
965
966               if (warn_shadow && !err)
967                 {
968                   warning (OPT_Wshadow, "declaration of %q#D shadows a parameter", x);
969                   warning (OPT_Wshadow, "%Jshadowed declaration is here", oldlocal);
970                 }
971             }
972
973           /* Maybe warn if shadowing something else.  */
974           else if (warn_shadow && !DECL_EXTERNAL (x)
975               /* No shadow warnings for internally generated vars.  */
976               && ! DECL_ARTIFICIAL (x)
977               /* No shadow warnings for vars made for inlining.  */
978               && ! DECL_FROM_INLINE (x))
979             {
980               tree member;
981
982               if (current_class_ptr)
983                 member = lookup_member (current_class_type,
984                                         name,
985                                         /*protect=*/0,
986                                         /*want_type=*/false);
987               else
988                 member = NULL_TREE;
989
990               if (member && !TREE_STATIC (member))
991                 {
992                   /* Location of previous decl is not useful in this case.  */
993                   warning (OPT_Wshadow, "declaration of %qD shadows a member of 'this'",
994                            x);
995                 }
996               else if (oldlocal != NULL_TREE
997                        && TREE_CODE (oldlocal) == VAR_DECL)
998                 {
999                   warning (OPT_Wshadow, "declaration of %qD shadows a previous local", x);
1000                   warning (OPT_Wshadow, "%Jshadowed declaration is here", oldlocal);
1001                 }
1002               else if (oldglobal != NULL_TREE
1003                        && TREE_CODE (oldglobal) == VAR_DECL)
1004                 /* XXX shadow warnings in outer-more namespaces */
1005                 {
1006                   warning (OPT_Wshadow, "declaration of %qD shadows a global declaration",
1007                            x);
1008                   warning (OPT_Wshadow, "%Jshadowed declaration is here", oldglobal);
1009                 }
1010             }
1011         }
1012
1013       if (TREE_CODE (x) == VAR_DECL)
1014         maybe_register_incomplete_var (x);
1015     }
1016
1017   if (need_new_binding)
1018     add_decl_to_level (x,
1019                        DECL_NAMESPACE_SCOPE_P (x)
1020                        ? NAMESPACE_LEVEL (CP_DECL_CONTEXT (x))
1021                        : current_binding_level);
1022
1023   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, x);
1024 }
1025
1026 /* Record a decl-node X as belonging to the current lexical scope.  */
1027
1028 tree
1029 pushdecl (tree x)
1030 {
1031   return pushdecl_maybe_friend (x, false);
1032 }
1033
1034 /* Enter DECL into the symbol table, if that's appropriate.  Returns
1035    DECL, or a modified version thereof.  */
1036
1037 tree
1038 maybe_push_decl (tree decl)
1039 {
1040   tree type = TREE_TYPE (decl);
1041
1042   /* Add this decl to the current binding level, but not if it comes
1043      from another scope, e.g. a static member variable.  TEM may equal
1044      DECL or it may be a previous decl of the same name.  */
1045   if (decl == error_mark_node
1046       || (TREE_CODE (decl) != PARM_DECL
1047           && DECL_CONTEXT (decl) != NULL_TREE
1048           /* Definitions of namespace members outside their namespace are
1049              possible.  */
1050           && TREE_CODE (DECL_CONTEXT (decl)) != NAMESPACE_DECL)
1051       || (TREE_CODE (decl) == TEMPLATE_DECL && !namespace_bindings_p ())
1052       || TREE_CODE (type) == UNKNOWN_TYPE
1053       /* The declaration of a template specialization does not affect
1054          the functions available for overload resolution, so we do not
1055          call pushdecl.  */
1056       || (TREE_CODE (decl) == FUNCTION_DECL
1057           && DECL_TEMPLATE_SPECIALIZATION (decl)))
1058     return decl;
1059   else
1060     return pushdecl (decl);
1061 }
1062
1063 /* Bind DECL to ID in the current_binding_level, assumed to be a local
1064    binding level.  If PUSH_USING is set in FLAGS, we know that DECL
1065    doesn't really belong to this binding level, that it got here
1066    through a using-declaration.  */
1067
1068 void
1069 push_local_binding (tree id, tree decl, int flags)
1070 {
1071   struct cp_binding_level *b;
1072
1073   /* Skip over any local classes.  This makes sense if we call
1074      push_local_binding with a friend decl of a local class.  */
1075   b = innermost_nonclass_level ();
1076
1077   if (lookup_name_innermost_nonclass_level (id))
1078     {
1079       /* Supplement the existing binding.  */
1080       if (!supplement_binding (IDENTIFIER_BINDING (id), decl))
1081         /* It didn't work.  Something else must be bound at this
1082            level.  Do not add DECL to the list of things to pop
1083            later.  */
1084         return;
1085     }
1086   else
1087     /* Create a new binding.  */
1088     push_binding (id, decl, b);
1089
1090   if (TREE_CODE (decl) == OVERLOAD || (flags & PUSH_USING))
1091     /* We must put the OVERLOAD into a TREE_LIST since the
1092        TREE_CHAIN of an OVERLOAD is already used.  Similarly for
1093        decls that got here through a using-declaration.  */
1094     decl = build_tree_list (NULL_TREE, decl);
1095
1096   /* And put DECL on the list of things declared by the current
1097      binding level.  */
1098   add_decl_to_level (decl, b);
1099 }
1100
1101 /* Check to see whether or not DECL is a variable that would have been
1102    in scope under the ARM, but is not in scope under the ANSI/ISO
1103    standard.  If so, issue an error message.  If name lookup would
1104    work in both cases, but return a different result, this function
1105    returns the result of ANSI/ISO lookup.  Otherwise, it returns
1106    DECL.  */
1107
1108 tree
1109 check_for_out_of_scope_variable (tree decl)
1110 {
1111   tree shadowed;
1112
1113   /* We only care about out of scope variables.  */
1114   if (!(TREE_CODE (decl) == VAR_DECL && DECL_DEAD_FOR_LOCAL (decl)))
1115     return decl;
1116
1117   shadowed = DECL_HAS_SHADOWED_FOR_VAR_P (decl)
1118     ? DECL_SHADOWED_FOR_VAR (decl) : NULL_TREE ;
1119   while (shadowed != NULL_TREE && TREE_CODE (shadowed) == VAR_DECL
1120          && DECL_DEAD_FOR_LOCAL (shadowed))
1121     shadowed = DECL_HAS_SHADOWED_FOR_VAR_P (shadowed)
1122       ? DECL_SHADOWED_FOR_VAR (shadowed) : NULL_TREE;
1123   if (!shadowed)
1124     shadowed = IDENTIFIER_NAMESPACE_VALUE (DECL_NAME (decl));
1125   if (shadowed)
1126     {
1127       if (!DECL_ERROR_REPORTED (decl))
1128         {
1129           warning (0, "name lookup of %qD changed", DECL_NAME (decl));
1130           warning (0, "  matches this %q+D under ISO standard rules",
1131                    shadowed);
1132           warning (0, "  matches this %q+D under old rules", decl);
1133           DECL_ERROR_REPORTED (decl) = 1;
1134         }
1135       return shadowed;
1136     }
1137
1138   /* If we have already complained about this declaration, there's no
1139      need to do it again.  */
1140   if (DECL_ERROR_REPORTED (decl))
1141     return decl;
1142
1143   DECL_ERROR_REPORTED (decl) = 1;
1144
1145   if (TREE_TYPE (decl) == error_mark_node)
1146     return decl;
1147
1148   if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (decl)))
1149     {
1150       error ("name lookup of %qD changed for new ISO %<for%> scoping",
1151              DECL_NAME (decl));
1152       error ("  cannot use obsolete binding at %q+D because "
1153              "it has a destructor", decl);
1154       return error_mark_node;
1155     }
1156   else
1157     {
1158       pedwarn ("name lookup of %qD changed for new ISO %<for%> scoping",
1159                DECL_NAME (decl));
1160       pedwarn ("  using obsolete binding at %q+D", decl);
1161     }
1162
1163   return decl;
1164 }
1165 \f
1166 /* true means unconditionally make a BLOCK for the next level pushed.  */
1167
1168 static bool keep_next_level_flag;
1169
1170 static int binding_depth = 0;
1171 static int is_class_level = 0;
1172
1173 static void
1174 indent (int depth)
1175 {
1176   int i;
1177
1178   for (i = 0; i < depth * 2; i++)
1179     putc (' ', stderr);
1180 }
1181
1182 /* Return a string describing the kind of SCOPE we have.  */
1183 static const char *
1184 cxx_scope_descriptor (cxx_scope *scope)
1185 {
1186   /* The order of this table must match the "scope_kind"
1187      enumerators.  */
1188   static const char* scope_kind_names[] = {
1189     "block-scope",
1190     "cleanup-scope",
1191     "try-scope",
1192     "catch-scope",
1193     "for-scope",
1194     "function-parameter-scope",
1195     "class-scope",
1196     "namespace-scope",
1197     "template-parameter-scope",
1198     "template-explicit-spec-scope"
1199   };
1200   const scope_kind kind = scope->explicit_spec_p
1201     ? sk_template_spec : scope->kind;
1202
1203   return scope_kind_names[kind];
1204 }
1205
1206 /* Output a debugging information about SCOPE when performing
1207    ACTION at LINE.  */
1208 static void
1209 cxx_scope_debug (cxx_scope *scope, int line, const char *action)
1210 {
1211   const char *desc = cxx_scope_descriptor (scope);
1212   if (scope->this_entity)
1213     verbatim ("%s %s(%E) %p %d\n", action, desc,
1214               scope->this_entity, (void *) scope, line);
1215   else
1216     verbatim ("%s %s %p %d\n", action, desc, (void *) scope, line);
1217 }
1218
1219 /* Return the estimated initial size of the hashtable of a NAMESPACE
1220    scope.  */
1221
1222 static inline size_t
1223 namespace_scope_ht_size (tree ns)
1224 {
1225   tree name = DECL_NAME (ns);
1226
1227   return name == std_identifier
1228     ? NAMESPACE_STD_HT_SIZE
1229     : (name == global_scope_name
1230        ? GLOBAL_SCOPE_HT_SIZE
1231        : NAMESPACE_ORDINARY_HT_SIZE);
1232 }
1233
1234 /* A chain of binding_level structures awaiting reuse.  */
1235
1236 static GTY((deletable)) struct cp_binding_level *free_binding_level;
1237
1238 /* Insert SCOPE as the innermost binding level.  */
1239
1240 void
1241 push_binding_level (struct cp_binding_level *scope)
1242 {
1243   /* Add it to the front of currently active scopes stack.  */
1244   scope->level_chain = current_binding_level;
1245   current_binding_level = scope;
1246   keep_next_level_flag = false;
1247
1248   if (ENABLE_SCOPE_CHECKING)
1249     {
1250       scope->binding_depth = binding_depth;
1251       indent (binding_depth);
1252       cxx_scope_debug (scope, input_line, "push");
1253       is_class_level = 0;
1254       binding_depth++;
1255     }
1256 }
1257
1258 /* Create a new KIND scope and make it the top of the active scopes stack.
1259    ENTITY is the scope of the associated C++ entity (namespace, class,
1260    function); it is NULL otherwise.  */
1261
1262 cxx_scope *
1263 begin_scope (scope_kind kind, tree entity)
1264 {
1265   cxx_scope *scope;
1266
1267   /* Reuse or create a struct for this binding level.  */
1268   if (!ENABLE_SCOPE_CHECKING && free_binding_level)
1269     {
1270       scope = free_binding_level;
1271       free_binding_level = scope->level_chain;
1272     }
1273   else
1274     scope = GGC_NEW (cxx_scope);
1275   memset (scope, 0, sizeof (cxx_scope));
1276
1277   scope->this_entity = entity;
1278   scope->more_cleanups_ok = true;
1279   switch (kind)
1280     {
1281     case sk_cleanup:
1282       scope->keep = true;
1283       break;
1284
1285     case sk_template_spec:
1286       scope->explicit_spec_p = true;
1287       kind = sk_template_parms;
1288       /* Fall through.  */
1289     case sk_template_parms:
1290     case sk_block:
1291     case sk_try:
1292     case sk_catch:
1293     case sk_for:
1294     case sk_class:
1295     case sk_function_parms:
1296     case sk_omp:
1297       scope->keep = keep_next_level_flag;
1298       break;
1299
1300     case sk_namespace:
1301       NAMESPACE_LEVEL (entity) = scope;
1302       scope->static_decls =
1303         VEC_alloc (tree, gc,
1304                    DECL_NAME (entity) == std_identifier
1305                    || DECL_NAME (entity) == global_scope_name
1306                    ? 200 : 10);
1307       break;
1308
1309     default:
1310       /* Should not happen.  */
1311       gcc_unreachable ();
1312       break;
1313     }
1314   scope->kind = kind;
1315
1316   push_binding_level (scope);
1317
1318   return scope;
1319 }
1320
1321 /* We're about to leave current scope.  Pop the top of the stack of
1322    currently active scopes.  Return the enclosing scope, now active.  */
1323
1324 cxx_scope *
1325 leave_scope (void)
1326 {
1327   cxx_scope *scope = current_binding_level;
1328
1329   if (scope->kind == sk_namespace && class_binding_level)
1330     current_binding_level = class_binding_level;
1331
1332   /* We cannot leave a scope, if there are none left.  */
1333   if (NAMESPACE_LEVEL (global_namespace))
1334     gcc_assert (!global_scope_p (scope));
1335
1336   if (ENABLE_SCOPE_CHECKING)
1337     {
1338       indent (--binding_depth);
1339       cxx_scope_debug (scope, input_line, "leave");
1340       if (is_class_level != (scope == class_binding_level))
1341         {
1342           indent (binding_depth);
1343           verbatim ("XXX is_class_level != (current_scope == class_scope)\n");
1344         }
1345       is_class_level = 0;
1346     }
1347
1348 #ifdef HANDLE_PRAGMA_VISIBILITY
1349   if (scope->has_visibility)
1350     pop_visibility ();
1351 #endif
1352
1353   /* Move one nesting level up.  */
1354   current_binding_level = scope->level_chain;
1355
1356   /* Namespace-scopes are left most probably temporarily, not
1357      completely; they can be reopened later, e.g. in namespace-extension
1358      or any name binding activity that requires us to resume a
1359      namespace.  For classes, we cache some binding levels.  For other
1360      scopes, we just make the structure available for reuse.  */
1361   if (scope->kind != sk_namespace
1362       && scope->kind != sk_class)
1363     {
1364       scope->level_chain = free_binding_level;
1365       gcc_assert (!ENABLE_SCOPE_CHECKING
1366                   || scope->binding_depth == binding_depth);
1367       free_binding_level = scope;
1368     }
1369
1370   /* Find the innermost enclosing class scope, and reset
1371      CLASS_BINDING_LEVEL appropriately.  */
1372   if (scope->kind == sk_class)
1373     {
1374       class_binding_level = NULL;
1375       for (scope = current_binding_level; scope; scope = scope->level_chain)
1376         if (scope->kind == sk_class)
1377           {
1378             class_binding_level = scope;
1379             break;
1380           }
1381     }
1382
1383   return current_binding_level;
1384 }
1385
1386 static void
1387 resume_scope (struct cp_binding_level* b)
1388 {
1389   /* Resuming binding levels is meant only for namespaces,
1390      and those cannot nest into classes.  */
1391   gcc_assert (!class_binding_level);
1392   /* Also, resuming a non-directly nested namespace is a no-no.  */
1393   gcc_assert (b->level_chain == current_binding_level);
1394   current_binding_level = b;
1395   if (ENABLE_SCOPE_CHECKING)
1396     {
1397       b->binding_depth = binding_depth;
1398       indent (binding_depth);
1399       cxx_scope_debug (b, input_line, "resume");
1400       is_class_level = 0;
1401       binding_depth++;
1402     }
1403 }
1404
1405 /* Return the innermost binding level that is not for a class scope.  */
1406
1407 static cxx_scope *
1408 innermost_nonclass_level (void)
1409 {
1410   cxx_scope *b;
1411
1412   b = current_binding_level;
1413   while (b->kind == sk_class)
1414     b = b->level_chain;
1415
1416   return b;
1417 }
1418
1419 /* We're defining an object of type TYPE.  If it needs a cleanup, but
1420    we're not allowed to add any more objects with cleanups to the current
1421    scope, create a new binding level.  */
1422
1423 void
1424 maybe_push_cleanup_level (tree type)
1425 {
1426   if (type != error_mark_node
1427       && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
1428       && current_binding_level->more_cleanups_ok == 0)
1429     {
1430       begin_scope (sk_cleanup, NULL);
1431       current_binding_level->statement_list = push_stmt_list ();
1432     }
1433 }
1434
1435 /* Nonzero if we are currently in the global binding level.  */
1436
1437 int
1438 global_bindings_p (void)
1439 {
1440   return global_scope_p (current_binding_level);
1441 }
1442
1443 /* True if we are currently in a toplevel binding level.  This
1444    means either the global binding level or a namespace in a toplevel
1445    binding level.  Since there are no non-toplevel namespace levels,
1446    this really means any namespace or template parameter level.  We
1447    also include a class whose context is toplevel.  */
1448
1449 bool
1450 toplevel_bindings_p (void)
1451 {
1452   struct cp_binding_level *b = innermost_nonclass_level ();
1453
1454   return b->kind == sk_namespace || b->kind == sk_template_parms;
1455 }
1456
1457 /* True if this is a namespace scope, or if we are defining a class
1458    which is itself at namespace scope, or whose enclosing class is
1459    such a class, etc.  */
1460
1461 bool
1462 namespace_bindings_p (void)
1463 {
1464   struct cp_binding_level *b = innermost_nonclass_level ();
1465
1466   return b->kind == sk_namespace;
1467 }
1468
1469 /* True if the current level needs to have a BLOCK made.  */
1470
1471 bool
1472 kept_level_p (void)
1473 {
1474   return (current_binding_level->blocks != NULL_TREE
1475           || current_binding_level->keep
1476           || current_binding_level->kind == sk_cleanup
1477           || current_binding_level->names != NULL_TREE);
1478 }
1479
1480 /* Returns the kind of the innermost scope.  */
1481
1482 scope_kind
1483 innermost_scope_kind (void)
1484 {
1485   return current_binding_level->kind;
1486 }
1487
1488 /* Returns true if this scope was created to store template parameters.  */
1489
1490 bool
1491 template_parm_scope_p (void)
1492 {
1493   return innermost_scope_kind () == sk_template_parms;
1494 }
1495
1496 /* If KEEP is true, make a BLOCK node for the next binding level,
1497    unconditionally.  Otherwise, use the normal logic to decide whether
1498    or not to create a BLOCK.  */
1499
1500 void
1501 keep_next_level (bool keep)
1502 {
1503   keep_next_level_flag = keep;
1504 }
1505
1506 /* Return the list of declarations of the current level.
1507    Note that this list is in reverse order unless/until
1508    you nreverse it; and when you do nreverse it, you must
1509    store the result back using `storedecls' or you will lose.  */
1510
1511 tree
1512 getdecls (void)
1513 {
1514   return current_binding_level->names;
1515 }
1516
1517 /* For debugging.  */
1518 static int no_print_functions = 0;
1519 static int no_print_builtins = 0;
1520
1521 static void
1522 print_binding_level (struct cp_binding_level* lvl)
1523 {
1524   tree t;
1525   int i = 0, len;
1526   fprintf (stderr, " blocks=%p", (void *) lvl->blocks);
1527   if (lvl->more_cleanups_ok)
1528     fprintf (stderr, " more-cleanups-ok");
1529   if (lvl->have_cleanups)
1530     fprintf (stderr, " have-cleanups");
1531   fprintf (stderr, "\n");
1532   if (lvl->names)
1533     {
1534       fprintf (stderr, " names:\t");
1535       /* We can probably fit 3 names to a line?  */
1536       for (t = lvl->names; t; t = TREE_CHAIN (t))
1537         {
1538           if (no_print_functions && (TREE_CODE (t) == FUNCTION_DECL))
1539             continue;
1540           if (no_print_builtins
1541               && (TREE_CODE (t) == TYPE_DECL)
1542               && DECL_IS_BUILTIN (t))
1543             continue;
1544
1545           /* Function decls tend to have longer names.  */
1546           if (TREE_CODE (t) == FUNCTION_DECL)
1547             len = 3;
1548           else
1549             len = 2;
1550           i += len;
1551           if (i > 6)
1552             {
1553               fprintf (stderr, "\n\t");
1554               i = len;
1555             }
1556           print_node_brief (stderr, "", t, 0);
1557           if (t == error_mark_node)
1558             break;
1559         }
1560       if (i)
1561         fprintf (stderr, "\n");
1562     }
1563   if (VEC_length (cp_class_binding, lvl->class_shadowed))
1564     {
1565       size_t i;
1566       cp_class_binding *b;
1567       fprintf (stderr, " class-shadowed:");
1568       for (i = 0;
1569            VEC_iterate(cp_class_binding, lvl->class_shadowed, i, b);
1570            ++i)
1571         fprintf (stderr, " %s ", IDENTIFIER_POINTER (b->identifier));
1572       fprintf (stderr, "\n");
1573     }
1574   if (lvl->type_shadowed)
1575     {
1576       fprintf (stderr, " type-shadowed:");
1577       for (t = lvl->type_shadowed; t; t = TREE_CHAIN (t))
1578         {
1579           fprintf (stderr, " %s ", IDENTIFIER_POINTER (TREE_PURPOSE (t)));
1580         }
1581       fprintf (stderr, "\n");
1582     }
1583 }
1584
1585 void
1586 print_other_binding_stack (struct cp_binding_level *stack)
1587 {
1588   struct cp_binding_level *level;
1589   for (level = stack; !global_scope_p (level); level = level->level_chain)
1590     {
1591       fprintf (stderr, "binding level %p\n", (void *) level);
1592       print_binding_level (level);
1593     }
1594 }
1595
1596 void
1597 print_binding_stack (void)
1598 {
1599   struct cp_binding_level *b;
1600   fprintf (stderr, "current_binding_level=%p\n"
1601            "class_binding_level=%p\n"
1602            "NAMESPACE_LEVEL (global_namespace)=%p\n",
1603            (void *) current_binding_level, (void *) class_binding_level,
1604            (void *) NAMESPACE_LEVEL (global_namespace));
1605   if (class_binding_level)
1606     {
1607       for (b = class_binding_level; b; b = b->level_chain)
1608         if (b == current_binding_level)
1609           break;
1610       if (b)
1611         b = class_binding_level;
1612       else
1613         b = current_binding_level;
1614     }
1615   else
1616     b = current_binding_level;
1617   print_other_binding_stack (b);
1618   fprintf (stderr, "global:\n");
1619   print_binding_level (NAMESPACE_LEVEL (global_namespace));
1620 }
1621 \f
1622 /* Return the type associated with id.  */
1623
1624 tree
1625 identifier_type_value (tree id)
1626 {
1627   timevar_push (TV_NAME_LOOKUP);
1628   /* There is no type with that name, anywhere.  */
1629   if (REAL_IDENTIFIER_TYPE_VALUE (id) == NULL_TREE)
1630     POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, NULL_TREE);
1631   /* This is not the type marker, but the real thing.  */
1632   if (REAL_IDENTIFIER_TYPE_VALUE (id) != global_type_node)
1633     POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, REAL_IDENTIFIER_TYPE_VALUE (id));
1634   /* Have to search for it. It must be on the global level, now.
1635      Ask lookup_name not to return non-types.  */
1636   id = lookup_name_real (id, 2, 1, /*block_p=*/true, 0, LOOKUP_COMPLAIN);
1637   if (id)
1638     POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, TREE_TYPE (id));
1639   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, NULL_TREE);
1640 }
1641
1642 /* Return the IDENTIFIER_GLOBAL_VALUE of T, for use in common code, since
1643    the definition of IDENTIFIER_GLOBAL_VALUE is different for C and C++.  */
1644
1645 tree
1646 identifier_global_value (tree t)
1647 {
1648   return IDENTIFIER_GLOBAL_VALUE (t);
1649 }
1650
1651 /* Push a definition of struct, union or enum tag named ID.  into
1652    binding_level B.  DECL is a TYPE_DECL for the type.  We assume that
1653    the tag ID is not already defined.  */
1654
1655 static void
1656 set_identifier_type_value_with_scope (tree id, tree decl, cxx_scope *b)
1657 {
1658   tree type;
1659
1660   if (b->kind != sk_namespace)
1661     {
1662       /* Shadow the marker, not the real thing, so that the marker
1663          gets restored later.  */
1664       tree old_type_value = REAL_IDENTIFIER_TYPE_VALUE (id);
1665       b->type_shadowed
1666         = tree_cons (id, old_type_value, b->type_shadowed);
1667       type = decl ? TREE_TYPE (decl) : NULL_TREE;
1668       TREE_TYPE (b->type_shadowed) = type;
1669     }
1670   else
1671     {
1672       cxx_binding *binding =
1673         binding_for_name (NAMESPACE_LEVEL (current_namespace), id);
1674       gcc_assert (decl);
1675       if (binding->value)
1676         supplement_binding (binding, decl);
1677       else
1678         binding->value = decl;
1679
1680       /* Store marker instead of real type.  */
1681       type = global_type_node;
1682     }
1683   SET_IDENTIFIER_TYPE_VALUE (id, type);
1684 }
1685
1686 /* As set_identifier_type_value_with_scope, but using
1687    current_binding_level.  */
1688
1689 void
1690 set_identifier_type_value (tree id, tree decl)
1691 {
1692   set_identifier_type_value_with_scope (id, decl, current_binding_level);
1693 }
1694
1695 /* Return the name for the constructor (or destructor) for the
1696    specified class TYPE.  When given a template, this routine doesn't
1697    lose the specialization.  */
1698
1699 static inline tree
1700 constructor_name_full (tree type)
1701 {
1702   return TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
1703 }
1704
1705 /* Return the name for the constructor (or destructor) for the
1706    specified class.  When given a template, return the plain
1707    unspecialized name.  */
1708
1709 tree
1710 constructor_name (tree type)
1711 {
1712   tree name;
1713   name = constructor_name_full (type);
1714   if (IDENTIFIER_TEMPLATE (name))
1715     name = IDENTIFIER_TEMPLATE (name);
1716   return name;
1717 }
1718
1719 /* Returns TRUE if NAME is the name for the constructor for TYPE.  */
1720
1721 bool
1722 constructor_name_p (tree name, tree type)
1723 {
1724   tree ctor_name;
1725
1726   if (!name)
1727     return false;
1728
1729   if (TREE_CODE (name) != IDENTIFIER_NODE)
1730     return false;
1731
1732   ctor_name = constructor_name_full (type);
1733   if (name == ctor_name)
1734     return true;
1735   if (IDENTIFIER_TEMPLATE (ctor_name)
1736       && name == IDENTIFIER_TEMPLATE (ctor_name))
1737     return true;
1738   return false;
1739 }
1740
1741 /* Counter used to create anonymous type names.  */
1742
1743 static GTY(()) int anon_cnt;
1744
1745 /* Return an IDENTIFIER which can be used as a name for
1746    anonymous structs and unions.  */
1747
1748 tree
1749 make_anon_name (void)
1750 {
1751   char buf[32];
1752
1753   sprintf (buf, ANON_AGGRNAME_FORMAT, anon_cnt++);
1754   return get_identifier (buf);
1755 }
1756
1757 /* Return (from the stack of) the BINDING, if any, established at SCOPE.  */
1758
1759 static inline cxx_binding *
1760 find_binding (cxx_scope *scope, cxx_binding *binding)
1761 {
1762   timevar_push (TV_NAME_LOOKUP);
1763
1764   for (; binding != NULL; binding = binding->previous)
1765     if (binding->scope == scope)
1766       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, binding);
1767
1768   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, (cxx_binding *)0);
1769 }
1770
1771 /* Return the binding for NAME in SCOPE, if any.  Otherwise, return NULL.  */
1772
1773 static inline cxx_binding *
1774 cxx_scope_find_binding_for_name (cxx_scope *scope, tree name)
1775 {
1776   cxx_binding *b = IDENTIFIER_NAMESPACE_BINDINGS (name);
1777   if (b)
1778     {
1779       /* Fold-in case where NAME is used only once.  */
1780       if (scope == b->scope && b->previous == NULL)
1781         return b;
1782       return find_binding (scope, b);
1783     }
1784   return NULL;
1785 }
1786
1787 /* Always returns a binding for name in scope.  If no binding is
1788    found, make a new one.  */
1789
1790 static cxx_binding *
1791 binding_for_name (cxx_scope *scope, tree name)
1792 {
1793   cxx_binding *result;
1794
1795   result = cxx_scope_find_binding_for_name (scope, name);
1796   if (result)
1797     return result;
1798   /* Not found, make a new one.  */
1799   result = cxx_binding_make (NULL, NULL);
1800   result->previous = IDENTIFIER_NAMESPACE_BINDINGS (name);
1801   result->scope = scope;
1802   result->is_local = false;
1803   result->value_is_inherited = false;
1804   IDENTIFIER_NAMESPACE_BINDINGS (name) = result;
1805   return result;
1806 }
1807
1808 /* Insert another USING_DECL into the current binding level, returning
1809    this declaration. If this is a redeclaration, do nothing, and
1810    return NULL_TREE if this not in namespace scope (in namespace
1811    scope, a using decl might extend any previous bindings).  */
1812
1813 static tree
1814 push_using_decl (tree scope, tree name)
1815 {
1816   tree decl;
1817
1818   timevar_push (TV_NAME_LOOKUP);
1819   gcc_assert (TREE_CODE (scope) == NAMESPACE_DECL);
1820   gcc_assert (TREE_CODE (name) == IDENTIFIER_NODE);
1821   for (decl = current_binding_level->usings; decl; decl = TREE_CHAIN (decl))
1822     if (USING_DECL_SCOPE (decl) == scope && DECL_NAME (decl) == name)
1823       break;
1824   if (decl)
1825     POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP,
1826                             namespace_bindings_p () ? decl : NULL_TREE);
1827   decl = build_lang_decl (USING_DECL, name, NULL_TREE);
1828   USING_DECL_SCOPE (decl) = scope;
1829   TREE_CHAIN (decl) = current_binding_level->usings;
1830   current_binding_level->usings = decl;
1831   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, decl);
1832 }
1833
1834 /* Same as pushdecl, but define X in binding-level LEVEL.  We rely on the
1835    caller to set DECL_CONTEXT properly.  */
1836
1837 tree
1838 pushdecl_with_scope (tree x, cxx_scope *level, bool is_friend)
1839 {
1840   struct cp_binding_level *b;
1841   tree function_decl = current_function_decl;
1842
1843   timevar_push (TV_NAME_LOOKUP);
1844   current_function_decl = NULL_TREE;
1845   if (level->kind == sk_class)
1846     {
1847       b = class_binding_level;
1848       class_binding_level = level;
1849       pushdecl_class_level (x);
1850       class_binding_level = b;
1851     }
1852   else
1853     {
1854       b = current_binding_level;
1855       current_binding_level = level;
1856       x = pushdecl_maybe_friend (x, is_friend);
1857       current_binding_level = b;
1858     }
1859   current_function_decl = function_decl;
1860   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, x);
1861 }
1862
1863 /* DECL is a FUNCTION_DECL for a non-member function, which may have
1864    other definitions already in place.  We get around this by making
1865    the value of the identifier point to a list of all the things that
1866    want to be referenced by that name.  It is then up to the users of
1867    that name to decide what to do with that list.
1868
1869    DECL may also be a TEMPLATE_DECL, with a FUNCTION_DECL in its
1870    DECL_TEMPLATE_RESULT.  It is dealt with the same way.
1871
1872    FLAGS is a bitwise-or of the following values:
1873      PUSH_LOCAL: Bind DECL in the current scope, rather than at
1874                  namespace scope.
1875      PUSH_USING: DECL is being pushed as the result of a using
1876                  declaration.
1877
1878    IS_FRIEND is true if this is a friend declaration.
1879
1880    The value returned may be a previous declaration if we guessed wrong
1881    about what language DECL should belong to (C or C++).  Otherwise,
1882    it's always DECL (and never something that's not a _DECL).  */
1883
1884 static tree
1885 push_overloaded_decl (tree decl, int flags, bool is_friend)
1886 {
1887   tree name = DECL_NAME (decl);
1888   tree old;
1889   tree new_binding;
1890   int doing_global = (namespace_bindings_p () || !(flags & PUSH_LOCAL));
1891
1892   timevar_push (TV_NAME_LOOKUP);
1893   if (doing_global)
1894     old = namespace_binding (name, DECL_CONTEXT (decl));
1895   else
1896     old = lookup_name_innermost_nonclass_level (name);
1897
1898   if (old)
1899     {
1900       if (TREE_CODE (old) == TYPE_DECL && DECL_ARTIFICIAL (old))
1901         {
1902           tree t = TREE_TYPE (old);
1903           if (IS_AGGR_TYPE (t) && warn_shadow
1904               && (! DECL_IN_SYSTEM_HEADER (decl)
1905                   || ! DECL_IN_SYSTEM_HEADER (old)))
1906             warning (0, "%q#D hides constructor for %q#T", decl, t);
1907           old = NULL_TREE;
1908         }
1909       else if (is_overloaded_fn (old))
1910         {
1911           tree tmp;
1912
1913           for (tmp = old; tmp; tmp = OVL_NEXT (tmp))
1914             {
1915               tree fn = OVL_CURRENT (tmp);
1916               tree dup;
1917
1918               if (TREE_CODE (tmp) == OVERLOAD && OVL_USED (tmp)
1919                   && !(flags & PUSH_USING)
1920                   && compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1921                                 TYPE_ARG_TYPES (TREE_TYPE (decl)))
1922                   && ! decls_match (fn, decl))
1923                 error ("%q#D conflicts with previous using declaration %q#D",
1924                        decl, fn);
1925
1926               dup = duplicate_decls (decl, fn, is_friend);
1927               /* If DECL was a redeclaration of FN -- even an invalid
1928                  one -- pass that information along to our caller.  */
1929               if (dup == fn || dup == error_mark_node)
1930                 POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, dup);
1931             }
1932
1933           /* We don't overload implicit built-ins.  duplicate_decls()
1934              may fail to merge the decls if the new decl is e.g. a
1935              template function.  */
1936           if (TREE_CODE (old) == FUNCTION_DECL
1937               && DECL_ANTICIPATED (old)
1938               && !DECL_HIDDEN_FRIEND_P (old))
1939             old = NULL;
1940         }
1941       else if (old == error_mark_node)
1942         /* Ignore the undefined symbol marker.  */
1943         old = NULL_TREE;
1944       else
1945         {
1946           error ("previous non-function declaration %q+#D", old);
1947           error ("conflicts with function declaration %q#D", decl);
1948           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, decl);
1949         }
1950     }
1951
1952   if (old || TREE_CODE (decl) == TEMPLATE_DECL
1953       /* If it's a using declaration, we always need to build an OVERLOAD,
1954          because it's the only way to remember that the declaration comes
1955          from 'using', and have the lookup behave correctly.  */
1956       || (flags & PUSH_USING))
1957     {
1958       if (old && TREE_CODE (old) != OVERLOAD)
1959         new_binding = ovl_cons (decl, ovl_cons (old, NULL_TREE));
1960       else
1961         new_binding = ovl_cons (decl, old);
1962       if (flags & PUSH_USING)
1963         OVL_USED (new_binding) = 1;
1964     }
1965   else
1966     /* NAME is not ambiguous.  */
1967     new_binding = decl;
1968
1969   if (doing_global)
1970     set_namespace_binding (name, current_namespace, new_binding);
1971   else
1972     {
1973       /* We only create an OVERLOAD if there was a previous binding at
1974          this level, or if decl is a template. In the former case, we
1975          need to remove the old binding and replace it with the new
1976          binding.  We must also run through the NAMES on the binding
1977          level where the name was bound to update the chain.  */
1978
1979       if (TREE_CODE (new_binding) == OVERLOAD && old)
1980         {
1981           tree *d;
1982
1983           for (d = &IDENTIFIER_BINDING (name)->scope->names;
1984                *d;
1985                d = &TREE_CHAIN (*d))
1986             if (*d == old
1987                 || (TREE_CODE (*d) == TREE_LIST
1988                     && TREE_VALUE (*d) == old))
1989               {
1990                 if (TREE_CODE (*d) == TREE_LIST)
1991                   /* Just replace the old binding with the new.  */
1992                   TREE_VALUE (*d) = new_binding;
1993                 else
1994                   /* Build a TREE_LIST to wrap the OVERLOAD.  */
1995                   *d = tree_cons (NULL_TREE, new_binding,
1996                                   TREE_CHAIN (*d));
1997
1998                 /* And update the cxx_binding node.  */
1999                 IDENTIFIER_BINDING (name)->value = new_binding;
2000                 POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, decl);
2001               }
2002
2003           /* We should always find a previous binding in this case.  */
2004           gcc_unreachable ();
2005         }
2006
2007       /* Install the new binding.  */
2008       push_local_binding (name, new_binding, flags);
2009     }
2010
2011   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, decl);
2012 }
2013
2014 /* Check a non-member using-declaration. Return the name and scope
2015    being used, and the USING_DECL, or NULL_TREE on failure.  */
2016
2017 static tree
2018 validate_nonmember_using_decl (tree decl, tree scope, tree name)
2019 {
2020   /* [namespace.udecl]
2021        A using-declaration for a class member shall be a
2022        member-declaration.  */
2023   if (TYPE_P (scope))
2024     {
2025       error ("%qT is not a namespace", scope);
2026       return NULL_TREE;
2027     }
2028   else if (scope == error_mark_node)
2029     return NULL_TREE;
2030
2031   if (TREE_CODE (decl) == TEMPLATE_ID_EXPR)
2032     {
2033       /* 7.3.3/5
2034            A using-declaration shall not name a template-id.  */
2035       error ("a using-declaration cannot specify a template-id.  "
2036              "Try %<using %D%>", name);
2037       return NULL_TREE;
2038     }
2039
2040   if (TREE_CODE (decl) == NAMESPACE_DECL)
2041     {
2042       error ("namespace %qD not allowed in using-declaration", decl);
2043       return NULL_TREE;
2044     }
2045
2046   if (TREE_CODE (decl) == SCOPE_REF)
2047     {
2048       /* It's a nested name with template parameter dependent scope.
2049          This can only be using-declaration for class member.  */
2050       error ("%qT is not a namespace", TREE_OPERAND (decl, 0));
2051       return NULL_TREE;
2052     }
2053
2054   if (is_overloaded_fn (decl))
2055     decl = get_first_fn (decl);
2056
2057   gcc_assert (DECL_P (decl));
2058
2059   /* Make a USING_DECL.  */
2060   return push_using_decl (scope, name);
2061 }
2062
2063 /* Process local and global using-declarations.  */
2064
2065 static void
2066 do_nonmember_using_decl (tree scope, tree name, tree oldval, tree oldtype,
2067                          tree *newval, tree *newtype)
2068 {
2069   struct scope_binding decls = EMPTY_SCOPE_BINDING;
2070
2071   *newval = *newtype = NULL_TREE;
2072   if (!qualified_lookup_using_namespace (name, scope, &decls, 0))
2073     /* Lookup error */
2074     return;
2075
2076   if (!decls.value && !decls.type)
2077     {
2078       error ("%qD not declared", name);
2079       return;
2080     }
2081
2082   /* It is impossible to overload a built-in function; any explicit
2083      declaration eliminates the built-in declaration.  So, if OLDVAL
2084      is a built-in, then we can just pretend it isn't there.  */
2085   if (oldval
2086       && TREE_CODE (oldval) == FUNCTION_DECL
2087       && DECL_ANTICIPATED (oldval)
2088       && !DECL_HIDDEN_FRIEND_P (oldval))
2089     oldval = NULL_TREE;
2090
2091   /* Check for using functions.  */
2092   if (decls.value && is_overloaded_fn (decls.value))
2093     {
2094       tree tmp, tmp1;
2095
2096       if (oldval && !is_overloaded_fn (oldval))
2097         {
2098           if (!DECL_IMPLICIT_TYPEDEF_P (oldval))
2099             error ("%qD is already declared in this scope", name);
2100           oldval = NULL_TREE;
2101         }
2102
2103       *newval = oldval;
2104       for (tmp = decls.value; tmp; tmp = OVL_NEXT (tmp))
2105         {
2106           tree new_fn = OVL_CURRENT (tmp);
2107
2108           /* [namespace.udecl]
2109
2110              If a function declaration in namespace scope or block
2111              scope has the same name and the same parameter types as a
2112              function introduced by a using declaration the program is
2113              ill-formed.  */
2114           for (tmp1 = oldval; tmp1; tmp1 = OVL_NEXT (tmp1))
2115             {
2116               tree old_fn = OVL_CURRENT (tmp1);
2117
2118               if (new_fn == old_fn)
2119                 /* The function already exists in the current namespace.  */
2120                 break;
2121               else if (OVL_USED (tmp1))
2122                 continue; /* this is a using decl */
2123               else if (compparms (TYPE_ARG_TYPES (TREE_TYPE (new_fn)),
2124                                   TYPE_ARG_TYPES (TREE_TYPE (old_fn))))
2125                 {
2126                   gcc_assert (!DECL_ANTICIPATED (old_fn)
2127                               || DECL_HIDDEN_FRIEND_P (old_fn));
2128
2129                   /* There was already a non-using declaration in
2130                      this scope with the same parameter types. If both
2131                      are the same extern "C" functions, that's ok.  */
2132                   if (decls_match (new_fn, old_fn))
2133                     break;
2134                   else
2135                     {
2136                       error ("%qD is already declared in this scope", name);
2137                       break;
2138                     }
2139                 }
2140             }
2141
2142           /* If we broke out of the loop, there's no reason to add
2143              this function to the using declarations for this
2144              scope.  */
2145           if (tmp1)
2146             continue;
2147
2148           /* If we are adding to an existing OVERLOAD, then we no
2149              longer know the type of the set of functions.  */
2150           if (*newval && TREE_CODE (*newval) == OVERLOAD)
2151             TREE_TYPE (*newval) = unknown_type_node;
2152           /* Add this new function to the set.  */
2153           *newval = build_overload (OVL_CURRENT (tmp), *newval);
2154           /* If there is only one function, then we use its type.  (A
2155              using-declaration naming a single function can be used in
2156              contexts where overload resolution cannot be
2157              performed.)  */
2158           if (TREE_CODE (*newval) != OVERLOAD)
2159             {
2160               *newval = ovl_cons (*newval, NULL_TREE);
2161               TREE_TYPE (*newval) = TREE_TYPE (OVL_CURRENT (tmp));
2162             }
2163           OVL_USED (*newval) = 1;
2164         }
2165     }
2166   else
2167     {
2168       *newval = decls.value;
2169       if (oldval && !decls_match (*newval, oldval))
2170         error ("%qD is already declared in this scope", name);
2171     }
2172
2173   *newtype = decls.type;
2174   if (oldtype && *newtype && !same_type_p (oldtype, *newtype))
2175     {
2176       error ("using declaration %qD introduced ambiguous type %qT",
2177              name, oldtype);
2178       return;
2179     }
2180 }
2181
2182 /* Process a using-declaration at function scope.  */
2183
2184 void
2185 do_local_using_decl (tree decl, tree scope, tree name)
2186 {
2187   tree oldval, oldtype, newval, newtype;
2188   tree orig_decl = decl;
2189
2190   decl = validate_nonmember_using_decl (decl, scope, name);
2191   if (decl == NULL_TREE)
2192     return;
2193
2194   if (building_stmt_tree ()
2195       && at_function_scope_p ())
2196     add_decl_expr (decl);
2197
2198   oldval = lookup_name_innermost_nonclass_level (name);
2199   oldtype = lookup_type_current_level (name);
2200
2201   do_nonmember_using_decl (scope, name, oldval, oldtype, &newval, &newtype);
2202
2203   if (newval)
2204     {
2205       if (is_overloaded_fn (newval))
2206         {
2207           tree fn, term;
2208
2209           /* We only need to push declarations for those functions
2210              that were not already bound in the current level.
2211              The old value might be NULL_TREE, it might be a single
2212              function, or an OVERLOAD.  */
2213           if (oldval && TREE_CODE (oldval) == OVERLOAD)
2214             term = OVL_FUNCTION (oldval);
2215           else
2216             term = oldval;
2217           for (fn = newval; fn && OVL_CURRENT (fn) != term;
2218                fn = OVL_NEXT (fn))
2219             push_overloaded_decl (OVL_CURRENT (fn),
2220                                   PUSH_LOCAL | PUSH_USING,
2221                                   false);
2222         }
2223       else
2224         push_local_binding (name, newval, PUSH_USING);
2225     }
2226   if (newtype)
2227     {
2228       push_local_binding (name, newtype, PUSH_USING);
2229       set_identifier_type_value (name, newtype);
2230     }
2231
2232   /* Emit debug info.  */
2233   if (!processing_template_decl)
2234     cp_emit_debug_info_for_using (orig_decl, current_scope());
2235 }
2236
2237 /* Returns true if ROOT (a namespace, class, or function) encloses
2238    CHILD.  CHILD may be either a class type or a namespace.  */
2239
2240 bool
2241 is_ancestor (tree root, tree child)
2242 {
2243   gcc_assert ((TREE_CODE (root) == NAMESPACE_DECL
2244                || TREE_CODE (root) == FUNCTION_DECL
2245                || CLASS_TYPE_P (root)));
2246   gcc_assert ((TREE_CODE (child) == NAMESPACE_DECL
2247                || CLASS_TYPE_P (child)));
2248
2249   /* The global namespace encloses everything.  */
2250   if (root == global_namespace)
2251     return true;
2252
2253   while (true)
2254     {
2255       /* If we've run out of scopes, stop.  */
2256       if (!child)
2257         return false;
2258       /* If we've reached the ROOT, it encloses CHILD.  */
2259       if (root == child)
2260         return true;
2261       /* Go out one level.  */
2262       if (TYPE_P (child))
2263         child = TYPE_NAME (child);
2264       child = DECL_CONTEXT (child);
2265     }
2266 }
2267
2268 /* Enter the class or namespace scope indicated by T suitable for name
2269    lookup.  T can be arbitrary scope, not necessary nested inside the
2270    current scope.  Returns a non-null scope to pop iff pop_scope
2271    should be called later to exit this scope.  */
2272
2273 tree
2274 push_scope (tree t)
2275 {
2276   if (TREE_CODE (t) == NAMESPACE_DECL)
2277     push_decl_namespace (t);
2278   else if (CLASS_TYPE_P (t))
2279     {
2280       if (!at_class_scope_p ()
2281           || !same_type_p (current_class_type, t))
2282         push_nested_class (t);
2283       else
2284         /* T is the same as the current scope.  There is therefore no
2285            need to re-enter the scope.  Since we are not actually
2286            pushing a new scope, our caller should not call
2287            pop_scope.  */
2288         t = NULL_TREE;
2289     }
2290
2291   return t;
2292 }
2293
2294 /* Leave scope pushed by push_scope.  */
2295
2296 void
2297 pop_scope (tree t)
2298 {
2299   if (TREE_CODE (t) == NAMESPACE_DECL)
2300     pop_decl_namespace ();
2301   else if CLASS_TYPE_P (t)
2302     pop_nested_class ();
2303 }
2304
2305 /* Subroutine of push_inner_scope.  */
2306
2307 static void
2308 push_inner_scope_r (tree outer, tree inner)
2309 {
2310   tree prev;
2311
2312   if (outer == inner
2313       || (TREE_CODE (inner) != NAMESPACE_DECL && !CLASS_TYPE_P (inner)))
2314     return;
2315
2316   prev = CP_DECL_CONTEXT (TREE_CODE (inner) == NAMESPACE_DECL ? inner : TYPE_NAME (inner));
2317   if (outer != prev)
2318     push_inner_scope_r (outer, prev);
2319   if (TREE_CODE (inner) == NAMESPACE_DECL)
2320     {
2321       struct cp_binding_level *save_template_parm = 0;
2322       /* Temporary take out template parameter scopes.  They are saved
2323          in reversed order in save_template_parm.  */
2324       while (current_binding_level->kind == sk_template_parms)
2325         {
2326           struct cp_binding_level *b = current_binding_level;
2327           current_binding_level = b->level_chain;
2328           b->level_chain = save_template_parm;
2329           save_template_parm = b;
2330         }
2331
2332       resume_scope (NAMESPACE_LEVEL (inner));
2333       current_namespace = inner;
2334
2335       /* Restore template parameter scopes.  */
2336       while (save_template_parm)
2337         {
2338           struct cp_binding_level *b = save_template_parm;
2339           save_template_parm = b->level_chain;
2340           b->level_chain = current_binding_level;
2341           current_binding_level = b;
2342         }
2343     }
2344   else
2345     pushclass (inner);
2346 }
2347
2348 /* Enter the scope INNER from current scope.  INNER must be a scope
2349    nested inside current scope.  This works with both name lookup and
2350    pushing name into scope.  In case a template parameter scope is present,
2351    namespace is pushed under the template parameter scope according to
2352    name lookup rule in 14.6.1/6.
2353
2354    Return the former current scope suitable for pop_inner_scope.  */
2355
2356 tree
2357 push_inner_scope (tree inner)
2358 {
2359   tree outer = current_scope ();
2360   if (!outer)
2361     outer = current_namespace;
2362
2363   push_inner_scope_r (outer, inner);
2364   return outer;
2365 }
2366
2367 /* Exit the current scope INNER back to scope OUTER.  */
2368
2369 void
2370 pop_inner_scope (tree outer, tree inner)
2371 {
2372   if (outer == inner
2373       || (TREE_CODE (inner) != NAMESPACE_DECL && !CLASS_TYPE_P (inner)))
2374     return;
2375
2376   while (outer != inner)
2377     {
2378       if (TREE_CODE (inner) == NAMESPACE_DECL)
2379         {
2380           struct cp_binding_level *save_template_parm = 0;
2381           /* Temporary take out template parameter scopes.  They are saved
2382              in reversed order in save_template_parm.  */
2383           while (current_binding_level->kind == sk_template_parms)
2384             {
2385               struct cp_binding_level *b = current_binding_level;
2386               current_binding_level = b->level_chain;
2387               b->level_chain = save_template_parm;
2388               save_template_parm = b;
2389             }
2390
2391           pop_namespace ();
2392
2393           /* Restore template parameter scopes.  */
2394           while (save_template_parm)
2395             {
2396               struct cp_binding_level *b = save_template_parm;
2397               save_template_parm = b->level_chain;
2398               b->level_chain = current_binding_level;
2399               current_binding_level = b;
2400             }
2401         }
2402       else
2403         popclass ();
2404
2405       inner = CP_DECL_CONTEXT (TREE_CODE (inner) == NAMESPACE_DECL ? inner : TYPE_NAME (inner));
2406     }
2407 }
2408 \f
2409 /* Do a pushlevel for class declarations.  */
2410
2411 void
2412 pushlevel_class (void)
2413 {
2414   if (ENABLE_SCOPE_CHECKING)
2415     is_class_level = 1;
2416
2417   class_binding_level = begin_scope (sk_class, current_class_type);
2418 }
2419
2420 /* ...and a poplevel for class declarations.  */
2421
2422 void
2423 poplevel_class (void)
2424 {
2425   struct cp_binding_level *level = class_binding_level;
2426   cp_class_binding *cb;
2427   size_t i;
2428   tree shadowed;
2429
2430   timevar_push (TV_NAME_LOOKUP);
2431   gcc_assert (level != 0);
2432
2433   /* If we're leaving a toplevel class, cache its binding level.  */
2434   if (current_class_depth == 1)
2435     previous_class_level = level;
2436   for (shadowed = level->type_shadowed;
2437        shadowed;
2438        shadowed = TREE_CHAIN (shadowed))
2439     SET_IDENTIFIER_TYPE_VALUE (TREE_PURPOSE (shadowed), TREE_VALUE (shadowed));
2440
2441   /* Remove the bindings for all of the class-level declarations.  */
2442   if (level->class_shadowed)
2443     {
2444       for (i = 0;
2445            VEC_iterate (cp_class_binding, level->class_shadowed, i, cb);
2446            ++i)
2447         IDENTIFIER_BINDING (cb->identifier) = cb->base.previous;
2448       ggc_free (level->class_shadowed);
2449       level->class_shadowed = NULL;
2450     }
2451
2452   /* Now, pop out of the binding level which we created up in the
2453      `pushlevel_class' routine.  */
2454   if (ENABLE_SCOPE_CHECKING)
2455     is_class_level = 1;
2456
2457   leave_scope ();
2458   timevar_pop (TV_NAME_LOOKUP);
2459 }
2460
2461 /* Set INHERITED_VALUE_BINDING_P on BINDING to true or false, as
2462    appropriate.  DECL is the value to which a name has just been
2463    bound.  CLASS_TYPE is the class in which the lookup occurred.  */
2464
2465 static void
2466 set_inherited_value_binding_p (cxx_binding *binding, tree decl,
2467                                tree class_type)
2468 {
2469   if (binding->value == decl && TREE_CODE (decl) != TREE_LIST)
2470     {
2471       tree context;
2472
2473       if (TREE_CODE (decl) == OVERLOAD)
2474         context = CP_DECL_CONTEXT (OVL_CURRENT (decl));
2475       else
2476         {
2477           gcc_assert (DECL_P (decl));
2478           context = context_for_name_lookup (decl);
2479         }
2480
2481       if (is_properly_derived_from (class_type, context))
2482         INHERITED_VALUE_BINDING_P (binding) = 1;
2483       else
2484         INHERITED_VALUE_BINDING_P (binding) = 0;
2485     }
2486   else if (binding->value == decl)
2487     /* We only encounter a TREE_LIST when there is an ambiguity in the
2488        base classes.  Such an ambiguity can be overridden by a
2489        definition in this class.  */
2490     INHERITED_VALUE_BINDING_P (binding) = 1;
2491   else
2492     INHERITED_VALUE_BINDING_P (binding) = 0;
2493 }
2494
2495 /* Make the declaration of X appear in CLASS scope.  */
2496
2497 bool
2498 pushdecl_class_level (tree x)
2499 {
2500   tree name;
2501   bool is_valid = true;
2502
2503   timevar_push (TV_NAME_LOOKUP);
2504   /* Get the name of X.  */
2505   if (TREE_CODE (x) == OVERLOAD)
2506     name = DECL_NAME (get_first_fn (x));
2507   else
2508     name = DECL_NAME (x);
2509
2510   if (name)
2511     {
2512       is_valid = push_class_level_binding (name, x);
2513       if (TREE_CODE (x) == TYPE_DECL)
2514         set_identifier_type_value (name, x);
2515     }
2516   else if (ANON_AGGR_TYPE_P (TREE_TYPE (x)))
2517     {
2518       /* If X is an anonymous aggregate, all of its members are
2519          treated as if they were members of the class containing the
2520          aggregate, for naming purposes.  */
2521       tree f;
2522
2523       for (f = TYPE_FIELDS (TREE_TYPE (x)); f; f = TREE_CHAIN (f))
2524         {
2525           location_t save_location = input_location;
2526           input_location = DECL_SOURCE_LOCATION (f);
2527           if (!pushdecl_class_level (f))
2528             is_valid = false;
2529           input_location = save_location;
2530         }
2531     }
2532   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, is_valid);
2533 }
2534
2535 /* Return the BINDING (if any) for NAME in SCOPE, which is a class
2536    scope.  If the value returned is non-NULL, and the PREVIOUS field
2537    is not set, callers must set the PREVIOUS field explicitly.  */
2538
2539 static cxx_binding *
2540 get_class_binding (tree name, cxx_scope *scope)
2541 {
2542   tree class_type;
2543   tree type_binding;
2544   tree value_binding;
2545   cxx_binding *binding;
2546
2547   class_type = scope->this_entity;
2548
2549   /* Get the type binding.  */
2550   type_binding = lookup_member (class_type, name,
2551                                 /*protect=*/2, /*want_type=*/true);
2552   /* Get the value binding.  */
2553   value_binding = lookup_member (class_type, name,
2554                                  /*protect=*/2, /*want_type=*/false);
2555
2556   if (value_binding
2557       && (TREE_CODE (value_binding) == TYPE_DECL
2558           || DECL_CLASS_TEMPLATE_P (value_binding)
2559           || (TREE_CODE (value_binding) == TREE_LIST
2560               && TREE_TYPE (value_binding) == error_mark_node
2561               && (TREE_CODE (TREE_VALUE (value_binding))
2562                   == TYPE_DECL))))
2563     /* We found a type binding, even when looking for a non-type
2564        binding.  This means that we already processed this binding
2565        above.  */
2566     ;
2567   else if (value_binding)
2568     {
2569       if (TREE_CODE (value_binding) == TREE_LIST
2570           && TREE_TYPE (value_binding) == error_mark_node)
2571         /* NAME is ambiguous.  */
2572         ;
2573       else if (BASELINK_P (value_binding))
2574         /* NAME is some overloaded functions.  */
2575         value_binding = BASELINK_FUNCTIONS (value_binding);
2576     }
2577
2578   /* If we found either a type binding or a value binding, create a
2579      new binding object.  */
2580   if (type_binding || value_binding)
2581     {
2582       binding = new_class_binding (name,
2583                                    value_binding,
2584                                    type_binding,
2585                                    scope);
2586       /* This is a class-scope binding, not a block-scope binding.  */
2587       LOCAL_BINDING_P (binding) = 0;
2588       set_inherited_value_binding_p (binding, value_binding, class_type);
2589     }
2590   else
2591     binding = NULL;
2592
2593   return binding;
2594 }
2595
2596 /* Make the declaration(s) of X appear in CLASS scope under the name
2597    NAME.  Returns true if the binding is valid.  */
2598
2599 bool
2600 push_class_level_binding (tree name, tree x)
2601 {
2602   cxx_binding *binding;
2603   tree decl = x;
2604   bool ok;
2605
2606   timevar_push (TV_NAME_LOOKUP);
2607   /* The class_binding_level will be NULL if x is a template
2608      parameter name in a member template.  */
2609   if (!class_binding_level)
2610     POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, true);
2611
2612   /* Check for invalid member names.  */
2613   gcc_assert (TYPE_BEING_DEFINED (current_class_type));
2614   /* We could have been passed a tree list if this is an ambiguous
2615      declaration. If so, pull the declaration out because
2616      check_template_shadow will not handle a TREE_LIST.  */
2617   if (TREE_CODE (decl) == TREE_LIST
2618       && TREE_TYPE (decl) == error_mark_node)
2619     decl = TREE_VALUE (decl);
2620
2621   check_template_shadow (decl);
2622
2623   /* [class.mem]
2624
2625      If T is the name of a class, then each of the following shall
2626      have a name different from T:
2627
2628      -- every static data member of class T;
2629
2630      -- every member of class T that is itself a type;
2631
2632      -- every enumerator of every member of class T that is an
2633         enumerated type;
2634
2635      -- every member of every anonymous union that is a member of
2636         class T.
2637
2638      (Non-static data members were also forbidden to have the same
2639      name as T until TC1.)  */
2640   if ((TREE_CODE (x) == VAR_DECL
2641        || TREE_CODE (x) == CONST_DECL
2642        || (TREE_CODE (x) == TYPE_DECL
2643            && !DECL_SELF_REFERENCE_P (x))
2644        /* A data member of an anonymous union.  */
2645        || (TREE_CODE (x) == FIELD_DECL
2646            && DECL_CONTEXT (x) != current_class_type))
2647       && DECL_NAME (x) == constructor_name (current_class_type))
2648     {
2649       tree scope = context_for_name_lookup (x);
2650       if (TYPE_P (scope) && same_type_p (scope, current_class_type))
2651         {
2652           error ("%qD has the same name as the class in which it is "
2653                  "declared",
2654                  x);
2655           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, false);
2656         }
2657     }
2658
2659   /* Get the current binding for NAME in this class, if any.  */
2660   binding = IDENTIFIER_BINDING (name);
2661   if (!binding || binding->scope != class_binding_level)
2662     {
2663       binding = get_class_binding (name, class_binding_level);
2664       /* If a new binding was created, put it at the front of the
2665          IDENTIFIER_BINDING list.  */
2666       if (binding)
2667         {
2668           binding->previous = IDENTIFIER_BINDING (name);
2669           IDENTIFIER_BINDING (name) = binding;
2670         }
2671     }
2672
2673   /* If there is already a binding, then we may need to update the
2674      current value.  */
2675   if (binding && binding->value)
2676     {
2677       tree bval = binding->value;
2678       tree old_decl = NULL_TREE;
2679
2680       if (INHERITED_VALUE_BINDING_P (binding))
2681         {
2682           /* If the old binding was from a base class, and was for a
2683              tag name, slide it over to make room for the new binding.
2684              The old binding is still visible if explicitly qualified
2685              with a class-key.  */
2686           if (TREE_CODE (bval) == TYPE_DECL && DECL_ARTIFICIAL (bval)
2687               && !(TREE_CODE (x) == TYPE_DECL && DECL_ARTIFICIAL (x)))
2688             {
2689               old_decl = binding->type;
2690               binding->type = bval;
2691               binding->value = NULL_TREE;
2692               INHERITED_VALUE_BINDING_P (binding) = 0;
2693             }
2694           else
2695             {
2696               old_decl = bval;
2697               /* Any inherited type declaration is hidden by the type
2698                  declaration in the derived class.  */
2699               if (TREE_CODE (x) == TYPE_DECL && DECL_ARTIFICIAL (x))
2700                 binding->type = NULL_TREE;
2701             }
2702         }
2703       else if (TREE_CODE (x) == OVERLOAD && is_overloaded_fn (bval))
2704         old_decl = bval;
2705       else if (TREE_CODE (x) == USING_DECL && TREE_CODE (bval) == USING_DECL)
2706         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, true);
2707       else if (TREE_CODE (x) == USING_DECL && is_overloaded_fn (bval))
2708         old_decl = bval;
2709       else if (TREE_CODE (bval) == USING_DECL && is_overloaded_fn (x))
2710         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, true);
2711
2712       if (old_decl && binding->scope == class_binding_level)
2713         {
2714           binding->value = x;
2715           /* It is always safe to clear INHERITED_VALUE_BINDING_P
2716              here.  This function is only used to register bindings
2717              from with the class definition itself.  */
2718           INHERITED_VALUE_BINDING_P (binding) = 0;
2719           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, true);
2720         }
2721     }
2722
2723   /* Note that we declared this value so that we can issue an error if
2724      this is an invalid redeclaration of a name already used for some
2725      other purpose.  */
2726   note_name_declared_in_class (name, decl);
2727
2728   /* If we didn't replace an existing binding, put the binding on the
2729      stack of bindings for the identifier, and update the shadowed
2730      list.  */
2731   if (binding && binding->scope == class_binding_level)
2732     /* Supplement the existing binding.  */
2733     ok = supplement_binding (binding, decl);
2734   else
2735     {
2736       /* Create a new binding.  */
2737       push_binding (name, decl, class_binding_level);
2738       ok = true;
2739     }
2740
2741   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, ok);
2742 }
2743
2744 /* Process "using SCOPE::NAME" in a class scope.  Return the
2745    USING_DECL created.  */
2746
2747 tree
2748 do_class_using_decl (tree scope, tree name)
2749 {
2750   /* The USING_DECL returned by this function.  */
2751   tree value;
2752   /* The declaration (or declarations) name by this using
2753      declaration.  NULL if we are in a template and cannot figure out
2754      what has been named.  */
2755   tree decl;
2756   /* True if SCOPE is a dependent type.  */
2757   bool scope_dependent_p;
2758   /* True if SCOPE::NAME is dependent.  */
2759   bool name_dependent_p;
2760   /* True if any of the bases of CURRENT_CLASS_TYPE are dependent.  */
2761   bool bases_dependent_p;
2762   tree binfo;
2763   tree base_binfo;
2764   int i;
2765
2766   if (!scope || !TYPE_P (scope))
2767     {
2768       error ("using-declaration for non-member at class scope");
2769       return NULL_TREE;
2770     }
2771
2772   /* Make sure the name is not invalid */
2773   if (TREE_CODE (name) == BIT_NOT_EXPR)
2774     {
2775       error ("%<%T::%D%> names destructor", scope, name);
2776       return NULL_TREE;
2777     }
2778   if (constructor_name_p (name, scope))
2779     {
2780       error ("%<%T::%D%> names constructor", scope, name);
2781       return NULL_TREE;
2782     }
2783   if (constructor_name_p (name, current_class_type))
2784     {
2785       error ("%<%T::%D%> names constructor in %qT",
2786              scope, name, current_class_type);
2787       return NULL_TREE;
2788     }
2789
2790   scope_dependent_p = dependent_type_p (scope);
2791   name_dependent_p = (scope_dependent_p
2792                       || (IDENTIFIER_TYPENAME_P (name)
2793                           && dependent_type_p (TREE_TYPE (name))));
2794
2795   bases_dependent_p = false;
2796   if (processing_template_decl)
2797     for (binfo = TYPE_BINFO (current_class_type), i = 0;
2798          BINFO_BASE_ITERATE (binfo, i, base_binfo);
2799          i++)
2800       if (dependent_type_p (TREE_TYPE (base_binfo)))
2801         {
2802           bases_dependent_p = true;
2803           break;
2804         }
2805
2806   decl = NULL_TREE;
2807
2808   /* From [namespace.udecl]:
2809
2810        A using-declaration used as a member-declaration shall refer to a
2811        member of a base class of the class being defined.
2812
2813      In general, we cannot check this constraint in a template because
2814      we do not know the entire set of base classes of the current
2815      class type.  However, if all of the base classes are
2816      non-dependent, then we can avoid delaying the check until
2817      instantiation.  */
2818   if (!scope_dependent_p && !bases_dependent_p)
2819     {
2820       base_kind b_kind;
2821       tree binfo;
2822       binfo = lookup_base (current_class_type, scope, ba_any, &b_kind);
2823       if (b_kind < bk_proper_base)
2824         {
2825           error_not_base_type (scope, current_class_type);
2826           return NULL_TREE;
2827         }
2828
2829       if (!name_dependent_p)
2830         {
2831           decl = lookup_member (binfo, name, 0, false);
2832           if (!decl)
2833             {
2834               error ("no members matching %<%T::%D%> in %q#T", scope, name,
2835                      scope);
2836               return NULL_TREE;
2837             }
2838           /* The binfo from which the functions came does not matter.  */
2839           if (BASELINK_P (decl))
2840             decl = BASELINK_FUNCTIONS (decl);
2841         }
2842    }
2843
2844   value = build_lang_decl (USING_DECL, name, NULL_TREE);
2845   USING_DECL_DECLS (value) = decl;
2846   USING_DECL_SCOPE (value) = scope;
2847   DECL_DEPENDENT_P (value) = !decl;
2848
2849   return value;
2850 }
2851
2852 \f
2853 /* Return the binding value for name in scope.  */
2854
2855 tree
2856 namespace_binding (tree name, tree scope)
2857 {
2858   cxx_binding *binding;
2859
2860   if (scope == NULL)
2861     scope = global_namespace;
2862   else
2863     /* Unnecessary for the global namespace because it can't be an alias. */
2864     scope = ORIGINAL_NAMESPACE (scope);
2865
2866   binding = cxx_scope_find_binding_for_name (NAMESPACE_LEVEL (scope), name);
2867
2868   return binding ? binding->value : NULL_TREE;
2869 }
2870
2871 /* Set the binding value for name in scope.  */
2872
2873 void
2874 set_namespace_binding (tree name, tree scope, tree val)
2875 {
2876   cxx_binding *b;
2877
2878   timevar_push (TV_NAME_LOOKUP);
2879   if (scope == NULL_TREE)
2880     scope = global_namespace;
2881   b = binding_for_name (NAMESPACE_LEVEL (scope), name);
2882   if (!b->value || TREE_CODE (val) == OVERLOAD || val == error_mark_node)
2883     b->value = val;
2884   else
2885     supplement_binding (b, val);
2886   timevar_pop (TV_NAME_LOOKUP);
2887 }
2888
2889 /* Set the context of a declaration to scope. Complain if we are not
2890    outside scope.  */
2891
2892 void
2893 set_decl_namespace (tree decl, tree scope, bool friendp)
2894 {
2895   tree old, fn;
2896
2897   /* Get rid of namespace aliases.  */
2898   scope = ORIGINAL_NAMESPACE (scope);
2899
2900   /* It is ok for friends to be qualified in parallel space.  */
2901   if (!friendp && !is_ancestor (current_namespace, scope))
2902     error ("declaration of %qD not in a namespace surrounding %qD",
2903            decl, scope);
2904   DECL_CONTEXT (decl) = FROB_CONTEXT (scope);
2905
2906   /* Writing "int N::i" to declare a variable within "N" is invalid.  */
2907   if (scope == current_namespace)
2908     {
2909       if (at_namespace_scope_p ())
2910         error ("explicit qualification in declaration of %qD",
2911                decl);
2912       return;
2913     }
2914
2915   /* See whether this has been declared in the namespace.  */
2916   old = lookup_qualified_name (scope, DECL_NAME (decl), false, true);
2917   if (!old)
2918     /* No old declaration at all.  */
2919     goto complain;
2920   if (!is_overloaded_fn (decl))
2921     /* Don't compare non-function decls with decls_match here, since
2922        it can't check for the correct constness at this
2923        point. pushdecl will find those errors later.  */
2924     return;
2925   /* Since decl is a function, old should contain a function decl.  */
2926   if (!is_overloaded_fn (old))
2927     goto complain;
2928   fn = OVL_CURRENT (old);
2929   if (!is_associated_namespace (scope, CP_DECL_CONTEXT (fn)))
2930     goto complain;
2931   /* A template can be explicitly specialized in any namespace.  */
2932   if (processing_explicit_instantiation)
2933     return;
2934   if (processing_template_decl || processing_specialization)
2935     /* We have not yet called push_template_decl to turn a
2936        FUNCTION_DECL into a TEMPLATE_DECL, so the declarations won't
2937        match.  But, we'll check later, when we construct the
2938        template.  */
2939     return;
2940   /* Instantiations or specializations of templates may be declared as
2941      friends in any namespace.  */
2942   if (friendp && DECL_USE_TEMPLATE (decl))
2943     return;
2944   if (is_overloaded_fn (old))
2945     {
2946       for (; old; old = OVL_NEXT (old))
2947         if (decls_match (decl, OVL_CURRENT (old)))
2948           return;
2949     }
2950   else if (decls_match (decl, old))
2951       return;
2952  complain:
2953   error ("%qD should have been declared inside %qD", decl, scope);
2954 }
2955
2956 /* Return the namespace where the current declaration is declared.  */
2957
2958 static tree
2959 current_decl_namespace (void)
2960 {
2961   tree result;
2962   /* If we have been pushed into a different namespace, use it.  */
2963   if (decl_namespace_list)
2964     return TREE_PURPOSE (decl_namespace_list);
2965
2966   if (current_class_type)
2967     result = decl_namespace_context (current_class_type);
2968   else if (current_function_decl)
2969     result = decl_namespace_context (current_function_decl);
2970   else
2971     result = current_namespace;
2972   return result;
2973 }
2974
2975 /* Push into the scope of the NAME namespace.  If NAME is NULL_TREE, then we
2976    select a name that is unique to this compilation unit.  */
2977
2978 void
2979 push_namespace (tree name)
2980 {
2981   push_namespace_with_attribs (name, NULL_TREE);
2982 }
2983
2984 /* Same, but specify attributes to apply to the namespace.  The attributes
2985    only apply to the current namespace-body, not to any later extensions. */
2986
2987 void
2988 push_namespace_with_attribs (tree name, tree attributes)
2989 {
2990   tree d = NULL_TREE;
2991   int need_new = 1;
2992   int implicit_use = 0;
2993   bool anon = !name;
2994
2995   timevar_push (TV_NAME_LOOKUP);
2996
2997   /* We should not get here if the global_namespace is not yet constructed
2998      nor if NAME designates the global namespace:  The global scope is
2999      constructed elsewhere.  */
3000   gcc_assert (global_namespace != NULL && name != global_scope_name);
3001
3002   if (anon)
3003     {
3004       /* The name of anonymous namespace is unique for the translation
3005          unit.  */
3006       if (!anonymous_namespace_name)
3007         anonymous_namespace_name = get_file_function_name ('N');
3008       name = anonymous_namespace_name;
3009       d = IDENTIFIER_NAMESPACE_VALUE (name);
3010       if (d)
3011         /* Reopening anonymous namespace.  */
3012         need_new = 0;
3013       implicit_use = 1;
3014     }
3015   else
3016     {
3017       /* Check whether this is an extended namespace definition.  */
3018       d = IDENTIFIER_NAMESPACE_VALUE (name);
3019       if (d != NULL_TREE && TREE_CODE (d) == NAMESPACE_DECL)
3020         {
3021           need_new = 0;
3022           if (DECL_NAMESPACE_ALIAS (d))
3023             {
3024               error ("namespace alias %qD not allowed here, assuming %qD",
3025                      d, DECL_NAMESPACE_ALIAS (d));
3026               d = DECL_NAMESPACE_ALIAS (d);
3027             }
3028         }
3029     }
3030
3031   if (need_new)
3032     {
3033       /* Make a new namespace, binding the name to it.  */
3034       d = build_lang_decl (NAMESPACE_DECL, name, void_type_node);
3035       DECL_CONTEXT (d) = FROB_CONTEXT (current_namespace);
3036       TREE_PUBLIC (d) = 1;
3037       pushdecl (d);
3038       if (anon)
3039         {
3040           /* Clear DECL_NAME for the benefit of debugging back ends.  */
3041           SET_DECL_ASSEMBLER_NAME (d, name);
3042           DECL_NAME (d) = NULL_TREE;
3043         }
3044       begin_scope (sk_namespace, d);
3045     }
3046   else
3047     resume_scope (NAMESPACE_LEVEL (d));
3048
3049   if (implicit_use)
3050     do_using_directive (d);
3051   /* Enter the name space.  */
3052   current_namespace = d;
3053
3054 #ifdef HANDLE_PRAGMA_VISIBILITY
3055   /* Clear has_visibility in case a previous namespace-definition had a
3056      visibility attribute and this one doesn't.  */
3057   current_binding_level->has_visibility = 0;
3058   for (d = attributes; d; d = TREE_CHAIN (d))
3059     {
3060       tree name = TREE_PURPOSE (d);
3061       tree args = TREE_VALUE (d);
3062       tree x;
3063
3064       if (! is_attribute_p ("visibility", name))
3065         {
3066           warning (OPT_Wattributes, "%qs attribute directive ignored",
3067                    IDENTIFIER_POINTER (name));
3068           continue;
3069         }
3070
3071       x = args ? TREE_VALUE (args) : NULL_TREE;
3072       if (x == NULL_TREE || TREE_CODE (x) != STRING_CST || TREE_CHAIN (args))
3073         {
3074           warning (OPT_Wattributes, "%qs attribute requires a single NTBS argument",
3075                    IDENTIFIER_POINTER (name));
3076           continue;
3077         }
3078
3079       current_binding_level->has_visibility = 1;
3080       push_visibility (TREE_STRING_POINTER (x));
3081       goto found;
3082     }
3083 #if 0
3084   if (anon)
3085     {
3086       /* Anonymous namespaces default to hidden visibility.  This might
3087          change once we implement export.  */
3088       current_binding_level->has_visibility = 1;
3089       push_visibility ("hidden");
3090     }
3091 #endif
3092  found:
3093 #endif
3094
3095   timevar_pop (TV_NAME_LOOKUP);
3096 }
3097
3098 /* Pop from the scope of the current namespace.  */
3099
3100 void
3101 pop_namespace (void)
3102 {
3103   gcc_assert (current_namespace != global_namespace);
3104   current_namespace = CP_DECL_CONTEXT (current_namespace);
3105   /* The binding level is not popped, as it might be re-opened later.  */
3106   leave_scope ();
3107 }
3108
3109 /* Push into the scope of the namespace NS, even if it is deeply
3110    nested within another namespace.  */
3111
3112 void
3113 push_nested_namespace (tree ns)
3114 {
3115   if (ns == global_namespace)
3116     push_to_top_level ();
3117   else
3118     {
3119       push_nested_namespace (CP_DECL_CONTEXT (ns));
3120       push_namespace (DECL_NAME (ns));
3121     }
3122 }
3123
3124 /* Pop back from the scope of the namespace NS, which was previously
3125    entered with push_nested_namespace.  */
3126
3127 void
3128 pop_nested_namespace (tree ns)
3129 {
3130   timevar_push (TV_NAME_LOOKUP);
3131   while (ns != global_namespace)
3132     {
3133       pop_namespace ();
3134       ns = CP_DECL_CONTEXT (ns);
3135     }
3136
3137   pop_from_top_level ();
3138   timevar_pop (TV_NAME_LOOKUP);
3139 }
3140
3141 /* Temporarily set the namespace for the current declaration.  */
3142
3143 void
3144 push_decl_namespace (tree decl)
3145 {
3146   if (TREE_CODE (decl) != NAMESPACE_DECL)
3147     decl = decl_namespace_context (decl);
3148   decl_namespace_list = tree_cons (ORIGINAL_NAMESPACE (decl),
3149                                    NULL_TREE, decl_namespace_list);
3150 }
3151
3152 /* [namespace.memdef]/2 */
3153
3154 void
3155 pop_decl_namespace (void)
3156 {
3157   decl_namespace_list = TREE_CHAIN (decl_namespace_list);
3158 }
3159
3160 /* Return the namespace that is the common ancestor
3161    of two given namespaces.  */
3162
3163 static tree
3164 namespace_ancestor (tree ns1, tree ns2)
3165 {
3166   timevar_push (TV_NAME_LOOKUP);
3167   if (is_ancestor (ns1, ns2))
3168     POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, ns1);
3169   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP,
3170                           namespace_ancestor (CP_DECL_CONTEXT (ns1), ns2));
3171 }
3172
3173 /* Process a namespace-alias declaration.  */
3174
3175 void
3176 do_namespace_alias (tree alias, tree namespace)
3177 {
3178   if (namespace == error_mark_node)
3179     return;
3180
3181   gcc_assert (TREE_CODE (namespace) == NAMESPACE_DECL);
3182
3183   namespace = ORIGINAL_NAMESPACE (namespace);
3184
3185   /* Build the alias.  */
3186   alias = build_lang_decl (NAMESPACE_DECL, alias, void_type_node);
3187   DECL_NAMESPACE_ALIAS (alias) = namespace;
3188   DECL_EXTERNAL (alias) = 1;
3189   DECL_CONTEXT (alias) = FROB_CONTEXT (current_scope ());
3190   pushdecl (alias);
3191
3192   /* Emit debug info for namespace alias.  */
3193   (*debug_hooks->global_decl) (alias);
3194 }
3195
3196 /* Like pushdecl, only it places X in the current namespace,
3197    if appropriate.  */
3198
3199 tree
3200 pushdecl_namespace_level (tree x, bool is_friend)
3201 {
3202   struct cp_binding_level *b = current_binding_level;
3203   tree t;
3204
3205   timevar_push (TV_NAME_LOOKUP);
3206   t = pushdecl_with_scope (x, NAMESPACE_LEVEL (current_namespace), is_friend);
3207
3208   /* Now, the type_shadowed stack may screw us.  Munge it so it does
3209      what we want.  */
3210   if (TREE_CODE (t) == TYPE_DECL)
3211     {
3212       tree name = DECL_NAME (t);
3213       tree newval;
3214       tree *ptr = (tree *)0;
3215       for (; !global_scope_p (b); b = b->level_chain)
3216         {
3217           tree shadowed = b->type_shadowed;
3218           for (; shadowed; shadowed = TREE_CHAIN (shadowed))
3219             if (TREE_PURPOSE (shadowed) == name)
3220               {
3221                 ptr = &TREE_VALUE (shadowed);
3222                 /* Can't break out of the loop here because sometimes
3223                    a binding level will have duplicate bindings for
3224                    PT names.  It's gross, but I haven't time to fix it.  */
3225               }
3226         }
3227       newval = TREE_TYPE (t);
3228       if (ptr == (tree *)0)
3229         {
3230           /* @@ This shouldn't be needed.  My test case "zstring.cc" trips
3231              up here if this is changed to an assertion.  --KR  */
3232           SET_IDENTIFIER_TYPE_VALUE (name, t);
3233         }
3234       else
3235         {
3236           *ptr = newval;
3237         }
3238     }
3239   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
3240 }
3241
3242 /* Insert USED into the using list of USER. Set INDIRECT_flag if this
3243    directive is not directly from the source. Also find the common
3244    ancestor and let our users know about the new namespace */
3245 static void
3246 add_using_namespace (tree user, tree used, bool indirect)
3247 {
3248   tree t;
3249   timevar_push (TV_NAME_LOOKUP);
3250   /* Using oneself is a no-op.  */
3251   if (user == used)
3252     {
3253       timevar_pop (TV_NAME_LOOKUP);
3254       return;
3255     }
3256   gcc_assert (TREE_CODE (user) == NAMESPACE_DECL);
3257   gcc_assert (TREE_CODE (used) == NAMESPACE_DECL);
3258   /* Check if we already have this.  */
3259   t = purpose_member (used, DECL_NAMESPACE_USING (user));
3260   if (t != NULL_TREE)
3261     {
3262       if (!indirect)
3263         /* Promote to direct usage.  */
3264         TREE_INDIRECT_USING (t) = 0;
3265       timevar_pop (TV_NAME_LOOKUP);
3266       return;
3267     }
3268
3269   /* Add used to the user's using list.  */
3270   DECL_NAMESPACE_USING (user)
3271     = tree_cons (used, namespace_ancestor (user, used),
3272                  DECL_NAMESPACE_USING (user));
3273
3274   TREE_INDIRECT_USING (DECL_NAMESPACE_USING (user)) = indirect;
3275
3276   /* Add user to the used's users list.  */
3277   DECL_NAMESPACE_USERS (used)
3278     = tree_cons (user, 0, DECL_NAMESPACE_USERS (used));
3279
3280   /* Recursively add all namespaces used.  */
3281   for (t = DECL_NAMESPACE_USING (used); t; t = TREE_CHAIN (t))
3282     /* indirect usage */
3283     add_using_namespace (user, TREE_PURPOSE (t), 1);
3284
3285   /* Tell everyone using us about the new used namespaces.  */
3286   for (t = DECL_NAMESPACE_USERS (user); t; t = TREE_CHAIN (t))
3287     add_using_namespace (TREE_PURPOSE (t), used, 1);
3288   timevar_pop (TV_NAME_LOOKUP);
3289 }
3290
3291 /* Process a using-declaration not appearing in class or local scope.  */
3292
3293 void
3294 do_toplevel_using_decl (tree decl, tree scope, tree name)
3295 {
3296   tree oldval, oldtype, newval, newtype;
3297   tree orig_decl = decl;
3298   cxx_binding *binding;
3299
3300   decl = validate_nonmember_using_decl (decl, scope, name);
3301   if (decl == NULL_TREE)
3302     return;
3303
3304   binding = binding_for_name (NAMESPACE_LEVEL (current_namespace), name);
3305
3306   oldval = binding->value;
3307   oldtype = binding->type;
3308
3309   do_nonmember_using_decl (scope, name, oldval, oldtype, &newval, &newtype);
3310
3311   /* Emit debug info.  */
3312   if (!processing_template_decl)
3313     cp_emit_debug_info_for_using (orig_decl, current_namespace);
3314
3315   /* Copy declarations found.  */
3316   if (newval)
3317     binding->value = newval;
3318   if (newtype)
3319     binding->type = newtype;
3320 }
3321
3322 /* Process a using-directive.  */
3323
3324 void
3325 do_using_directive (tree namespace)
3326 {
3327   tree context = NULL_TREE;
3328
3329   if (namespace == error_mark_node)
3330     return;
3331
3332   gcc_assert (TREE_CODE (namespace) == NAMESPACE_DECL);
3333
3334   if (building_stmt_tree ())
3335     add_stmt (build_stmt (USING_STMT, namespace));
3336   namespace = ORIGINAL_NAMESPACE (namespace);
3337
3338   if (!toplevel_bindings_p ())
3339     {
3340       push_using_directive (namespace);
3341       context = current_scope ();
3342     }
3343   else
3344     {
3345       /* direct usage */
3346       add_using_namespace (current_namespace, namespace, 0);
3347       if (current_namespace != global_namespace)
3348         context = current_namespace;
3349     }
3350
3351   /* Emit debugging info.  */
3352   if (!processing_template_decl)
3353     (*debug_hooks->imported_module_or_decl) (namespace, context);
3354 }
3355
3356 /* Deal with a using-directive seen by the parser.  Currently we only
3357    handle attributes here, since they cannot appear inside a template.  */
3358
3359 void
3360 parse_using_directive (tree namespace, tree attribs)
3361 {
3362   tree a;
3363
3364   do_using_directive (namespace);
3365
3366   for (a = attribs; a; a = TREE_CHAIN (a))
3367     {
3368       tree name = TREE_PURPOSE (a);
3369       if (is_attribute_p ("strong", name))
3370         {
3371           if (!toplevel_bindings_p ())
3372             error ("strong using only meaningful at namespace scope");
3373           else if (namespace != error_mark_node)
3374             {
3375               if (!is_ancestor (current_namespace, namespace))
3376                 error ("current namespace %qD does not enclose strongly used namespace %qD",
3377                        current_namespace, namespace);
3378               DECL_NAMESPACE_ASSOCIATIONS (namespace)
3379                 = tree_cons (current_namespace, 0,
3380                              DECL_NAMESPACE_ASSOCIATIONS (namespace));
3381             }
3382         }
3383       else
3384         warning (OPT_Wattributes, "%qD attribute directive ignored", name);
3385     }
3386 }
3387
3388 /* Like pushdecl, only it places X in the global scope if appropriate.
3389    Calls cp_finish_decl to register the variable, initializing it with
3390    *INIT, if INIT is non-NULL.  */
3391
3392 static tree
3393 pushdecl_top_level_1 (tree x, tree *init, bool is_friend)
3394 {
3395   timevar_push (TV_NAME_LOOKUP);
3396   push_to_top_level ();
3397   x = pushdecl_namespace_level (x, is_friend);
3398   if (init)
3399     finish_decl (x, *init, NULL_TREE);
3400   pop_from_top_level ();
3401   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, x);
3402 }
3403
3404 /* Like pushdecl, only it places X in the global scope if appropriate.  */
3405
3406 tree
3407 pushdecl_top_level (tree x)
3408 {
3409   return pushdecl_top_level_1 (x, NULL, false);
3410 }
3411
3412 /* Like pushdecl_top_level, but adding the IS_FRIEND parameter.  */
3413
3414 tree
3415 pushdecl_top_level_maybe_friend (tree x, bool is_friend)
3416 {
3417   return pushdecl_top_level_1 (x, NULL, is_friend);
3418 }
3419
3420 /* Like pushdecl, only it places X in the global scope if
3421    appropriate.  Calls cp_finish_decl to register the variable,
3422    initializing it with INIT.  */
3423
3424 tree
3425 pushdecl_top_level_and_finish (tree x, tree init)
3426 {
3427   return pushdecl_top_level_1 (x, &init, false);
3428 }
3429
3430 /* Combines two sets of overloaded functions into an OVERLOAD chain, removing
3431    duplicates.  The first list becomes the tail of the result.
3432
3433    The algorithm is O(n^2).  We could get this down to O(n log n) by
3434    doing a sort on the addresses of the functions, if that becomes
3435    necessary.  */
3436
3437 static tree
3438 merge_functions (tree s1, tree s2)
3439 {
3440   for (; s2; s2 = OVL_NEXT (s2))
3441     {
3442       tree fn2 = OVL_CURRENT (s2);
3443       tree fns1;
3444
3445       for (fns1 = s1; fns1; fns1 = OVL_NEXT (fns1))
3446         {
3447           tree fn1 = OVL_CURRENT (fns1);
3448
3449           /* If the function from S2 is already in S1, there is no
3450              need to add it again.  For `extern "C"' functions, we
3451              might have two FUNCTION_DECLs for the same function, in
3452              different namespaces; again, we only need one of them.  */
3453           if (fn1 == fn2
3454               || (DECL_EXTERN_C_P (fn1) && DECL_EXTERN_C_P (fn2)
3455                   && DECL_NAME (fn1) == DECL_NAME (fn2)))
3456             break;
3457         }
3458
3459       /* If we exhausted all of the functions in S1, FN2 is new.  */
3460       if (!fns1)
3461         s1 = build_overload (fn2, s1);
3462     }
3463   return s1;
3464 }
3465
3466 /* This should return an error not all definitions define functions.
3467    It is not an error if we find two functions with exactly the
3468    same signature, only if these are selected in overload resolution.
3469    old is the current set of bindings, new the freshly-found binding.
3470    XXX Do we want to give *all* candidates in case of ambiguity?
3471    XXX In what way should I treat extern declarations?
3472    XXX I don't want to repeat the entire duplicate_decls here */
3473
3474 static void
3475 ambiguous_decl (tree name, struct scope_binding *old, cxx_binding *new,
3476                 int flags)
3477 {
3478   tree val, type;
3479   gcc_assert (old != NULL);
3480   /* Copy the value.  */
3481   val = new->value;
3482   if (val)
3483     switch (TREE_CODE (val))
3484       {
3485       case TEMPLATE_DECL:
3486         /* If we expect types or namespaces, and not templates,
3487            or this is not a template class.  */
3488         if ((LOOKUP_QUALIFIERS_ONLY (flags)
3489              && !DECL_CLASS_TEMPLATE_P (val))
3490             || hidden_name_p (val))
3491           val = NULL_TREE;
3492         break;
3493       case TYPE_DECL:
3494         if (LOOKUP_NAMESPACES_ONLY (flags) || hidden_name_p (val))
3495           val = NULL_TREE;
3496         break;
3497       case NAMESPACE_DECL:
3498         if (LOOKUP_TYPES_ONLY (flags))
3499           val = NULL_TREE;
3500         break;
3501       case FUNCTION_DECL:
3502         /* Ignore built-in functions that are still anticipated.  */
3503         if (LOOKUP_QUALIFIERS_ONLY (flags) || hidden_name_p (val))
3504           val = NULL_TREE;
3505         break;
3506       default:
3507         if (LOOKUP_QUALIFIERS_ONLY (flags))
3508           val = NULL_TREE;
3509       }
3510
3511   if (!old->value)
3512     old->value = val;
3513   else if (val && val != old->value)
3514     {
3515       if (is_overloaded_fn (old->value) && is_overloaded_fn (val))
3516         old->value = merge_functions (old->value, val);
3517       else
3518         {
3519           old->value = tree_cons (NULL_TREE, old->value,
3520                                   build_tree_list (NULL_TREE, new->value));
3521           TREE_TYPE (old->value) = error_mark_node;
3522         }
3523     }
3524   /* ... and copy the type.  */
3525   type = new->type;
3526   if (LOOKUP_NAMESPACES_ONLY (flags))
3527     type = NULL_TREE;
3528   if (!old->type)
3529     old->type = type;
3530   else if (type && old->type != type)
3531     {
3532       if (flags & LOOKUP_COMPLAIN)
3533         {
3534           error ("%qD denotes an ambiguous type",name);
3535           error ("%J  first type here", TYPE_MAIN_DECL (old->type));
3536           error ("%J  other type here", TYPE_MAIN_DECL (type));
3537         }
3538     }
3539 }
3540
3541 /* Return the declarations that are members of the namespace NS.  */
3542
3543 tree
3544 cp_namespace_decls (tree ns)
3545 {
3546   return NAMESPACE_LEVEL (ns)->names;
3547 }
3548
3549 /* Combine prefer_type and namespaces_only into flags.  */
3550
3551 static int
3552 lookup_flags (int prefer_type, int namespaces_only)
3553 {
3554   if (namespaces_only)
3555     return LOOKUP_PREFER_NAMESPACES;
3556   if (prefer_type > 1)
3557     return LOOKUP_PREFER_TYPES;
3558   if (prefer_type > 0)
3559     return LOOKUP_PREFER_BOTH;
3560   return 0;
3561 }
3562
3563 /* Given a lookup that returned VAL, use FLAGS to decide if we want to
3564    ignore it or not.  Subroutine of lookup_name_real and
3565    lookup_type_scope.  */
3566
3567 static bool
3568 qualify_lookup (tree val, int flags)
3569 {
3570   if (val == NULL_TREE)
3571     return false;
3572   if ((flags & LOOKUP_PREFER_NAMESPACES) && TREE_CODE (val) == NAMESPACE_DECL)
3573     return true;
3574   if ((flags & LOOKUP_PREFER_TYPES)
3575       && (TREE_CODE (val) == TYPE_DECL || TREE_CODE (val) == TEMPLATE_DECL))
3576     return true;
3577   if (flags & (LOOKUP_PREFER_NAMESPACES | LOOKUP_PREFER_TYPES))
3578     return false;
3579   return true;
3580 }
3581
3582 /* Given a lookup that returned VAL, decide if we want to ignore it or
3583    not based on DECL_ANTICIPATED.  */
3584
3585 bool
3586 hidden_name_p (tree val)
3587 {
3588   if (DECL_P (val)
3589       && DECL_LANG_SPECIFIC (val)
3590       && DECL_ANTICIPATED (val))
3591     return true;
3592   return false;
3593 }
3594
3595 /* Remove any hidden friend functions from a possibly overloaded set
3596    of functions.  */
3597
3598 tree
3599 remove_hidden_names (tree fns)
3600 {
3601   if (!fns)
3602     return fns;
3603
3604   if (TREE_CODE (fns) == FUNCTION_DECL && hidden_name_p (fns))
3605     fns = NULL_TREE;
3606   else if (TREE_CODE (fns) == OVERLOAD)
3607     {
3608       tree o;
3609
3610       for (o = fns; o; o = OVL_NEXT (o))
3611         if (hidden_name_p (OVL_CURRENT (o)))
3612           break;
3613       if (o)
3614         {
3615           tree n = NULL_TREE;
3616
3617           for (o = fns; o; o = OVL_NEXT (o))
3618             if (!hidden_name_p (OVL_CURRENT (o)))
3619               n = build_overload (OVL_CURRENT (o), n);
3620           fns = n;
3621         }
3622     }
3623
3624   return fns;
3625 }
3626
3627 /* Select the right _DECL from multiple choices.  */
3628
3629 static tree
3630 select_decl (const struct scope_binding *binding, int flags)
3631 {
3632   tree val;
3633   val = binding->value;
3634
3635   timevar_push (TV_NAME_LOOKUP);
3636   if (LOOKUP_NAMESPACES_ONLY (flags))
3637     {
3638       /* We are not interested in types.  */
3639       if (val && (TREE_CODE (val) == NAMESPACE_DECL
3640                   || TREE_CODE (val) == TREE_LIST))
3641         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, val);
3642       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, NULL_TREE);
3643     }
3644
3645   /* If looking for a type, or if there is no non-type binding, select
3646      the value binding.  */
3647   if (binding->type && (!val || (flags & LOOKUP_PREFER_TYPES)))
3648     val = binding->type;
3649   /* Don't return non-types if we really prefer types.  */
3650   else if (val && LOOKUP_TYPES_ONLY (flags)
3651            && ! DECL_DECLARES_TYPE_P (val))
3652     val = NULL_TREE;
3653
3654   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, val);
3655 }
3656
3657 /* Unscoped lookup of a global: iterate over current namespaces,
3658    considering using-directives.  */
3659
3660 static tree
3661 unqualified_namespace_lookup (tree name, int flags)
3662 {
3663   tree initial = current_decl_namespace ();
3664   tree scope = initial;
3665   tree siter;
3666   struct cp_binding_level *level;
3667   tree val = NULL_TREE;
3668   struct scope_binding binding = EMPTY_SCOPE_BINDING;
3669
3670   timevar_push (TV_NAME_LOOKUP);
3671
3672   for (; !val; scope = CP_DECL_CONTEXT (scope))
3673     {
3674       cxx_binding *b =
3675          cxx_scope_find_binding_for_name (NAMESPACE_LEVEL (scope), name);
3676
3677       if (b)
3678         {
3679           if (b->value && hidden_name_p (b->value))
3680             /* Ignore anticipated built-in functions and friends.  */
3681             ;
3682           else
3683             binding.value = b->value;
3684           binding.type = b->type;
3685         }
3686
3687       /* Add all _DECLs seen through local using-directives.  */
3688       for (level = current_binding_level;
3689            level->kind != sk_namespace;
3690            level = level->level_chain)
3691         if (!lookup_using_namespace (name, &binding, level->using_directives,
3692                                      scope, flags))
3693           /* Give up because of error.  */
3694           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
3695
3696       /* Add all _DECLs seen through global using-directives.  */
3697       /* XXX local and global using lists should work equally.  */
3698       siter = initial;
3699       while (1)
3700         {
3701           if (!lookup_using_namespace (name, &binding,
3702                                        DECL_NAMESPACE_USING (siter),
3703                                        scope, flags))
3704             /* Give up because of error.  */
3705             POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
3706           if (siter == scope) break;
3707           siter = CP_DECL_CONTEXT (siter);
3708         }
3709
3710       val = select_decl (&binding, flags);
3711       if (scope == global_namespace)
3712         break;
3713     }
3714   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, val);
3715 }
3716
3717 /* Look up NAME (an IDENTIFIER_NODE) in SCOPE (either a NAMESPACE_DECL
3718    or a class TYPE).  If IS_TYPE_P is TRUE, then ignore non-type
3719    bindings.
3720
3721    Returns a DECL (or OVERLOAD, or BASELINK) representing the
3722    declaration found.  If no suitable declaration can be found,
3723    ERROR_MARK_NODE is returned.  If COMPLAIN is true and SCOPE is
3724    neither a class-type nor a namespace a diagnostic is issued.  */
3725
3726 tree
3727 lookup_qualified_name (tree scope, tree name, bool is_type_p, bool complain)
3728 {
3729   int flags = 0;
3730   tree t = NULL_TREE;
3731
3732   if (TREE_CODE (scope) == NAMESPACE_DECL)
3733     {
3734       struct scope_binding binding = EMPTY_SCOPE_BINDING;
3735
3736       flags |= LOOKUP_COMPLAIN;
3737       if (is_type_p)
3738         flags |= LOOKUP_PREFER_TYPES;
3739       if (qualified_lookup_using_namespace (name, scope, &binding, flags))
3740         t = select_decl (&binding, flags);
3741     }
3742   else if (is_aggr_type (scope, complain))
3743     t = lookup_member (scope, name, 2, is_type_p);
3744
3745   if (!t)
3746     return error_mark_node;
3747   return t;
3748 }
3749
3750 /* Subroutine of unqualified_namespace_lookup:
3751    Add the bindings of NAME in used namespaces to VAL.
3752    We are currently looking for names in namespace SCOPE, so we
3753    look through USINGS for using-directives of namespaces
3754    which have SCOPE as a common ancestor with the current scope.
3755    Returns false on errors.  */
3756
3757 static bool
3758 lookup_using_namespace (tree name, struct scope_binding *val,
3759                         tree usings, tree scope, int flags)
3760 {
3761   tree iter;
3762   timevar_push (TV_NAME_LOOKUP);
3763   /* Iterate over all used namespaces in current, searching for using
3764      directives of scope.  */
3765   for (iter = usings; iter; iter = TREE_CHAIN (iter))
3766     if (TREE_VALUE (iter) == scope)
3767       {
3768         tree used = ORIGINAL_NAMESPACE (TREE_PURPOSE (iter));
3769         cxx_binding *val1 =
3770           cxx_scope_find_binding_for_name (NAMESPACE_LEVEL (used), name);
3771         /* Resolve ambiguities.  */
3772         if (val1)
3773           ambiguous_decl (name, val, val1, flags);
3774       }
3775   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, val->value != error_mark_node);
3776 }
3777
3778 /* [namespace.qual]
3779    Accepts the NAME to lookup and its qualifying SCOPE.
3780    Returns the name/type pair found into the cxx_binding *RESULT,
3781    or false on error.  */
3782
3783 static bool
3784 qualified_lookup_using_namespace (tree name, tree scope,
3785                                   struct scope_binding *result, int flags)
3786 {
3787   /* Maintain a list of namespaces visited...  */
3788   tree seen = NULL_TREE;
3789   /* ... and a list of namespace yet to see.  */
3790   tree todo = NULL_TREE;
3791   tree todo_maybe = NULL_TREE;
3792   tree usings;
3793   timevar_push (TV_NAME_LOOKUP);
3794   /* Look through namespace aliases.  */
3795   scope = ORIGINAL_NAMESPACE (scope);
3796   while (scope && result->value != error_mark_node)
3797     {
3798       cxx_binding *binding =
3799         cxx_scope_find_binding_for_name (NAMESPACE_LEVEL (scope), name);
3800       seen = tree_cons (scope, NULL_TREE, seen);
3801       if (binding)
3802         ambiguous_decl (name, result, binding, flags);
3803
3804       /* Consider strong using directives always, and non-strong ones
3805          if we haven't found a binding yet.  ??? Shouldn't we consider
3806          non-strong ones if the initial RESULT is non-NULL, but the
3807          binding in the given namespace is?  */
3808       for (usings = DECL_NAMESPACE_USING (scope); usings;
3809            usings = TREE_CHAIN (usings))
3810         /* If this was a real directive, and we have not seen it.  */
3811         if (!TREE_INDIRECT_USING (usings))
3812           {
3813             /* Try to avoid queuing the same namespace more than once,
3814                the exception being when a namespace was already
3815                enqueued for todo_maybe and then a strong using is
3816                found for it.  We could try to remove it from
3817                todo_maybe, but it's probably not worth the effort.  */
3818             if (is_associated_namespace (scope, TREE_PURPOSE (usings))
3819                 && !purpose_member (TREE_PURPOSE (usings), seen)
3820                 && !purpose_member (TREE_PURPOSE (usings), todo))
3821               todo = tree_cons (TREE_PURPOSE (usings), NULL_TREE, todo);
3822             else if ((!result->value && !result->type)
3823                      && !purpose_member (TREE_PURPOSE (usings), seen)
3824                      && !purpose_member (TREE_PURPOSE (usings), todo)
3825                      && !purpose_member (TREE_PURPOSE (usings), todo_maybe))
3826               todo_maybe = tree_cons (TREE_PURPOSE (usings), NULL_TREE,
3827                                       todo_maybe);
3828           }
3829       if (todo)
3830         {
3831           scope = TREE_PURPOSE (todo);
3832           todo = TREE_CHAIN (todo);
3833         }
3834       else if (todo_maybe
3835                && (!result->value && !result->type))
3836         {
3837           scope = TREE_PURPOSE (todo_maybe);
3838           todo = TREE_CHAIN (todo_maybe);
3839           todo_maybe = NULL_TREE;
3840         }
3841       else
3842         scope = NULL_TREE; /* If there never was a todo list.  */
3843     }
3844   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, result->value != error_mark_node);
3845 }
3846
3847 /* Return the innermost non-namespace binding for NAME from a scope
3848    containing BINDING, or, if BINDING is NULL, the current scope.  If
3849    CLASS_P is false, then class bindings are ignored.  */
3850
3851 cxx_binding *
3852 outer_binding (tree name,
3853                cxx_binding *binding,
3854                bool class_p)
3855 {
3856   cxx_binding *outer;
3857   cxx_scope *scope;
3858   cxx_scope *outer_scope;
3859
3860   if (binding)
3861     {
3862       scope = binding->scope->level_chain;
3863       outer = binding->previous;
3864     }
3865   else
3866     {
3867       scope = current_binding_level;
3868       outer = IDENTIFIER_BINDING (name);
3869     }
3870   outer_scope = outer ? outer->scope : NULL;
3871
3872   /* Because we create class bindings lazily, we might be missing a
3873      class binding for NAME.  If there are any class binding levels
3874      between the LAST_BINDING_LEVEL and the scope in which OUTER was
3875      declared, we must lookup NAME in those class scopes.  */
3876   if (class_p)
3877     while (scope && scope != outer_scope && scope->kind != sk_namespace)
3878       {
3879         if (scope->kind == sk_class)
3880           {
3881             cxx_binding *class_binding;
3882
3883             class_binding = get_class_binding (name, scope);
3884             if (class_binding)
3885               {
3886                 /* Thread this new class-scope binding onto the
3887                    IDENTIFIER_BINDING list so that future lookups
3888                    find it quickly.  */
3889                 class_binding->previous = outer;
3890                 if (binding)
3891                   binding->previous = class_binding;
3892                 else
3893                   IDENTIFIER_BINDING (name) = class_binding;
3894                 return class_binding;
3895               }
3896           }
3897         scope = scope->level_chain;
3898       }
3899
3900   return outer;
3901 }
3902
3903 /* Return the innermost block-scope or class-scope value binding for
3904    NAME, or NULL_TREE if there is no such binding.  */
3905
3906 tree
3907 innermost_non_namespace_value (tree name)
3908 {
3909   cxx_binding *binding;
3910   binding = outer_binding (name, /*binding=*/NULL, /*class_p=*/true);
3911   return binding ? binding->value : NULL_TREE;
3912 }
3913
3914 /* Look up NAME in the current binding level and its superiors in the
3915    namespace of variables, functions and typedefs.  Return a ..._DECL
3916    node of some kind representing its definition if there is only one
3917    such declaration, or return a TREE_LIST with all the overloaded
3918    definitions if there are many, or return 0 if it is undefined.
3919    Hidden name, either friend declaration or built-in function, are
3920    not ignored.
3921
3922    If PREFER_TYPE is > 0, we prefer TYPE_DECLs or namespaces.
3923    If PREFER_TYPE is > 1, we reject non-type decls (e.g. namespaces).
3924    Otherwise we prefer non-TYPE_DECLs.
3925
3926    If NONCLASS is nonzero, bindings in class scopes are ignored.  If
3927    BLOCK_P is false, bindings in block scopes are ignored.  */
3928
3929 tree
3930 lookup_name_real (tree name, int prefer_type, int nonclass, bool block_p,
3931                   int namespaces_only, int flags)
3932 {
3933   cxx_binding *iter;
3934   tree val = NULL_TREE;
3935
3936   timevar_push (TV_NAME_LOOKUP);
3937   /* Conversion operators are handled specially because ordinary
3938      unqualified name lookup will not find template conversion
3939      operators.  */
3940   if (IDENTIFIER_TYPENAME_P (name))
3941     {
3942       struct cp_binding_level *level;
3943
3944       for (level = current_binding_level;
3945            level && level->kind != sk_namespace;
3946            level = level->level_chain)
3947         {
3948           tree class_type;
3949           tree operators;
3950
3951           /* A conversion operator can only be declared in a class
3952              scope.  */
3953           if (level->kind != sk_class)
3954             continue;
3955
3956           /* Lookup the conversion operator in the class.  */
3957           class_type = level->this_entity;
3958           operators = lookup_fnfields (class_type, name, /*protect=*/0);
3959           if (operators)
3960             POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, operators);
3961         }
3962
3963       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, NULL_TREE);
3964     }
3965
3966   flags |= lookup_flags (prefer_type, namespaces_only);
3967
3968   /* First, look in non-namespace scopes.  */
3969
3970   if (current_class_type == NULL_TREE)
3971     nonclass = 1;
3972
3973   if (block_p || !nonclass)
3974     for (iter = outer_binding (name, NULL, !nonclass);
3975          iter;
3976          iter = outer_binding (name, iter, !nonclass))
3977       {
3978         tree binding;
3979
3980         /* Skip entities we don't want.  */
3981         if (LOCAL_BINDING_P (iter) ? !block_p : nonclass)
3982           continue;
3983
3984         /* If this is the kind of thing we're looking for, we're done.  */
3985         if (qualify_lookup (iter->value, flags)
3986             && !hidden_name_p (iter->value))
3987           binding = iter->value;
3988         else if ((flags & LOOKUP_PREFER_TYPES)
3989                  && qualify_lookup (iter->type, flags)
3990                  && !hidden_name_p (iter->type))
3991           binding = iter->type;
3992         else
3993           binding = NULL_TREE;
3994
3995         if (binding)
3996           {
3997             val = binding;
3998             break;
3999           }
4000       }
4001
4002   /* Now lookup in namespace scopes.  */
4003   if (!val)
4004     val = unqualified_namespace_lookup (name, flags);
4005
4006   /* If we have a single function from a using decl, pull it out.  */
4007   if (val && TREE_CODE (val) == OVERLOAD && !really_overloaded_fn (val))
4008     val = OVL_FUNCTION (val);
4009
4010   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, val);
4011 }
4012
4013 tree
4014 lookup_name_nonclass (tree name)
4015 {
4016   return lookup_name_real (name, 0, 1, /*block_p=*/true, 0, LOOKUP_COMPLAIN);
4017 }
4018
4019 tree
4020 lookup_function_nonclass (tree name, tree args, bool block_p)
4021 {
4022   return
4023     lookup_arg_dependent (name,
4024                           lookup_name_real (name, 0, 1, block_p, 0,
4025                                             LOOKUP_COMPLAIN),
4026                           args);
4027 }
4028
4029 tree
4030 lookup_name (tree name)
4031 {
4032   return lookup_name_real (name, 0, 0, /*block_p=*/true, 0, LOOKUP_COMPLAIN);
4033 }
4034
4035 tree
4036 lookup_name_prefer_type (tree name, int prefer_type)
4037 {
4038   return lookup_name_real (name, prefer_type, 0, /*block_p=*/true,
4039                            0, LOOKUP_COMPLAIN);
4040 }
4041
4042 /* Look up NAME for type used in elaborated name specifier in
4043    the scopes given by SCOPE.  SCOPE can be either TS_CURRENT or
4044    TS_WITHIN_ENCLOSING_NON_CLASS.  Although not implied by the
4045    name, more scopes are checked if cleanup or template parameter
4046    scope is encountered.
4047
4048    Unlike lookup_name_real, we make sure that NAME is actually
4049    declared in the desired scope, not from inheritance, nor using
4050    directive.  For using declaration, there is DR138 still waiting
4051    to be resolved.  Hidden name coming from an earlier friend
4052    declaration is also returned.
4053
4054    A TYPE_DECL best matching the NAME is returned.  Catching error
4055    and issuing diagnostics are caller's responsibility.  */
4056
4057 tree
4058 lookup_type_scope (tree name, tag_scope scope)
4059 {
4060   cxx_binding *iter = NULL;
4061   tree val = NULL_TREE;
4062
4063   timevar_push (TV_NAME_LOOKUP);
4064
4065   /* Look in non-namespace scope first.  */
4066   if (current_binding_level->kind != sk_namespace)
4067     iter = outer_binding (name, NULL, /*class_p=*/ true);
4068   for (; iter; iter = outer_binding (name, iter, /*class_p=*/ true))
4069     {
4070       /* Check if this is the kind of thing we're looking for.
4071          If SCOPE is TS_CURRENT, also make sure it doesn't come from
4072          base class.  For ITER->VALUE, we can simply use
4073          INHERITED_VALUE_BINDING_P.  For ITER->TYPE, we have to use
4074          our own check.
4075
4076          We check ITER->TYPE before ITER->VALUE in order to handle
4077            typedef struct C {} C;
4078          correctly.  */
4079
4080       if (qualify_lookup (iter->type, LOOKUP_PREFER_TYPES)
4081           && (scope != ts_current
4082               || LOCAL_BINDING_P (iter)
4083               || DECL_CONTEXT (iter->type) == iter->scope->this_entity))
4084         val = iter->type;
4085       else if ((scope != ts_current
4086                 || !INHERITED_VALUE_BINDING_P (iter))
4087                && qualify_lookup (iter->value, LOOKUP_PREFER_TYPES))
4088         val = iter->value;
4089
4090       if (val)
4091         break;
4092     }
4093
4094   /* Look in namespace scope.  */
4095   if (!val)
4096     {
4097       iter = cxx_scope_find_binding_for_name
4098                (NAMESPACE_LEVEL (current_decl_namespace ()), name);
4099
4100       if (iter)
4101         {
4102           /* If this is the kind of thing we're looking for, we're done.  */
4103           if (qualify_lookup (iter->type, LOOKUP_PREFER_TYPES))
4104             val = iter->type;
4105           else if (qualify_lookup (iter->value, LOOKUP_PREFER_TYPES))
4106             val = iter->value;
4107         }
4108
4109     }
4110
4111   /* Type found, check if it is in the allowed scopes, ignoring cleanup
4112      and template parameter scopes.  */
4113   if (val)
4114     {
4115       struct cp_binding_level *b = current_binding_level;
4116       while (b)
4117         {
4118           if (iter->scope == b)
4119             POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, val);
4120
4121           if (b->kind == sk_cleanup || b->kind == sk_template_parms)
4122             b = b->level_chain;
4123           else if (b->kind == sk_class
4124                    && scope == ts_within_enclosing_non_class)
4125             b = b->level_chain;
4126           else
4127             break;
4128         }
4129     }
4130
4131   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, NULL_TREE);
4132 }
4133
4134 /* Similar to `lookup_name' but look only in the innermost non-class
4135    binding level.  */
4136
4137 static tree
4138 lookup_name_innermost_nonclass_level (tree name)
4139 {
4140   struct cp_binding_level *b;
4141   tree t = NULL_TREE;
4142
4143   timevar_push (TV_NAME_LOOKUP);
4144   b = innermost_nonclass_level ();
4145
4146   if (b->kind == sk_namespace)
4147     {
4148       t = IDENTIFIER_NAMESPACE_VALUE (name);
4149
4150       /* extern "C" function() */
4151       if (t != NULL_TREE && TREE_CODE (t) == TREE_LIST)
4152         t = TREE_VALUE (t);
4153     }
4154   else if (IDENTIFIER_BINDING (name)
4155            && LOCAL_BINDING_P (IDENTIFIER_BINDING (name)))
4156     {
4157       cxx_binding *binding;
4158       binding = IDENTIFIER_BINDING (name);
4159       while (1)
4160         {
4161           if (binding->scope == b
4162               && !(TREE_CODE (binding->value) == VAR_DECL
4163                    && DECL_DEAD_FOR_LOCAL (binding->value)))
4164             POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, binding->value);
4165
4166           if (b->kind == sk_cleanup)
4167             b = b->level_chain;
4168           else
4169             break;
4170         }
4171     }
4172
4173   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
4174 }
4175
4176 /* Like lookup_name_innermost_nonclass_level, but for types.  */
4177
4178 static tree
4179 lookup_type_current_level (tree name)
4180 {
4181   tree t = NULL_TREE;
4182
4183   timevar_push (TV_NAME_LOOKUP);
4184   gcc_assert (current_binding_level->kind != sk_namespace);
4185
4186   if (REAL_IDENTIFIER_TYPE_VALUE (name) != NULL_TREE
4187       && REAL_IDENTIFIER_TYPE_VALUE (name) != global_type_node)
4188     {
4189       struct cp_binding_level *b = current_binding_level;
4190       while (1)
4191         {
4192           if (purpose_member (name, b->type_shadowed))
4193             POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP,
4194                                     REAL_IDENTIFIER_TYPE_VALUE (name));
4195           if (b->kind == sk_cleanup)
4196             b = b->level_chain;
4197           else
4198             break;
4199         }
4200     }
4201
4202   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
4203 }
4204
4205 /* [basic.lookup.koenig] */
4206 /* A nonzero return value in the functions below indicates an error.  */
4207
4208 struct arg_lookup
4209 {
4210   tree name;
4211   tree args;
4212   tree namespaces;
4213   tree classes;
4214   tree functions;
4215 };
4216
4217 static bool arg_assoc (struct arg_lookup*, tree);
4218 static bool arg_assoc_args (struct arg_lookup*, tree);
4219 static bool arg_assoc_type (struct arg_lookup*, tree);
4220 static bool add_function (struct arg_lookup *, tree);
4221 static bool arg_assoc_namespace (struct arg_lookup *, tree);
4222 static bool arg_assoc_class (struct arg_lookup *, tree);
4223 static bool arg_assoc_template_arg (struct arg_lookup*, tree);
4224
4225 /* Add a function to the lookup structure.
4226    Returns true on error.  */
4227
4228 static bool
4229 add_function (struct arg_lookup *k, tree fn)
4230 {
4231   /* We used to check here to see if the function was already in the list,
4232      but that's O(n^2), which is just too expensive for function lookup.
4233      Now we deal with the occasional duplicate in joust.  In doing this, we
4234      assume that the number of duplicates will be small compared to the
4235      total number of functions being compared, which should usually be the
4236      case.  */
4237
4238   /* We must find only functions, or exactly one non-function.  */
4239   if (!k->functions)
4240     k->functions = fn;
4241   else if (fn == k->functions)
4242     ;
4243   else if (is_overloaded_fn (k->functions) && is_overloaded_fn (fn))
4244     k->functions = build_overload (fn, k->functions);
4245   else
4246     {
4247       tree f1 = OVL_CURRENT (k->functions);
4248       tree f2 = fn;
4249       if (is_overloaded_fn (f1))
4250         {
4251           fn = f1; f1 = f2; f2 = fn;
4252         }
4253       error ("%q+D is not a function,", f1);
4254       error ("  conflict with %q+D", f2);
4255       error ("  in call to %qD", k->name);
4256       return true;
4257     }
4258
4259   return false;
4260 }
4261
4262 /* Returns true iff CURRENT has declared itself to be an associated
4263    namespace of SCOPE via a strong using-directive (or transitive chain
4264    thereof).  Both are namespaces.  */
4265
4266 bool
4267 is_associated_namespace (tree current, tree scope)
4268 {
4269   tree seen = NULL_TREE;
4270   tree todo = NULL_TREE;
4271   tree t;
4272   while (1)
4273     {
4274       if (scope == current)
4275         return true;
4276       seen = tree_cons (scope, NULL_TREE, seen);
4277       for (t = DECL_NAMESPACE_ASSOCIATIONS (scope); t; t = TREE_CHAIN (t))
4278         if (!purpose_member (TREE_PURPOSE (t), seen))
4279           todo = tree_cons (TREE_PURPOSE (t), NULL_TREE, todo);
4280       if (todo)
4281         {
4282           scope = TREE_PURPOSE (todo);
4283           todo = TREE_CHAIN (todo);
4284         }
4285       else
4286         return false;
4287     }
4288 }
4289
4290 /* Return whether FN is a friend of an associated class of ARG.  */
4291
4292 static bool
4293 friend_of_associated_class_p (tree arg, tree fn)
4294 {
4295   tree type;
4296
4297   if (TYPE_P (arg))
4298     type = arg;
4299   else if (type_unknown_p (arg))
4300     return false;
4301   else
4302     type = TREE_TYPE (arg);
4303
4304   /* If TYPE is a class, the class itself and all base classes are
4305      associated classes.  */
4306   if (CLASS_TYPE_P (type))
4307     {
4308       if (is_friend (type, fn))
4309         return true;
4310
4311       if (TYPE_BINFO (type))
4312         {
4313           tree binfo, base_binfo;
4314           int i;
4315
4316           for (binfo = TYPE_BINFO (type), i = 0;
4317                BINFO_BASE_ITERATE (binfo, i, base_binfo);
4318                i++)
4319             if (is_friend (BINFO_TYPE (base_binfo), fn))
4320               return true;
4321         }
4322     }
4323
4324   /* If TYPE is a class member, the class of which it is a member is
4325      an associated class.  */
4326   if ((CLASS_TYPE_P (type)
4327        || TREE_CODE (type) == UNION_TYPE
4328        || TREE_CODE (type) == ENUMERAL_TYPE)
4329       && TYPE_CONTEXT (type)
4330       && CLASS_TYPE_P (TYPE_CONTEXT (type))
4331       && is_friend (TYPE_CONTEXT (type), fn))
4332     return true;
4333
4334   return false;
4335 }
4336
4337 /* Add functions of a namespace to the lookup structure.
4338    Returns true on error.  */
4339
4340 static bool
4341 arg_assoc_namespace (struct arg_lookup *k, tree scope)
4342 {
4343   tree value;
4344
4345   if (purpose_member (scope, k->namespaces))
4346     return 0;
4347   k->namespaces = tree_cons (scope, NULL_TREE, k->namespaces);
4348
4349   /* Check out our super-users.  */
4350   for (value = DECL_NAMESPACE_ASSOCIATIONS (scope); value;
4351        value = TREE_CHAIN (value))
4352     if (arg_assoc_namespace (k, TREE_PURPOSE (value)))
4353       return true;
4354
4355   value = namespace_binding (k->name, scope);
4356   if (!value)
4357     return false;
4358
4359   for (; value; value = OVL_NEXT (value))
4360     {
4361       /* We don't want to find arbitrary hidden functions via argument
4362          dependent lookup.  We only want to find friends of associated
4363          classes.  */
4364       if (hidden_name_p (OVL_CURRENT (value)))
4365         {
4366           tree args;
4367
4368           for (args = k->args; args; args = TREE_CHAIN (args))
4369             if (friend_of_associated_class_p (TREE_VALUE (args),
4370                                               OVL_CURRENT (value)))
4371               break;
4372           if (!args)
4373             continue;
4374         }
4375
4376       if (add_function (k, OVL_CURRENT (value)))
4377         return true;
4378     }
4379
4380   return false;
4381 }
4382
4383 /* Adds everything associated with a template argument to the lookup
4384    structure.  Returns true on error.  */
4385
4386 static bool
4387 arg_assoc_template_arg (struct arg_lookup *k, tree arg)
4388 {
4389   /* [basic.lookup.koenig]
4390
4391      If T is a template-id, its associated namespaces and classes are
4392      ... the namespaces and classes associated with the types of the
4393      template arguments provided for template type parameters
4394      (excluding template template parameters); the namespaces in which
4395      any template template arguments are defined; and the classes in
4396      which any member templates used as template template arguments
4397      are defined.  [Note: non-type template arguments do not
4398      contribute to the set of associated namespaces.  ]  */
4399
4400   /* Consider first template template arguments.  */
4401   if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4402       || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
4403     return false;
4404   else if (TREE_CODE (arg) == TEMPLATE_DECL)
4405     {
4406       tree ctx = CP_DECL_CONTEXT (arg);
4407
4408       /* It's not a member template.  */
4409       if (TREE_CODE (ctx) == NAMESPACE_DECL)
4410         return arg_assoc_namespace (k, ctx);
4411       /* Otherwise, it must be member template.  */
4412       else
4413         return arg_assoc_class (k, ctx);
4414     }
4415   /* It's not a template template argument, but it is a type template
4416      argument.  */
4417   else if (TYPE_P (arg))
4418     return arg_assoc_type (k, arg);
4419   /* It's a non-type template argument.  */
4420   else
4421     return false;
4422 }
4423
4424 /* Adds everything associated with class to the lookup structure.
4425    Returns true on error.  */
4426
4427 static bool
4428 arg_assoc_class (struct arg_lookup *k, tree type)
4429 {
4430   tree list, friends, context;
4431   int i;
4432
4433   /* Backend build structures, such as __builtin_va_list, aren't
4434      affected by all this.  */
4435   if (!CLASS_TYPE_P (type))
4436     return false;
4437
4438   if (purpose_member (type, k->classes))
4439     return false;
4440   k->classes = tree_cons (type, NULL_TREE, k->classes);
4441
4442   context = decl_namespace_context (type);
4443   if (arg_assoc_namespace (k, context))
4444     return true;
4445
4446   if (TYPE_BINFO (type))
4447     {
4448       /* Process baseclasses.  */
4449       tree binfo, base_binfo;
4450
4451       for (binfo = TYPE_BINFO (type), i = 0;
4452            BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
4453         if (arg_assoc_class (k, BINFO_TYPE (base_binfo)))
4454           return true;
4455     }
4456
4457   /* Process friends.  */
4458   for (list = DECL_FRIENDLIST (TYPE_MAIN_DECL (type)); list;
4459        list = TREE_CHAIN (list))
4460     if (k->name == FRIEND_NAME (list))
4461       for (friends = FRIEND_DECLS (list); friends;
4462            friends = TREE_CHAIN (friends))
4463         {
4464           tree fn = TREE_VALUE (friends);
4465
4466           /* Only interested in global functions with potentially hidden
4467              (i.e. unqualified) declarations.  */
4468           if (CP_DECL_CONTEXT (fn) != context)
4469             continue;
4470           /* Template specializations are never found by name lookup.
4471              (Templates themselves can be found, but not template
4472              specializations.)  */
4473           if (TREE_CODE (fn) == FUNCTION_DECL && DECL_USE_TEMPLATE (fn))
4474             continue;
4475           if (add_function (k, fn))
4476             return true;
4477         }
4478
4479   /* Process template arguments.  */
4480   if (CLASSTYPE_TEMPLATE_INFO (type)
4481       && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
4482     {
4483       list = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
4484       for (i = 0; i < TREE_VEC_LENGTH (list); ++i)
4485         arg_assoc_template_arg (k, TREE_VEC_ELT (list, i));
4486     }
4487
4488   return false;
4489 }
4490
4491 /* Adds everything associated with a given type.
4492    Returns 1 on error.  */
4493
4494 static bool
4495 arg_assoc_type (struct arg_lookup *k, tree type)
4496 {
4497   /* As we do not get the type of non-type dependent expressions
4498      right, we can end up with such things without a type.  */
4499   if (!type)
4500     return false;
4501
4502   if (TYPE_PTRMEM_P (type))
4503     {
4504       /* Pointer to member: associate class type and value type.  */
4505       if (arg_assoc_type (k, TYPE_PTRMEM_CLASS_TYPE (type)))
4506         return true;
4507       return arg_assoc_type (k, TYPE_PTRMEM_POINTED_TO_TYPE (type));
4508     }
4509   else switch (TREE_CODE (type))
4510     {
4511     case ERROR_MARK:
4512       return false;
4513     case VOID_TYPE:
4514     case INTEGER_TYPE:
4515     case REAL_TYPE:
4516     case COMPLEX_TYPE:
4517     case VECTOR_TYPE:
4518     case BOOLEAN_TYPE:
4519       return false;
4520     case RECORD_TYPE:
4521       if (TYPE_PTRMEMFUNC_P (type))
4522         return arg_assoc_type (k, TYPE_PTRMEMFUNC_FN_TYPE (type));
4523       return arg_assoc_class (k, type);
4524     case POINTER_TYPE:
4525     case REFERENCE_TYPE:
4526     case ARRAY_TYPE:
4527       return arg_assoc_type (k, TREE_TYPE (type));
4528     case UNION_TYPE:
4529     case ENUMERAL_TYPE:
4530       return arg_assoc_namespace (k, decl_namespace_context (type));
4531     case METHOD_TYPE:
4532       /* The basetype is referenced in the first arg type, so just
4533          fall through.  */
4534     case FUNCTION_TYPE:
4535       /* Associate the parameter types.  */
4536       if (arg_assoc_args (k, TYPE_ARG_TYPES (type)))
4537         return true;
4538       /* Associate the return type.  */
4539       return arg_assoc_type (k, TREE_TYPE (type));
4540     case TEMPLATE_TYPE_PARM:
4541     case BOUND_TEMPLATE_TEMPLATE_PARM:
4542       return false;
4543     case TYPENAME_TYPE:
4544       return false;
4545     case LANG_TYPE:
4546       gcc_assert (type == unknown_type_node);
4547       return false;
4548     default:
4549       gcc_unreachable ();
4550     }
4551   return false;
4552 }
4553
4554 /* Adds everything associated with arguments.  Returns true on error.  */
4555
4556 static bool
4557 arg_assoc_args (struct arg_lookup *k, tree args)
4558 {
4559   for (; args; args = TREE_CHAIN (args))
4560     if (arg_assoc (k, TREE_VALUE (args)))
4561       return true;
4562   return false;
4563 }
4564
4565 /* Adds everything associated with a given tree_node.  Returns 1 on error.  */
4566
4567 static bool
4568 arg_assoc (struct arg_lookup *k, tree n)
4569 {
4570   if (n == error_mark_node)
4571     return false;
4572
4573   if (TYPE_P (n))
4574     return arg_assoc_type (k, n);
4575
4576   if (! type_unknown_p (n))
4577     return arg_assoc_type (k, TREE_TYPE (n));
4578
4579   if (TREE_CODE (n) == ADDR_EXPR)
4580     n = TREE_OPERAND (n, 0);
4581   if (TREE_CODE (n) == COMPONENT_REF)
4582     n = TREE_OPERAND (n, 1);
4583   if (TREE_CODE (n) == OFFSET_REF)
4584     n = TREE_OPERAND (n, 1);
4585   while (TREE_CODE (n) == TREE_LIST)
4586     n = TREE_VALUE (n);
4587   if (TREE_CODE (n) == BASELINK)
4588     n = BASELINK_FUNCTIONS (n);
4589
4590   if (TREE_CODE (n) == FUNCTION_DECL)
4591     return arg_assoc_type (k, TREE_TYPE (n));
4592   if (TREE_CODE (n) == TEMPLATE_ID_EXPR)
4593     {
4594       /* [basic.lookup.koenig]
4595
4596          If T is a template-id, its associated namespaces and classes
4597          are the namespace in which the template is defined; for
4598          member templates, the member template's class...  */
4599       tree template = TREE_OPERAND (n, 0);
4600       tree args = TREE_OPERAND (n, 1);
4601       tree ctx;
4602       int ix;
4603
4604       if (TREE_CODE (template) == COMPONENT_REF)
4605         template = TREE_OPERAND (template, 1);
4606
4607       /* First, the template.  There may actually be more than one if
4608          this is an overloaded function template.  But, in that case,
4609          we only need the first; all the functions will be in the same
4610          namespace.  */
4611       template = OVL_CURRENT (template);
4612
4613       ctx = CP_DECL_CONTEXT (template);
4614
4615       if (TREE_CODE (ctx) == NAMESPACE_DECL)
4616         {
4617           if (arg_assoc_namespace (k, ctx) == 1)
4618             return true;
4619         }
4620       /* It must be a member template.  */
4621       else if (arg_assoc_class (k, ctx) == 1)
4622         return true;
4623
4624       /* Now the arguments.  */
4625       if (args)
4626         for (ix = TREE_VEC_LENGTH (args); ix--;)
4627           if (arg_assoc_template_arg (k, TREE_VEC_ELT (args, ix)) == 1)
4628             return true;
4629     }
4630   else if (TREE_CODE (n) == OVERLOAD)
4631     {
4632       for (; n; n = OVL_CHAIN (n))
4633         if (arg_assoc_type (k, TREE_TYPE (OVL_FUNCTION (n))))
4634           return true;
4635     }
4636
4637   return false;
4638 }
4639
4640 /* Performs Koenig lookup depending on arguments, where fns
4641    are the functions found in normal lookup.  */
4642
4643 tree
4644 lookup_arg_dependent (tree name, tree fns, tree args)
4645 {
4646   struct arg_lookup k;
4647
4648   timevar_push (TV_NAME_LOOKUP);
4649
4650   /* Remove any hidden friend functions from the list of functions
4651      found so far.  They will be added back by arg_assoc_class as
4652      appropriate.  */
4653   fns = remove_hidden_names (fns);
4654
4655   k.name = name;
4656   k.args = args;
4657   k.functions = fns;
4658   k.classes = NULL_TREE;
4659
4660   /* We previously performed an optimization here by setting
4661      NAMESPACES to the current namespace when it was safe. However, DR
4662      164 says that namespaces that were already searched in the first
4663      stage of template processing are searched again (potentially
4664      picking up later definitions) in the second stage. */
4665   k.namespaces = NULL_TREE;
4666
4667   arg_assoc_args (&k, args);
4668   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, k.functions);
4669 }
4670
4671 /* Add namespace to using_directives. Return NULL_TREE if nothing was
4672    changed (i.e. there was already a directive), or the fresh
4673    TREE_LIST otherwise.  */
4674
4675 static tree
4676 push_using_directive (tree used)
4677 {
4678   tree ud = current_binding_level->using_directives;
4679   tree iter, ancestor;
4680
4681   timevar_push (TV_NAME_LOOKUP);
4682   /* Check if we already have this.  */
4683   if (purpose_member (used, ud) != NULL_TREE)
4684     POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, NULL_TREE);
4685
4686   ancestor = namespace_ancestor (current_decl_namespace (), used);
4687   ud = current_binding_level->using_directives;
4688   ud = tree_cons (used, ancestor, ud);
4689   current_binding_level->using_directives = ud;
4690
4691   /* Recursively add all namespaces used.  */
4692   for (iter = DECL_NAMESPACE_USING (used); iter; iter = TREE_CHAIN (iter))
4693     push_using_directive (TREE_PURPOSE (iter));
4694
4695   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, ud);
4696 }
4697
4698 /* The type TYPE is being declared.  If it is a class template, or a
4699    specialization of a class template, do any processing required and
4700    perform error-checking.  If IS_FRIEND is nonzero, this TYPE is
4701    being declared a friend.  B is the binding level at which this TYPE
4702    should be bound.
4703
4704    Returns the TYPE_DECL for TYPE, which may have been altered by this
4705    processing.  */
4706
4707 static tree
4708 maybe_process_template_type_declaration (tree type, int is_friend,
4709                                          cxx_scope *b)
4710 {
4711   tree decl = TYPE_NAME (type);
4712
4713   if (processing_template_parmlist)
4714     /* You can't declare a new template type in a template parameter
4715        list.  But, you can declare a non-template type:
4716
4717          template <class A*> struct S;
4718
4719        is a forward-declaration of `A'.  */
4720     ;
4721   else if (b->kind == sk_namespace
4722            && current_binding_level->kind != sk_namespace)
4723     /* If this new type is being injected into a containing scope,
4724        then it's not a template type.  */
4725     ;
4726   else
4727     {
4728       gcc_assert (IS_AGGR_TYPE (type) || TREE_CODE (type) == ENUMERAL_TYPE);
4729
4730       if (processing_template_decl)
4731         {
4732           /* This may change after the call to
4733              push_template_decl_real, but we want the original value.  */
4734           tree name = DECL_NAME (decl);
4735
4736           decl = push_template_decl_real (decl, is_friend);
4737           /* If the current binding level is the binding level for the
4738              template parameters (see the comment in
4739              begin_template_parm_list) and the enclosing level is a class
4740              scope, and we're not looking at a friend, push the
4741              declaration of the member class into the class scope.  In the
4742              friend case, push_template_decl will already have put the
4743              friend into global scope, if appropriate.  */
4744           if (TREE_CODE (type) != ENUMERAL_TYPE
4745               && !is_friend && b->kind == sk_template_parms
4746               && b->level_chain->kind == sk_class)
4747             {
4748               finish_member_declaration (CLASSTYPE_TI_TEMPLATE (type));
4749
4750               if (!COMPLETE_TYPE_P (current_class_type))
4751                 {
4752                   maybe_add_class_template_decl_list (current_class_type,
4753                                                       type, /*friend_p=*/0);
4754                   /* Put this UTD in the table of UTDs for the class.  */
4755                   if (CLASSTYPE_NESTED_UTDS (current_class_type) == NULL)
4756                     CLASSTYPE_NESTED_UTDS (current_class_type) =
4757                       binding_table_new (SCOPE_DEFAULT_HT_SIZE);
4758
4759                   binding_table_insert
4760                     (CLASSTYPE_NESTED_UTDS (current_class_type), name, type);
4761                 }
4762             }
4763         }
4764     }
4765
4766   return decl;
4767 }
4768
4769 /* Push a tag name NAME for struct/class/union/enum type TYPE.  In case
4770    that the NAME is a class template, the tag is processed but not pushed.
4771
4772    The pushed scope depend on the SCOPE parameter:
4773    - When SCOPE is TS_CURRENT, put it into the inner-most non-sk_cleanup
4774      scope.
4775    - When SCOPE is TS_GLOBAL, put it in the inner-most non-class and
4776      non-template-parameter scope.  This case is needed for forward
4777      declarations.
4778    - When SCOPE is TS_WITHIN_ENCLOSING_NON_CLASS, this is similar to
4779      TS_GLOBAL case except that names within template-parameter scopes
4780      are not pushed at all.
4781
4782    Returns TYPE upon success and ERROR_MARK_NODE otherwise.  */
4783
4784 tree
4785 pushtag (tree name, tree type, tag_scope scope)
4786 {
4787   struct cp_binding_level *b;
4788   tree decl;
4789
4790   timevar_push (TV_NAME_LOOKUP);
4791   b = current_binding_level;
4792   while (/* Cleanup scopes are not scopes from the point of view of
4793             the language.  */
4794          b->kind == sk_cleanup
4795          /* Neither are the scopes used to hold template parameters
4796             for an explicit specialization.  For an ordinary template
4797             declaration, these scopes are not scopes from the point of
4798             view of the language.  */
4799          || (b->kind == sk_template_parms
4800              && (b->explicit_spec_p || scope == ts_global))
4801          || (b->kind == sk_class
4802              && (scope != ts_current
4803                  /* We may be defining a new type in the initializer
4804                     of a static member variable. We allow this when
4805                     not pedantic, and it is particularly useful for
4806                     type punning via an anonymous union.  */
4807                  || COMPLETE_TYPE_P (b->this_entity))))
4808     b = b->level_chain;
4809
4810   gcc_assert (TREE_CODE (name) == IDENTIFIER_NODE);
4811
4812   /* Do C++ gratuitous typedefing.  */
4813   if (IDENTIFIER_TYPE_VALUE (name) != type)
4814     {
4815       tree tdef;
4816       int in_class = 0;
4817       tree context = TYPE_CONTEXT (type);
4818
4819       if (! context)
4820         {
4821           tree cs = current_scope ();
4822
4823           if (scope == ts_current)
4824             context = cs;
4825           else if (cs != NULL_TREE && TYPE_P (cs))
4826             /* When declaring a friend class of a local class, we want
4827                to inject the newly named class into the scope
4828                containing the local class, not the namespace
4829                scope.  */
4830             context = decl_function_context (get_type_decl (cs));
4831         }
4832       if (!context)
4833         context = current_namespace;
4834
4835       if (b->kind == sk_class
4836           || (b->kind == sk_template_parms
4837               && b->level_chain->kind == sk_class))
4838         in_class = 1;
4839
4840       if (current_lang_name == lang_name_java)
4841         TYPE_FOR_JAVA (type) = 1;
4842
4843       tdef = create_implicit_typedef (name, type);
4844       DECL_CONTEXT (tdef) = FROB_CONTEXT (context);
4845       if (scope == ts_within_enclosing_non_class)
4846         {
4847           /* This is a friend.  Make this TYPE_DECL node hidden from
4848              ordinary name lookup.  Its corresponding TEMPLATE_DECL
4849              will be marked in push_template_decl_real.  */
4850           retrofit_lang_decl (tdef);
4851           DECL_ANTICIPATED (tdef) = 1;
4852           DECL_FRIEND_P (tdef) = 1;
4853         }
4854
4855       decl = maybe_process_template_type_declaration
4856         (type, scope == ts_within_enclosing_non_class, b);
4857       if (decl == error_mark_node)
4858         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, decl);
4859
4860       if (! in_class)
4861         set_identifier_type_value_with_scope (name, tdef, b);
4862
4863       if (b->kind == sk_class)
4864         {
4865           if (!PROCESSING_REAL_TEMPLATE_DECL_P ())
4866             /* Put this TYPE_DECL on the TYPE_FIELDS list for the
4867                class.  But if it's a member template class, we want
4868                the TEMPLATE_DECL, not the TYPE_DECL, so this is done
4869                later.  */
4870             finish_member_declaration (decl);
4871           else
4872             pushdecl_class_level (decl);
4873         }
4874       else if (b->kind != sk_template_parms)
4875         {
4876           decl = pushdecl_with_scope (decl, b, /*is_friend=*/false);
4877           if (decl == error_mark_node)
4878             POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, decl);
4879         }
4880
4881       TYPE_CONTEXT (type) = DECL_CONTEXT (decl);
4882
4883       /* If this is a local class, keep track of it.  We need this
4884          information for name-mangling, and so that it is possible to
4885          find all function definitions in a translation unit in a
4886          convenient way.  (It's otherwise tricky to find a member
4887          function definition it's only pointed to from within a local
4888          class.)  */
4889       if (TYPE_CONTEXT (type)
4890           && TREE_CODE (TYPE_CONTEXT (type)) == FUNCTION_DECL)
4891         VEC_safe_push (tree, gc, local_classes, type);
4892     }
4893   if (b->kind == sk_class
4894       && !COMPLETE_TYPE_P (current_class_type))
4895     {
4896       maybe_add_class_template_decl_list (current_class_type,
4897                                           type, /*friend_p=*/0);
4898
4899       if (CLASSTYPE_NESTED_UTDS (current_class_type) == NULL)
4900         CLASSTYPE_NESTED_UTDS (current_class_type)
4901           = binding_table_new (SCOPE_DEFAULT_HT_SIZE);
4902
4903       binding_table_insert
4904         (CLASSTYPE_NESTED_UTDS (current_class_type), name, type);
4905     }
4906
4907   decl = TYPE_NAME (type);
4908   gcc_assert (TREE_CODE (decl) == TYPE_DECL);
4909   TYPE_STUB_DECL (type) = decl;
4910
4911   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, type);
4912 }
4913 \f
4914 /* Subroutines for reverting temporarily to top-level for instantiation
4915    of templates and such.  We actually need to clear out the class- and
4916    local-value slots of all identifiers, so that only the global values
4917    are at all visible.  Simply setting current_binding_level to the global
4918    scope isn't enough, because more binding levels may be pushed.  */
4919 struct saved_scope *scope_chain;
4920
4921 /* If ID has not already been marked, add an appropriate binding to
4922    *OLD_BINDINGS.  */
4923
4924 static void
4925 store_binding (tree id, VEC(cxx_saved_binding,gc) **old_bindings)
4926 {
4927   cxx_saved_binding *saved;
4928
4929   if (!id || !IDENTIFIER_BINDING (id))
4930     return;
4931
4932   if (IDENTIFIER_MARKED (id))
4933     return;
4934
4935   IDENTIFIER_MARKED (id) = 1;
4936
4937   saved = VEC_safe_push (cxx_saved_binding, gc, *old_bindings, NULL);
4938   saved->identifier = id;
4939   saved->binding = IDENTIFIER_BINDING (id);
4940   saved->real_type_value = REAL_IDENTIFIER_TYPE_VALUE (id);
4941   IDENTIFIER_BINDING (id) = NULL;
4942 }
4943
4944 static void
4945 store_bindings (tree names, VEC(cxx_saved_binding,gc) **old_bindings)
4946 {
4947   tree t;
4948
4949   timevar_push (TV_NAME_LOOKUP);
4950   for (t = names; t; t = TREE_CHAIN (t))
4951     {
4952       tree id;
4953
4954       if (TREE_CODE (t) == TREE_LIST)
4955         id = TREE_PURPOSE (t);
4956       else
4957         id = DECL_NAME (t);
4958
4959       store_binding (id, old_bindings);
4960     }
4961   timevar_pop (TV_NAME_LOOKUP);
4962 }
4963
4964 /* Like store_bindings, but NAMES is a vector of cp_class_binding
4965    objects, rather than a TREE_LIST.  */
4966
4967 static void
4968 store_class_bindings (VEC(cp_class_binding,gc) *names,
4969                       VEC(cxx_saved_binding,gc) **old_bindings)
4970 {
4971   size_t i;
4972   cp_class_binding *cb;
4973
4974   timevar_push (TV_NAME_LOOKUP);
4975   for (i = 0; VEC_iterate(cp_class_binding, names, i, cb); ++i)
4976     store_binding (cb->identifier, old_bindings);
4977   timevar_pop (TV_NAME_LOOKUP);
4978 }
4979
4980 void
4981 push_to_top_level (void)
4982 {
4983   struct saved_scope *s;
4984   struct cp_binding_level *b;
4985   cxx_saved_binding *sb;
4986   size_t i;
4987   int need_pop;
4988
4989   timevar_push (TV_NAME_LOOKUP);
4990   s = GGC_CNEW (struct saved_scope);
4991
4992   b = scope_chain ? current_binding_level : 0;
4993
4994   /* If we're in the middle of some function, save our state.  */
4995   if (cfun)
4996     {
4997       need_pop = 1;
4998       push_function_context_to (NULL_TREE);
4999     }
5000   else
5001     need_pop = 0;
5002
5003   if (scope_chain && previous_class_level)
5004     store_class_bindings (previous_class_level->class_shadowed,
5005                           &s->old_bindings);
5006
5007   /* Have to include the global scope, because class-scope decls
5008      aren't listed anywhere useful.  */
5009   for (; b; b = b->level_chain)
5010     {
5011       tree t;
5012
5013       /* Template IDs are inserted into the global level. If they were
5014          inserted into namespace level, finish_file wouldn't find them
5015          when doing pending instantiations. Therefore, don't stop at
5016          namespace level, but continue until :: .  */
5017       if (global_scope_p (b))
5018         break;
5019
5020       store_bindings (b->names, &s->old_bindings);
5021       /* We also need to check class_shadowed to save class-level type
5022          bindings, since pushclass doesn't fill in b->names.  */
5023       if (b->kind == sk_class)
5024         store_class_bindings (b->class_shadowed, &s->old_bindings);
5025
5026       /* Unwind type-value slots back to top level.  */
5027       for (t = b->type_shadowed; t; t = TREE_CHAIN (t))
5028         SET_IDENTIFIER_TYPE_VALUE (TREE_PURPOSE (t), TREE_VALUE (t));
5029     }
5030
5031   for (i = 0; VEC_iterate (cxx_saved_binding, s->old_bindings, i, sb); ++i)
5032     IDENTIFIER_MARKED (sb->identifier) = 0;
5033
5034   s->prev = scope_chain;
5035   s->bindings = b;
5036   s->need_pop_function_context = need_pop;
5037   s->function_decl = current_function_decl;
5038   s->skip_evaluation = skip_evaluation;
5039
5040   scope_chain = s;
5041   current_function_decl = NULL_TREE;
5042   current_lang_base = VEC_alloc (tree, gc, 10);
5043   current_lang_name = lang_name_cplusplus;
5044   current_namespace = global_namespace;
5045   push_class_stack ();
5046   skip_evaluation = 0;
5047   timevar_pop (TV_NAME_LOOKUP);
5048 }
5049
5050 void
5051 pop_from_top_level (void)
5052 {
5053   struct saved_scope *s = scope_chain;
5054   cxx_saved_binding *saved;
5055   size_t i;
5056
5057   timevar_push (TV_NAME_LOOKUP);
5058   /* Clear out class-level bindings cache.  */
5059   if (previous_class_level)
5060     invalidate_class_lookup_cache ();
5061   pop_class_stack ();
5062
5063   current_lang_base = 0;
5064
5065   scope_chain = s->prev;
5066   for (i = 0; VEC_iterate (cxx_saved_binding, s->old_bindings, i, saved); ++i)
5067     {
5068       tree id = saved->identifier;
5069
5070       IDENTIFIER_BINDING (id) = saved->binding;
5071       SET_IDENTIFIER_TYPE_VALUE (id, saved->real_type_value);
5072     }
5073
5074   /* If we were in the middle of compiling a function, restore our
5075      state.  */
5076   if (s->need_pop_function_context)
5077     pop_function_context_from (NULL_TREE);
5078   current_function_decl = s->function_decl;
5079   skip_evaluation = s->skip_evaluation;
5080   timevar_pop (TV_NAME_LOOKUP);
5081 }
5082
5083 /* Pop off extraneous binding levels left over due to syntax errors.
5084
5085    We don't pop past namespaces, as they might be valid.  */
5086
5087 void
5088 pop_everything (void)
5089 {
5090   if (ENABLE_SCOPE_CHECKING)
5091     verbatim ("XXX entering pop_everything ()\n");
5092   while (!toplevel_bindings_p ())
5093     {
5094       if (current_binding_level->kind == sk_class)
5095         pop_nested_class ();
5096       else
5097         poplevel (0, 0, 0);
5098     }
5099   if (ENABLE_SCOPE_CHECKING)
5100     verbatim ("XXX leaving pop_everything ()\n");
5101 }
5102
5103 /* Emit debugging information for using declarations and directives.
5104    If input tree is overloaded fn then emit debug info for all
5105    candidates.  */
5106
5107 void
5108 cp_emit_debug_info_for_using (tree t, tree context)
5109 {
5110   /* Don't try to emit any debug information if we have errors.  */
5111   if (sorrycount || errorcount)
5112     return;
5113
5114   /* Ignore this FUNCTION_DECL if it refers to a builtin declaration
5115      of a builtin function.  */
5116   if (TREE_CODE (t) == FUNCTION_DECL
5117       && DECL_EXTERNAL (t)
5118       && DECL_BUILT_IN (t))
5119     return;
5120
5121   /* Do not supply context to imported_module_or_decl, if
5122      it is a global namespace.  */
5123   if (context == global_namespace)
5124     context = NULL_TREE;
5125
5126   if (BASELINK_P (t))
5127     t = BASELINK_FUNCTIONS (t);
5128
5129   /* FIXME: Handle TEMPLATE_DECLs.  */
5130   for (t = OVL_CURRENT (t); t; t = OVL_NEXT (t))
5131     if (TREE_CODE (t) != TEMPLATE_DECL)
5132       (*debug_hooks->imported_module_or_decl) (t, context);
5133 }
5134
5135 #include "gt-cp-name-lookup.h"