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