OSDN Git Service

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