OSDN Git Service

PR c++/10956
[pf3gnuchains/gcc-fork.git] / gcc / cp / pt.c
1 /* Handle parameterized types (templates) for GNU C++.
2    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3    2001, 2002, 2003  Free Software Foundation, Inc.
4    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
5    Rewritten by Jason Merrill (jason@cygnus.com).
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2, or (at your option)
12 any later version.
13
14 GCC is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING.  If not, write to
21 the Free Software Foundation, 59 Temple Place - Suite 330,
22 Boston, MA 02111-1307, USA.  */
23
24 /* Known bugs or deficiencies include:
25
26      all methods must be provided in header files; can't use a source
27      file that contains only the method templates and "just win".  */
28
29 #include "config.h"
30 #include "system.h"
31 #include "coretypes.h"
32 #include "tm.h"
33 #include "obstack.h"
34 #include "tree.h"
35 #include "flags.h"
36 #include "cp-tree.h"
37 #include "tree-inline.h"
38 #include "decl.h"
39 #include "lex.h"
40 #include "output.h"
41 #include "except.h"
42 #include "toplev.h"
43 #include "rtl.h"
44 #include "timevar.h"
45
46 /* The type of functions taking a tree, and some additional data, and
47    returning an int.  */
48 typedef int (*tree_fn_t) PARAMS ((tree, void*));
49
50 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
51    instantiations have been deferred, either because their definitions
52    were not yet available, or because we were putting off doing the work.
53    The TREE_PURPOSE of each entry is either a DECL (for a function or
54    static data member), or a TYPE (for a class) indicating what we are
55    hoping to instantiate.  The TREE_VALUE is not used.  */
56 static GTY(()) tree pending_templates;
57 static GTY(()) tree last_pending_template;
58
59 int processing_template_parmlist;
60 static int template_header_count;
61
62 static GTY(()) tree saved_trees;
63 static GTY(()) varray_type inline_parm_levels;
64 static size_t inline_parm_levels_used;
65
66 static GTY(()) tree current_tinst_level;
67
68 static GTY(()) tree saved_access_scope;
69
70 /* A map from local variable declarations in the body of the template
71    presently being instantiated to the corresponding instantiated
72    local variables.  */
73 static htab_t local_specializations;
74
75 #define UNIFY_ALLOW_NONE 0
76 #define UNIFY_ALLOW_MORE_CV_QUAL 1
77 #define UNIFY_ALLOW_LESS_CV_QUAL 2
78 #define UNIFY_ALLOW_DERIVED 4
79 #define UNIFY_ALLOW_INTEGER 8
80 #define UNIFY_ALLOW_OUTER_LEVEL 16
81 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
82 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
83 #define UNIFY_ALLOW_MAX_CORRECTION 128
84
85 #define GTB_VIA_VIRTUAL 1 /* The base class we are examining is
86                              virtual, or a base class of a virtual
87                              base.  */
88 #define GTB_IGNORE_TYPE 2 /* We don't need to try to unify the current
89                              type with the desired type.  */
90
91 static void push_access_scope_real PARAMS ((tree, tree, tree));
92 static void push_access_scope PARAMS ((tree));
93 static void pop_access_scope PARAMS ((tree));
94 static int resolve_overloaded_unification PARAMS ((tree, tree, tree, tree,
95                                                    unification_kind_t, int));
96 static int try_one_overload PARAMS ((tree, tree, tree, tree, tree,
97                                      unification_kind_t, int));
98 static int unify PARAMS ((tree, tree, tree, tree, int));
99 static void add_pending_template PARAMS ((tree));
100 static void reopen_tinst_level PARAMS ((tree));
101 static tree classtype_mangled_name PARAMS ((tree));
102 static char *mangle_class_name_for_template PARAMS ((const char *,
103                                                      tree, tree));
104 static tree tsubst_initializer_list PARAMS ((tree, tree));
105 static int list_eq PARAMS ((tree, tree));
106 static tree get_class_bindings PARAMS ((tree, tree, tree));
107 static tree coerce_template_parms PARAMS ((tree, tree, tree,
108                                            tsubst_flags_t, int));
109 static void tsubst_enum PARAMS ((tree, tree, tree));
110 static tree add_to_template_args PARAMS ((tree, tree));
111 static tree add_outermost_template_args PARAMS ((tree, tree));
112 static bool check_instantiated_args PARAMS ((tree, tree, tsubst_flags_t));
113 static int maybe_adjust_types_for_deduction PARAMS ((unification_kind_t, tree*,
114                                                      tree*)); 
115 static int  type_unification_real PARAMS ((tree, tree, tree, tree,
116                                            int, unification_kind_t, int, int));
117 static void note_template_header PARAMS ((int));
118 static tree maybe_fold_nontype_arg PARAMS ((tree));
119 static void maybe_fold_nontype_args PARAMS ((tree));
120 static tree convert_nontype_argument PARAMS ((tree, tree));
121 static tree convert_template_argument PARAMS ((tree, tree, tree,
122                                                tsubst_flags_t, int, tree));
123 static tree get_bindings_overload PARAMS ((tree, tree, tree));
124 static int for_each_template_parm PARAMS ((tree, tree_fn_t, void*, htab_t));
125 static tree build_template_parm_index PARAMS ((int, int, int, tree, tree));
126 static int inline_needs_template_parms PARAMS ((tree));
127 static void push_inline_template_parms_recursive PARAMS ((tree, int));
128 static tree retrieve_specialization PARAMS ((tree, tree));
129 static tree retrieve_local_specialization PARAMS ((tree));
130 static tree register_specialization PARAMS ((tree, tree, tree));
131 static void register_local_specialization PARAMS ((tree, tree));
132 static int unregister_specialization PARAMS ((tree, tree));
133 static tree reduce_template_parm_level PARAMS ((tree, tree, int));
134 static tree build_template_decl PARAMS ((tree, tree));
135 static int mark_template_parm PARAMS ((tree, void *));
136 static int template_parm_this_level_p PARAMS ((tree, void *));
137 static tree tsubst_friend_function PARAMS ((tree, tree));
138 static tree tsubst_friend_class PARAMS ((tree, tree));
139 static int can_complete_type_without_circularity PARAMS ((tree));
140 static tree get_bindings_real PARAMS ((tree, tree, tree, int, int, int));
141 static int template_decl_level PARAMS ((tree));
142 static int check_cv_quals_for_unify PARAMS ((int, tree, tree));
143 static tree tsubst_template_arg_vector PARAMS ((tree, tree, tsubst_flags_t));
144 static tree tsubst_template_parms PARAMS ((tree, tree, tsubst_flags_t));
145 static void regenerate_decl_from_template PARAMS ((tree, tree));
146 static tree most_specialized PARAMS ((tree, tree, tree));
147 static tree most_specialized_class PARAMS ((tree, tree));
148 static int template_class_depth_real PARAMS ((tree, int));
149 static tree tsubst_aggr_type PARAMS ((tree, tree, tsubst_flags_t, tree, int));
150 static tree tsubst_decl PARAMS ((tree, tree, tree, tsubst_flags_t));
151 static tree tsubst_arg_types PARAMS ((tree, tree, tsubst_flags_t, tree));
152 static tree tsubst_function_type PARAMS ((tree, tree, tsubst_flags_t, tree));
153 static void check_specialization_scope PARAMS ((void));
154 static tree process_partial_specialization PARAMS ((tree));
155 static void set_current_access_from_decl PARAMS ((tree));
156 static void check_default_tmpl_args PARAMS ((tree, tree, int, int));
157 static tree tsubst_call_declarator_parms PARAMS ((tree, tree,
158                                                   tsubst_flags_t, tree));
159 static tree get_template_base_recursive PARAMS ((tree, tree,
160                                                  tree, tree, tree, int)); 
161 static tree get_template_base PARAMS ((tree, tree, tree, tree));
162 static int verify_class_unification PARAMS ((tree, tree, tree));
163 static tree try_class_unification PARAMS ((tree, tree, tree, tree));
164 static int coerce_template_template_parms PARAMS ((tree, tree, tsubst_flags_t,
165                                                    tree, tree));
166 static tree determine_specialization PARAMS ((tree, tree, tree *, int));
167 static int template_args_equal PARAMS ((tree, tree));
168 static void tsubst_default_arguments PARAMS ((tree));
169 static tree for_each_template_parm_r PARAMS ((tree *, int *, void *));
170 static tree copy_default_args_to_explicit_spec_1 PARAMS ((tree, tree));
171 static void copy_default_args_to_explicit_spec PARAMS ((tree));
172 static int invalid_nontype_parm_type_p PARAMS ((tree, tsubst_flags_t));
173 static int eq_local_specializations (const void *, const void *);
174 static tree template_for_substitution (tree);
175 static bool dependent_type_p_r (tree);
176 static bool dependent_template_id_p (tree, tree);
177 static tree tsubst (tree, tree, tsubst_flags_t, tree);
178 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree);
179 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
180 static tree tsubst_copy_and_build (tree, tree, tsubst_flags_t, tree);
181
182 /* Make the current scope suitable for access checking when we are
183    processing T.  T can be FUNCTION_DECL for instantiated function
184    template, TEMPLATE_DECL for uninstantiated one, or VAR_DECL for
185    static member variable (need by instantiate_decl).  ARGS is the 
186    template argument for TEMPLATE_DECL.  If CONTEXT is not NULL_TREE, 
187    this is used instead of the context of T.  */
188
189 void
190 push_access_scope_real (t, args, context)
191   tree t, args, context;
192 {
193   if (TREE_CODE (t) == FUNCTION_DECL || DECL_FUNCTION_TEMPLATE_P (t))
194     {
195       /* When we are processing specialization `foo<Outer>' for code like
196
197            template <class U> typename U::Inner foo ();
198            class Outer {
199              struct Inner {};
200              friend Outer::Inner foo<Outer> ();
201            };
202
203          `T' is a TEMPLATE_DECL, but `Outer' is only a friend of one of
204          its specialization.  We can get the FUNCTION_DECL with the right
205          information because this specialization has already been
206          registered by the friend declaration above.  */
207
208       if (DECL_FUNCTION_TEMPLATE_P (t) && args)
209         {
210           tree full_args = tsubst_template_arg_vector
211             (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t)), args, tf_none);
212           tree spec = NULL_TREE;
213           if (full_args != error_mark_node)
214             spec = retrieve_specialization (t, full_args);
215           if (spec)
216             t = spec;
217         }
218     }
219
220   if (!context)
221     context = DECL_CONTEXT (t);
222   if (context && TYPE_P (context))
223     push_nested_class (context);
224   else
225     push_to_top_level ();
226     
227   if (TREE_CODE (t) == FUNCTION_DECL || DECL_FUNCTION_TEMPLATE_P (t))
228     {
229       saved_access_scope = tree_cons
230         (NULL_TREE, current_function_decl, saved_access_scope);
231       current_function_decl = t;
232     }
233 }
234
235 /* Like push_access_scope_real, but always uses DECL_CONTEXT.  */
236
237 void
238 push_access_scope (t)
239   tree t;
240 {
241   push_access_scope_real (t, NULL_TREE, NULL_TREE);
242 }
243
244 /* Restore the scope set up by push_access_scope.  T is the node we
245    are processing.  */
246
247 void
248 pop_access_scope (t)
249   tree t;
250 {
251   if (TREE_CODE (t) == FUNCTION_DECL || DECL_FUNCTION_TEMPLATE_P (t))
252     {
253       current_function_decl = TREE_VALUE (saved_access_scope);
254       saved_access_scope = TREE_CHAIN (saved_access_scope);
255     }
256
257   if (DECL_CLASS_SCOPE_P (t))
258     pop_nested_class ();
259   else
260     pop_from_top_level ();
261 }
262
263 /* Do any processing required when DECL (a member template
264    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
265    to DECL, unless it is a specialization, in which case the DECL
266    itself is returned.  */
267
268 tree
269 finish_member_template_decl (decl)
270   tree decl;
271 {
272   if (decl == error_mark_node)
273     return error_mark_node;
274
275   my_friendly_assert (DECL_P (decl), 20020812);
276
277   if (TREE_CODE (decl) == TYPE_DECL)
278     {
279       tree type;
280
281       type = TREE_TYPE (decl);
282       if (IS_AGGR_TYPE (type) 
283           && CLASSTYPE_TEMPLATE_INFO (type)
284           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
285         {
286           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
287           check_member_template (tmpl);
288           return tmpl;
289         }
290       return NULL_TREE;
291     }
292   else if (TREE_CODE (decl) == FIELD_DECL)
293     error ("data member `%D' cannot be a member template", decl);
294   else if (DECL_TEMPLATE_INFO (decl))
295     {
296       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
297         {
298           check_member_template (DECL_TI_TEMPLATE (decl));
299           return DECL_TI_TEMPLATE (decl);
300         }
301       else
302         return decl;
303     } 
304   else
305     error ("invalid member template declaration `%D'", decl);
306
307   return error_mark_node;
308 }
309
310 /* Returns the template nesting level of the indicated class TYPE.
311    
312    For example, in:
313      template <class T>
314      struct A
315      {
316        template <class U>
317        struct B {};
318      };
319
320    A<T>::B<U> has depth two, while A<T> has depth one.  
321    Both A<T>::B<int> and A<int>::B<U> have depth one, if
322    COUNT_SPECIALIZATIONS is 0 or if they are instantiations, not
323    specializations.  
324
325    This function is guaranteed to return 0 if passed NULL_TREE so
326    that, for example, `template_class_depth (current_class_type)' is
327    always safe.  */
328
329 static int 
330 template_class_depth_real (type, count_specializations)
331      tree type;
332      int count_specializations;
333 {
334   int depth;
335
336   for (depth = 0; 
337        type && TREE_CODE (type) != NAMESPACE_DECL;
338        type = (TREE_CODE (type) == FUNCTION_DECL) 
339          ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
340     {
341       if (TREE_CODE (type) != FUNCTION_DECL)
342         {
343           if (CLASSTYPE_TEMPLATE_INFO (type)
344               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type))
345               && ((count_specializations
346                    && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
347                   || uses_template_parms (CLASSTYPE_TI_ARGS (type))))
348             ++depth;
349         }
350       else 
351         {
352           if (DECL_TEMPLATE_INFO (type)
353               && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (type))
354               && ((count_specializations
355                    && DECL_TEMPLATE_SPECIALIZATION (type))
356                   || uses_template_parms (DECL_TI_ARGS (type))))
357             ++depth;
358         }
359     }
360
361   return depth;
362 }
363
364 /* Returns the template nesting level of the indicated class TYPE.
365    Like template_class_depth_real, but instantiations do not count in
366    the depth.  */
367
368 int 
369 template_class_depth (type)
370      tree type;
371 {
372   return template_class_depth_real (type, /*count_specializations=*/0);
373 }
374
375 /* Returns 1 if processing DECL as part of do_pending_inlines
376    needs us to push template parms.  */
377
378 static int
379 inline_needs_template_parms (decl)
380      tree decl;
381 {
382   if (! DECL_TEMPLATE_INFO (decl))
383     return 0;
384
385   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
386           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
387 }
388
389 /* Subroutine of maybe_begin_member_template_processing.
390    Push the template parms in PARMS, starting from LEVELS steps into the
391    chain, and ending at the beginning, since template parms are listed
392    innermost first.  */
393
394 static void
395 push_inline_template_parms_recursive (parmlist, levels)
396      tree parmlist;
397      int levels;
398 {
399   tree parms = TREE_VALUE (parmlist);
400   int i;
401
402   if (levels > 1)
403     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
404
405   ++processing_template_decl;
406   current_template_parms
407     = tree_cons (size_int (processing_template_decl),
408                  parms, current_template_parms);
409   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
410
411   pushlevel (0);
412   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i) 
413     {
414       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
415       my_friendly_assert (DECL_P (parm), 0);
416
417       switch (TREE_CODE (parm))
418         {
419         case TYPE_DECL:
420         case TEMPLATE_DECL:
421           pushdecl (parm);
422           break;
423
424         case PARM_DECL:
425           {
426             /* Make a CONST_DECL as is done in process_template_parm.
427                It is ugly that we recreate this here; the original
428                version built in process_template_parm is no longer
429                available.  */
430             tree decl = build_decl (CONST_DECL, DECL_NAME (parm),
431                                     TREE_TYPE (parm));
432             DECL_ARTIFICIAL (decl) = 1;
433             TREE_CONSTANT (decl) = TREE_READONLY (decl) = 1;
434             DECL_INITIAL (decl) = DECL_INITIAL (parm);
435             SET_DECL_TEMPLATE_PARM_P (decl);
436             pushdecl (decl);
437           }
438           break;
439
440         default:
441           abort ();
442         }
443     }
444 }
445
446 /* Restore the template parameter context for a member template or
447    a friend template defined in a class definition.  */
448
449 void
450 maybe_begin_member_template_processing (decl)
451      tree decl;
452 {
453   tree parms;
454   int levels = 0;
455
456   if (inline_needs_template_parms (decl))
457     {
458       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
459       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
460
461       if (DECL_TEMPLATE_SPECIALIZATION (decl))
462         {
463           --levels;
464           parms = TREE_CHAIN (parms);
465         }
466
467       push_inline_template_parms_recursive (parms, levels);
468     }
469
470   /* Remember how many levels of template parameters we pushed so that
471      we can pop them later.  */
472   if (!inline_parm_levels)
473     VARRAY_INT_INIT (inline_parm_levels, 4, "inline_parm_levels");
474   if (inline_parm_levels_used == inline_parm_levels->num_elements)
475     VARRAY_GROW (inline_parm_levels, 2 * inline_parm_levels_used);
476   VARRAY_INT (inline_parm_levels, inline_parm_levels_used) = levels;
477   ++inline_parm_levels_used;
478 }
479
480 /* Undo the effects of begin_member_template_processing.  */
481
482 void 
483 maybe_end_member_template_processing ()
484 {
485   int i;
486
487   if (!inline_parm_levels_used)
488     return;
489
490   --inline_parm_levels_used;
491   for (i = 0; 
492        i < VARRAY_INT (inline_parm_levels, inline_parm_levels_used);
493        ++i) 
494     {
495       --processing_template_decl;
496       current_template_parms = TREE_CHAIN (current_template_parms);
497       poplevel (0, 0, 0);
498     }
499 }
500
501 /* Returns nonzero iff T is a member template function.  We must be
502    careful as in
503
504      template <class T> class C { void f(); }
505
506    Here, f is a template function, and a member, but not a member
507    template.  This function does not concern itself with the origin of
508    T, only its present state.  So if we have 
509
510      template <class T> class C { template <class U> void f(U); }
511
512    then neither C<int>::f<char> nor C<T>::f<double> is considered
513    to be a member template.  But, `template <class U> void
514    C<int>::f(U)' is considered a member template.  */
515
516 int
517 is_member_template (t)
518      tree t;
519 {
520   if (!DECL_FUNCTION_TEMPLATE_P (t))
521     /* Anything that isn't a function or a template function is
522        certainly not a member template.  */
523     return 0;
524
525   /* A local class can't have member templates.  */
526   if (decl_function_context (t))
527     return 0;
528
529   return (DECL_FUNCTION_MEMBER_P (DECL_TEMPLATE_RESULT (t))
530           /* If there are more levels of template parameters than
531              there are template classes surrounding the declaration,
532              then we have a member template.  */
533           && (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (t)) > 
534               template_class_depth (DECL_CONTEXT (t))));
535 }
536
537 #if 0 /* UNUSED */
538 /* Returns nonzero iff T is a member template class.  See
539    is_member_template for a description of what precisely constitutes
540    a member template.  */
541
542 int
543 is_member_template_class (t)
544      tree t;
545 {
546   if (!DECL_CLASS_TEMPLATE_P (t))
547     /* Anything that isn't a class template, is certainly not a member
548        template.  */
549     return 0;
550
551   if (!DECL_CLASS_SCOPE_P (t))
552     /* Anything whose context isn't a class type is surely not a
553        member template.  */
554     return 0;
555
556   /* If there are more levels of template parameters than there are
557      template classes surrounding the declaration, then we have a
558      member template.  */
559   return  (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (t)) > 
560            template_class_depth (DECL_CONTEXT (t)));
561 }
562 #endif
563
564 /* Return a new template argument vector which contains all of ARGS,
565    but has as its innermost set of arguments the EXTRA_ARGS.  */
566
567 static tree
568 add_to_template_args (args, extra_args)
569      tree args;
570      tree extra_args;
571 {
572   tree new_args;
573   int extra_depth;
574   int i;
575   int j;
576
577   extra_depth = TMPL_ARGS_DEPTH (extra_args);
578   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
579
580   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
581     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
582
583   for (j = 1; j <= extra_depth; ++j, ++i)
584     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
585     
586   return new_args;
587 }
588
589 /* Like add_to_template_args, but only the outermost ARGS are added to
590    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
591    (EXTRA_ARGS) levels are added.  This function is used to combine
592    the template arguments from a partial instantiation with the
593    template arguments used to attain the full instantiation from the
594    partial instantiation.  */
595
596 static tree
597 add_outermost_template_args (args, extra_args)
598      tree args;
599      tree extra_args;
600 {
601   tree new_args;
602
603   /* If there are more levels of EXTRA_ARGS than there are ARGS,
604      something very fishy is going on.  */
605   my_friendly_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args),
606                       0);
607
608   /* If *all* the new arguments will be the EXTRA_ARGS, just return
609      them.  */
610   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
611     return extra_args;
612
613   /* For the moment, we make ARGS look like it contains fewer levels.  */
614   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
615   
616   new_args = add_to_template_args (args, extra_args);
617
618   /* Now, we restore ARGS to its full dimensions.  */
619   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
620
621   return new_args;
622 }
623
624 /* Return the N levels of innermost template arguments from the ARGS.  */
625
626 tree
627 get_innermost_template_args (args, n)
628      tree args;
629      int n;
630 {
631   tree new_args;
632   int extra_levels;
633   int i;
634
635   my_friendly_assert (n >= 0, 20000603);
636
637   /* If N is 1, just return the innermost set of template arguments.  */
638   if (n == 1)
639     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
640   
641   /* If we're not removing anything, just return the arguments we were
642      given.  */
643   extra_levels = TMPL_ARGS_DEPTH (args) - n;
644   my_friendly_assert (extra_levels >= 0, 20000603);
645   if (extra_levels == 0)
646     return args;
647
648   /* Make a new set of arguments, not containing the outer arguments.  */
649   new_args = make_tree_vec (n);
650   for (i = 1; i <= n; ++i)
651     SET_TMPL_ARGS_LEVEL (new_args, i, 
652                          TMPL_ARGS_LEVEL (args, i + extra_levels));
653
654   return new_args;
655 }
656
657 /* We've got a template header coming up; push to a new level for storing
658    the parms.  */
659
660 void
661 begin_template_parm_list ()
662 {
663   /* We use a non-tag-transparent scope here, which causes pushtag to
664      put tags in this scope, rather than in the enclosing class or
665      namespace scope.  This is the right thing, since we want
666      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
667      global template class, push_template_decl handles putting the
668      TEMPLATE_DECL into top-level scope.  For a nested template class,
669      e.g.:
670
671        template <class T> struct S1 {
672          template <class T> struct S2 {}; 
673        };
674
675      pushtag contains special code to call pushdecl_with_scope on the
676      TEMPLATE_DECL for S2.  */
677   begin_scope (sk_template_parms);
678   ++processing_template_decl;
679   ++processing_template_parmlist;
680   note_template_header (0);
681 }
682
683 /* This routine is called when a specialization is declared.  If it is
684    invalid to declare a specialization here, an error is reported.  */
685
686 static void
687 check_specialization_scope ()
688 {
689   tree scope = current_scope ();
690
691   /* [temp.expl.spec] 
692      
693      An explicit specialization shall be declared in the namespace of
694      which the template is a member, or, for member templates, in the
695      namespace of which the enclosing class or enclosing class
696      template is a member.  An explicit specialization of a member
697      function, member class or static data member of a class template
698      shall be declared in the namespace of which the class template
699      is a member.  */
700   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
701     error ("explicit specialization in non-namespace scope `%D'",
702               scope);
703
704   /* [temp.expl.spec] 
705
706      In an explicit specialization declaration for a member of a class
707      template or a member template that appears in namespace scope,
708      the member template and some of its enclosing class templates may
709      remain unspecialized, except that the declaration shall not
710      explicitly specialize a class member template if its enclosing
711      class templates are not explicitly specialized as well.  */
712   if (current_template_parms) 
713     error ("enclosing class templates are not explicitly specialized");
714 }
715
716 /* We've just seen template <>.  */
717
718 void
719 begin_specialization ()
720 {
721   begin_scope (sk_template_spec);
722   note_template_header (1);
723   check_specialization_scope ();
724 }
725
726 /* Called at then end of processing a declaration preceded by
727    template<>.  */
728
729 void 
730 end_specialization ()
731 {
732   finish_scope ();
733   reset_specialization ();
734 }
735
736 /* Any template <>'s that we have seen thus far are not referring to a
737    function specialization.  */
738
739 void
740 reset_specialization ()
741 {
742   processing_specialization = 0;
743   template_header_count = 0;
744 }
745
746 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
747    it was of the form template <>.  */
748
749 static void 
750 note_template_header (specialization)
751      int specialization;
752 {
753   processing_specialization = specialization;
754   template_header_count++;
755 }
756
757 /* We're beginning an explicit instantiation.  */
758
759 void
760 begin_explicit_instantiation ()
761 {
762   my_friendly_assert (!processing_explicit_instantiation, 20020913);
763   processing_explicit_instantiation = true;
764 }
765
766
767 void
768 end_explicit_instantiation ()
769 {
770   my_friendly_assert(processing_explicit_instantiation, 20020913);
771   processing_explicit_instantiation = false;
772 }
773
774 /* The TYPE is being declared.  If it is a template type, that means it
775    is a partial specialization.  Do appropriate error-checking.  */
776
777 void 
778 maybe_process_partial_specialization (type)
779      tree type;
780 {
781   /* TYPE maybe an ERROR_MARK_NODE.  */
782   tree context = TYPE_P (type) ? TYPE_CONTEXT (type) : NULL_TREE;
783
784   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
785     {
786       /* This is for ordinary explicit specialization and partial
787          specialization of a template class such as:
788
789            template <> class C<int>;
790
791          or:
792
793            template <class T> class C<T*>;
794
795          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
796
797       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
798           && !COMPLETE_TYPE_P (type))
799         {
800           if (current_namespace
801               != decl_namespace_context (CLASSTYPE_TI_TEMPLATE (type)))
802             {
803               pedwarn ("specializing `%#T' in different namespace", type);
804               cp_pedwarn_at ("  from definition of `%#D'",
805                              CLASSTYPE_TI_TEMPLATE (type));
806             }
807           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
808           if (processing_template_decl)
809             push_template_decl (TYPE_MAIN_DECL (type));
810         }
811       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
812         error ("specialization of `%T' after instantiation", type);
813     }
814   else if (CLASS_TYPE_P (type)
815            && !CLASSTYPE_USE_TEMPLATE (type)
816            && CLASSTYPE_TEMPLATE_INFO (type)
817            && context && CLASS_TYPE_P (context)
818            && CLASSTYPE_TEMPLATE_INFO (context))
819     {
820       /* This is for an explicit specialization of member class
821          template according to [temp.expl.spec/18]:
822
823            template <> template <class U> class C<int>::D;
824
825          The context `C<int>' must be an implicit instantiation.
826          Otherwise this is just a member class template declared
827          earlier like:
828
829            template <> class C<int> { template <class U> class D; };
830            template <> template <class U> class C<int>::D;
831
832          In the first case, `C<int>::D' is a specialization of `C<T>::D'
833          while in the second case, `C<int>::D' is a primary template
834          and `C<T>::D' may not exist.  */
835
836       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
837           && !COMPLETE_TYPE_P (type))
838         {
839           tree t;
840
841           if (current_namespace
842               != decl_namespace_context (CLASSTYPE_TI_TEMPLATE (type)))
843             {
844               pedwarn ("specializing `%#T' in different namespace", type);
845               cp_pedwarn_at ("  from definition of `%#D'",
846                              CLASSTYPE_TI_TEMPLATE (type));
847             }
848
849           /* Check for invalid specialization after instantiation:
850
851                template <> template <> class C<int>::D<int>;
852                template <> template <class U> class C<int>::D;  */
853
854           for (t = DECL_TEMPLATE_INSTANTIATIONS
855                  (most_general_template (CLASSTYPE_TI_TEMPLATE (type)));
856                t; t = TREE_CHAIN (t))
857             if (TREE_VALUE (t) != type
858                 && TYPE_CONTEXT (TREE_VALUE (t)) == context)
859               error ("specialization `%T' after instantiation `%T'",
860                      type, TREE_VALUE (t));
861
862           /* Mark TYPE as a specialization.  And as a result, we only
863              have one level of template argument for the innermost
864              class template.  */
865           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
866           CLASSTYPE_TI_ARGS (type)
867             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
868         }
869     }
870   else if (processing_specialization)
871     error ("explicit specialization of non-template `%T'", type);
872 }
873
874 /* Retrieve the specialization (in the sense of [temp.spec] - a
875    specialization is either an instantiation or an explicit
876    specialization) of TMPL for the given template ARGS.  If there is
877    no such specialization, return NULL_TREE.  The ARGS are a vector of
878    arguments, or a vector of vectors of arguments, in the case of
879    templates with more than one level of parameters.  */
880    
881 static tree
882 retrieve_specialization (tmpl, args)
883      tree tmpl;
884      tree args;
885 {
886   tree s;
887
888   my_friendly_assert (TREE_CODE (tmpl) == TEMPLATE_DECL, 0);
889
890   /* There should be as many levels of arguments as there are
891      levels of parameters.  */
892   my_friendly_assert (TMPL_ARGS_DEPTH (args) 
893                       == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)),
894                       0);
895                       
896   for (s = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
897        s != NULL_TREE;
898        s = TREE_CHAIN (s))
899     if (comp_template_args (TREE_PURPOSE (s), args))
900       return TREE_VALUE (s);
901
902   return NULL_TREE;
903 }
904
905 /* Like retrieve_specialization, but for local declarations.  */
906
907 static tree
908 retrieve_local_specialization (tmpl)
909      tree tmpl;
910 {
911   tree spec = 
912     (tree) htab_find_with_hash (local_specializations, tmpl,
913                                 htab_hash_pointer (tmpl));
914   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
915 }
916
917 /* Returns nonzero iff DECL is a specialization of TMPL.  */
918
919 int
920 is_specialization_of (decl, tmpl)
921      tree decl;
922      tree tmpl;
923 {
924   tree t;
925
926   if (TREE_CODE (decl) == FUNCTION_DECL)
927     {
928       for (t = decl; 
929            t != NULL_TREE;
930            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
931         if (t == tmpl)
932           return 1;
933     }
934   else 
935     {
936       my_friendly_assert (TREE_CODE (decl) == TYPE_DECL, 0);
937
938       for (t = TREE_TYPE (decl);
939            t != NULL_TREE;
940            t = CLASSTYPE_USE_TEMPLATE (t)
941              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
942         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
943           return 1;
944     }  
945
946   return 0;
947 }
948
949 /* Register the specialization SPEC as a specialization of TMPL with
950    the indicated ARGS.  Returns SPEC, or an equivalent prior
951    declaration, if available.  */
952
953 static tree
954 register_specialization (spec, tmpl, args)
955      tree spec;
956      tree tmpl;
957      tree args;
958 {
959   tree s;
960
961   my_friendly_assert (TREE_CODE (tmpl) == TEMPLATE_DECL, 0);
962
963   if (TREE_CODE (spec) == FUNCTION_DECL 
964       && uses_template_parms (DECL_TI_ARGS (spec)))
965     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
966        register it; we want the corresponding TEMPLATE_DECL instead.
967        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
968        the more obvious `uses_template_parms (spec)' to avoid problems
969        with default function arguments.  In particular, given
970        something like this:
971
972           template <class T> void f(T t1, T t = T())
973
974        the default argument expression is not substituted for in an
975        instantiation unless and until it is actually needed.  */
976     return spec;
977     
978   /* There should be as many levels of arguments as there are
979      levels of parameters.  */
980   my_friendly_assert (TMPL_ARGS_DEPTH (args) 
981                       == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)),
982                       0);
983
984   for (s = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
985        s != NULL_TREE;
986        s = TREE_CHAIN (s))
987     {
988       tree fn = TREE_VALUE (s);
989
990       /* We can sometimes try to re-register a specialization that we've
991          already got.  In particular, regenerate_decl_from_template
992          calls duplicate_decls which will update the specialization
993          list.  But, we'll still get called again here anyhow.  It's
994          more convenient to simply allow this than to try to prevent it.  */
995       if (fn == spec)
996         return spec;
997       else if (comp_template_args (TREE_PURPOSE (s), args))
998         {
999           if (DECL_TEMPLATE_SPECIALIZATION (spec))
1000             {
1001               if (DECL_TEMPLATE_INSTANTIATION (fn))
1002                 {
1003                   if (TREE_USED (fn) 
1004                       || DECL_EXPLICIT_INSTANTIATION (fn))
1005                     {
1006                       error ("specialization of %D after instantiation",
1007                                 fn);
1008                       return spec;
1009                     }
1010                   else
1011                     {
1012                       /* This situation should occur only if the first
1013                          specialization is an implicit instantiation,
1014                          the second is an explicit specialization, and
1015                          the implicit instantiation has not yet been
1016                          used.  That situation can occur if we have
1017                          implicitly instantiated a member function and
1018                          then specialized it later.
1019
1020                          We can also wind up here if a friend
1021                          declaration that looked like an instantiation
1022                          turns out to be a specialization:
1023
1024                            template <class T> void foo(T);
1025                            class S { friend void foo<>(int) };
1026                            template <> void foo(int);  
1027
1028                          We transform the existing DECL in place so that
1029                          any pointers to it become pointers to the
1030                          updated declaration.  
1031
1032                          If there was a definition for the template, but
1033                          not for the specialization, we want this to
1034                          look as if there is no definition, and vice
1035                          versa.  */
1036                       DECL_INITIAL (fn) = NULL_TREE;
1037                       duplicate_decls (spec, fn);
1038
1039                       return fn;
1040                     }
1041                 }
1042               else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1043                 {
1044                   if (!duplicate_decls (spec, fn) && DECL_INITIAL (spec))
1045                     /* Dup decl failed, but this is a new
1046                        definition. Set the line number so any errors
1047                        match this new definition. */
1048                     DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1049                   
1050                   return fn;
1051                 }
1052             }
1053         }
1054       }
1055
1056   DECL_TEMPLATE_SPECIALIZATIONS (tmpl)
1057      = tree_cons (args, spec, DECL_TEMPLATE_SPECIALIZATIONS (tmpl));
1058
1059   return spec;
1060 }
1061
1062 /* Unregister the specialization SPEC as a specialization of TMPL.
1063    Returns nonzero if the SPEC was listed as a specialization of
1064    TMPL.  */
1065
1066 static int
1067 unregister_specialization (spec, tmpl)
1068      tree spec;
1069      tree tmpl;
1070 {
1071   tree* s;
1072
1073   for (s = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
1074        *s != NULL_TREE;
1075        s = &TREE_CHAIN (*s))
1076     if (TREE_VALUE (*s) == spec)
1077       {
1078         *s = TREE_CHAIN (*s);
1079         return 1;
1080       }
1081
1082   return 0;
1083 }
1084
1085 /* Compare an entry in the local specializations hash table P1 (which
1086    is really a pointer to a TREE_LIST) with P2 (which is really a
1087    DECL).  */
1088
1089 static int
1090 eq_local_specializations (const void *p1, const void *p2)
1091 {
1092   return TREE_VALUE ((tree) p1) == (tree) p2;
1093 }
1094
1095 /* Hash P1, an entry in the local specializations table.  */
1096
1097 static hashval_t
1098 hash_local_specialization (const void* p1)
1099 {
1100   return htab_hash_pointer (TREE_VALUE ((tree) p1));
1101 }
1102
1103 /* Like register_specialization, but for local declarations.  We are
1104    registering SPEC, an instantiation of TMPL.  */
1105
1106 static void
1107 register_local_specialization (spec, tmpl)
1108      tree spec;
1109      tree tmpl;
1110 {
1111   void **slot;
1112
1113   slot = htab_find_slot_with_hash (local_specializations, tmpl, 
1114                                    htab_hash_pointer (tmpl), INSERT);
1115   *slot = build_tree_list (spec, tmpl);
1116 }
1117
1118 /* Print the list of candidate FNS in an error message.  */
1119
1120 void
1121 print_candidates (fns)
1122      tree fns;
1123 {
1124   tree fn;
1125
1126   const char *str = "candidates are:";
1127
1128   for (fn = fns; fn != NULL_TREE; fn = TREE_CHAIN (fn))
1129     {
1130       tree f;
1131
1132       for (f = TREE_VALUE (fn); f; f = OVL_NEXT (f))
1133         cp_error_at ("%s %+#D", str, OVL_CURRENT (f));
1134       str = "               ";
1135     }
1136 }
1137
1138 /* Returns the template (one of the functions given by TEMPLATE_ID)
1139    which can be specialized to match the indicated DECL with the
1140    explicit template args given in TEMPLATE_ID.  The DECL may be
1141    NULL_TREE if none is available.  In that case, the functions in
1142    TEMPLATE_ID are non-members.
1143
1144    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1145    specialization of a member template.
1146
1147    The template args (those explicitly specified and those deduced)
1148    are output in a newly created vector *TARGS_OUT.
1149
1150    If it is impossible to determine the result, an error message is
1151    issued.  The error_mark_node is returned to indicate failure.  */
1152
1153 static tree
1154 determine_specialization (template_id, decl, targs_out, 
1155                           need_member_template)
1156      tree template_id;
1157      tree decl;
1158      tree* targs_out;
1159      int need_member_template;
1160 {
1161   tree fns;
1162   tree targs;
1163   tree explicit_targs;
1164   tree candidates = NULL_TREE;
1165   tree templates = NULL_TREE;
1166
1167   *targs_out = NULL_TREE;
1168
1169   if (template_id == error_mark_node)
1170     return error_mark_node;
1171
1172   fns = TREE_OPERAND (template_id, 0);
1173   explicit_targs = TREE_OPERAND (template_id, 1);
1174
1175   if (fns == error_mark_node)
1176     return error_mark_node;
1177
1178   /* Check for baselinks.  */
1179   if (BASELINK_P (fns))
1180     fns = BASELINK_FUNCTIONS (fns);
1181
1182   if (!is_overloaded_fn (fns))
1183     {
1184       error ("`%D' is not a function template", fns);
1185       return error_mark_node;
1186     }
1187
1188   for (; fns; fns = OVL_NEXT (fns))
1189     {
1190       tree fn = OVL_CURRENT (fns);
1191
1192       if (TREE_CODE (fn) == TEMPLATE_DECL)
1193         {
1194           tree decl_arg_types;
1195
1196           /* DECL might be a specialization of FN.  */
1197
1198           /* Adjust the type of DECL in case FN is a static member.  */
1199           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1200           if (DECL_STATIC_FUNCTION_P (fn) 
1201               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1202             decl_arg_types = TREE_CHAIN (decl_arg_types);
1203
1204           /* Check that the number of function parameters matches.
1205              For example,
1206                template <class T> void f(int i = 0);
1207                template <> void f<int>();
1208              The specialization f<int> is invalid but is not caught
1209              by get_bindings below.  */
1210
1211           if (list_length (TYPE_ARG_TYPES (TREE_TYPE (fn)))
1212               != list_length (decl_arg_types))
1213             continue;
1214
1215           /* See whether this function might be a specialization of this
1216              template.  */
1217           targs = get_bindings (fn, decl, explicit_targs);
1218
1219           if (!targs)
1220             /* We cannot deduce template arguments that when used to
1221                specialize TMPL will produce DECL.  */
1222             continue;
1223
1224           /* Save this template, and the arguments deduced.  */
1225           templates = tree_cons (targs, fn, templates);
1226         }
1227       else if (need_member_template)
1228         /* FN is an ordinary member function, and we need a
1229            specialization of a member template.  */
1230         ;
1231       else if (TREE_CODE (fn) != FUNCTION_DECL)
1232         /* We can get IDENTIFIER_NODEs here in certain erroneous
1233            cases.  */
1234         ;
1235       else if (!DECL_FUNCTION_MEMBER_P (fn))
1236         /* This is just an ordinary non-member function.  Nothing can
1237            be a specialization of that.  */
1238         ;
1239       else if (DECL_ARTIFICIAL (fn))
1240         /* Cannot specialize functions that are created implicitly.  */
1241         ;
1242       else
1243         {
1244           tree decl_arg_types;
1245
1246           /* This is an ordinary member function.  However, since
1247              we're here, we can assume it's enclosing class is a
1248              template class.  For example,
1249              
1250                template <typename T> struct S { void f(); };
1251                template <> void S<int>::f() {}
1252
1253              Here, S<int>::f is a non-template, but S<int> is a
1254              template class.  If FN has the same type as DECL, we
1255              might be in business.  */
1256
1257           if (!DECL_TEMPLATE_INFO (fn))
1258             /* Its enclosing class is an explicit specialization
1259                of a template class.  This is not a candidate.  */
1260             continue;
1261
1262           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1263                             TREE_TYPE (TREE_TYPE (fn))))
1264             /* The return types differ.  */
1265             continue;
1266
1267           /* Adjust the type of DECL in case FN is a static member.  */
1268           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1269           if (DECL_STATIC_FUNCTION_P (fn) 
1270               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1271             decl_arg_types = TREE_CHAIN (decl_arg_types);
1272
1273           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)), 
1274                          decl_arg_types))
1275             /* They match!  */
1276             candidates = tree_cons (NULL_TREE, fn, candidates);
1277         }
1278     }
1279
1280   if (templates && TREE_CHAIN (templates))
1281     {
1282       /* We have:
1283          
1284            [temp.expl.spec]
1285
1286            It is possible for a specialization with a given function
1287            signature to be instantiated from more than one function
1288            template.  In such cases, explicit specification of the
1289            template arguments must be used to uniquely identify the
1290            function template specialization being specialized.
1291
1292          Note that here, there's no suggestion that we're supposed to
1293          determine which of the candidate templates is most
1294          specialized.  However, we, also have:
1295
1296            [temp.func.order]
1297
1298            Partial ordering of overloaded function template
1299            declarations is used in the following contexts to select
1300            the function template to which a function template
1301            specialization refers: 
1302
1303            -- when an explicit specialization refers to a function
1304               template. 
1305
1306          So, we do use the partial ordering rules, at least for now.
1307          This extension can only serve to make invalid programs valid,
1308          so it's safe.  And, there is strong anecdotal evidence that
1309          the committee intended the partial ordering rules to apply;
1310          the EDG front-end has that behavior, and John Spicer claims
1311          that the committee simply forgot to delete the wording in
1312          [temp.expl.spec].  */
1313      tree tmpl = most_specialized (templates, decl, explicit_targs);
1314      if (tmpl && tmpl != error_mark_node)
1315        {
1316          targs = get_bindings (tmpl, decl, explicit_targs);
1317          templates = tree_cons (targs, tmpl, NULL_TREE);
1318        }
1319     }
1320
1321   if (templates == NULL_TREE && candidates == NULL_TREE)
1322     {
1323       cp_error_at ("template-id `%D' for `%+D' does not match any template declaration",
1324                    template_id, decl);
1325       return error_mark_node;
1326     }
1327   else if ((templates && TREE_CHAIN (templates))
1328            || (candidates && TREE_CHAIN (candidates))
1329            || (templates && candidates))
1330     {
1331       cp_error_at ("ambiguous template specialization `%D' for `%+D'",
1332                    template_id, decl);
1333       chainon (candidates, templates);
1334       print_candidates (candidates);
1335       return error_mark_node;
1336     }
1337
1338   /* We have one, and exactly one, match.  */
1339   if (candidates)
1340     {
1341       /* It was a specialization of an ordinary member function in a
1342          template class.  */
1343       *targs_out = copy_node (DECL_TI_ARGS (TREE_VALUE (candidates)));
1344       return DECL_TI_TEMPLATE (TREE_VALUE (candidates));
1345     }
1346
1347   /* It was a specialization of a template.  */
1348   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
1349   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
1350     {
1351       *targs_out = copy_node (targs);
1352       SET_TMPL_ARGS_LEVEL (*targs_out, 
1353                            TMPL_ARGS_DEPTH (*targs_out),
1354                            TREE_PURPOSE (templates));
1355     }
1356   else
1357     *targs_out = TREE_PURPOSE (templates);
1358   return TREE_VALUE (templates);
1359 }
1360
1361 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
1362    but with the default argument values filled in from those in the
1363    TMPL_TYPES.  */
1364       
1365 static tree
1366 copy_default_args_to_explicit_spec_1 (spec_types,
1367                                       tmpl_types)
1368      tree spec_types;
1369      tree tmpl_types;
1370 {
1371   tree new_spec_types;
1372
1373   if (!spec_types)
1374     return NULL_TREE;
1375
1376   if (spec_types == void_list_node)
1377     return void_list_node;
1378
1379   /* Substitute into the rest of the list.  */
1380   new_spec_types =
1381     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
1382                                           TREE_CHAIN (tmpl_types));
1383   
1384   /* Add the default argument for this parameter.  */
1385   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
1386                          TREE_VALUE (spec_types),
1387                          new_spec_types);
1388 }
1389
1390 /* DECL is an explicit specialization.  Replicate default arguments
1391    from the template it specializes.  (That way, code like:
1392
1393      template <class T> void f(T = 3);
1394      template <> void f(double);
1395      void g () { f (); } 
1396
1397    works, as required.)  An alternative approach would be to look up
1398    the correct default arguments at the call-site, but this approach
1399    is consistent with how implicit instantiations are handled.  */
1400
1401 static void
1402 copy_default_args_to_explicit_spec (decl)
1403      tree decl;
1404 {
1405   tree tmpl;
1406   tree spec_types;
1407   tree tmpl_types;
1408   tree new_spec_types;
1409   tree old_type;
1410   tree new_type;
1411   tree t;
1412   tree object_type = NULL_TREE;
1413   tree in_charge = NULL_TREE;
1414   tree vtt = NULL_TREE;
1415
1416   /* See if there's anything we need to do.  */
1417   tmpl = DECL_TI_TEMPLATE (decl);
1418   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
1419   for (t = tmpl_types; t; t = TREE_CHAIN (t))
1420     if (TREE_PURPOSE (t))
1421       break;
1422   if (!t)
1423     return;
1424
1425   old_type = TREE_TYPE (decl);
1426   spec_types = TYPE_ARG_TYPES (old_type);
1427   
1428   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1429     {
1430       /* Remove the this pointer, but remember the object's type for
1431          CV quals.  */
1432       object_type = TREE_TYPE (TREE_VALUE (spec_types));
1433       spec_types = TREE_CHAIN (spec_types);
1434       tmpl_types = TREE_CHAIN (tmpl_types);
1435       
1436       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
1437         {
1438           /* DECL may contain more parameters than TMPL due to the extra
1439              in-charge parameter in constructors and destructors.  */
1440           in_charge = spec_types;
1441           spec_types = TREE_CHAIN (spec_types);
1442         }
1443       if (DECL_HAS_VTT_PARM_P (decl))
1444         {
1445           vtt = spec_types;
1446           spec_types = TREE_CHAIN (spec_types);
1447         }
1448     }
1449
1450   /* Compute the merged default arguments.  */
1451   new_spec_types = 
1452     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
1453
1454   /* Compute the new FUNCTION_TYPE.  */
1455   if (object_type)
1456     {
1457       if (vtt)
1458         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
1459                                          TREE_VALUE (vtt),
1460                                          new_spec_types);
1461
1462       if (in_charge)
1463         /* Put the in-charge parameter back.  */
1464         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
1465                                          TREE_VALUE (in_charge),
1466                                          new_spec_types);
1467
1468       new_type = build_cplus_method_type (object_type,
1469                                           TREE_TYPE (old_type),
1470                                           new_spec_types);
1471     }
1472   else
1473     new_type = build_function_type (TREE_TYPE (old_type),
1474                                     new_spec_types);
1475   new_type = build_type_attribute_variant (new_type,
1476                                            TYPE_ATTRIBUTES (old_type));
1477   new_type = build_exception_variant (new_type,
1478                                       TYPE_RAISES_EXCEPTIONS (old_type));
1479   TREE_TYPE (decl) = new_type;
1480 }
1481
1482 /* Check to see if the function just declared, as indicated in
1483    DECLARATOR, and in DECL, is a specialization of a function
1484    template.  We may also discover that the declaration is an explicit
1485    instantiation at this point.
1486
1487    Returns DECL, or an equivalent declaration that should be used
1488    instead if all goes well.  Issues an error message if something is
1489    amiss.  Returns error_mark_node if the error is not easily
1490    recoverable.
1491    
1492    FLAGS is a bitmask consisting of the following flags: 
1493
1494    2: The function has a definition.
1495    4: The function is a friend.
1496
1497    The TEMPLATE_COUNT is the number of references to qualifying
1498    template classes that appeared in the name of the function.  For
1499    example, in
1500
1501      template <class T> struct S { void f(); };
1502      void S<int>::f();
1503      
1504    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
1505    classes are not counted in the TEMPLATE_COUNT, so that in
1506
1507      template <class T> struct S {};
1508      template <> struct S<int> { void f(); }
1509      template <> void S<int>::f();
1510
1511    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
1512    invalid; there should be no template <>.)
1513
1514    If the function is a specialization, it is marked as such via
1515    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
1516    is set up correctly, and it is added to the list of specializations 
1517    for that template.  */
1518
1519 tree
1520 check_explicit_specialization (declarator, decl, template_count, flags)
1521      tree declarator;
1522      tree decl;
1523      int template_count;
1524      int flags;
1525 {
1526   int have_def = flags & 2;
1527   int is_friend = flags & 4;
1528   int specialization = 0;
1529   int explicit_instantiation = 0;
1530   int member_specialization = 0;
1531   tree ctype = DECL_CLASS_CONTEXT (decl);
1532   tree dname = DECL_NAME (decl);
1533   tmpl_spec_kind tsk;
1534
1535   tsk = current_tmpl_spec_kind (template_count);
1536
1537   switch (tsk)
1538     {
1539     case tsk_none:
1540       if (processing_specialization) 
1541         {
1542           specialization = 1;
1543           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1544         }
1545       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1546         {
1547           if (is_friend)
1548             /* This could be something like:
1549
1550                template <class T> void f(T);
1551                class S { friend void f<>(int); }  */
1552             specialization = 1;
1553           else
1554             {
1555               /* This case handles bogus declarations like template <>
1556                  template <class T> void f<int>(); */
1557
1558               error ("template-id `%D' in declaration of primary template",
1559                         declarator);
1560               return decl;
1561             }
1562         }
1563       break;
1564
1565     case tsk_invalid_member_spec:
1566       /* The error has already been reported in
1567          check_specialization_scope.  */
1568       return error_mark_node;
1569
1570     case tsk_invalid_expl_inst:
1571       error ("template parameter list used in explicit instantiation");
1572
1573       /* Fall through.  */
1574
1575     case tsk_expl_inst:
1576       if (have_def)
1577         error ("definition provided for explicit instantiation");
1578       
1579       explicit_instantiation = 1;
1580       break;
1581
1582     case tsk_excessive_parms:
1583       error ("too many template parameter lists in declaration of `%D'", 
1584                 decl);
1585       return error_mark_node;
1586
1587       /* Fall through.  */
1588     case tsk_expl_spec:
1589       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1590       if (ctype)
1591         member_specialization = 1;
1592       else
1593         specialization = 1;
1594       break;
1595      
1596     case tsk_insufficient_parms:
1597       if (template_header_count)
1598         {
1599           error("too few template parameter lists in declaration of `%D'", 
1600                    decl);
1601           return decl;
1602         }
1603       else if (ctype != NULL_TREE
1604                && !TYPE_BEING_DEFINED (ctype)
1605                && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype)
1606                && !is_friend)
1607         {
1608           /* For backwards compatibility, we accept:
1609
1610                template <class T> struct S { void f(); };
1611                void S<int>::f() {} // Missing template <>
1612
1613              That used to be valid C++.  */
1614           if (pedantic)
1615             pedwarn
1616               ("explicit specialization not preceded by `template <>'");
1617           specialization = 1;
1618           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1619         }
1620       break;
1621
1622     case tsk_template:
1623       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1624         {
1625           /* This case handles bogus declarations like template <>
1626              template <class T> void f<int>(); */
1627
1628           if (uses_template_parms (declarator))
1629             error ("partial specialization `%D' of function template",
1630                       declarator);
1631           else
1632             error ("template-id `%D' in declaration of primary template",
1633                       declarator);
1634           return decl;
1635         }
1636
1637       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
1638         /* This is a specialization of a member template, without
1639            specialization the containing class.  Something like:
1640
1641              template <class T> struct S {
1642                template <class U> void f (U); 
1643              };
1644              template <> template <class U> void S<int>::f(U) {}
1645              
1646            That's a specialization -- but of the entire template.  */
1647         specialization = 1;
1648       break;
1649
1650     default:
1651       abort ();
1652     }
1653
1654   if (specialization || member_specialization)
1655     {
1656       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
1657       for (; t; t = TREE_CHAIN (t))
1658         if (TREE_PURPOSE (t))
1659           {
1660             pedwarn
1661               ("default argument specified in explicit specialization");
1662             break;
1663           }
1664       if (current_lang_name == lang_name_c)
1665         error ("template specialization with C linkage");
1666     }
1667
1668   if (specialization || member_specialization || explicit_instantiation)
1669     {
1670       tree tmpl = NULL_TREE;
1671       tree targs = NULL_TREE;
1672
1673       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
1674       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
1675         {
1676           tree fns;
1677
1678           my_friendly_assert (TREE_CODE (declarator) == IDENTIFIER_NODE, 
1679                               0);
1680           if (!ctype)
1681             fns = IDENTIFIER_NAMESPACE_VALUE (dname);
1682           else
1683             fns = dname;
1684
1685           declarator = 
1686             lookup_template_function (fns, NULL_TREE);
1687         }
1688
1689       if (declarator == error_mark_node)
1690         return error_mark_node;
1691
1692       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
1693         {
1694           if (!explicit_instantiation)
1695             /* A specialization in class scope.  This is invalid,
1696                but the error will already have been flagged by
1697                check_specialization_scope.  */
1698             return error_mark_node;
1699           else
1700             {
1701               /* It's not valid to write an explicit instantiation in
1702                  class scope, e.g.:
1703
1704                    class C { template void f(); }
1705
1706                    This case is caught by the parser.  However, on
1707                    something like:
1708                
1709                    template class C { void f(); };
1710
1711                    (which is invalid) we can get here.  The error will be
1712                    issued later.  */
1713               ;
1714             }
1715
1716           return decl;
1717         }
1718       else if (TREE_CODE (TREE_OPERAND (declarator, 0)) == LOOKUP_EXPR)
1719         {
1720           /* A friend declaration.  We can't do much, because we don't
1721              know what this resolves to, yet.  */
1722           my_friendly_assert (is_friend != 0, 0);
1723           my_friendly_assert (!explicit_instantiation, 0);
1724           SET_DECL_IMPLICIT_INSTANTIATION (decl);
1725           return decl;
1726         } 
1727       else if (ctype != NULL_TREE 
1728                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
1729                    IDENTIFIER_NODE))
1730         {
1731           /* Find the list of functions in ctype that have the same
1732              name as the declared function.  */
1733           tree name = TREE_OPERAND (declarator, 0);
1734           tree fns = NULL_TREE;
1735           int idx;
1736
1737           if (constructor_name_p (name, ctype))
1738             {
1739               int is_constructor = DECL_CONSTRUCTOR_P (decl);
1740               
1741               if (is_constructor ? !TYPE_HAS_CONSTRUCTOR (ctype)
1742                   : !TYPE_HAS_DESTRUCTOR (ctype))
1743                 {
1744                   /* From [temp.expl.spec]:
1745                        
1746                      If such an explicit specialization for the member
1747                      of a class template names an implicitly-declared
1748                      special member function (clause _special_), the
1749                      program is ill-formed.  
1750
1751                      Similar language is found in [temp.explicit].  */
1752                   error ("specialization of implicitly-declared special member function");
1753                   return error_mark_node;
1754                 }
1755
1756               name = is_constructor ? ctor_identifier : dtor_identifier;
1757             }
1758
1759           if (!DECL_CONV_FN_P (decl))
1760             {
1761               idx = lookup_fnfields_1 (ctype, name);
1762               if (idx >= 0)
1763                 fns = TREE_VEC_ELT (CLASSTYPE_METHOD_VEC (ctype), idx);
1764             }
1765           else
1766             {
1767               tree methods;
1768
1769               /* For a type-conversion operator, we cannot do a
1770                  name-based lookup.  We might be looking for `operator
1771                  int' which will be a specialization of `operator T'.
1772                  So, we find *all* the conversion operators, and then
1773                  select from them.  */
1774               fns = NULL_TREE;
1775
1776               methods = CLASSTYPE_METHOD_VEC (ctype);
1777               if (methods)
1778                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
1779                      idx < TREE_VEC_LENGTH (methods); ++idx) 
1780                   {
1781                     tree ovl = TREE_VEC_ELT (methods, idx);
1782
1783                     if (!ovl || !DECL_CONV_FN_P (OVL_CURRENT (ovl)))
1784                       /* There are no more conversion functions.  */
1785                       break;
1786
1787                     /* Glue all these conversion functions together
1788                        with those we already have.  */
1789                     for (; ovl; ovl = OVL_NEXT (ovl))
1790                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
1791                   }
1792             }
1793               
1794           if (fns == NULL_TREE) 
1795             {
1796               error ("no member function `%D' declared in `%T'",
1797                         name, ctype);
1798               return error_mark_node;
1799             }
1800           else
1801             TREE_OPERAND (declarator, 0) = fns;
1802         }
1803       
1804       /* Figure out what exactly is being specialized at this point.
1805          Note that for an explicit instantiation, even one for a
1806          member function, we cannot tell apriori whether the
1807          instantiation is for a member template, or just a member
1808          function of a template class.  Even if a member template is
1809          being instantiated, the member template arguments may be
1810          elided if they can be deduced from the rest of the
1811          declaration.  */
1812       tmpl = determine_specialization (declarator, decl,
1813                                        &targs, 
1814                                        member_specialization);
1815             
1816       if (!tmpl || tmpl == error_mark_node)
1817         /* We couldn't figure out what this declaration was
1818            specializing.  */
1819         return error_mark_node;
1820       else
1821         {
1822           tree gen_tmpl = most_general_template (tmpl);
1823
1824           if (explicit_instantiation)
1825             {
1826               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
1827                  is done by do_decl_instantiation later.  */ 
1828
1829               int arg_depth = TMPL_ARGS_DEPTH (targs);
1830               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
1831
1832               if (arg_depth > parm_depth)
1833                 {
1834                   /* If TMPL is not the most general template (for
1835                      example, if TMPL is a friend template that is
1836                      injected into namespace scope), then there will
1837                      be too many levels of TARGS.  Remove some of them
1838                      here.  */
1839                   int i;
1840                   tree new_targs;
1841
1842                   new_targs = make_tree_vec (parm_depth);
1843                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
1844                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
1845                       = TREE_VEC_ELT (targs, i);
1846                   targs = new_targs;
1847                 }
1848                   
1849               return instantiate_template (tmpl, targs, tf_error);
1850             }
1851
1852           /* If this is a specialization of a member template of a
1853              template class.  In we want to return the TEMPLATE_DECL,
1854              not the specialization of it.  */
1855           if (tsk == tsk_template)
1856             {
1857               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
1858               DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl)) = NULL_TREE;
1859               if (have_def)
1860                 {
1861                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
1862                   DECL_SOURCE_LOCATION (DECL_TEMPLATE_RESULT (tmpl))
1863                     = DECL_SOURCE_LOCATION (decl);
1864                 }
1865               return tmpl;
1866             }
1867
1868           /* If we thought that the DECL was a member function, but it
1869              turns out to be specializing a static member function,
1870              make DECL a static member function as well.  */
1871           if (DECL_STATIC_FUNCTION_P (tmpl)
1872               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1873             {
1874               revert_static_member_fn (decl);
1875               last_function_parms = TREE_CHAIN (last_function_parms);
1876             }
1877
1878           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
1879           DECL_TEMPLATE_INFO (decl) = tree_cons (tmpl, targs, NULL_TREE);
1880
1881           /* Inherit default function arguments from the template
1882              DECL is specializing.  */
1883           copy_default_args_to_explicit_spec (decl);
1884
1885           /* This specialization has the same protection as the
1886              template it specializes.  */
1887           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
1888           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
1889
1890           if (is_friend && !have_def)
1891             /* This is not really a declaration of a specialization.
1892                It's just the name of an instantiation.  But, it's not
1893                a request for an instantiation, either.  */
1894             SET_DECL_IMPLICIT_INSTANTIATION (decl);
1895           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
1896             /* This is indeed a specialization.  In case of constructors
1897                and destructors, we need in-charge and not-in-charge
1898                versions in V3 ABI.  */
1899             clone_function_decl (decl, /*update_method_vec_p=*/0);
1900
1901           /* Register this specialization so that we can find it
1902              again.  */
1903           decl = register_specialization (decl, gen_tmpl, targs);
1904         }
1905     }
1906   
1907   return decl;
1908 }
1909
1910 /* TYPE is being declared.  Verify that the use of template headers
1911    and such is reasonable.  Issue error messages if not.  */
1912
1913 void
1914 maybe_check_template_type (type)
1915      tree type;
1916 {
1917   if (template_header_count)
1918     {
1919       /* We are in the scope of some `template <...>' header.  */
1920
1921       int context_depth 
1922         = template_class_depth_real (TYPE_CONTEXT (type),
1923                                      /*count_specializations=*/1);
1924
1925       if (template_header_count <= context_depth)
1926         /* This is OK; the template headers are for the context.  We
1927            are actually too lenient here; like
1928            check_explicit_specialization we should consider the number
1929            of template types included in the actual declaration.  For
1930            example, 
1931
1932              template <class T> struct S {
1933                template <class U> template <class V>
1934                struct I {};
1935              }; 
1936
1937            is invalid, but:
1938
1939              template <class T> struct S {
1940                template <class U> struct I;
1941              }; 
1942
1943              template <class T> template <class U.
1944              struct S<T>::I {};
1945
1946            is not.  */
1947         ; 
1948       else if (template_header_count > context_depth + 1)
1949         /* There are two many template parameter lists.  */
1950         error ("too many template parameter lists in declaration of `%T'", type); 
1951     }
1952 }
1953
1954 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
1955    parameters.  These are represented in the same format used for
1956    DECL_TEMPLATE_PARMS.  */
1957
1958 int comp_template_parms (parms1, parms2)
1959      tree parms1;
1960      tree parms2;
1961 {
1962   tree p1;
1963   tree p2;
1964
1965   if (parms1 == parms2)
1966     return 1;
1967
1968   for (p1 = parms1, p2 = parms2; 
1969        p1 != NULL_TREE && p2 != NULL_TREE;
1970        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
1971     {
1972       tree t1 = TREE_VALUE (p1);
1973       tree t2 = TREE_VALUE (p2);
1974       int i;
1975
1976       my_friendly_assert (TREE_CODE (t1) == TREE_VEC, 0);
1977       my_friendly_assert (TREE_CODE (t2) == TREE_VEC, 0);
1978
1979       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
1980         return 0;
1981
1982       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i) 
1983         {
1984           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
1985           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
1986
1987           if (TREE_CODE (parm1) != TREE_CODE (parm2))
1988             return 0;
1989
1990           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM)
1991             continue;
1992           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
1993             return 0;
1994         }
1995     }
1996
1997   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
1998     /* One set of parameters has more parameters lists than the
1999        other.  */
2000     return 0;
2001
2002   return 1;
2003 }
2004
2005 /* Complain if DECL shadows a template parameter.
2006
2007    [temp.local]: A template-parameter shall not be redeclared within its
2008    scope (including nested scopes).  */
2009
2010 void
2011 check_template_shadow (decl)
2012      tree decl;
2013 {
2014   tree olddecl;
2015
2016   /* If we're not in a template, we can't possibly shadow a template
2017      parameter.  */
2018   if (!current_template_parms)
2019     return;
2020
2021   /* Figure out what we're shadowing.  */
2022   if (TREE_CODE (decl) == OVERLOAD)
2023     decl = OVL_CURRENT (decl);
2024   olddecl = IDENTIFIER_VALUE (DECL_NAME (decl));
2025
2026   /* If there's no previous binding for this name, we're not shadowing
2027      anything, let alone a template parameter.  */
2028   if (!olddecl)
2029     return;
2030
2031   /* If we're not shadowing a template parameter, we're done.  Note
2032      that OLDDECL might be an OVERLOAD (or perhaps even an
2033      ERROR_MARK), so we can't just blithely assume it to be a _DECL
2034      node.  */
2035   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
2036     return;
2037
2038   /* We check for decl != olddecl to avoid bogus errors for using a
2039      name inside a class.  We check TPFI to avoid duplicate errors for
2040      inline member templates.  */
2041   if (decl == olddecl 
2042       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
2043     return;
2044
2045   cp_error_at ("declaration of `%#D'", decl);
2046   cp_error_at (" shadows template parm `%#D'", olddecl);
2047 }
2048
2049 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
2050    ORIG_LEVEL, DECL, and TYPE.  */
2051
2052 static tree
2053 build_template_parm_index (index, level, orig_level, decl, type)
2054      int index;
2055      int level;
2056      int orig_level;
2057      tree decl;
2058      tree type;
2059 {
2060   tree t = make_node (TEMPLATE_PARM_INDEX);
2061   TEMPLATE_PARM_IDX (t) = index;
2062   TEMPLATE_PARM_LEVEL (t) = level;
2063   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
2064   TEMPLATE_PARM_DECL (t) = decl;
2065   TREE_TYPE (t) = type;
2066   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
2067   TREE_READONLY (t) = TREE_READONLY (decl);
2068
2069   return t;
2070 }
2071
2072 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
2073    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
2074    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
2075    new one is created.  */
2076
2077 static tree 
2078 reduce_template_parm_level (index, type, levels)
2079      tree index;
2080      tree type;
2081      int levels;
2082 {
2083   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
2084       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
2085           != TEMPLATE_PARM_LEVEL (index) - levels))
2086     {
2087       tree orig_decl = TEMPLATE_PARM_DECL (index);
2088       tree decl, t;
2089       
2090       decl = build_decl (TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
2091       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
2092       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
2093       DECL_ARTIFICIAL (decl) = 1;
2094       SET_DECL_TEMPLATE_PARM_P (decl);
2095       
2096       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
2097                                      TEMPLATE_PARM_LEVEL (index) - levels,
2098                                      TEMPLATE_PARM_ORIG_LEVEL (index),
2099                                      decl, type);
2100       TEMPLATE_PARM_DESCENDANTS (index) = t;
2101
2102       /* Template template parameters need this.  */
2103       DECL_TEMPLATE_PARMS (decl)
2104         = DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index));
2105     }
2106
2107   return TEMPLATE_PARM_DESCENDANTS (index);
2108 }
2109
2110 /* Process information from new template parameter NEXT and append it to the
2111    LIST being built.  */
2112
2113 tree
2114 process_template_parm (list, next)
2115      tree list, next;
2116 {
2117   tree parm;
2118   tree decl = 0;
2119   tree defval;
2120   int is_type, idx;
2121
2122   parm = next;
2123   my_friendly_assert (TREE_CODE (parm) == TREE_LIST, 259);
2124   defval = TREE_PURPOSE (parm);
2125   parm = TREE_VALUE (parm);
2126   is_type = TREE_PURPOSE (parm) == class_type_node;
2127
2128   if (list)
2129     {
2130       tree p = TREE_VALUE (tree_last (list));
2131
2132       if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
2133         idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
2134       else
2135         idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
2136       ++idx;
2137     }
2138   else
2139     idx = 0;
2140
2141   if (!is_type)
2142     {
2143       my_friendly_assert (TREE_CODE (TREE_PURPOSE (parm)) == TREE_LIST, 260);
2144       /* is a const-param */
2145       parm = grokdeclarator (TREE_VALUE (parm), TREE_PURPOSE (parm),
2146                              PARM, 0, NULL);
2147       SET_DECL_TEMPLATE_PARM_P (parm);
2148
2149       /* [temp.param]
2150
2151          The top-level cv-qualifiers on the template-parameter are
2152          ignored when determining its type.  */
2153       TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
2154
2155       /* A template parameter is not modifiable.  */
2156       TREE_READONLY (parm) = TREE_CONSTANT (parm) = 1;
2157       if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
2158         TREE_TYPE (parm) = void_type_node;
2159       decl = build_decl (CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
2160       TREE_CONSTANT (decl) = TREE_READONLY (decl) = 1;
2161       DECL_INITIAL (parm) = DECL_INITIAL (decl) 
2162         = build_template_parm_index (idx, processing_template_decl,
2163                                      processing_template_decl,
2164                                      decl, TREE_TYPE (parm));
2165     }
2166   else
2167     {
2168       tree t;
2169       parm = TREE_VALUE (parm);
2170       
2171       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
2172         {
2173           t = make_aggr_type (TEMPLATE_TEMPLATE_PARM);
2174           /* This is for distinguishing between real templates and template 
2175              template parameters */
2176           TREE_TYPE (parm) = t;
2177           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
2178           decl = parm;
2179         }
2180       else
2181         {
2182           t = make_aggr_type (TEMPLATE_TYPE_PARM);
2183           /* parm is either IDENTIFIER_NODE or NULL_TREE */
2184           decl = build_decl (TYPE_DECL, parm, t);
2185         }
2186         
2187       TYPE_NAME (t) = decl;
2188       TYPE_STUB_DECL (t) = decl;
2189       parm = decl;
2190       TEMPLATE_TYPE_PARM_INDEX (t)
2191         = build_template_parm_index (idx, processing_template_decl, 
2192                                      processing_template_decl,
2193                                      decl, TREE_TYPE (parm));
2194     }
2195   DECL_ARTIFICIAL (decl) = 1;
2196   SET_DECL_TEMPLATE_PARM_P (decl);
2197   pushdecl (decl);
2198   parm = build_tree_list (defval, parm);
2199   return chainon (list, parm);
2200 }
2201
2202 /* The end of a template parameter list has been reached.  Process the
2203    tree list into a parameter vector, converting each parameter into a more
2204    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
2205    as PARM_DECLs.  */
2206
2207 tree
2208 end_template_parm_list (parms)
2209      tree parms;
2210 {
2211   int nparms;
2212   tree parm, next;
2213   tree saved_parmlist = make_tree_vec (list_length (parms));
2214
2215   current_template_parms
2216     = tree_cons (size_int (processing_template_decl),
2217                  saved_parmlist, current_template_parms);
2218
2219   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
2220     {
2221       next = TREE_CHAIN (parm);
2222       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
2223       TREE_CHAIN (parm) = NULL_TREE;
2224     }
2225
2226   --processing_template_parmlist;
2227
2228   return saved_parmlist;
2229 }
2230
2231 /* end_template_decl is called after a template declaration is seen.  */
2232
2233 void
2234 end_template_decl ()
2235 {
2236   reset_specialization ();
2237
2238   if (! processing_template_decl)
2239     return;
2240
2241   /* This matches the pushlevel in begin_template_parm_list.  */
2242   finish_scope ();
2243
2244   --processing_template_decl;
2245   current_template_parms = TREE_CHAIN (current_template_parms);
2246 }
2247
2248 /* Given a template argument vector containing the template PARMS.
2249    The innermost PARMS are given first.  */
2250
2251 tree
2252 current_template_args ()
2253 {
2254   tree header;
2255   tree args = NULL_TREE;
2256   int length = TMPL_PARMS_DEPTH (current_template_parms);
2257   int l = length;
2258
2259   /* If there is only one level of template parameters, we do not
2260      create a TREE_VEC of TREE_VECs.  Instead, we return a single
2261      TREE_VEC containing the arguments.  */
2262   if (length > 1)
2263     args = make_tree_vec (length);
2264
2265   for (header = current_template_parms; header; header = TREE_CHAIN (header))
2266     {
2267       tree a = copy_node (TREE_VALUE (header));
2268       int i;
2269
2270       TREE_TYPE (a) = NULL_TREE;
2271       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
2272         {
2273           tree t = TREE_VEC_ELT (a, i);
2274
2275           /* T will be a list if we are called from within a
2276              begin/end_template_parm_list pair, but a vector directly
2277              if within a begin/end_member_template_processing pair.  */
2278           if (TREE_CODE (t) == TREE_LIST) 
2279             {
2280               t = TREE_VALUE (t);
2281               
2282               if (TREE_CODE (t) == TYPE_DECL 
2283                   || TREE_CODE (t) == TEMPLATE_DECL)
2284                 t = TREE_TYPE (t);
2285               else
2286                 t = DECL_INITIAL (t);
2287               TREE_VEC_ELT (a, i) = t;
2288             }
2289         }
2290
2291       if (length > 1)
2292         TREE_VEC_ELT (args, --l) = a;
2293       else
2294         args = a;
2295     }
2296
2297   return args;
2298 }
2299
2300 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
2301    template PARMS.  Used by push_template_decl below.  */
2302
2303 static tree
2304 build_template_decl (decl, parms)
2305      tree decl;
2306      tree parms;
2307 {
2308   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
2309   DECL_TEMPLATE_PARMS (tmpl) = parms;
2310   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
2311   if (DECL_LANG_SPECIFIC (decl))
2312     {
2313       DECL_STATIC_FUNCTION_P (tmpl) = DECL_STATIC_FUNCTION_P (decl);
2314       DECL_CONSTRUCTOR_P (tmpl) = DECL_CONSTRUCTOR_P (decl);
2315       DECL_DESTRUCTOR_P (tmpl) = DECL_DESTRUCTOR_P (decl);
2316       DECL_NONCONVERTING_P (tmpl) = DECL_NONCONVERTING_P (decl);
2317       DECL_ASSIGNMENT_OPERATOR_P (tmpl) = DECL_ASSIGNMENT_OPERATOR_P (decl);
2318       if (DECL_OVERLOADED_OPERATOR_P (decl))
2319         SET_OVERLOADED_OPERATOR_CODE (tmpl, 
2320                                       DECL_OVERLOADED_OPERATOR_P (decl));
2321     }
2322
2323   return tmpl;
2324 }
2325
2326 struct template_parm_data
2327 {
2328   /* The level of the template parameters we are currently
2329      processing.  */
2330   int level;
2331
2332   /* The index of the specialization argument we are currently
2333      processing.  */
2334   int current_arg;
2335
2336   /* An array whose size is the number of template parameters.  The
2337      elements are nonzero if the parameter has been used in any one
2338      of the arguments processed so far.  */
2339   int* parms;
2340
2341   /* An array whose size is the number of template arguments.  The
2342      elements are nonzero if the argument makes use of template
2343      parameters of this level.  */
2344   int* arg_uses_template_parms;
2345 };
2346
2347 /* Subroutine of push_template_decl used to see if each template
2348    parameter in a partial specialization is used in the explicit
2349    argument list.  If T is of the LEVEL given in DATA (which is
2350    treated as a template_parm_data*), then DATA->PARMS is marked
2351    appropriately.  */
2352
2353 static int
2354 mark_template_parm (t, data)
2355      tree t;
2356      void* data;
2357 {
2358   int level;
2359   int idx;
2360   struct template_parm_data* tpd = (struct template_parm_data*) data;
2361
2362   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
2363     {
2364       level = TEMPLATE_PARM_LEVEL (t);
2365       idx = TEMPLATE_PARM_IDX (t);
2366     }
2367   else
2368     {
2369       level = TEMPLATE_TYPE_LEVEL (t);
2370       idx = TEMPLATE_TYPE_IDX (t);
2371     }
2372
2373   if (level == tpd->level)
2374     {
2375       tpd->parms[idx] = 1;
2376       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
2377     }
2378
2379   /* Return zero so that for_each_template_parm will continue the
2380      traversal of the tree; we want to mark *every* template parm.  */
2381   return 0;
2382 }
2383
2384 /* Process the partial specialization DECL.  */
2385
2386 static tree
2387 process_partial_specialization (decl)
2388      tree decl;
2389 {
2390   tree type = TREE_TYPE (decl);
2391   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
2392   tree specargs = CLASSTYPE_TI_ARGS (type);
2393   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
2394   tree inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
2395   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
2396   int nargs = TREE_VEC_LENGTH (inner_args);
2397   int ntparms = TREE_VEC_LENGTH (inner_parms);
2398   int  i;
2399   int did_error_intro = 0;
2400   struct template_parm_data tpd;
2401   struct template_parm_data tpd2;
2402
2403   /* We check that each of the template parameters given in the
2404      partial specialization is used in the argument list to the
2405      specialization.  For example:
2406
2407        template <class T> struct S;
2408        template <class T> struct S<T*>;
2409
2410      The second declaration is OK because `T*' uses the template
2411      parameter T, whereas
2412
2413        template <class T> struct S<int>;
2414
2415      is no good.  Even trickier is:
2416
2417        template <class T>
2418        struct S1
2419        {
2420           template <class U>
2421           struct S2;
2422           template <class U>
2423           struct S2<T>;
2424        };
2425
2426      The S2<T> declaration is actually invalid; it is a
2427      full-specialization.  Of course, 
2428
2429           template <class U>
2430           struct S2<T (*)(U)>;
2431
2432      or some such would have been OK.  */
2433   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
2434   tpd.parms = alloca (sizeof (int) * ntparms);
2435   memset ((PTR) tpd.parms, 0, sizeof (int) * ntparms);
2436
2437   tpd.arg_uses_template_parms = alloca (sizeof (int) * nargs);
2438   memset ((PTR) tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
2439   for (i = 0; i < nargs; ++i)
2440     {
2441       tpd.current_arg = i;
2442       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
2443                               &mark_template_parm,
2444                               &tpd,
2445                               NULL);
2446     }
2447   for (i = 0; i < ntparms; ++i)
2448     if (tpd.parms[i] == 0)
2449       {
2450         /* One of the template parms was not used in the
2451            specialization.  */
2452         if (!did_error_intro)
2453           {
2454             error ("template parameters not used in partial specialization:");
2455             did_error_intro = 1;
2456           }
2457
2458         error ("        `%D'", 
2459                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
2460       }
2461
2462   /* [temp.class.spec]
2463
2464      The argument list of the specialization shall not be identical to
2465      the implicit argument list of the primary template.  */
2466   if (comp_template_args 
2467       (inner_args, 
2468        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
2469                                                    (maintmpl)))))
2470     error ("partial specialization `%T' does not specialize any template arguments", type);
2471
2472   /* [temp.class.spec]
2473
2474      A partially specialized non-type argument expression shall not
2475      involve template parameters of the partial specialization except
2476      when the argument expression is a simple identifier.
2477
2478      The type of a template parameter corresponding to a specialized
2479      non-type argument shall not be dependent on a parameter of the
2480      specialization.  */
2481   my_friendly_assert (nargs == DECL_NTPARMS (maintmpl), 0);
2482   tpd2.parms = 0;
2483   for (i = 0; i < nargs; ++i)
2484     {
2485       tree arg = TREE_VEC_ELT (inner_args, i);
2486       if (/* These first two lines are the `non-type' bit.  */
2487           !TYPE_P (arg)
2488           && TREE_CODE (arg) != TEMPLATE_DECL
2489           /* This next line is the `argument expression is not just a
2490              simple identifier' condition and also the `specialized
2491              non-type argument' bit.  */
2492           && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
2493         {
2494           if (tpd.arg_uses_template_parms[i])
2495             error ("template argument `%E' involves template parameter(s)", arg);
2496           else 
2497             {
2498               /* Look at the corresponding template parameter,
2499                  marking which template parameters its type depends
2500                  upon.  */
2501               tree type = 
2502                 TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (main_inner_parms, 
2503                                                      i)));
2504
2505               if (!tpd2.parms)
2506                 {
2507                   /* We haven't yet initialized TPD2.  Do so now.  */
2508                   tpd2.arg_uses_template_parms 
2509                     =  (int*) alloca (sizeof (int) * nargs);
2510                   /* The number of parameters here is the number in the
2511                      main template, which, as checked in the assertion
2512                      above, is NARGS.  */
2513                   tpd2.parms = (int*) alloca (sizeof (int) * nargs);
2514                   tpd2.level = 
2515                     TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
2516                 }
2517
2518               /* Mark the template parameters.  But this time, we're
2519                  looking for the template parameters of the main
2520                  template, not in the specialization.  */
2521               tpd2.current_arg = i;
2522               tpd2.arg_uses_template_parms[i] = 0;
2523               memset ((PTR) tpd2.parms, 0, sizeof (int) * nargs);
2524               for_each_template_parm (type,
2525                                       &mark_template_parm,
2526                                       &tpd2,
2527                                       NULL);
2528                   
2529               if (tpd2.arg_uses_template_parms [i])
2530                 {
2531                   /* The type depended on some template parameters.
2532                      If they are fully specialized in the
2533                      specialization, that's OK.  */
2534                   int j;
2535                   for (j = 0; j < nargs; ++j)
2536                     if (tpd2.parms[j] != 0
2537                         && tpd.arg_uses_template_parms [j])
2538                       {
2539                         error ("type `%T' of template argument `%E' depends on template parameter(s)", 
2540                                   type,
2541                                   arg);
2542                         break;
2543                       }
2544                 }
2545             }
2546         }
2547     }
2548
2549   if (retrieve_specialization (maintmpl, specargs))
2550     /* We've already got this specialization.  */
2551     return decl;
2552
2553   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
2554     = tree_cons (inner_args, inner_parms,
2555                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
2556   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
2557   return decl;
2558 }
2559
2560 /* Check that a template declaration's use of default arguments is not
2561    invalid.  Here, PARMS are the template parameters.  IS_PRIMARY is
2562    nonzero if DECL is the thing declared by a primary template.
2563    IS_PARTIAL is nonzero if DECL is a partial specialization.  */
2564
2565 static void
2566 check_default_tmpl_args (decl, parms, is_primary, is_partial)
2567      tree decl;
2568      tree parms;
2569      int is_primary;
2570      int is_partial;
2571 {
2572   const char *msg;
2573   int last_level_to_check;
2574   tree parm_level;
2575
2576   /* [temp.param] 
2577
2578      A default template-argument shall not be specified in a
2579      function template declaration or a function template definition, nor
2580      in the template-parameter-list of the definition of a member of a
2581      class template.  */
2582
2583   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
2584     /* You can't have a function template declaration in a local
2585        scope, nor you can you define a member of a class template in a
2586        local scope.  */
2587     return;
2588
2589   if (current_class_type
2590       && !TYPE_BEING_DEFINED (current_class_type)
2591       && DECL_LANG_SPECIFIC (decl)
2592       /* If this is either a friend defined in the scope of the class
2593          or a member function.  */
2594       && ((DECL_CONTEXT (decl) 
2595            && same_type_p (DECL_CONTEXT (decl), current_class_type))
2596           || (DECL_FRIEND_CONTEXT (decl)
2597               && same_type_p (DECL_FRIEND_CONTEXT (decl), 
2598                               current_class_type)))
2599       /* And, if it was a member function, it really was defined in
2600          the scope of the class.  */
2601       && (!DECL_FUNCTION_MEMBER_P (decl) || DECL_INITIALIZED_IN_CLASS_P (decl)))
2602     /* We already checked these parameters when the template was
2603        declared, so there's no need to do it again now.  This function
2604        was defined in class scope, but we're processing it's body now
2605        that the class is complete.  */
2606     return;
2607
2608   /* [temp.param]
2609          
2610      If a template-parameter has a default template-argument, all
2611      subsequent template-parameters shall have a default
2612      template-argument supplied.  */
2613   for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
2614     {
2615       tree inner_parms = TREE_VALUE (parm_level);
2616       int ntparms = TREE_VEC_LENGTH (inner_parms);
2617       int seen_def_arg_p = 0; 
2618       int i;
2619
2620       for (i = 0; i < ntparms; ++i) 
2621         {
2622           tree parm = TREE_VEC_ELT (inner_parms, i);
2623           if (TREE_PURPOSE (parm))
2624             seen_def_arg_p = 1;
2625           else if (seen_def_arg_p)
2626             {
2627               error ("no default argument for `%D'", TREE_VALUE (parm));
2628               /* For better subsequent error-recovery, we indicate that
2629                  there should have been a default argument.  */
2630               TREE_PURPOSE (parm) = error_mark_node;
2631             }
2632         }
2633     }
2634
2635   if (TREE_CODE (decl) != TYPE_DECL || is_partial || !is_primary)
2636     /* For an ordinary class template, default template arguments are
2637        allowed at the innermost level, e.g.:
2638          template <class T = int>
2639          struct S {};
2640        but, in a partial specialization, they're not allowed even
2641        there, as we have in [temp.class.spec]:
2642      
2643          The template parameter list of a specialization shall not
2644          contain default template argument values.  
2645
2646        So, for a partial specialization, or for a function template,
2647        we look at all of them.  */
2648     ;
2649   else
2650     /* But, for a primary class template that is not a partial
2651        specialization we look at all template parameters except the
2652        innermost ones.  */
2653     parms = TREE_CHAIN (parms);
2654
2655   /* Figure out what error message to issue.  */
2656   if (TREE_CODE (decl) == FUNCTION_DECL)
2657     msg = "default template arguments may not be used in function templates";
2658   else if (is_partial)
2659     msg = "default template arguments may not be used in partial specializations";
2660   else
2661     msg = "default argument for template parameter for class enclosing `%D'";
2662
2663   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
2664     /* If we're inside a class definition, there's no need to
2665        examine the parameters to the class itself.  On the one
2666        hand, they will be checked when the class is defined, and,
2667        on the other, default arguments are valid in things like:
2668          template <class T = double>
2669          struct S { template <class U> void f(U); };
2670        Here the default argument for `S' has no bearing on the
2671        declaration of `f'.  */
2672     last_level_to_check = template_class_depth (current_class_type) + 1;
2673   else
2674     /* Check everything.  */
2675     last_level_to_check = 0;
2676
2677   for (parm_level = parms; 
2678        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check; 
2679        parm_level = TREE_CHAIN (parm_level))
2680     {
2681       tree inner_parms = TREE_VALUE (parm_level);
2682       int i;
2683       int ntparms;
2684
2685       ntparms = TREE_VEC_LENGTH (inner_parms);
2686       for (i = 0; i < ntparms; ++i) 
2687         if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
2688           {
2689             if (msg)
2690               {
2691                 error (msg, decl);
2692                 msg = 0;
2693               }
2694
2695             /* Clear out the default argument so that we are not
2696                confused later.  */
2697             TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
2698           }
2699
2700       /* At this point, if we're still interested in issuing messages,
2701          they must apply to classes surrounding the object declared.  */
2702       if (msg)
2703         msg = "default argument for template parameter for class enclosing `%D'"; 
2704     }
2705 }
2706
2707 /* Worker for push_template_decl_real, called via
2708    for_each_template_parm.  DATA is really an int, indicating the
2709    level of the parameters we are interested in.  If T is a template
2710    parameter of that level, return nonzero.  */
2711
2712 static int
2713 template_parm_this_level_p (t, data)
2714      tree t;
2715      void *data;
2716 {
2717   int this_level = *(int *)data;
2718   int level;
2719
2720   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
2721     level = TEMPLATE_PARM_LEVEL (t);
2722   else
2723     level = TEMPLATE_TYPE_LEVEL (t);
2724   return level == this_level;
2725 }
2726
2727 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
2728    parameters given by current_template_args, or reuses a
2729    previously existing one, if appropriate.  Returns the DECL, or an
2730    equivalent one, if it is replaced via a call to duplicate_decls.  
2731
2732    If IS_FRIEND is nonzero, DECL is a friend declaration.  */
2733
2734 tree
2735 push_template_decl_real (decl, is_friend)
2736      tree decl;
2737      int is_friend;
2738 {
2739   tree tmpl;
2740   tree args;
2741   tree info;
2742   tree ctx;
2743   int primary;
2744   int is_partial;
2745   int new_template_p = 0;
2746
2747   /* See if this is a partial specialization.  */
2748   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
2749                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
2750                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
2751
2752   is_friend |= (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl));
2753
2754   if (is_friend)
2755     /* For a friend, we want the context of the friend function, not
2756        the type of which it is a friend.  */
2757     ctx = DECL_CONTEXT (decl);
2758   else if (CP_DECL_CONTEXT (decl)
2759            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
2760     /* In the case of a virtual function, we want the class in which
2761        it is defined.  */
2762     ctx = CP_DECL_CONTEXT (decl);
2763   else
2764     /* Otherwise, if we're currently defining some class, the DECL
2765        is assumed to be a member of the class.  */
2766     ctx = current_scope ();
2767
2768   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
2769     ctx = NULL_TREE;
2770
2771   if (!DECL_CONTEXT (decl))
2772     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
2773
2774   /* See if this is a primary template.  */
2775   primary = template_parm_scope_p ();
2776
2777   if (primary)
2778     {
2779       if (current_lang_name == lang_name_c)
2780         error ("template with C linkage");
2781       else if (TREE_CODE (decl) == TYPE_DECL 
2782                && ANON_AGGRNAME_P (DECL_NAME (decl))) 
2783         error ("template class without a name");
2784       else if ((DECL_IMPLICIT_TYPEDEF_P (decl)
2785                 && CLASS_TYPE_P (TREE_TYPE (decl)))
2786                || (TREE_CODE (decl) == VAR_DECL && ctx && CLASS_TYPE_P (ctx))
2787                || TREE_CODE (decl) == FUNCTION_DECL)
2788         /* OK */;
2789       else
2790         error ("template declaration of `%#D'", decl);
2791     }
2792
2793   /* Check to see that the rules regarding the use of default
2794      arguments are not being violated.  */
2795   check_default_tmpl_args (decl, current_template_parms, 
2796                            primary, is_partial);
2797
2798   if (is_partial)
2799     return process_partial_specialization (decl);
2800
2801   args = current_template_args ();
2802
2803   if (!ctx 
2804       || TREE_CODE (ctx) == FUNCTION_DECL
2805       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
2806       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
2807     {
2808       if (DECL_LANG_SPECIFIC (decl)
2809           && DECL_TEMPLATE_INFO (decl)
2810           && DECL_TI_TEMPLATE (decl))
2811         tmpl = DECL_TI_TEMPLATE (decl);
2812       /* If DECL is a TYPE_DECL for a class-template, then there won't
2813          be DECL_LANG_SPECIFIC.  The information equivalent to
2814          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
2815       else if (DECL_IMPLICIT_TYPEDEF_P (decl) 
2816                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
2817                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
2818         {
2819           /* Since a template declaration already existed for this
2820              class-type, we must be redeclaring it here.  Make sure
2821              that the redeclaration is valid.  */
2822           redeclare_class_template (TREE_TYPE (decl),
2823                                     current_template_parms);
2824           /* We don't need to create a new TEMPLATE_DECL; just use the
2825              one we already had.  */
2826           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
2827         }
2828       else
2829         {
2830           tmpl = build_template_decl (decl, current_template_parms);
2831           new_template_p = 1;
2832
2833           if (DECL_LANG_SPECIFIC (decl)
2834               && DECL_TEMPLATE_SPECIALIZATION (decl))
2835             {
2836               /* A specialization of a member template of a template
2837                  class.  */
2838               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2839               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
2840               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
2841             }
2842         }
2843     }
2844   else
2845     {
2846       tree a, t, current, parms;
2847       int i;
2848
2849       if (TREE_CODE (decl) == TYPE_DECL)
2850         {
2851           if ((IS_AGGR_TYPE_CODE (TREE_CODE (TREE_TYPE (decl)))
2852                || TREE_CODE (TREE_TYPE (decl)) == ENUMERAL_TYPE)
2853               && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
2854               && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
2855             tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
2856           else
2857             {
2858               error ("`%D' does not declare a template type", decl);
2859               return decl;
2860             }
2861         }
2862       else if (!DECL_LANG_SPECIFIC (decl) || !DECL_TEMPLATE_INFO (decl))
2863         {
2864           error ("template definition of non-template `%#D'", decl);
2865           return decl;
2866         }
2867       else
2868         tmpl = DECL_TI_TEMPLATE (decl);
2869       
2870       if (is_member_template (tmpl)
2871           && DECL_FUNCTION_TEMPLATE_P (tmpl)
2872           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl) 
2873           && DECL_TEMPLATE_SPECIALIZATION (decl))
2874         {
2875           tree new_tmpl;
2876
2877           /* The declaration is a specialization of a member
2878              template, declared outside the class.  Therefore, the
2879              innermost template arguments will be NULL, so we
2880              replace them with the arguments determined by the
2881              earlier call to check_explicit_specialization.  */
2882           args = DECL_TI_ARGS (decl);
2883
2884           new_tmpl 
2885             = build_template_decl (decl, current_template_parms);
2886           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
2887           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
2888           DECL_TI_TEMPLATE (decl) = new_tmpl;
2889           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
2890           DECL_TEMPLATE_INFO (new_tmpl) 
2891             = tree_cons (tmpl, args, NULL_TREE);
2892
2893           register_specialization (new_tmpl, 
2894                                    most_general_template (tmpl), 
2895                                    args);
2896           return decl;
2897         }
2898
2899       /* Make sure the template headers we got make sense.  */
2900
2901       parms = DECL_TEMPLATE_PARMS (tmpl);
2902       i = TMPL_PARMS_DEPTH (parms);
2903       if (TMPL_ARGS_DEPTH (args) != i)
2904         {
2905           error ("expected %d levels of template parms for `%#D', got %d",
2906                     i, decl, TMPL_ARGS_DEPTH (args));
2907         }
2908       else
2909         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
2910           {
2911             a = TMPL_ARGS_LEVEL (args, i);
2912             t = INNERMOST_TEMPLATE_PARMS (parms);
2913
2914             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
2915               {
2916                 if (current == decl)
2917                   error ("got %d template parameters for `%#D'",
2918                             TREE_VEC_LENGTH (a), decl);
2919                 else
2920                   error ("got %d template parameters for `%#T'",
2921                             TREE_VEC_LENGTH (a), current);
2922                 error ("  but %d required", TREE_VEC_LENGTH (t));
2923               }
2924
2925             /* Perhaps we should also check that the parms are used in the
2926                appropriate qualifying scopes in the declarator?  */
2927
2928             if (current == decl)
2929               current = ctx;
2930             else
2931               current = TYPE_CONTEXT (current);
2932           }
2933     }
2934
2935   DECL_TEMPLATE_RESULT (tmpl) = decl;
2936   TREE_TYPE (tmpl) = TREE_TYPE (decl);
2937
2938   /* Push template declarations for global functions and types.  Note
2939      that we do not try to push a global template friend declared in a
2940      template class; such a thing may well depend on the template
2941      parameters of the class.  */
2942   if (new_template_p && !ctx 
2943       && !(is_friend && template_class_depth (current_class_type) > 0))
2944     tmpl = pushdecl_namespace_level (tmpl);
2945
2946   if (primary)
2947     {
2948       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
2949       if (DECL_CONV_FN_P (tmpl))
2950         {
2951           int depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2952
2953           /* It is a conversion operator. See if the type converted to
2954              depends on innermost template operands.  */
2955           
2956           if (for_each_template_parm (TREE_TYPE (TREE_TYPE (tmpl)),
2957                                       template_parm_this_level_p,
2958                                       &depth,
2959                                       NULL))
2960             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
2961         }
2962     }
2963
2964   info = tree_cons (tmpl, args, NULL_TREE);
2965
2966   if (DECL_IMPLICIT_TYPEDEF_P (decl))
2967     {
2968       SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
2969       if ((!ctx || TREE_CODE (ctx) != FUNCTION_DECL)
2970           && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
2971           /* Don't change the name if we've already set it up.  */
2972           && !IDENTIFIER_TEMPLATE (DECL_NAME (decl)))
2973         DECL_NAME (decl) = classtype_mangled_name (TREE_TYPE (decl));
2974     }
2975   else if (DECL_LANG_SPECIFIC (decl))
2976     DECL_TEMPLATE_INFO (decl) = info;
2977
2978   return DECL_TEMPLATE_RESULT (tmpl);
2979 }
2980
2981 tree
2982 push_template_decl (decl)
2983      tree decl;
2984 {
2985   return push_template_decl_real (decl, 0);
2986 }
2987
2988 /* Called when a class template TYPE is redeclared with the indicated
2989    template PARMS, e.g.:
2990
2991      template <class T> struct S;
2992      template <class T> struct S {};  */
2993
2994 void 
2995 redeclare_class_template (type, parms)
2996      tree type;
2997      tree parms;
2998 {
2999   tree tmpl;
3000   tree tmpl_parms;
3001   int i;
3002
3003   if (!TYPE_TEMPLATE_INFO (type))
3004     {
3005       error ("`%T' is not a template type", type);
3006       return;
3007     }
3008
3009   tmpl = TYPE_TI_TEMPLATE (type);
3010   if (!PRIMARY_TEMPLATE_P (tmpl))
3011     /* The type is nested in some template class.  Nothing to worry
3012        about here; there are no new template parameters for the nested
3013        type.  */
3014     return;
3015
3016   parms = INNERMOST_TEMPLATE_PARMS (parms);
3017   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
3018
3019   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
3020     {
3021       cp_error_at ("previous declaration `%D'", tmpl);
3022       error ("used %d template parameter%s instead of %d",
3023                 TREE_VEC_LENGTH (tmpl_parms), 
3024                 TREE_VEC_LENGTH (tmpl_parms) == 1 ? "" : "s",
3025                 TREE_VEC_LENGTH (parms));
3026       return;
3027     }
3028
3029   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
3030     {
3031       tree tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
3032       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
3033       tree tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
3034       tree parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
3035
3036       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm))
3037         {
3038           cp_error_at ("template parameter `%#D'", tmpl_parm);
3039           error ("redeclared here as `%#D'", parm);
3040           return;
3041         }
3042
3043       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
3044         {
3045           /* We have in [temp.param]:
3046
3047              A template-parameter may not be given default arguments
3048              by two different declarations in the same scope.  */
3049           error ("redefinition of default argument for `%#D'", parm);
3050           cp_error_at ("  original definition appeared here", tmpl_parm);
3051           return;
3052         }
3053
3054       if (parm_default != NULL_TREE)
3055         /* Update the previous template parameters (which are the ones
3056            that will really count) with the new default value.  */
3057         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
3058       else if (tmpl_default != NULL_TREE)
3059         /* Update the new parameters, too; they'll be used as the
3060            parameters for any members.  */
3061         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
3062     }
3063 }
3064
3065 /* Attempt to convert the non-type template parameter EXPR to the
3066    indicated TYPE.  If the conversion is successful, return the
3067    converted value.  If the conversion is unsuccessful, return
3068    NULL_TREE if we issued an error message, or error_mark_node if we
3069    did not.  We issue error messages for out-and-out bad template
3070    parameters, but not simply because the conversion failed, since we
3071    might be just trying to do argument deduction.  By the time this
3072    function is called, neither TYPE nor EXPR may make use of template
3073    parameters.  */
3074
3075 static tree
3076 convert_nontype_argument (type, expr)
3077      tree type;
3078      tree expr;
3079 {
3080   tree expr_type = TREE_TYPE (expr);
3081
3082   /* A template-argument for a non-type, non-template
3083      template-parameter shall be one of:
3084
3085      --an integral constant-expression of integral or enumeration
3086      type; or
3087      
3088      --the name of a non-type template-parameter; or
3089      
3090      --the name of an object or function with external linkage,
3091      including function templates and function template-ids but
3092      excluding non-static class members, expressed as id-expression;
3093      or
3094      
3095      --the address of an object or function with external linkage,
3096      including function templates and function template-ids but
3097      excluding non-static class members, expressed as & id-expression
3098      where the & is optional if the name refers to a function or
3099      array; or
3100      
3101      --a pointer to member expressed as described in _expr.unary.op_.  */
3102
3103   /* An integral constant-expression can include const variables or
3104      enumerators.  Simplify things by folding them to their values,
3105      unless we're about to bind the declaration to a reference
3106      parameter.  */
3107   if (INTEGRAL_TYPE_P (expr_type)
3108       && TREE_CODE (type) != REFERENCE_TYPE)
3109     expr = decl_constant_value (expr);
3110
3111   if (is_overloaded_fn (expr))
3112     /* OK for now.  We'll check that it has external linkage later.
3113        Check this first since if expr_type is the unknown_type_node
3114        we would otherwise complain below.  */
3115     ;
3116   else if (TYPE_PTRMEM_P (expr_type)
3117            || TYPE_PTRMEMFUNC_P (expr_type))
3118     {
3119       if (TREE_CODE (expr) != PTRMEM_CST)
3120         goto bad_argument;
3121     }
3122   else if (TYPE_PTR_P (expr_type)
3123            || TYPE_PTRMEM_P (expr_type)
3124            || TREE_CODE (expr_type) == ARRAY_TYPE
3125            || TREE_CODE (type) == REFERENCE_TYPE
3126            /* If expr is the address of an overloaded function, we
3127               will get the unknown_type_node at this point.  */
3128            || expr_type == unknown_type_node)
3129     {
3130       tree referent;
3131       tree e = expr;
3132       STRIP_NOPS (e);
3133
3134       if (TREE_CODE (expr_type) == ARRAY_TYPE
3135           || (TREE_CODE (type) == REFERENCE_TYPE
3136               && TREE_CODE (e) != ADDR_EXPR))
3137         referent = e;
3138       else
3139         {
3140           if (TREE_CODE (e) != ADDR_EXPR)
3141             {
3142             bad_argument:
3143               error ("`%E' is not a valid template argument", expr);
3144               if (TYPE_PTR_P (expr_type))
3145                 {
3146                   if (TREE_CODE (TREE_TYPE (expr_type)) == FUNCTION_TYPE)
3147                     error ("it must be the address of a function with external linkage");
3148                   else
3149                     error ("it must be the address of an object with external linkage");
3150                 }
3151               else if (TYPE_PTRMEM_P (expr_type)
3152                        || TYPE_PTRMEMFUNC_P (expr_type))
3153                 error ("it must be a pointer-to-member of the form `&X::Y'");
3154
3155               return NULL_TREE;
3156             }
3157
3158           referent = TREE_OPERAND (e, 0);
3159           STRIP_NOPS (referent);
3160         }
3161
3162       if (TREE_CODE (referent) == STRING_CST)
3163         {
3164           error ("string literal %E is not a valid template argument because it is the address of an object with static linkage", 
3165                     referent);
3166           return NULL_TREE;
3167         }
3168
3169       if (is_overloaded_fn (referent))
3170         /* We'll check that it has external linkage later.  */
3171         ;
3172       else if (TREE_CODE (referent) != VAR_DECL)
3173         goto bad_argument;
3174       else if (!DECL_EXTERNAL_LINKAGE_P (referent))
3175         {
3176           error ("address of non-extern `%E' cannot be used as template argument", referent); 
3177           return error_mark_node;
3178         }
3179     }
3180   else if (INTEGRAL_TYPE_P (expr_type) 
3181            || TYPE_PTRMEM_P (expr_type) 
3182            || TYPE_PTRMEMFUNC_P (expr_type))
3183     {
3184       if (! TREE_CONSTANT (expr))
3185         {
3186         non_constant:
3187           error ("non-constant `%E' cannot be used as template argument",
3188                     expr);
3189           return NULL_TREE;
3190         }
3191     }
3192   else 
3193     {
3194       error ("object `%E' cannot be used as template argument", expr);
3195       return NULL_TREE;
3196     }
3197
3198   switch (TREE_CODE (type))
3199     {
3200     case INTEGER_TYPE:
3201     case BOOLEAN_TYPE:
3202     case ENUMERAL_TYPE:
3203       /* For a non-type template-parameter of integral or enumeration
3204          type, integral promotions (_conv.prom_) and integral
3205          conversions (_conv.integral_) are applied.  */
3206       if (!INTEGRAL_TYPE_P (expr_type))
3207         return error_mark_node;
3208       
3209       /* It's safe to call digest_init in this case; we know we're
3210          just converting one integral constant expression to another.  */
3211       expr = digest_init (type, expr, (tree*) 0);
3212
3213       if (TREE_CODE (expr) != INTEGER_CST)
3214         /* Curiously, some TREE_CONSTANT integral expressions do not
3215            simplify to integer constants.  For example, `3 % 0',
3216            remains a TRUNC_MOD_EXPR.  */
3217         goto non_constant;
3218       
3219       return expr;
3220         
3221     case POINTER_TYPE:
3222       {
3223         tree type_pointed_to = TREE_TYPE (type);
3224  
3225         if (TYPE_PTRMEM_P (type))
3226           {
3227             tree e;
3228
3229             /* For a non-type template-parameter of type pointer to data
3230                member, qualification conversions (_conv.qual_) are
3231                applied.  */
3232             e = perform_qualification_conversions (type, expr);
3233             if (TREE_CODE (e) == NOP_EXPR)
3234               /* The call to perform_qualification_conversions will
3235                  insert a NOP_EXPR over EXPR to do express conversion,
3236                  if necessary.  But, that will confuse us if we use
3237                  this (converted) template parameter to instantiate
3238                  another template; then the thing will not look like a
3239                  valid template argument.  So, just make a new
3240                  constant, of the appropriate type.  */
3241               e = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
3242             return e;
3243           }
3244         else if (TREE_CODE (type_pointed_to) == FUNCTION_TYPE)
3245           { 
3246             /* For a non-type template-parameter of type pointer to
3247                function, only the function-to-pointer conversion
3248                (_conv.func_) is applied.  If the template-argument
3249                represents a set of overloaded functions (or a pointer to
3250                such), the matching function is selected from the set
3251                (_over.over_).  */
3252             tree fns;
3253             tree fn;
3254
3255             if (TREE_CODE (expr) == ADDR_EXPR)
3256               fns = TREE_OPERAND (expr, 0);
3257             else
3258               fns = expr;
3259
3260             fn = instantiate_type (type_pointed_to, fns, tf_none);
3261
3262             if (fn == error_mark_node)
3263               return error_mark_node;
3264
3265             if (!DECL_EXTERNAL_LINKAGE_P (fn))
3266               {
3267                 if (really_overloaded_fn (fns))
3268                   return error_mark_node;
3269                 else
3270                   goto bad_argument;
3271               }
3272
3273             expr = build_unary_op (ADDR_EXPR, fn, 0);
3274
3275             my_friendly_assert (same_type_p (type, TREE_TYPE (expr)), 
3276                                 0);
3277             return expr;
3278           }
3279         else 
3280           {
3281             /* For a non-type template-parameter of type pointer to
3282                object, qualification conversions (_conv.qual_) and the
3283                array-to-pointer conversion (_conv.array_) are applied.
3284                [Note: In particular, neither the null pointer conversion
3285                (_conv.ptr_) nor the derived-to-base conversion
3286                (_conv.ptr_) are applied.  Although 0 is a valid
3287                template-argument for a non-type template-parameter of
3288                integral type, it is not a valid template-argument for a
3289                non-type template-parameter of pointer type.]  
3290             
3291                The call to decay_conversion performs the
3292                array-to-pointer conversion, if appropriate.  */
3293             expr = decay_conversion (expr);
3294
3295             if (expr == error_mark_node)
3296               return error_mark_node;
3297             else
3298               return perform_qualification_conversions (type, expr);
3299           }
3300       }
3301       break;
3302
3303     case REFERENCE_TYPE:
3304       {
3305         tree type_referred_to = TREE_TYPE (type);
3306
3307         /* If this expression already has reference type, get the
3308            underling object.  */
3309         if (TREE_CODE (expr_type) == REFERENCE_TYPE) 
3310           {
3311             my_friendly_assert (TREE_CODE (expr) == ADDR_EXPR, 20000604);
3312             expr = TREE_OPERAND (expr, 0);
3313             expr_type = TREE_TYPE (expr);
3314           }
3315
3316         if (TREE_CODE (type_referred_to) == FUNCTION_TYPE)
3317           {
3318             /* For a non-type template-parameter of type reference to
3319                function, no conversions apply.  If the
3320                template-argument represents a set of overloaded
3321                functions, the matching function is selected from the
3322                set (_over.over_).  */
3323             tree fn;
3324
3325             fn = instantiate_type (type_referred_to, expr, tf_none);
3326
3327             if (fn == error_mark_node)
3328               return error_mark_node;
3329
3330             if (!DECL_EXTERNAL_LINKAGE_P (fn))
3331               {
3332                 if (really_overloaded_fn (expr))
3333                   /* Don't issue an error here; we might get a different
3334                      function if the overloading had worked out
3335                      differently.  */
3336                   return error_mark_node;
3337                 else
3338                   goto bad_argument;
3339               }
3340
3341             my_friendly_assert (same_type_p (type_referred_to, 
3342                                              TREE_TYPE (fn)),
3343                                 0);
3344
3345             expr = fn;
3346           }
3347         else
3348           {
3349             /* For a non-type template-parameter of type reference to
3350                object, no conversions apply.  The type referred to by the
3351                reference may be more cv-qualified than the (otherwise
3352                identical) type of the template-argument.  The
3353                template-parameter is bound directly to the
3354                template-argument, which must be an lvalue.  */
3355             if (!same_type_p (TYPE_MAIN_VARIANT (expr_type),
3356                               TYPE_MAIN_VARIANT (type_referred_to))
3357                 || !at_least_as_qualified_p (type_referred_to,
3358                                              expr_type)
3359                 || !real_lvalue_p (expr))
3360               return error_mark_node;
3361           }
3362
3363         cxx_mark_addressable (expr);
3364         return build1 (ADDR_EXPR, type, expr);
3365       }
3366       break;
3367
3368     case RECORD_TYPE:
3369       {
3370         my_friendly_assert (TYPE_PTRMEMFUNC_P (type), 20010112);
3371
3372         /* For a non-type template-parameter of type pointer to member
3373            function, no conversions apply.  If the template-argument
3374            represents a set of overloaded member functions, the
3375            matching member function is selected from the set
3376            (_over.over_).  */
3377
3378         if (!TYPE_PTRMEMFUNC_P (expr_type) && 
3379             expr_type != unknown_type_node)
3380           return error_mark_node;
3381
3382         if (TREE_CODE (expr) == PTRMEM_CST)
3383           {
3384             /* A ptr-to-member constant.  */
3385             if (!same_type_p (type, expr_type))
3386               return error_mark_node;
3387             else 
3388               return expr;
3389           }
3390
3391         if (TREE_CODE (expr) != ADDR_EXPR)
3392           return error_mark_node;
3393
3394         expr = instantiate_type (type, expr, tf_none);
3395         
3396         if (expr == error_mark_node)
3397           return error_mark_node;
3398
3399         my_friendly_assert (same_type_p (type, TREE_TYPE (expr)),
3400                             0);
3401         return expr;
3402       }
3403       break;
3404
3405     default:
3406       /* All non-type parameters must have one of these types.  */
3407       abort ();
3408       break;
3409     }
3410
3411   return error_mark_node;
3412 }
3413
3414 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for 
3415    template template parameters.  Both PARM_PARMS and ARG_PARMS are 
3416    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL 
3417    or PARM_DECL.
3418    
3419    ARG_PARMS may contain more parameters than PARM_PARMS.  If this is 
3420    the case, then extra parameters must have default arguments.
3421
3422    Consider the example:
3423      template <class T, class Allocator = allocator> class vector;
3424      template<template <class U> class TT> class C;
3425
3426    C<vector> is a valid instantiation.  PARM_PARMS for the above code 
3427    contains a TYPE_DECL (for U),  ARG_PARMS contains two TYPE_DECLs (for 
3428    T and Allocator) and OUTER_ARGS contains the argument that is used to 
3429    substitute the TT parameter.  */
3430
3431 static int
3432 coerce_template_template_parms (parm_parms, arg_parms, complain, 
3433                                 in_decl, outer_args)
3434      tree parm_parms, arg_parms;
3435      tsubst_flags_t complain;
3436      tree in_decl, outer_args;
3437 {
3438   int nparms, nargs, i;
3439   tree parm, arg;
3440
3441   my_friendly_assert (TREE_CODE (parm_parms) == TREE_VEC, 0);
3442   my_friendly_assert (TREE_CODE (arg_parms) == TREE_VEC, 0);
3443
3444   nparms = TREE_VEC_LENGTH (parm_parms);
3445   nargs = TREE_VEC_LENGTH (arg_parms);
3446
3447   /* The rule here is opposite of coerce_template_parms.  */
3448   if (nargs < nparms
3449       || (nargs > nparms
3450           && TREE_PURPOSE (TREE_VEC_ELT (arg_parms, nparms)) == NULL_TREE))
3451     return 0;
3452
3453   for (i = 0; i < nparms; ++i)
3454     {
3455       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
3456       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
3457
3458       if (arg == NULL_TREE || arg == error_mark_node
3459           || parm == NULL_TREE || parm == error_mark_node)
3460         return 0;
3461
3462       if (TREE_CODE (arg) != TREE_CODE (parm))
3463         return 0;
3464
3465       switch (TREE_CODE (parm))
3466         {
3467         case TYPE_DECL:
3468           break;
3469
3470         case TEMPLATE_DECL:
3471           /* We encounter instantiations of templates like
3472                template <template <template <class> class> class TT>
3473                class C;  */
3474           {
3475             tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
3476             tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
3477
3478             if (!coerce_template_template_parms (parmparm, argparm, 
3479                                                  complain, in_decl,
3480                                                  outer_args))
3481               return 0;
3482           }
3483           break;
3484
3485         case PARM_DECL:
3486           /* The tsubst call is used to handle cases such as
3487                template <class T, template <T> class TT> class D;  
3488              i.e. the parameter list of TT depends on earlier parameters.  */
3489           if (!same_type_p (tsubst (TREE_TYPE (parm), outer_args, 
3490                                     complain, in_decl),
3491                             TREE_TYPE (arg)))
3492             return 0;
3493           break;
3494           
3495         default:
3496           abort ();
3497         }
3498     }
3499   return 1;
3500 }
3501
3502 /* Convert the indicated template ARG as necessary to match the
3503    indicated template PARM.  Returns the converted ARG, or
3504    error_mark_node if the conversion was unsuccessful.  Error and
3505    warning messages are issued under control of COMPLAIN.  This
3506    conversion is for the Ith parameter in the parameter list.  ARGS is
3507    the full set of template arguments deduced so far.  */
3508
3509 static tree
3510 convert_template_argument (parm, arg, args, complain, i, in_decl)
3511      tree parm;
3512      tree arg;
3513      tree args;
3514      tsubst_flags_t complain;
3515      int i;
3516      tree in_decl;
3517 {
3518   tree val;
3519   tree inner_args;
3520   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
3521   
3522   inner_args = INNERMOST_TEMPLATE_ARGS (args);
3523
3524   if (TREE_CODE (arg) == TREE_LIST 
3525       && TREE_TYPE (arg) != NULL_TREE
3526       && TREE_CODE (TREE_TYPE (arg)) == OFFSET_TYPE)
3527     {  
3528       /* The template argument was the name of some
3529          member function.  That's usually
3530          invalid, but static members are OK.  In any
3531          case, grab the underlying fields/functions
3532          and issue an error later if required.  */
3533       arg = TREE_VALUE (arg);
3534       TREE_TYPE (arg) = unknown_type_node;
3535     }
3536
3537   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
3538   requires_type = (TREE_CODE (parm) == TYPE_DECL
3539                    || requires_tmpl_type);
3540
3541   if (TREE_CODE (arg) != RECORD_TYPE)
3542     is_tmpl_type = ((TREE_CODE (arg) == TEMPLATE_DECL
3543                      && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
3544                     || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
3545                     || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
3546   else if (CLASSTYPE_TEMPLATE_INFO (arg) && !CLASSTYPE_USE_TEMPLATE (arg)
3547            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (arg)))
3548     {
3549       if (is_base_of_enclosing_class (arg, current_class_type))
3550         /* This is a template name used within the scope of the
3551            template. It could be the template, or it could be the
3552            instantiation. Choose whichever makes sense.  */
3553         is_tmpl_type = requires_tmpl_type;
3554       else
3555         is_tmpl_type = 1;
3556     }
3557   else
3558     /* It is a non-template class, or a specialization of a template
3559        class, or a non-template member of a template class.  */
3560     is_tmpl_type = 0;
3561   
3562   if (is_tmpl_type
3563       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
3564           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
3565     arg = TYPE_STUB_DECL (arg);
3566   else if (is_tmpl_type && TREE_CODE (arg) == RECORD_TYPE)
3567     arg = CLASSTYPE_TI_TEMPLATE (arg);
3568
3569   is_type = TYPE_P (arg) || is_tmpl_type;
3570
3571   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
3572       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
3573     {
3574       pedwarn ("to refer to a type member of a template parameter, use `typename %E'", arg);
3575       
3576       arg = make_typename_type (TREE_OPERAND (arg, 0),
3577                                 TREE_OPERAND (arg, 1),
3578                                 complain & tf_error);
3579       is_type = 1;
3580     }
3581   if (is_type != requires_type)
3582     {
3583       if (in_decl)
3584         {
3585           if (complain & tf_error)
3586             {
3587               error ("type/value mismatch at argument %d in template parameter list for `%D'",
3588                         i + 1, in_decl);
3589               if (is_type)
3590                 error ("  expected a constant of type `%T', got `%T'",
3591                           TREE_TYPE (parm),
3592                           (is_tmpl_type ? DECL_NAME (arg) : arg));
3593               else if (requires_tmpl_type)
3594                 error ("  expected a class template, got `%E'", arg);
3595               else
3596                 error ("  expected a type, got `%E'", arg);
3597             }
3598         }
3599       return error_mark_node;
3600     }
3601   if (is_tmpl_type ^ requires_tmpl_type)
3602     {
3603       if (in_decl && (complain & tf_error))
3604         {
3605           error ("type/value mismatch at argument %d in template parameter list for `%D'",
3606                     i + 1, in_decl);
3607           if (is_tmpl_type)
3608             error ("  expected a type, got `%T'", DECL_NAME (arg));
3609           else
3610             error ("  expected a class template, got `%T'", arg);
3611         }
3612       return error_mark_node;
3613     }
3614       
3615   if (is_type)
3616     {
3617       if (requires_tmpl_type)
3618         {
3619           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
3620             /* The number of argument required is not known yet.
3621                Just accept it for now.  */
3622             val = TREE_TYPE (arg);
3623           else
3624             {
3625               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
3626               tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
3627
3628               if (coerce_template_template_parms (parmparm, argparm,
3629                                                   complain, in_decl,
3630                                                   inner_args))
3631                 {
3632                   val = arg;
3633                   
3634                   /* TEMPLATE_TEMPLATE_PARM node is preferred over 
3635                      TEMPLATE_DECL.  */
3636                   if (val != error_mark_node 
3637                       && DECL_TEMPLATE_TEMPLATE_PARM_P (val))
3638                     val = TREE_TYPE (val);
3639                 }
3640               else
3641                 {
3642                   if (in_decl && (complain & tf_error))
3643                     {
3644                       error ("type/value mismatch at argument %d in template parameter list for `%D'",
3645                                 i + 1, in_decl);
3646                       error ("  expected a template of type `%D', got `%D'", parm, arg);
3647                     }
3648                   
3649                   val = error_mark_node;
3650                 }
3651             }
3652         }
3653       else
3654         val = groktypename (arg);
3655     }
3656   else
3657     {
3658       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
3659
3660       if (invalid_nontype_parm_type_p (t, complain))
3661         return error_mark_node;
3662       
3663       if (processing_template_decl)
3664         arg = maybe_fold_nontype_arg (arg);
3665
3666       if (!uses_template_parms (arg) && !uses_template_parms (t))
3667         /* We used to call digest_init here.  However, digest_init
3668            will report errors, which we don't want when complain
3669            is zero.  More importantly, digest_init will try too
3670            hard to convert things: for example, `0' should not be
3671            converted to pointer type at this point according to
3672            the standard.  Accepting this is not merely an
3673            extension, since deciding whether or not these
3674            conversions can occur is part of determining which
3675            function template to call, or whether a given explicit
3676            argument specification is valid.  */
3677         val = convert_nontype_argument (t, arg);
3678       else
3679         val = arg;
3680
3681       if (val == NULL_TREE)
3682         val = error_mark_node;
3683       else if (val == error_mark_node && (complain & tf_error))
3684         error ("could not convert template argument `%E' to `%T'", 
3685                   arg, t);
3686     }
3687
3688   return val;
3689 }
3690
3691 /* Convert all template arguments to their appropriate types, and
3692    return a vector containing the innermost resulting template
3693    arguments.  If any error occurs, return error_mark_node. Error and
3694    warning messages are issued under control of COMPLAIN.
3695
3696    If REQUIRE_ALL_ARGUMENTS is nonzero, all arguments must be
3697    provided in ARGLIST, or else trailing parameters must have default
3698    values.  If REQUIRE_ALL_ARGUMENTS is zero, we will attempt argument
3699    deduction for any unspecified trailing arguments.  */
3700    
3701 static tree
3702 coerce_template_parms (parms, args, in_decl,
3703                        complain,
3704                        require_all_arguments)
3705      tree parms, args;
3706      tree in_decl;
3707      tsubst_flags_t complain;
3708      int require_all_arguments;
3709 {
3710   int nparms, nargs, i, lost = 0;
3711   tree inner_args;
3712   tree new_args;
3713   tree new_inner_args;
3714
3715   inner_args = INNERMOST_TEMPLATE_ARGS (args);
3716   nargs = NUM_TMPL_ARGS (inner_args);
3717   nparms = TREE_VEC_LENGTH (parms);
3718
3719   if (nargs > nparms
3720       || (nargs < nparms
3721           && require_all_arguments
3722           && TREE_PURPOSE (TREE_VEC_ELT (parms, nargs)) == NULL_TREE))
3723     {
3724       if (complain & tf_error) 
3725         {
3726           error ("wrong number of template arguments (%d, should be %d)",
3727                     nargs, nparms);
3728           
3729           if (in_decl)
3730             cp_error_at ("provided for `%D'", in_decl);
3731         }
3732
3733       return error_mark_node;
3734     }
3735
3736   new_inner_args = make_tree_vec (nparms);
3737   new_args = add_outermost_template_args (args, new_inner_args);
3738   for (i = 0; i < nparms; i++)
3739     {
3740       tree arg;
3741       tree parm;
3742
3743       /* Get the Ith template parameter.  */
3744       parm = TREE_VEC_ELT (parms, i);
3745
3746       /* Calculate the Ith argument.  */
3747       if (inner_args && TREE_CODE (inner_args) == TREE_LIST)
3748         {
3749           arg = TREE_VALUE (inner_args);
3750           inner_args = TREE_CHAIN (inner_args);
3751         }
3752       else if (i < nargs)
3753         arg = TREE_VEC_ELT (inner_args, i);
3754       /* If no template argument was supplied, look for a default
3755          value.  */
3756       else if (TREE_PURPOSE (parm) == NULL_TREE)
3757         {
3758           /* There was no default value.  */
3759           my_friendly_assert (!require_all_arguments, 0);
3760           break;
3761         }
3762       else if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL)
3763         arg = tsubst (TREE_PURPOSE (parm), new_args, complain, in_decl);
3764       else
3765         arg = tsubst_expr (TREE_PURPOSE (parm), new_args, complain,
3766                            in_decl);
3767
3768       /* Now, convert the Ith argument, as necessary.  */
3769       if (arg == NULL_TREE)
3770         /* We're out of arguments.  */
3771         {
3772           my_friendly_assert (!require_all_arguments, 0);
3773           break;
3774         }
3775       else if (arg == error_mark_node)
3776         {
3777           error ("template argument %d is invalid", i + 1);
3778           arg = error_mark_node;
3779         }
3780       else 
3781         arg = convert_template_argument (TREE_VALUE (parm), 
3782                                          arg, new_args, complain, i,
3783                                          in_decl); 
3784       
3785       if (arg == error_mark_node)
3786         lost++;
3787       TREE_VEC_ELT (new_inner_args, i) = arg;
3788     }
3789
3790   if (lost)
3791     return error_mark_node;
3792
3793   return new_inner_args;
3794 }
3795
3796 /* Returns 1 if template args OT and NT are equivalent.  */
3797
3798 static int
3799 template_args_equal (ot, nt)
3800      tree ot, nt;
3801 {
3802   if (nt == ot)
3803     return 1;
3804
3805   if (TREE_CODE (nt) == TREE_VEC)
3806     /* For member templates */
3807     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
3808   else if (TYPE_P (nt))
3809     return TYPE_P (ot) && same_type_p (ot, nt);
3810   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
3811     return 0;
3812   else
3813     return (cp_tree_equal (ot, nt) > 0);
3814 }
3815
3816 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
3817    of template arguments.  Returns 0 otherwise.  */
3818
3819 int
3820 comp_template_args (oldargs, newargs)
3821      tree oldargs, newargs;
3822 {
3823   int i;
3824
3825   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
3826     return 0;
3827
3828   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
3829     {
3830       tree nt = TREE_VEC_ELT (newargs, i);
3831       tree ot = TREE_VEC_ELT (oldargs, i);
3832
3833       if (! template_args_equal (ot, nt))
3834         return 0;
3835     }
3836   return 1;
3837 }
3838
3839 /* Given class template name and parameter list, produce a user-friendly name
3840    for the instantiation.  */
3841
3842 static char *
3843 mangle_class_name_for_template (name, parms, arglist)
3844      const char *name;
3845      tree parms, arglist;
3846 {
3847   static struct obstack scratch_obstack;
3848   static char *scratch_firstobj;
3849   int i, nparms;
3850
3851   if (!scratch_firstobj)
3852     gcc_obstack_init (&scratch_obstack);
3853   else
3854     obstack_free (&scratch_obstack, scratch_firstobj);
3855   scratch_firstobj = obstack_alloc (&scratch_obstack, 1);
3856
3857 #define ccat(C) obstack_1grow (&scratch_obstack, (C));
3858 #define cat(S)  obstack_grow (&scratch_obstack, (S), strlen (S))
3859
3860   cat (name);
3861   ccat ('<');
3862   nparms = TREE_VEC_LENGTH (parms);
3863   arglist = INNERMOST_TEMPLATE_ARGS (arglist);
3864   my_friendly_assert (nparms == TREE_VEC_LENGTH (arglist), 268);
3865   for (i = 0; i < nparms; i++)
3866     {
3867       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
3868       tree arg = TREE_VEC_ELT (arglist, i);
3869
3870       if (i)
3871         ccat (',');
3872
3873       if (TREE_CODE (parm) == TYPE_DECL)
3874         {
3875           cat (type_as_string (arg, TFF_CHASE_TYPEDEF));
3876           continue;
3877         }
3878       else if (TREE_CODE (parm) == TEMPLATE_DECL)
3879         {
3880           if (TREE_CODE (arg) == TEMPLATE_DECL)
3881             {
3882               /* Already substituted with real template.  Just output 
3883                  the template name here */
3884               tree context = DECL_CONTEXT (arg);
3885               if (context)
3886                 {
3887                   /* The template may be defined in a namespace, or
3888                      may be a member template.  */
3889                   my_friendly_assert (TREE_CODE (context) == NAMESPACE_DECL
3890                                       || CLASS_TYPE_P (context), 
3891                                       980422);
3892                   cat(decl_as_string (DECL_CONTEXT (arg), TFF_PLAIN_IDENTIFIER));
3893                   cat("::");
3894                 }
3895               cat (IDENTIFIER_POINTER (DECL_NAME (arg)));
3896             }
3897           else
3898             /* Output the parameter declaration */
3899             cat (type_as_string (arg, TFF_CHASE_TYPEDEF));
3900           continue;
3901         }
3902       else
3903         my_friendly_assert (TREE_CODE (parm) == PARM_DECL, 269);
3904
3905       if (TREE_CODE (arg) == TREE_LIST)
3906         {
3907           /* New list cell was built because old chain link was in
3908              use.  */
3909           my_friendly_assert (TREE_PURPOSE (arg) == NULL_TREE, 270);
3910           arg = TREE_VALUE (arg);
3911         }
3912       /* No need to check arglist against parmlist here; we did that
3913          in coerce_template_parms, called from lookup_template_class.  */
3914       cat (expr_as_string (arg, TFF_PLAIN_IDENTIFIER));
3915     }
3916   {
3917     char *bufp = obstack_next_free (&scratch_obstack);
3918     int offset = 0;
3919     while (bufp[offset - 1] == ' ')
3920       offset--;
3921     obstack_blank_fast (&scratch_obstack, offset);
3922
3923     /* B<C<char> >, not B<C<char>> */
3924     if (bufp[offset - 1] == '>')
3925       ccat (' ');
3926   }
3927   ccat ('>');
3928   ccat ('\0');
3929   return (char *) obstack_base (&scratch_obstack);
3930 }
3931
3932 static tree
3933 classtype_mangled_name (t)
3934      tree t;
3935 {
3936   if (CLASSTYPE_TEMPLATE_INFO (t)
3937       /* Specializations have already had their names set up in
3938          lookup_template_class.  */
3939       && !CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
3940     {
3941       tree tmpl = most_general_template (CLASSTYPE_TI_TEMPLATE (t));
3942
3943       /* For non-primary templates, the template parameters are
3944          implicit from their surrounding context.  */
3945       if (PRIMARY_TEMPLATE_P (tmpl))
3946         {
3947           tree name = DECL_NAME (tmpl);
3948           char *mangled_name = mangle_class_name_for_template
3949             (IDENTIFIER_POINTER (name), 
3950              DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
3951              CLASSTYPE_TI_ARGS (t));
3952           tree id = get_identifier (mangled_name);
3953           IDENTIFIER_TEMPLATE (id) = name;
3954           return id;
3955         }
3956     }
3957
3958   return TYPE_IDENTIFIER (t);
3959 }
3960
3961 static void
3962 add_pending_template (d)
3963      tree d;
3964 {
3965   tree ti = (TYPE_P (d)
3966              ? CLASSTYPE_TEMPLATE_INFO (d)
3967              : DECL_TEMPLATE_INFO (d));
3968   tree pt;
3969   int level;
3970
3971   if (TI_PENDING_TEMPLATE_FLAG (ti))
3972     return;
3973
3974   /* We are called both from instantiate_decl, where we've already had a
3975      tinst_level pushed, and instantiate_template, where we haven't.
3976      Compensate.  */
3977   level = !(current_tinst_level && TINST_DECL (current_tinst_level) == d);
3978
3979   if (level)
3980     push_tinst_level (d);
3981
3982   pt = tree_cons (current_tinst_level, d, NULL_TREE);
3983   if (last_pending_template)
3984     TREE_CHAIN (last_pending_template) = pt;
3985   else
3986     pending_templates = pt;
3987
3988   last_pending_template = pt;
3989
3990   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
3991
3992   if (level)
3993     pop_tinst_level ();
3994 }
3995
3996
3997 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
3998    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
3999    documentation for TEMPLATE_ID_EXPR.  */
4000
4001 tree
4002 lookup_template_function (fns, arglist)
4003      tree fns, arglist;
4004 {
4005   tree type;
4006
4007   if (fns == error_mark_node || arglist == error_mark_node)
4008     return error_mark_node;
4009
4010   if (fns == NULL_TREE)
4011     {
4012       error ("non-template used as template");
4013       return error_mark_node;
4014     }
4015
4016   my_friendly_assert (TREE_CODE (fns) == TEMPLATE_DECL
4017                       || TREE_CODE (fns) == OVERLOAD
4018                       || BASELINK_P (fns)
4019                       || TREE_CODE (fns) == IDENTIFIER_NODE
4020                       || TREE_CODE (fns) == LOOKUP_EXPR,
4021                       20020730);
4022
4023   if (BASELINK_P (fns))
4024     {
4025       BASELINK_FUNCTIONS (fns) = build (TEMPLATE_ID_EXPR,
4026                                         unknown_type_node,
4027                                         BASELINK_FUNCTIONS (fns),
4028                                         arglist);
4029       return fns;
4030     }
4031
4032   type = TREE_TYPE (fns);
4033   if (TREE_CODE (fns) == OVERLOAD || !type)
4034     type = unknown_type_node;
4035   
4036   return build (TEMPLATE_ID_EXPR, type, fns, arglist);
4037 }
4038
4039 /* Within the scope of a template class S<T>, the name S gets bound
4040    (in build_self_reference) to a TYPE_DECL for the class, not a
4041    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
4042    or one of its enclosing classes, and that type is a template,
4043    return the associated TEMPLATE_DECL.  Otherwise, the original
4044    DECL is returned.  */
4045
4046 tree
4047 maybe_get_template_decl_from_type_decl (decl)
4048      tree decl;
4049 {
4050   return (decl != NULL_TREE
4051           && TREE_CODE (decl) == TYPE_DECL 
4052           && DECL_ARTIFICIAL (decl)
4053           && CLASS_TYPE_P (TREE_TYPE (decl))
4054           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl))) 
4055     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
4056 }
4057
4058 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
4059    parameters, find the desired type.
4060
4061    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
4062    (Actually ARGLIST may be either a TREE_LIST or a TREE_VEC.  It will
4063    be a TREE_LIST if called directly from the parser, and a TREE_VEC
4064    otherwise.)
4065
4066    IN_DECL, if non-NULL, is the template declaration we are trying to
4067    instantiate.  
4068
4069    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
4070    the class we are looking up.
4071    
4072    Issue error and warning messages under control of COMPLAIN.
4073
4074    If the template class is really a local class in a template
4075    function, then the FUNCTION_CONTEXT is the function in which it is
4076    being instantiated.  */
4077
4078 tree
4079 lookup_template_class (d1, arglist, in_decl, context, entering_scope, complain)
4080      tree d1, arglist;
4081      tree in_decl;
4082      tree context;
4083      int entering_scope;
4084      tsubst_flags_t complain;
4085 {
4086   tree template = NULL_TREE, parmlist;
4087   tree t;
4088
4089   timevar_push (TV_NAME_LOOKUP);
4090   if (TREE_CODE (d1) == IDENTIFIER_NODE)
4091     {
4092       if (IDENTIFIER_VALUE (d1) 
4093           && DECL_TEMPLATE_TEMPLATE_PARM_P (IDENTIFIER_VALUE (d1)))
4094         template = IDENTIFIER_VALUE (d1);
4095       else
4096         {
4097           if (context)
4098             push_decl_namespace (context);
4099           template = lookup_name (d1, /*prefer_type=*/0);
4100           template = maybe_get_template_decl_from_type_decl (template);
4101           if (context)
4102             pop_decl_namespace ();
4103         }
4104       if (template)
4105         context = DECL_CONTEXT (template);
4106     }
4107   else if (TREE_CODE (d1) == TYPE_DECL && IS_AGGR_TYPE (TREE_TYPE (d1)))
4108     {
4109       tree type = TREE_TYPE (d1);
4110
4111       /* If we are declaring a constructor, say A<T>::A<T>, we will get
4112          an implicit typename for the second A.  Deal with it.  */
4113       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
4114         type = TREE_TYPE (type);
4115         
4116       if (CLASSTYPE_TEMPLATE_INFO (type))
4117         {
4118           template = CLASSTYPE_TI_TEMPLATE (type);
4119           d1 = DECL_NAME (template);
4120         }
4121     }
4122   else if (TREE_CODE (d1) == ENUMERAL_TYPE 
4123            || (TYPE_P (d1) && IS_AGGR_TYPE (d1)))
4124     {
4125       template = TYPE_TI_TEMPLATE (d1);
4126       d1 = DECL_NAME (template);
4127     }
4128   else if (TREE_CODE (d1) == TEMPLATE_DECL
4129            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
4130     {
4131       template = d1;
4132       d1 = DECL_NAME (template);
4133       context = DECL_CONTEXT (template);
4134     }
4135
4136   /* With something like `template <class T> class X class X { ... };'
4137      we could end up with D1 having nothing but an IDENTIFIER_VALUE.
4138      We don't want to do that, but we have to deal with the situation,
4139      so let's give them some syntax errors to chew on instead of a
4140      crash. Alternatively D1 might not be a template type at all.  */
4141   if (! template)
4142     {
4143       if (complain & tf_error)
4144         error ("`%T' is not a template", d1);
4145       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
4146     }
4147
4148   if (TREE_CODE (template) != TEMPLATE_DECL
4149          /* If we're called from the parser, make sure it's a user visible
4150             template.  */
4151       || ((!arglist || TREE_CODE (arglist) == TREE_LIST)
4152           && !DECL_TEMPLATE_PARM_P (template)
4153           && !PRIMARY_TEMPLATE_P (template)))
4154     {
4155       if (complain & tf_error)
4156         {
4157           error ("non-template type `%T' used as a template", d1);
4158           if (in_decl)
4159             cp_error_at ("for template declaration `%D'", in_decl);
4160         }
4161       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
4162     }
4163
4164   if (DECL_TEMPLATE_TEMPLATE_PARM_P (template))
4165     {
4166       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
4167          template arguments */
4168
4169       tree parm;
4170       tree arglist2;
4171
4172       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (template);
4173
4174       /* Consider an example where a template template parameter declared as
4175
4176            template <class T, class U = std::allocator<T> > class TT
4177
4178          The template parameter level of T and U are one level larger than 
4179          of TT.  To proper process the default argument of U, say when an 
4180          instantiation `TT<int>' is seen, we need to build the full
4181          arguments containing {int} as the innermost level.  Outer levels,
4182          available when not appearing as default template argument, can be
4183          obtained from `current_template_args ()'.
4184
4185          Suppose that TT is later substituted with std::vector.  The above
4186          instantiation is `TT<int, std::allocator<T> >' with TT at
4187          level 1, and T at level 2, while the template arguments at level 1
4188          becomes {std::vector} and the inner level 2 is {int}.  */
4189
4190       if (current_template_parms)
4191         arglist = add_to_template_args (current_template_args (), arglist);
4192
4193       arglist2 = coerce_template_parms (parmlist, arglist, template,
4194                                         complain, /*require_all_args=*/1);
4195       if (arglist2 == error_mark_node
4196           || (!uses_template_parms (arglist2)
4197               && check_instantiated_args (template, arglist2, complain)))
4198         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
4199
4200       parm = bind_template_template_parm (TREE_TYPE (template), arglist2);
4201       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
4202     }
4203   else 
4204     {
4205       tree template_type = TREE_TYPE (template);
4206       tree gen_tmpl;
4207       tree type_decl;
4208       tree found = NULL_TREE;
4209       tree *tp;
4210       int arg_depth;
4211       int parm_depth;
4212       int is_partial_instantiation;
4213
4214       gen_tmpl = most_general_template (template);
4215       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
4216       parm_depth = TMPL_PARMS_DEPTH (parmlist);
4217       arg_depth = TMPL_ARGS_DEPTH (arglist);
4218
4219       if (arg_depth == 1 && parm_depth > 1)
4220         {
4221           /* We've been given an incomplete set of template arguments.
4222              For example, given:
4223
4224                template <class T> struct S1 {
4225                  template <class U> struct S2 {};
4226                  template <class U> struct S2<U*> {};
4227                 };
4228              
4229              we will be called with an ARGLIST of `U*', but the
4230              TEMPLATE will be `template <class T> template
4231              <class U> struct S1<T>::S2'.  We must fill in the missing
4232              arguments.  */
4233           arglist 
4234             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (template)),
4235                                            arglist);
4236           arg_depth = TMPL_ARGS_DEPTH (arglist);
4237         }
4238
4239       /* Now we should have enough arguments.  */
4240       my_friendly_assert (parm_depth == arg_depth, 0);
4241       
4242       /* From here on, we're only interested in the most general
4243          template.  */
4244       template = gen_tmpl;
4245
4246       /* Calculate the BOUND_ARGS.  These will be the args that are
4247          actually tsubst'd into the definition to create the
4248          instantiation.  */
4249       if (parm_depth > 1)
4250         {
4251           /* We have multiple levels of arguments to coerce, at once.  */
4252           int i;
4253           int saved_depth = TMPL_ARGS_DEPTH (arglist);
4254
4255           tree bound_args = make_tree_vec (parm_depth);
4256           
4257           for (i = saved_depth,
4258                  t = DECL_TEMPLATE_PARMS (template); 
4259                i > 0 && t != NULL_TREE;
4260                --i, t = TREE_CHAIN (t))
4261             {
4262               tree a = coerce_template_parms (TREE_VALUE (t),
4263                                               arglist, template,
4264                                               complain, /*require_all_args=*/1);
4265
4266               /* Don't process further if one of the levels fails.  */
4267               if (a == error_mark_node)
4268                 {
4269                   /* Restore the ARGLIST to its full size.  */
4270                   TREE_VEC_LENGTH (arglist) = saved_depth;
4271                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
4272                 }
4273               
4274               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
4275
4276               /* We temporarily reduce the length of the ARGLIST so
4277                  that coerce_template_parms will see only the arguments
4278                  corresponding to the template parameters it is
4279                  examining.  */
4280               TREE_VEC_LENGTH (arglist)--;
4281             }
4282
4283           /* Restore the ARGLIST to its full size.  */
4284           TREE_VEC_LENGTH (arglist) = saved_depth;
4285
4286           arglist = bound_args;
4287         }
4288       else
4289         arglist
4290           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
4291                                    INNERMOST_TEMPLATE_ARGS (arglist),
4292                                    template,
4293                                    complain, /*require_all_args=*/1);
4294
4295       if (arglist == error_mark_node
4296           || (!uses_template_parms (INNERMOST_TEMPLATE_ARGS (arglist))
4297               && check_instantiated_args (template,
4298                                           INNERMOST_TEMPLATE_ARGS (arglist),
4299                                           complain)))
4300         /* We were unable to bind the arguments.  */
4301         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
4302
4303       /* In the scope of a template class, explicit references to the
4304          template class refer to the type of the template, not any
4305          instantiation of it.  For example, in:
4306          
4307            template <class T> class C { void f(C<T>); }
4308
4309          the `C<T>' is just the same as `C'.  Outside of the
4310          class, however, such a reference is an instantiation.  */
4311       if (comp_template_args (TYPE_TI_ARGS (template_type),
4312                               arglist))
4313         {
4314           found = template_type;
4315           
4316           if (!entering_scope && PRIMARY_TEMPLATE_P (template))
4317             {
4318               tree ctx;
4319               
4320               /* Note that we use DECL_CONTEXT, rather than
4321                  CP_DECL_CONTEXT, so that the termination test is
4322                  always just `ctx'.  We're not interested in namespace
4323                  scopes.  */
4324               for (ctx = current_class_type; 
4325                    ctx; 
4326                    ctx = (TYPE_P (ctx)) ? TYPE_CONTEXT (ctx) : DECL_CONTEXT (ctx))
4327                 if (same_type_p (ctx, template_type))
4328                   break;
4329               
4330               if (!ctx)
4331                 /* We're not in the scope of the class, so the
4332                    TEMPLATE_TYPE is not the type we want after
4333                    all.  */
4334                 found = NULL_TREE;
4335             }
4336         }
4337       if (found)
4338         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
4339
4340       for (tp = &DECL_TEMPLATE_INSTANTIATIONS (template);
4341            *tp;
4342            tp = &TREE_CHAIN (*tp))
4343         if (comp_template_args (TREE_PURPOSE (*tp), arglist))
4344           {
4345             found = *tp;
4346
4347             /* Use the move-to-front heuristic to speed up future
4348                searches.  */
4349             *tp = TREE_CHAIN (*tp);
4350             TREE_CHAIN (found) 
4351               = DECL_TEMPLATE_INSTANTIATIONS (template);
4352             DECL_TEMPLATE_INSTANTIATIONS (template) = found;
4353
4354             POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, TREE_VALUE (found));
4355           }
4356
4357       /* This type is a "partial instantiation" if any of the template
4358          arguments still involve template parameters.  Note that we set
4359          IS_PARTIAL_INSTANTIATION for partial specializations as
4360          well.  */
4361       is_partial_instantiation = uses_template_parms (arglist);
4362
4363       if (!is_partial_instantiation 
4364           && !PRIMARY_TEMPLATE_P (template)
4365           && TREE_CODE (CP_DECL_CONTEXT (template)) == NAMESPACE_DECL)
4366         {
4367           found = xref_tag_from_type (TREE_TYPE (template),
4368                                       DECL_NAME (template),
4369                                       /*globalize=*/1);
4370           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
4371         }
4372       
4373       context = tsubst (DECL_CONTEXT (template), arglist,
4374                         complain, in_decl);
4375       if (!context)
4376         context = global_namespace;
4377
4378       /* Create the type.  */
4379       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
4380         {
4381           if (!is_partial_instantiation)
4382             {
4383               set_current_access_from_decl (TYPE_NAME (template_type));
4384               t = start_enum (TYPE_IDENTIFIER (template_type));
4385             }
4386           else
4387             /* We don't want to call start_enum for this type, since
4388                the values for the enumeration constants may involve
4389                template parameters.  And, no one should be interested
4390                in the enumeration constants for such a type.  */
4391             t = make_node (ENUMERAL_TYPE);
4392         }
4393       else
4394         {
4395           t = make_aggr_type (TREE_CODE (template_type));
4396           CLASSTYPE_DECLARED_CLASS (t) 
4397             = CLASSTYPE_DECLARED_CLASS (template_type);
4398           CLASSTYPE_GOT_SEMICOLON (t) = 1;
4399           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
4400           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
4401
4402           /* A local class.  Make sure the decl gets registered properly.  */
4403           if (context == current_function_decl)
4404             pushtag (DECL_NAME (template), t, 0);
4405         }
4406
4407       /* If we called start_enum or pushtag above, this information
4408          will already be set up.  */
4409       if (!TYPE_NAME (t))
4410         {
4411           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
4412           
4413           type_decl = create_implicit_typedef (DECL_NAME (template), t);
4414           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
4415           TYPE_STUB_DECL (t) = type_decl;
4416           DECL_SOURCE_LOCATION (type_decl) 
4417             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
4418         }
4419       else
4420         type_decl = TYPE_NAME (t);
4421
4422       TREE_PRIVATE (type_decl)
4423         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
4424       TREE_PROTECTED (type_decl)
4425         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
4426
4427       /* Set up the template information.  We have to figure out which
4428          template is the immediate parent if this is a full
4429          instantiation.  */
4430       if (parm_depth == 1 || is_partial_instantiation
4431           || !PRIMARY_TEMPLATE_P (template))
4432         /* This case is easy; there are no member templates involved.  */
4433         found = template;
4434       else
4435         {
4436           /* This is a full instantiation of a member template.  Look
4437              for a partial instantiation of which this is an instance.  */
4438
4439           for (found = DECL_TEMPLATE_INSTANTIATIONS (template);
4440                found; found = TREE_CHAIN (found))
4441             {
4442               int success;
4443               tree tmpl = CLASSTYPE_TI_TEMPLATE (TREE_VALUE (found));
4444
4445               /* We only want partial instantiations, here, not
4446                  specializations or full instantiations.  */
4447               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_VALUE (found))
4448                   || !uses_template_parms (TREE_VALUE (found)))
4449                 continue;
4450
4451               /* Temporarily reduce by one the number of levels in the
4452                  ARGLIST and in FOUND so as to avoid comparing the
4453                  last set of arguments.  */
4454               TREE_VEC_LENGTH (arglist)--;
4455               TREE_VEC_LENGTH (TREE_PURPOSE (found)) --;
4456
4457               /* See if the arguments match.  If they do, then TMPL is
4458                  the partial instantiation we want.  */
4459               success = comp_template_args (TREE_PURPOSE (found), arglist);
4460
4461               /* Restore the argument vectors to their full size.  */
4462               TREE_VEC_LENGTH (arglist)++;
4463               TREE_VEC_LENGTH (TREE_PURPOSE (found))++;
4464
4465               if (success)
4466                 {
4467                   found = tmpl;
4468                   break;
4469                 }
4470             }
4471
4472           if (!found)
4473             {
4474               /* There was no partial instantiation. This happens
4475                  where C<T> is a member template of A<T> and it's used
4476                  in something like
4477                 
4478                   template <typename T> struct B { A<T>::C<int> m; };
4479                   B<float>;
4480                 
4481                  Create the partial instantiation.
4482                */
4483               TREE_VEC_LENGTH (arglist)--;
4484               found = tsubst (template, arglist, complain, NULL_TREE);
4485               TREE_VEC_LENGTH (arglist)++;
4486             }
4487         }
4488
4489       SET_TYPE_TEMPLATE_INFO (t, tree_cons (found, arglist, NULL_TREE));  
4490       DECL_TEMPLATE_INSTANTIATIONS (template) 
4491         = tree_cons (arglist, t, 
4492                      DECL_TEMPLATE_INSTANTIATIONS (template));
4493
4494       if (TREE_CODE (t) == ENUMERAL_TYPE 
4495           && !is_partial_instantiation)
4496         /* Now that the type has been registered on the instantiations
4497            list, we set up the enumerators.  Because the enumeration
4498            constants may involve the enumeration type itself, we make
4499            sure to register the type first, and then create the
4500            constants.  That way, doing tsubst_expr for the enumeration
4501            constants won't result in recursive calls here; we'll find
4502            the instantiation and exit above.  */
4503         tsubst_enum (template_type, t, arglist);
4504
4505       /* Reset the name of the type, now that CLASSTYPE_TEMPLATE_INFO
4506          is set up.  */
4507       if (TREE_CODE (t) != ENUMERAL_TYPE)
4508         DECL_NAME (type_decl) = classtype_mangled_name (t);
4509       if (!is_partial_instantiation)
4510         {
4511           /* For backwards compatibility; code that uses
4512              -fexternal-templates expects looking up a template to
4513              instantiate it.  I think DDD still relies on this.
4514              (jason 8/20/1998) */
4515           if (TREE_CODE (t) != ENUMERAL_TYPE
4516               && flag_external_templates
4517               && CLASSTYPE_INTERFACE_KNOWN (TREE_TYPE (template))
4518               && ! CLASSTYPE_INTERFACE_ONLY (TREE_TYPE (template)))
4519             add_pending_template (t);
4520         }
4521       else
4522         /* If the type makes use of template parameters, the
4523            code that generates debugging information will crash.  */
4524         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
4525
4526       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
4527     }
4528   timevar_pop (TV_NAME_LOOKUP);
4529 }
4530 \f
4531 struct pair_fn_data 
4532 {
4533   tree_fn_t fn;
4534   void *data;
4535   htab_t visited;
4536 };
4537
4538 /* Called from for_each_template_parm via walk_tree.  */
4539
4540 static tree
4541 for_each_template_parm_r (tp, walk_subtrees, d)
4542      tree *tp;
4543      int *walk_subtrees;
4544      void *d;
4545 {
4546   tree t = *tp;
4547   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
4548   tree_fn_t fn = pfd->fn;
4549   void *data = pfd->data;
4550   void **slot;
4551
4552   /* If we have already visited this tree, there's no need to walk
4553      subtrees.  Otherwise, add it to the visited table.  */
4554   slot = htab_find_slot (pfd->visited, *tp, INSERT);
4555   if (*slot)
4556     {
4557       *walk_subtrees = 0;
4558       return NULL_TREE;
4559     }
4560   *slot = *tp;
4561
4562   if (TYPE_P (t)
4563       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited))
4564     return error_mark_node;
4565
4566   switch (TREE_CODE (t))
4567     {
4568     case RECORD_TYPE:
4569       if (TYPE_PTRMEMFUNC_P (t))
4570         break;
4571       /* Fall through.  */
4572
4573     case UNION_TYPE:
4574     case ENUMERAL_TYPE:
4575       if (!TYPE_TEMPLATE_INFO (t))
4576         *walk_subtrees = 0;
4577       else if (for_each_template_parm (TREE_VALUE (TYPE_TEMPLATE_INFO (t)),
4578                                        fn, data, pfd->visited))
4579         return error_mark_node;
4580       break;
4581
4582     case METHOD_TYPE:
4583       /* Since we're not going to walk subtrees, we have to do this
4584          explicitly here.  */
4585       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
4586                                   pfd->visited))
4587         return error_mark_node;
4588       /* Fall through.  */
4589
4590     case FUNCTION_TYPE:
4591       /* Check the return type.  */
4592       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited))
4593         return error_mark_node;
4594
4595       /* Check the parameter types.  Since default arguments are not
4596          instantiated until they are needed, the TYPE_ARG_TYPES may
4597          contain expressions that involve template parameters.  But,
4598          no-one should be looking at them yet.  And, once they're
4599          instantiated, they don't contain template parameters, so
4600          there's no point in looking at them then, either.  */
4601       {
4602         tree parm;
4603
4604         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
4605           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
4606                                       pfd->visited))
4607             return error_mark_node;
4608
4609         /* Since we've already handled the TYPE_ARG_TYPES, we don't
4610            want walk_tree walking into them itself.  */
4611         *walk_subtrees = 0;
4612       }
4613       break;
4614
4615     case TYPEOF_TYPE:
4616       if (for_each_template_parm (TYPE_FIELDS (t), fn, data, 
4617                                   pfd->visited))
4618         return error_mark_node;
4619       break;
4620
4621     case FUNCTION_DECL:
4622     case VAR_DECL:
4623       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
4624           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
4625                                      pfd->visited))
4626         return error_mark_node;
4627       /* Fall through.  */
4628
4629     case PARM_DECL:
4630     case CONST_DECL:
4631       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
4632           && for_each_template_parm (DECL_INITIAL (t), fn, data,
4633                                      pfd->visited))
4634         return error_mark_node;
4635       if (DECL_CONTEXT (t) 
4636           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
4637                                      pfd->visited))
4638         return error_mark_node;
4639       break;
4640
4641     case BOUND_TEMPLATE_TEMPLATE_PARM:
4642       /* Record template parameters such as `T' inside `TT<T>'.  */
4643       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited))
4644         return error_mark_node;
4645       /* Fall through.  */
4646
4647     case TEMPLATE_TEMPLATE_PARM:
4648     case TEMPLATE_TYPE_PARM:
4649     case TEMPLATE_PARM_INDEX:
4650       if (fn && (*fn)(t, data))
4651         return error_mark_node;
4652       else if (!fn)
4653         return error_mark_node;
4654       break;
4655
4656     case TEMPLATE_DECL:
4657       /* A template template parameter is encountered */
4658       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
4659           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited))
4660         return error_mark_node;
4661
4662       /* Already substituted template template parameter */
4663       *walk_subtrees = 0;
4664       break;
4665
4666     case TYPENAME_TYPE:
4667       if (!fn 
4668           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
4669                                      data, pfd->visited))
4670         return error_mark_node;
4671       break;
4672
4673     case CONSTRUCTOR:
4674       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
4675           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
4676                                      (TREE_TYPE (t)), fn, data,
4677                                      pfd->visited))
4678         return error_mark_node;
4679       break;
4680       
4681     case INDIRECT_REF:
4682     case COMPONENT_REF:
4683       /* If there's no type, then this thing must be some expression
4684          involving template parameters.  */
4685       if (!fn && !TREE_TYPE (t))
4686         return error_mark_node;
4687       break;
4688
4689     case MODOP_EXPR:
4690     case CAST_EXPR:
4691     case REINTERPRET_CAST_EXPR:
4692     case CONST_CAST_EXPR:
4693     case STATIC_CAST_EXPR:
4694     case DYNAMIC_CAST_EXPR:
4695     case ARROW_EXPR:
4696     case DOTSTAR_EXPR:
4697     case TYPEID_EXPR:
4698     case LOOKUP_EXPR:
4699     case PSEUDO_DTOR_EXPR:
4700       if (!fn)
4701         return error_mark_node;
4702       break;
4703
4704     case BASELINK:
4705       /* If we do not handle this case specially, we end up walking
4706          the BINFO hierarchy, which is circular, and therefore
4707          confuses walk_tree.  */
4708       *walk_subtrees = 0;
4709       if (for_each_template_parm (BASELINK_FUNCTIONS (*tp), fn, data,
4710                                   pfd->visited))
4711         return error_mark_node;
4712       break;
4713
4714     default:
4715       break;
4716     }
4717
4718   /* We didn't find any template parameters we liked.  */
4719   return NULL_TREE;
4720 }
4721
4722 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM, 
4723    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T, 
4724    call FN with the parameter and the DATA.
4725    If FN returns nonzero, the iteration is terminated, and
4726    for_each_template_parm returns 1.  Otherwise, the iteration
4727    continues.  If FN never returns a nonzero value, the value
4728    returned by for_each_template_parm is 0.  If FN is NULL, it is
4729    considered to be the function which always returns 1.  */
4730
4731 static int
4732 for_each_template_parm (t, fn, data, visited)
4733      tree t;
4734      tree_fn_t fn;
4735      void* data;
4736      htab_t visited;
4737 {
4738   struct pair_fn_data pfd;
4739   int result;
4740
4741   /* Set up.  */
4742   pfd.fn = fn;
4743   pfd.data = data;
4744
4745   /* Walk the tree.  (Conceptually, we would like to walk without
4746      duplicates, but for_each_template_parm_r recursively calls
4747      for_each_template_parm, so we would need to reorganize a fair
4748      bit to use walk_tree_without_duplicates, so we keep our own
4749      visited list.)  */
4750   if (visited)
4751     pfd.visited = visited;
4752   else
4753     pfd.visited = htab_create (37, htab_hash_pointer, htab_eq_pointer, 
4754                                NULL);
4755   result = walk_tree (&t, 
4756                       for_each_template_parm_r, 
4757                       &pfd,
4758                       NULL) != NULL_TREE;
4759
4760   /* Clean up.  */
4761   if (!visited)
4762     htab_delete (pfd.visited);
4763
4764   return result;
4765 }
4766
4767 int
4768 uses_template_parms (t)
4769      tree t;
4770 {
4771   return for_each_template_parm (t, 0, 0, NULL);
4772 }
4773
4774 static int tinst_depth;
4775 extern int max_tinst_depth;
4776 #ifdef GATHER_STATISTICS
4777 int depth_reached;
4778 #endif
4779 static int tinst_level_tick;
4780 static int last_template_error_tick;
4781
4782 /* We're starting to instantiate D; record the template instantiation context
4783    for diagnostics and to restore it later.  */
4784
4785 int
4786 push_tinst_level (d)
4787      tree d;
4788 {
4789   tree new;
4790
4791   if (tinst_depth >= max_tinst_depth)
4792     {
4793       /* If the instantiation in question still has unbound template parms,
4794          we don't really care if we can't instantiate it, so just return.
4795          This happens with base instantiation for implicit `typename'.  */
4796       if (uses_template_parms (d))
4797         return 0;
4798
4799       last_template_error_tick = tinst_level_tick;
4800       error ("template instantiation depth exceeds maximum of %d (use -ftemplate-depth-NN to increase the maximum) instantiating `%D'",
4801              max_tinst_depth, d);
4802
4803       print_instantiation_context ();
4804
4805       return 0;
4806     }
4807
4808   new = build_expr_wfl (d, input_filename, input_line, 0);
4809   TREE_CHAIN (new) = current_tinst_level;
4810   current_tinst_level = new;
4811
4812   ++tinst_depth;
4813 #ifdef GATHER_STATISTICS
4814   if (tinst_depth > depth_reached)
4815     depth_reached = tinst_depth;
4816 #endif
4817
4818   ++tinst_level_tick;
4819   return 1;
4820 }
4821
4822 /* We're done instantiating this template; return to the instantiation
4823    context.  */
4824
4825 void
4826 pop_tinst_level ()
4827 {
4828   tree old = current_tinst_level;
4829
4830   /* Restore the filename and line number stashed away when we started
4831      this instantiation.  */
4832   input_line = TINST_LINE (old);
4833   input_filename = TINST_FILE (old);
4834   extract_interface_info ();
4835   
4836   current_tinst_level = TREE_CHAIN (old);
4837   --tinst_depth;
4838   ++tinst_level_tick;
4839 }
4840
4841 /* We're instantiating a deferred template; restore the template
4842    instantiation context in which the instantiation was requested, which
4843    is one step out from LEVEL.  */
4844
4845 static void
4846 reopen_tinst_level (level)
4847      tree level;
4848 {
4849   tree t;
4850
4851   tinst_depth = 0;
4852   for (t = level; t; t = TREE_CHAIN (t))
4853     ++tinst_depth;
4854
4855   current_tinst_level = level;
4856   pop_tinst_level ();
4857 }
4858
4859 /* Return the outermost template instantiation context, for use with
4860    -falt-external-templates.  */
4861
4862 tree
4863 tinst_for_decl ()
4864 {
4865   tree p = current_tinst_level;
4866
4867   if (p)
4868     for (; TREE_CHAIN (p) ; p = TREE_CHAIN (p))
4869       ;
4870   return p;
4871 }
4872
4873 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
4874    vector of template arguments, as for tsubst.
4875
4876    Returns an appropriate tsubst'd friend declaration.  */
4877
4878 static tree
4879 tsubst_friend_function (decl, args)
4880      tree decl;
4881      tree args;
4882 {
4883   tree new_friend;
4884   location_t saved_loc = input_location;
4885
4886   input_location = DECL_SOURCE_LOCATION (decl);
4887
4888   if (TREE_CODE (decl) == FUNCTION_DECL 
4889       && DECL_TEMPLATE_INSTANTIATION (decl)
4890       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
4891     /* This was a friend declared with an explicit template
4892        argument list, e.g.:
4893        
4894        friend void f<>(T);
4895        
4896        to indicate that f was a template instantiation, not a new
4897        function declaration.  Now, we have to figure out what
4898        instantiation of what template.  */
4899     {
4900       tree template_id, arglist, fns;
4901       tree new_args;
4902       tree tmpl;
4903       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
4904       
4905       /* Friend functions are looked up in the containing namespace scope.
4906          We must enter that scope, to avoid finding member functions of the
4907          current cless with same name.  */
4908       push_nested_namespace (ns);
4909       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
4910                          tf_error | tf_warning, NULL_TREE);
4911       pop_nested_namespace (ns);
4912       arglist = tsubst (DECL_TI_ARGS (decl), args,
4913                         tf_error | tf_warning, NULL_TREE);
4914       template_id = lookup_template_function (fns, arglist);
4915       
4916       new_friend = tsubst (decl, args, tf_error | tf_warning, NULL_TREE);
4917       tmpl = determine_specialization (template_id, new_friend,
4918                                        &new_args, 
4919                                        /*need_member_template=*/0);
4920       new_friend = instantiate_template (tmpl, new_args, tf_error);
4921       goto done;
4922     }
4923
4924   new_friend = tsubst (decl, args, tf_error | tf_warning, NULL_TREE);
4925         
4926   /* The NEW_FRIEND will look like an instantiation, to the
4927      compiler, but is not an instantiation from the point of view of
4928      the language.  For example, we might have had:
4929      
4930      template <class T> struct S {
4931        template <class U> friend void f(T, U);
4932      };
4933      
4934      Then, in S<int>, template <class U> void f(int, U) is not an
4935      instantiation of anything.  */
4936   DECL_USE_TEMPLATE (new_friend) = 0;
4937   if (TREE_CODE (decl) == TEMPLATE_DECL)
4938     {
4939       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
4940       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
4941         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
4942     }
4943
4944   /* The mangled name for the NEW_FRIEND is incorrect.  The function
4945      is not a template instantiation and should not be mangled like
4946      one.  Therefore, we forget the mangling here; we'll recompute it
4947      later if we need it.  */
4948   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
4949     {
4950       SET_DECL_RTL (new_friend, NULL_RTX);
4951       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
4952     }
4953       
4954   if (DECL_NAMESPACE_SCOPE_P (new_friend))
4955     {
4956       tree old_decl;
4957       tree new_friend_template_info;
4958       tree new_friend_result_template_info;
4959       tree ns;
4960       int  new_friend_is_defn;
4961
4962       /* We must save some information from NEW_FRIEND before calling
4963          duplicate decls since that function will free NEW_FRIEND if
4964          possible.  */
4965       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
4966       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
4967         {
4968           /* This declaration is a `primary' template.  */
4969           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
4970           
4971           new_friend_is_defn 
4972             = DECL_INITIAL (DECL_TEMPLATE_RESULT (new_friend)) != NULL_TREE;
4973           new_friend_result_template_info
4974             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
4975         }
4976       else
4977         {
4978           new_friend_is_defn = DECL_INITIAL (new_friend) != NULL_TREE;
4979           new_friend_result_template_info = NULL_TREE;
4980         }
4981
4982       /* Inside pushdecl_namespace_level, we will push into the
4983          current namespace. However, the friend function should go
4984          into the namespace of the template.  */
4985       ns = decl_namespace_context (new_friend);
4986       push_nested_namespace (ns);
4987       old_decl = pushdecl_namespace_level (new_friend);
4988       pop_nested_namespace (ns);
4989
4990       if (old_decl != new_friend)
4991         {
4992           /* This new friend declaration matched an existing
4993              declaration.  For example, given:
4994
4995                template <class T> void f(T);
4996                template <class U> class C { 
4997                  template <class T> friend void f(T) {} 
4998                };
4999
5000              the friend declaration actually provides the definition
5001              of `f', once C has been instantiated for some type.  So,
5002              old_decl will be the out-of-class template declaration,
5003              while new_friend is the in-class definition.
5004
5005              But, if `f' was called before this point, the
5006              instantiation of `f' will have DECL_TI_ARGS corresponding
5007              to `T' but not to `U', references to which might appear
5008              in the definition of `f'.  Previously, the most general
5009              template for an instantiation of `f' was the out-of-class
5010              version; now it is the in-class version.  Therefore, we
5011              run through all specialization of `f', adding to their
5012              DECL_TI_ARGS appropriately.  In particular, they need a
5013              new set of outer arguments, corresponding to the
5014              arguments for this class instantiation.  
5015
5016              The same situation can arise with something like this:
5017
5018                friend void f(int);
5019                template <class T> class C { 
5020                  friend void f(T) {}
5021                };
5022
5023              when `C<int>' is instantiated.  Now, `f(int)' is defined
5024              in the class.  */
5025
5026           if (!new_friend_is_defn)
5027             /* On the other hand, if the in-class declaration does
5028                *not* provide a definition, then we don't want to alter
5029                existing definitions.  We can just leave everything
5030                alone.  */
5031             ;
5032           else
5033             {
5034               /* Overwrite whatever template info was there before, if
5035                  any, with the new template information pertaining to
5036                  the declaration.  */
5037               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
5038
5039               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
5040                 /* duplicate_decls will take care of this case.  */
5041                 ;
5042               else 
5043                 {
5044                   tree t;
5045                   tree new_friend_args;
5046
5047                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl)) 
5048                     = new_friend_result_template_info;
5049                     
5050                   new_friend_args = TI_ARGS (new_friend_template_info);
5051                   for (t = DECL_TEMPLATE_SPECIALIZATIONS (old_decl); 
5052                        t != NULL_TREE;
5053                        t = TREE_CHAIN (t))
5054                     {
5055                       tree spec = TREE_VALUE (t);
5056                   
5057                       DECL_TI_ARGS (spec) 
5058                         = add_outermost_template_args (new_friend_args,
5059                                                        DECL_TI_ARGS (spec));
5060                     }
5061
5062                   /* Now, since specializations are always supposed to
5063                      hang off of the most general template, we must move
5064                      them.  */
5065                   t = most_general_template (old_decl);
5066                   if (t != old_decl)
5067                     {
5068                       DECL_TEMPLATE_SPECIALIZATIONS (t)
5069                         = chainon (DECL_TEMPLATE_SPECIALIZATIONS (t),
5070                                    DECL_TEMPLATE_SPECIALIZATIONS (old_decl));
5071                       DECL_TEMPLATE_SPECIALIZATIONS (old_decl) = NULL_TREE;
5072                     }
5073                 }
5074             }
5075
5076           /* The information from NEW_FRIEND has been merged into OLD_DECL
5077              by duplicate_decls.  */
5078           new_friend = old_decl;
5079         }
5080     }
5081   else if (COMPLETE_TYPE_P (DECL_CONTEXT (new_friend)))
5082     {
5083       /* Check to see that the declaration is really present, and,
5084          possibly obtain an improved declaration.  */
5085       tree fn = check_classfn (DECL_CONTEXT (new_friend),
5086                                new_friend);
5087       
5088       if (fn)
5089         new_friend = fn;
5090     }
5091
5092  done:
5093   input_location = saved_loc;
5094   return new_friend;
5095 }
5096
5097 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
5098    template arguments, as for tsubst.
5099
5100    Returns an appropriate tsubst'd friend type or error_mark_node on
5101    failure.  */
5102
5103 static tree
5104 tsubst_friend_class (friend_tmpl, args)
5105      tree friend_tmpl;
5106      tree args;
5107 {
5108   tree friend_type;
5109   tree tmpl;
5110   tree context;
5111
5112   context = DECL_CONTEXT (friend_tmpl);
5113
5114   if (context)
5115     {
5116       if (TREE_CODE (context) == NAMESPACE_DECL)
5117         push_nested_namespace (context);
5118       else
5119         push_nested_class (tsubst (context, args, tf_none, NULL_TREE)); 
5120     }
5121
5122   /* First, we look for a class template.  */
5123   tmpl = lookup_name (DECL_NAME (friend_tmpl), /*prefer_type=*/0); 
5124
5125   /* But, if we don't find one, it might be because we're in a
5126      situation like this:
5127
5128        template <class T>
5129        struct S {
5130          template <class U>
5131          friend struct S;
5132        };
5133
5134      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
5135      for `S<int>', not the TEMPLATE_DECL.  */
5136   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
5137     {
5138       tmpl = lookup_name (DECL_NAME (friend_tmpl), /*prefer_type=*/1);
5139       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
5140     }
5141
5142   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
5143     {
5144       /* The friend template has already been declared.  Just
5145          check to see that the declarations match, and install any new
5146          default parameters.  We must tsubst the default parameters,
5147          of course.  We only need the innermost template parameters
5148          because that is all that redeclare_class_template will look
5149          at.  */
5150       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
5151           > TMPL_ARGS_DEPTH (args))
5152         {
5153           tree parms;
5154           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
5155                                          args, tf_error | tf_warning);
5156           redeclare_class_template (TREE_TYPE (tmpl), parms);
5157         }
5158
5159       friend_type = TREE_TYPE (tmpl);
5160     }
5161   else
5162     {
5163       /* The friend template has not already been declared.  In this
5164          case, the instantiation of the template class will cause the
5165          injection of this template into the global scope.  */
5166       tmpl = tsubst (friend_tmpl, args, tf_error | tf_warning, NULL_TREE);
5167
5168       /* The new TMPL is not an instantiation of anything, so we
5169          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
5170          the new type because that is supposed to be the corresponding
5171          template decl, i.e., TMPL.  */
5172       DECL_USE_TEMPLATE (tmpl) = 0;
5173       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
5174       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
5175
5176       /* Inject this template into the global scope.  */
5177       friend_type = TREE_TYPE (pushdecl_top_level (tmpl));
5178     }
5179
5180   if (context) 
5181     {
5182       if (TREE_CODE (context) == NAMESPACE_DECL)
5183         pop_nested_namespace (context);
5184       else
5185         pop_nested_class ();
5186     }
5187
5188   return friend_type;
5189 }
5190
5191 /* Returns zero if TYPE cannot be completed later due to circularity.
5192    Otherwise returns one.  */
5193
5194 static int
5195 can_complete_type_without_circularity (type)
5196      tree type;
5197 {
5198   if (type == NULL_TREE || type == error_mark_node)
5199     return 0;
5200   else if (COMPLETE_TYPE_P (type))
5201     return 1;
5202   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
5203     return can_complete_type_without_circularity (TREE_TYPE (type));
5204   else if (CLASS_TYPE_P (type) && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
5205     return 0;
5206   else
5207     return 1;
5208 }
5209
5210 tree
5211 instantiate_class_template (type)
5212      tree type;
5213 {
5214   tree template, args, pattern, t, member;
5215   tree typedecl;
5216   tree pbinfo;
5217   
5218   if (type == error_mark_node)
5219     return error_mark_node;
5220
5221   if (TYPE_BEING_DEFINED (type) 
5222       || COMPLETE_TYPE_P (type)
5223       || dependent_type_p (type))
5224     return type;
5225
5226   /* Figure out which template is being instantiated.  */
5227   template = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
5228   my_friendly_assert (TREE_CODE (template) == TEMPLATE_DECL, 279);
5229
5230   /* Figure out which arguments are being used to do the
5231      instantiation.  */
5232   args = CLASSTYPE_TI_ARGS (type);
5233
5234   /* Determine what specialization of the original template to
5235      instantiate.  */
5236   t = most_specialized_class (template, args);
5237   if (t == error_mark_node)
5238     {
5239       const char *str = "candidates are:";
5240       error ("ambiguous class template instantiation for `%#T'", type);
5241       for (t = DECL_TEMPLATE_SPECIALIZATIONS (template); t; 
5242            t = TREE_CHAIN (t))
5243         {
5244           if (get_class_bindings (TREE_VALUE (t), TREE_PURPOSE (t),
5245                                   args))
5246             {
5247               cp_error_at ("%s %+#T", str, TREE_TYPE (t));
5248               str = "               ";
5249             }
5250         }
5251       TYPE_BEING_DEFINED (type) = 1;
5252       return error_mark_node;
5253     }
5254
5255   if (t)
5256     pattern = TREE_TYPE (t);
5257   else
5258     pattern = TREE_TYPE (template);
5259
5260   /* If the template we're instantiating is incomplete, then clearly
5261      there's nothing we can do.  */
5262   if (!COMPLETE_TYPE_P (pattern))
5263     return type;
5264
5265   /* If we've recursively instantiated too many templates, stop.  */
5266   if (! push_tinst_level (type))
5267     return type;
5268
5269   /* Now we're really doing the instantiation.  Mark the type as in
5270      the process of being defined.  */
5271   TYPE_BEING_DEFINED (type) = 1;
5272
5273   /* We may be in the middle of deferred access check.  Disable
5274      it now.  */
5275   push_deferring_access_checks (dk_no_deferred);
5276
5277   maybe_push_to_top_level (uses_template_parms (type));
5278
5279   if (t)
5280     {
5281       /* This TYPE is actually an instantiation of a partial
5282          specialization.  We replace the innermost set of ARGS with
5283          the arguments appropriate for substitution.  For example,
5284          given:
5285
5286            template <class T> struct S {};
5287            template <class T> struct S<T*> {};
5288          
5289          and supposing that we are instantiating S<int*>, ARGS will
5290          present be {int*} but we need {int}.  */
5291       tree inner_args 
5292         = get_class_bindings (TREE_VALUE (t), TREE_PURPOSE (t),
5293                               args);
5294
5295       /* If there were multiple levels in ARGS, replacing the
5296          innermost level would alter CLASSTYPE_TI_ARGS, which we don't
5297          want, so we make a copy first.  */
5298       if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
5299         {
5300           args = copy_node (args);
5301           SET_TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args), inner_args);
5302         }
5303       else
5304         args = inner_args;
5305     }
5306
5307   if (flag_external_templates)
5308     {
5309       if (flag_alt_external_templates)
5310         {
5311           CLASSTYPE_INTERFACE_ONLY (type) = interface_only;
5312           SET_CLASSTYPE_INTERFACE_UNKNOWN_X (type, interface_unknown);
5313         }
5314       else
5315         {
5316           CLASSTYPE_INTERFACE_ONLY (type) = CLASSTYPE_INTERFACE_ONLY (pattern);
5317           SET_CLASSTYPE_INTERFACE_UNKNOWN_X
5318             (type, CLASSTYPE_INTERFACE_UNKNOWN (pattern));
5319         }
5320     }
5321   else
5322     {
5323       SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
5324     }
5325
5326   TYPE_HAS_CONSTRUCTOR (type) = TYPE_HAS_CONSTRUCTOR (pattern);
5327   TYPE_HAS_DESTRUCTOR (type) = TYPE_HAS_DESTRUCTOR (pattern);
5328   TYPE_OVERLOADS_CALL_EXPR (type) = TYPE_OVERLOADS_CALL_EXPR (pattern);
5329   TYPE_OVERLOADS_ARRAY_REF (type) = TYPE_OVERLOADS_ARRAY_REF (pattern);
5330   TYPE_OVERLOADS_ARROW (type) = TYPE_OVERLOADS_ARROW (pattern);
5331   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
5332   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
5333   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
5334   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
5335   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
5336   TYPE_HAS_ABSTRACT_ASSIGN_REF (type) = TYPE_HAS_ABSTRACT_ASSIGN_REF (pattern);
5337   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
5338   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
5339   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
5340   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
5341   TYPE_BASE_CONVS_MAY_REQUIRE_CODE_P (type)
5342     = TYPE_BASE_CONVS_MAY_REQUIRE_CODE_P (pattern);
5343   TYPE_USES_MULTIPLE_INHERITANCE (type)
5344     = TYPE_USES_MULTIPLE_INHERITANCE (pattern);
5345   TYPE_USES_VIRTUAL_BASECLASSES (type)
5346     = TYPE_USES_VIRTUAL_BASECLASSES (pattern);
5347   TYPE_PACKED (type) = TYPE_PACKED (pattern);
5348   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
5349   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
5350   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
5351   if (ANON_AGGR_TYPE_P (pattern))
5352     SET_ANON_AGGR_TYPE_P (type);
5353
5354   pbinfo = TYPE_BINFO (pattern);
5355   
5356   if (BINFO_BASETYPES (pbinfo))
5357     {
5358       tree base_list = NULL_TREE;
5359       tree pbases = BINFO_BASETYPES (pbinfo);
5360       tree paccesses = BINFO_BASEACCESSES (pbinfo);
5361       int i;
5362
5363       /* Substitute into each of the bases to determine the actual
5364          basetypes.  */
5365       for (i = 0; i < TREE_VEC_LENGTH (pbases); ++i)
5366         {
5367           tree base;
5368           tree access;
5369           tree pbase;
5370
5371           pbase = TREE_VEC_ELT (pbases, i);
5372           access = TREE_VEC_ELT (paccesses, i);
5373
5374           /* Substitute to figure out the base class.  */
5375           base = tsubst (BINFO_TYPE (pbase), args, tf_error, NULL_TREE);
5376           if (base == error_mark_node)
5377             continue;
5378           
5379           base_list = tree_cons (access, base, base_list);
5380           TREE_VIA_VIRTUAL (base_list) = TREE_VIA_VIRTUAL (pbase);
5381         }
5382
5383       /* The list is now in reverse order; correct that.  */
5384       base_list = nreverse (base_list);
5385
5386       /* Now call xref_basetypes to set up all the base-class
5387          information.  */
5388       xref_basetypes (type, base_list);
5389     }
5390
5391   /* Now that our base classes are set up, enter the scope of the
5392      class, so that name lookups into base classes, etc. will work
5393      correctly.  This is precisely analogous to what we do in
5394      begin_class_definition when defining an ordinary non-template
5395      class.  */
5396   pushclass (type, true);
5397
5398   /* Now members are processed in the order of declaration.  */
5399   for (member = CLASSTYPE_DECL_LIST (pattern); member; member = TREE_CHAIN (member))
5400     {
5401       tree t = TREE_VALUE (member);
5402
5403       if (TREE_PURPOSE (member))
5404         {
5405           if (TYPE_P (t))
5406             {
5407               /* Build new CLASSTYPE_NESTED_UTDS.  */
5408
5409               tree tag = t;
5410               tree name = TYPE_IDENTIFIER (tag);
5411               tree newtag;
5412
5413               newtag = tsubst (tag, args, tf_error, NULL_TREE);
5414               my_friendly_assert (newtag != error_mark_node, 20010206);
5415               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
5416                 {
5417                   if (TYPE_LANG_SPECIFIC (tag) && CLASSTYPE_IS_TEMPLATE (tag))
5418                     /* Unfortunately, lookup_template_class sets
5419                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
5420                        instantiation (i.e., for the type of a member template
5421                        class nested within a template class.)  This behavior is
5422                        required for maybe_process_partial_specialization to work
5423                        correctly, but is not accurate in this case; the TAG is not
5424                        an instantiation of anything.  (The corresponding
5425                        TEMPLATE_DECL is an instantiation, but the TYPE is not.) */
5426                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
5427
5428                   /* Now, we call pushtag to put this NEWTAG into the scope of
5429                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
5430                      pushtag calling push_template_decl.  We don't have to do
5431                      this for enums because it will already have been done in
5432                      tsubst_enum.  */
5433                   if (name)
5434                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
5435                   pushtag (name, newtag, /*globalize=*/0);
5436                 }
5437             }
5438           else if (TREE_CODE (t) == FUNCTION_DECL 
5439                    || DECL_FUNCTION_TEMPLATE_P (t))
5440             {
5441               /* Build new TYPE_METHODS.  */
5442
5443               tree r = tsubst (t, args, tf_error, NULL_TREE);
5444               set_current_access_from_decl (r);
5445               grok_special_member_properties (r);
5446               finish_member_declaration (r);
5447             }
5448           else
5449             {
5450               /* Build new TYPE_FIELDS.  */
5451
5452               if (TREE_CODE (t) != CONST_DECL)
5453                 {
5454                   tree r;
5455
5456                   /* The the file and line for this declaration, to
5457                      assist in error message reporting.  Since we
5458                      called push_tinst_level above, we don't need to
5459                      restore these.  */
5460                   input_location = DECL_SOURCE_LOCATION (t);
5461
5462                   r = tsubst (t, args, tf_error | tf_warning, NULL_TREE);
5463                   if (TREE_CODE (r) == VAR_DECL)
5464                     {
5465                       tree init;
5466
5467                       if (DECL_INITIALIZED_IN_CLASS_P (r))
5468                         init = tsubst_expr (DECL_INITIAL (t), args,
5469                                             tf_error | tf_warning, NULL_TREE);
5470                       else
5471                         init = NULL_TREE;
5472
5473                       finish_static_data_member_decl (r, init,
5474                                                       /*asmspec_tree=*/NULL_TREE, 
5475                                                       /*flags=*/0);
5476
5477                       if (DECL_INITIALIZED_IN_CLASS_P (r))
5478                         check_static_variable_definition (r, TREE_TYPE (r));
5479                     }
5480                   else if (TREE_CODE (r) == FIELD_DECL)
5481                     {
5482                       /* Determine whether R has a valid type and can be
5483                          completed later.  If R is invalid, then it is
5484                          replaced by error_mark_node so that it will not be
5485                          added to TYPE_FIELDS.  */
5486                       tree rtype = TREE_TYPE (r);
5487                       if (can_complete_type_without_circularity (rtype))
5488                         complete_type (rtype);
5489
5490                       if (!COMPLETE_TYPE_P (rtype))
5491                         {
5492                           cxx_incomplete_type_error (r, rtype);
5493                           r = error_mark_node;
5494                         }
5495                     }
5496
5497                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
5498                      such a thing will already have been added to the field
5499                      list by tsubst_enum in finish_member_declaration in the
5500                      CLASSTYPE_NESTED_UTDS case above.  */
5501                   if (!(TREE_CODE (r) == TYPE_DECL
5502                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
5503                         && DECL_ARTIFICIAL (r)))
5504                     {
5505                       set_current_access_from_decl (r);
5506                       finish_member_declaration (r);
5507                     }
5508                 }
5509             }
5510         }
5511       else
5512         {
5513           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
5514             {
5515               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
5516
5517               tree friend_type = t;
5518               tree new_friend_type;
5519
5520               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
5521                 new_friend_type = tsubst_friend_class (friend_type, args);
5522               else if (uses_template_parms (friend_type))
5523                 new_friend_type = tsubst (friend_type, args,
5524                                           tf_error | tf_warning, NULL_TREE);
5525               else 
5526                 {
5527                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
5528
5529                   /* The call to xref_tag_from_type does injection for friend
5530                      classes.  */
5531                   push_nested_namespace (ns);
5532                   new_friend_type = 
5533                     xref_tag_from_type (friend_type, NULL_TREE, 1);
5534                   pop_nested_namespace (ns);
5535                 }
5536
5537               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
5538                 /* Trick make_friend_class into realizing that the friend
5539                    we're adding is a template, not an ordinary class.  It's
5540                    important that we use make_friend_class since it will
5541                    perform some error-checking and output cross-reference
5542                    information.  */
5543                 ++processing_template_decl;
5544
5545               if (new_friend_type != error_mark_node)
5546                 make_friend_class (type, new_friend_type);
5547
5548               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
5549                 --processing_template_decl;
5550             }
5551           else
5552             /* Build new DECL_FRIENDLIST.  */
5553             add_friend (type, tsubst_friend_function (t, args));
5554         }
5555     }
5556
5557   /* Set the file and line number information to whatever is given for
5558      the class itself.  This puts error messages involving generated
5559      implicit functions at a predictable point, and the same point
5560      that would be used for non-template classes.  */
5561   typedecl = TYPE_MAIN_DECL (type);
5562   input_location = DECL_SOURCE_LOCATION (typedecl);
5563   
5564   unreverse_member_declarations (type);
5565   finish_struct_1 (type);
5566   CLASSTYPE_GOT_SEMICOLON (type) = 1;
5567
5568   /* Clear this now so repo_template_used is happy.  */
5569   TYPE_BEING_DEFINED (type) = 0;
5570   repo_template_used (type);
5571
5572   /* Now that the class is complete, instantiate default arguments for
5573      any member functions.  We don't do this earlier because the
5574      default arguments may reference members of the class.  */
5575   if (!PRIMARY_TEMPLATE_P (template))
5576     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
5577       if (TREE_CODE (t) == FUNCTION_DECL 
5578           /* Implicitly generated member functions will not have template
5579              information; they are not instantiations, but instead are
5580              created "fresh" for each instantiation.  */
5581           && DECL_TEMPLATE_INFO (t))
5582         tsubst_default_arguments (t);
5583
5584   popclass ();
5585   pop_from_top_level ();
5586   pop_deferring_access_checks ();
5587   pop_tinst_level ();
5588
5589   if (TYPE_CONTAINS_VPTR_P (type))
5590     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
5591
5592   return type;
5593 }
5594
5595 static int
5596 list_eq (t1, t2)
5597      tree t1, t2;
5598 {
5599   if (t1 == NULL_TREE)
5600     return t2 == NULL_TREE;
5601   if (t2 == NULL_TREE)
5602     return 0;
5603   /* Don't care if one declares its arg const and the other doesn't -- the
5604      main variant of the arg type is all that matters.  */
5605   if (TYPE_MAIN_VARIANT (TREE_VALUE (t1))
5606       != TYPE_MAIN_VARIANT (TREE_VALUE (t2)))
5607     return 0;
5608   return list_eq (TREE_CHAIN (t1), TREE_CHAIN (t2));
5609 }
5610
5611 /* If arg is a non-type template parameter that does not depend on template
5612    arguments, fold it like we weren't in the body of a template.  */
5613
5614 static tree
5615 maybe_fold_nontype_arg (arg)
5616      tree arg;
5617 {
5618   if (arg && !TYPE_P (arg) && !uses_template_parms (arg))
5619     {
5620       /* Sometimes, one of the args was an expression involving a
5621          template constant parameter, like N - 1.  Now that we've
5622          tsubst'd, we might have something like 2 - 1.  This will
5623          confuse lookup_template_class, so we do constant folding
5624          here.  We have to unset processing_template_decl, to
5625          fool build_expr_from_tree() into building an actual
5626          tree.  */
5627
5628       /* If the TREE_TYPE of ARG is not NULL_TREE, ARG is already
5629          as simple as it's going to get, and trying to reprocess
5630          the trees will break.  */
5631       if (!TREE_TYPE (arg))
5632         {
5633           int saved_processing_template_decl = processing_template_decl; 
5634           processing_template_decl = 0;
5635           arg = build_expr_from_tree (arg);
5636           processing_template_decl = saved_processing_template_decl; 
5637         }
5638
5639       arg = fold (arg);
5640     }
5641   return arg;
5642 }
5643
5644 /* Apply maybe_fold_nontype_arg on a list or vector of args.  */
5645
5646 static void
5647 maybe_fold_nontype_args (tree targs)
5648 {
5649   if (!targs)
5650     /*OK*/;
5651   else if (TREE_CODE (targs) == TREE_LIST)
5652     {
5653       tree chain;
5654       for (chain = targs; chain; chain = TREE_CHAIN (chain))
5655         TREE_VALUE (chain) = maybe_fold_nontype_arg (TREE_VALUE (chain));
5656     }
5657   else
5658     {
5659       int i;
5660       for (i = 0; i < TREE_VEC_LENGTH (targs); ++i)
5661         TREE_VEC_ELT (targs, i)
5662           = maybe_fold_nontype_arg (TREE_VEC_ELT (targs, i));
5663     }
5664 }
5665
5666 /* Substitute ARGS into the vector of template arguments T.  */
5667
5668 static tree
5669 tsubst_template_arg_vector (t, args, complain)
5670      tree t;
5671      tree args;
5672      tsubst_flags_t complain;
5673 {
5674   int len = TREE_VEC_LENGTH (t), need_new = 0, i;
5675   tree *elts = (tree *) alloca (len * sizeof (tree));
5676   
5677   memset ((char *) elts, 0, len * sizeof (tree));
5678   
5679   for (i = 0; i < len; i++)
5680     {
5681       if (TREE_VEC_ELT (t, i) != NULL_TREE
5682           && TREE_CODE (TREE_VEC_ELT (t, i)) == TREE_VEC)
5683         elts[i] = tsubst_template_arg_vector (TREE_VEC_ELT (t, i),
5684                                               args, complain);
5685       else
5686         elts[i] = maybe_fold_nontype_arg
5687           (tsubst_expr (TREE_VEC_ELT (t, i), args, complain,
5688                         NULL_TREE));
5689       
5690       if (elts[i] == error_mark_node)
5691         return error_mark_node;
5692
5693       if (elts[i] != TREE_VEC_ELT (t, i))
5694         need_new = 1;
5695     }
5696   
5697   if (!need_new)
5698     return t;
5699   
5700   t = make_tree_vec (len);
5701   for (i = 0; i < len; i++)
5702     TREE_VEC_ELT (t, i) = elts[i];
5703   
5704   return t;
5705 }
5706
5707 /* Return the result of substituting ARGS into the template parameters
5708    given by PARMS.  If there are m levels of ARGS and m + n levels of
5709    PARMS, then the result will contain n levels of PARMS.  For
5710    example, if PARMS is `template <class T> template <class U>
5711    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
5712    result will be `template <int*, double, class V>'.  */
5713
5714 static tree
5715 tsubst_template_parms (parms, args, complain)
5716      tree parms;
5717      tree args;
5718      tsubst_flags_t complain;
5719 {
5720   tree r = NULL_TREE;
5721   tree* new_parms;
5722
5723   for (new_parms = &r;
5724        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
5725        new_parms = &(TREE_CHAIN (*new_parms)),
5726          parms = TREE_CHAIN (parms))
5727     {
5728       tree new_vec = 
5729         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
5730       int i;
5731       
5732       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
5733         {
5734           tree tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
5735           tree default_value = TREE_PURPOSE (tuple);
5736           tree parm_decl = TREE_VALUE (tuple);
5737
5738           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
5739           default_value = tsubst_expr (default_value, args,
5740                                        complain, NULL_TREE);
5741           tuple = build_tree_list (maybe_fold_nontype_arg (default_value), 
5742                                    parm_decl);
5743           TREE_VEC_ELT (new_vec, i) = tuple;
5744         }
5745       
5746       *new_parms = 
5747         tree_cons (size_int (TMPL_PARMS_DEPTH (parms) 
5748                              - TMPL_ARGS_DEPTH (args)),
5749                    new_vec, NULL_TREE);
5750     }
5751
5752   return r;
5753 }
5754
5755 /* Substitute the ARGS into the indicated aggregate (or enumeration)
5756    type T.  If T is not an aggregate or enumeration type, it is
5757    handled as if by tsubst.  IN_DECL is as for tsubst.  If
5758    ENTERING_SCOPE is nonzero, T is the context for a template which
5759    we are presently tsubst'ing.  Return the substituted value.  */
5760
5761 static tree
5762 tsubst_aggr_type (t, args, complain, in_decl, entering_scope)
5763      tree t;
5764      tree args;
5765      tsubst_flags_t complain;
5766      tree in_decl;
5767      int entering_scope;
5768 {
5769   if (t == NULL_TREE)
5770     return NULL_TREE;
5771
5772   switch (TREE_CODE (t))
5773     {
5774     case RECORD_TYPE:
5775       if (TYPE_PTRMEMFUNC_P (t))
5776         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
5777
5778       /* else fall through */
5779     case ENUMERAL_TYPE:
5780     case UNION_TYPE:
5781       if (TYPE_TEMPLATE_INFO (t))
5782         {
5783           tree argvec;
5784           tree context;
5785           tree r;
5786
5787           /* First, determine the context for the type we are looking
5788              up.  */
5789           if (TYPE_CONTEXT (t) != NULL_TREE)
5790             context = tsubst_aggr_type (TYPE_CONTEXT (t), args,
5791                                         complain,
5792                                         in_decl, /*entering_scope=*/1);
5793           else
5794             context = NULL_TREE;
5795
5796           /* Then, figure out what arguments are appropriate for the
5797              type we are trying to find.  For example, given:
5798
5799                template <class T> struct S;
5800                template <class T, class U> void f(T, U) { S<U> su; }
5801
5802              and supposing that we are instantiating f<int, double>,
5803              then our ARGS will be {int, double}, but, when looking up
5804              S we only want {double}.  */
5805           argvec = tsubst_template_arg_vector (TYPE_TI_ARGS (t), args,
5806                                                complain);
5807           if (argvec == error_mark_node)
5808             return error_mark_node;
5809
5810           r = lookup_template_class (t, argvec, in_decl, context,
5811                                      entering_scope, complain);
5812
5813           return cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
5814         }
5815       else 
5816         /* This is not a template type, so there's nothing to do.  */
5817         return t;
5818
5819     default:
5820       return tsubst (t, args, complain, in_decl);
5821     }
5822 }
5823
5824 /* Substitute into the default argument ARG (a default argument for
5825    FN), which has the indicated TYPE.  */
5826
5827 tree
5828 tsubst_default_argument (fn, type, arg)
5829      tree fn;
5830      tree type;
5831      tree arg;
5832 {
5833   /* This default argument came from a template.  Instantiate the
5834      default argument here, not in tsubst.  In the case of
5835      something like: 
5836      
5837        template <class T>
5838        struct S {
5839          static T t();
5840          void f(T = t());
5841        };
5842      
5843      we must be careful to do name lookup in the scope of S<T>,
5844      rather than in the current class.
5845
5846      ??? current_class_type affects a lot more than name lookup.  This is
5847      very fragile.  Fortunately, it will go away when we do 2-phase name
5848      binding properly.  */
5849
5850   /* FN is already the desired FUNCTION_DECL.  */
5851   push_access_scope (fn);
5852
5853   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
5854                      tf_error | tf_warning, NULL_TREE);
5855   
5856   pop_access_scope (fn);
5857
5858   /* Make sure the default argument is reasonable.  */
5859   arg = check_default_argument (type, arg);
5860
5861   return arg;
5862 }
5863
5864 /* Substitute into all the default arguments for FN.  */
5865
5866 static void
5867 tsubst_default_arguments (fn)
5868      tree fn;
5869 {
5870   tree arg;
5871   tree tmpl_args;
5872
5873   tmpl_args = DECL_TI_ARGS (fn);
5874
5875   /* If this function is not yet instantiated, we certainly don't need
5876      its default arguments.  */
5877   if (uses_template_parms (tmpl_args))
5878     return;
5879
5880   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn)); 
5881        arg; 
5882        arg = TREE_CHAIN (arg))
5883     if (TREE_PURPOSE (arg))
5884       TREE_PURPOSE (arg) = tsubst_default_argument (fn, 
5885                                                     TREE_VALUE (arg),
5886                                                     TREE_PURPOSE (arg));
5887 }
5888
5889 /* Substitute the ARGS into the T, which is a _DECL.  TYPE is the
5890    (already computed) substitution of ARGS into TREE_TYPE (T), if
5891    appropriate.  Return the result of the substitution.  Issue error
5892    and warning messages under control of COMPLAIN.  */
5893
5894 static tree
5895 tsubst_decl (t, args, type, complain)
5896      tree t;
5897      tree args;
5898      tree type;
5899      tsubst_flags_t complain;
5900 {
5901   location_t saved_loc;
5902   tree r = NULL_TREE;
5903   tree in_decl = t;
5904
5905   /* Set the filename and linenumber to improve error-reporting.  */
5906   saved_loc = input_location;
5907   input_location = DECL_SOURCE_LOCATION (t);
5908
5909   switch (TREE_CODE (t))
5910     {
5911     case TEMPLATE_DECL:
5912       {
5913         /* We can get here when processing a member template function
5914            of a template class.  */
5915         tree decl = DECL_TEMPLATE_RESULT (t);
5916         tree spec;
5917         int is_template_template_parm = DECL_TEMPLATE_TEMPLATE_PARM_P (t);
5918
5919         if (!is_template_template_parm)
5920           {
5921             /* We might already have an instance of this template.
5922                The ARGS are for the surrounding class type, so the
5923                full args contain the tsubst'd args for the context,
5924                plus the innermost args from the template decl.  */
5925             tree tmpl_args = DECL_CLASS_TEMPLATE_P (t) 
5926               ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
5927               : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
5928             tree full_args;
5929             
5930             full_args = tsubst_template_arg_vector (tmpl_args, args,
5931                                                     complain);
5932
5933             /* tsubst_template_arg_vector doesn't copy the vector if
5934                nothing changed.  But, *something* should have
5935                changed.  */
5936             my_friendly_assert (full_args != tmpl_args, 0);
5937
5938             spec = retrieve_specialization (t, full_args);
5939             if (spec != NULL_TREE)
5940               {
5941                 r = spec;
5942                 break;
5943               }
5944           }
5945
5946         /* Make a new template decl.  It will be similar to the
5947            original, but will record the current template arguments. 
5948            We also create a new function declaration, which is just
5949            like the old one, but points to this new template, rather
5950            than the old one.  */
5951         r = copy_decl (t);
5952         my_friendly_assert (DECL_LANG_SPECIFIC (r) != 0, 0);
5953         TREE_CHAIN (r) = NULL_TREE;
5954
5955         if (is_template_template_parm)
5956           {
5957             tree new_decl = tsubst (decl, args, complain, in_decl);
5958             DECL_TEMPLATE_RESULT (r) = new_decl;
5959             TREE_TYPE (r) = TREE_TYPE (new_decl);
5960             break;
5961           }
5962
5963         DECL_CONTEXT (r) 
5964           = tsubst_aggr_type (DECL_CONTEXT (t), args, 
5965                               complain, in_decl, 
5966                               /*entering_scope=*/1); 
5967         DECL_TEMPLATE_INFO (r) = build_tree_list (t, args);
5968
5969         if (TREE_CODE (decl) == TYPE_DECL)
5970           {
5971             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
5972             TREE_TYPE (r) = new_type;
5973             CLASSTYPE_TI_TEMPLATE (new_type) = r;
5974             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
5975             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
5976           }
5977         else
5978           {
5979             tree new_decl = tsubst (decl, args, complain, in_decl);
5980
5981             DECL_TEMPLATE_RESULT (r) = new_decl;
5982             DECL_TI_TEMPLATE (new_decl) = r;
5983             TREE_TYPE (r) = TREE_TYPE (new_decl);
5984             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
5985           }
5986
5987         SET_DECL_IMPLICIT_INSTANTIATION (r);
5988         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
5989         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
5990
5991         /* The template parameters for this new template are all the
5992            template parameters for the old template, except the
5993            outermost level of parameters.  */
5994         DECL_TEMPLATE_PARMS (r) 
5995           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
5996                                    complain);
5997
5998         if (PRIMARY_TEMPLATE_P (t))
5999           DECL_PRIMARY_TEMPLATE (r) = r;
6000
6001         /* We don't partially instantiate partial specializations.  */
6002         if (TREE_CODE (decl) == TYPE_DECL)
6003           break;
6004
6005         /* Record this partial instantiation.  */
6006         register_specialization (r, t, 
6007                                  DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)));
6008
6009       }
6010       break;
6011
6012     case FUNCTION_DECL:
6013       {
6014         tree ctx;
6015         tree argvec = NULL_TREE;
6016         tree *friends;
6017         tree gen_tmpl;
6018         int member;
6019         int args_depth;
6020         int parms_depth;
6021
6022         /* Nobody should be tsubst'ing into non-template functions.  */
6023         my_friendly_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE, 0);
6024
6025         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
6026           {
6027             tree spec;
6028
6029             /* Calculate the most general template of which R is a
6030                specialization, and the complete set of arguments used to
6031                specialize R.  */
6032             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
6033             argvec 
6034               = tsubst_template_arg_vector (DECL_TI_ARGS 
6035                                             (DECL_TEMPLATE_RESULT (gen_tmpl)),
6036                                             args, complain); 
6037
6038             /* Check to see if we already have this specialization.  */
6039             spec = retrieve_specialization (gen_tmpl, argvec);
6040
6041             if (spec)
6042               {
6043                 r = spec;
6044                 break;
6045               }
6046
6047             /* We can see more levels of arguments than parameters if
6048                there was a specialization of a member template, like
6049                this:
6050
6051                  template <class T> struct S { template <class U> void f(); }
6052                  template <> template <class U> void S<int>::f(U); 
6053
6054                Here, we'll be substituting into the specialization,
6055                because that's where we can find the code we actually
6056                want to generate, but we'll have enough arguments for
6057                the most general template.              
6058
6059                We also deal with the peculiar case:
6060
6061                  template <class T> struct S { 
6062                    template <class U> friend void f();
6063                  };
6064                  template <class U> void f() {}
6065                  template S<int>;
6066                  template void f<double>();
6067
6068                Here, the ARGS for the instantiation of will be {int,
6069                double}.  But, we only need as many ARGS as there are
6070                levels of template parameters in CODE_PATTERN.  We are
6071                careful not to get fooled into reducing the ARGS in
6072                situations like:
6073
6074                  template <class T> struct S { template <class U> void f(U); }
6075                  template <class T> template <> void S<T>::f(int) {}
6076
6077                which we can spot because the pattern will be a
6078                specialization in this case.  */
6079             args_depth = TMPL_ARGS_DEPTH (args);
6080             parms_depth = 
6081               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t))); 
6082             if (args_depth > parms_depth
6083                 && !DECL_TEMPLATE_SPECIALIZATION (t))
6084               args = get_innermost_template_args (args, parms_depth);
6085           }
6086         else
6087           {
6088             /* This special case arises when we have something like this:
6089
6090                  template <class T> struct S { 
6091                    friend void f<int>(int, double); 
6092                  };
6093
6094                Here, the DECL_TI_TEMPLATE for the friend declaration
6095                will be a LOOKUP_EXPR or an IDENTIFIER_NODE.  We are
6096                being called from tsubst_friend_function, and we want
6097                only to create a new decl (R) with appropriate types so
6098                that we can call determine_specialization.  */
6099             gen_tmpl = NULL_TREE;
6100           }
6101
6102         if (DECL_CLASS_SCOPE_P (t))
6103           {
6104             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
6105               member = 2;
6106             else
6107               member = 1;
6108             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, 
6109                                     complain, t, 
6110                                     /*entering_scope=*/1);
6111           }
6112         else
6113           {
6114             member = 0;
6115             ctx = DECL_CONTEXT (t);
6116           }
6117         type = tsubst (type, args, complain, in_decl);
6118         if (type == error_mark_node)
6119           return error_mark_node;
6120
6121         /* We do NOT check for matching decls pushed separately at this
6122            point, as they may not represent instantiations of this
6123            template, and in any case are considered separate under the
6124            discrete model.  */
6125         r = copy_decl (t);
6126         DECL_USE_TEMPLATE (r) = 0;
6127         TREE_TYPE (r) = type;
6128         /* Clear out the mangled name and RTL for the instantiation.  */
6129         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
6130         SET_DECL_RTL (r, NULL_RTX);
6131
6132         DECL_CONTEXT (r) = ctx;
6133
6134         if (member && DECL_CONV_FN_P (r)) 
6135           /* Type-conversion operator.  Reconstruct the name, in
6136              case it's the name of one of the template's parameters.  */
6137           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
6138
6139         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
6140                                      complain, t);
6141         DECL_RESULT (r) = NULL_TREE;
6142
6143         TREE_STATIC (r) = 0;
6144         TREE_PUBLIC (r) = TREE_PUBLIC (t);
6145         DECL_EXTERNAL (r) = 1;
6146         DECL_INTERFACE_KNOWN (r) = 0;
6147         DECL_DEFER_OUTPUT (r) = 0;
6148         TREE_CHAIN (r) = NULL_TREE;
6149         DECL_PENDING_INLINE_INFO (r) = 0;
6150         DECL_PENDING_INLINE_P (r) = 0;
6151         DECL_SAVED_TREE (r) = NULL_TREE;
6152         TREE_USED (r) = 0;
6153         if (DECL_CLONED_FUNCTION (r))
6154           {
6155             DECL_CLONED_FUNCTION (r) = tsubst (DECL_CLONED_FUNCTION (t),
6156                                                args, complain, t);
6157             TREE_CHAIN (r) = TREE_CHAIN (DECL_CLONED_FUNCTION (r));
6158             TREE_CHAIN (DECL_CLONED_FUNCTION (r)) = r;
6159           }
6160
6161         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
6162            this in the special friend case mentioned above where
6163            GEN_TMPL is NULL.  */
6164         if (gen_tmpl)
6165           {
6166             DECL_TEMPLATE_INFO (r) 
6167               = tree_cons (gen_tmpl, argvec, NULL_TREE);
6168             SET_DECL_IMPLICIT_INSTANTIATION (r);
6169             register_specialization (r, gen_tmpl, argvec);
6170
6171             /* We're not supposed to instantiate default arguments
6172                until they are called, for a template.  But, for a
6173                declaration like:
6174
6175                  template <class T> void f () 
6176                  { extern void g(int i = T()); }
6177                  
6178                we should do the substitution when the template is
6179                instantiated.  We handle the member function case in
6180                instantiate_class_template since the default arguments
6181                might refer to other members of the class.  */
6182             if (!member
6183                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
6184                 && !uses_template_parms (argvec))
6185               tsubst_default_arguments (r);
6186           }
6187
6188         /* Copy the list of befriending classes.  */
6189         for (friends = &DECL_BEFRIENDING_CLASSES (r);
6190              *friends;
6191              friends = &TREE_CHAIN (*friends)) 
6192           {
6193             *friends = copy_node (*friends);
6194             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
6195                                             args, complain,
6196                                             in_decl);
6197           }
6198
6199         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
6200           {
6201             maybe_retrofit_in_chrg (r);
6202             if (DECL_CONSTRUCTOR_P (r))
6203               grok_ctor_properties (ctx, r);
6204             /* If this is an instantiation of a member template, clone it.
6205                If it isn't, that'll be handled by
6206                clone_constructors_and_destructors.  */
6207             if (PRIMARY_TEMPLATE_P (gen_tmpl))
6208               clone_function_decl (r, /*update_method_vec_p=*/0);
6209           }
6210         else if (IDENTIFIER_OPNAME_P (DECL_NAME (r)))
6211           grok_op_properties (r, DECL_FRIEND_P (r));
6212       }
6213       break;
6214
6215     case PARM_DECL:
6216       {
6217         r = copy_node (t);
6218         if (DECL_TEMPLATE_PARM_P (t))
6219           SET_DECL_TEMPLATE_PARM_P (r);
6220
6221         TREE_TYPE (r) = type;
6222         c_apply_type_quals_to_decl (cp_type_quals (type), r);
6223
6224         if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
6225           DECL_INITIAL (r) = TREE_TYPE (r);
6226         else
6227           DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
6228                                      complain, in_decl);
6229
6230         DECL_CONTEXT (r) = NULL_TREE;
6231
6232         if (!DECL_TEMPLATE_PARM_P (r))
6233           DECL_ARG_TYPE (r) = type_passed_as (type);
6234         if (TREE_CHAIN (t))
6235           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
6236                                    complain, TREE_CHAIN (t));
6237       }
6238       break;
6239
6240     case FIELD_DECL:
6241       {
6242         r = copy_decl (t);
6243         TREE_TYPE (r) = type;
6244         c_apply_type_quals_to_decl (cp_type_quals (type), r);
6245
6246         /* We don't have to set DECL_CONTEXT here; it is set by
6247            finish_member_declaration.  */
6248         DECL_INITIAL (r) = tsubst_expr (DECL_INITIAL (t), args,
6249                                         complain, in_decl);
6250         TREE_CHAIN (r) = NULL_TREE;
6251         if (VOID_TYPE_P (type)) 
6252           cp_error_at ("instantiation of `%D' as type `%T'", r, type);
6253       }
6254       break;
6255
6256     case USING_DECL:
6257       {
6258         r = copy_node (t);
6259         DECL_INITIAL (r)
6260           = tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
6261         TREE_CHAIN (r) = NULL_TREE;
6262       }
6263       break;
6264
6265     case TYPE_DECL:
6266       if (TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM
6267           || t == TYPE_MAIN_DECL (TREE_TYPE (t)))
6268         {
6269           /* If this is the canonical decl, we don't have to mess with
6270              instantiations, and often we can't (for typename, template
6271              type parms and such).  Note that TYPE_NAME is not correct for
6272              the above test if we've copied the type for a typedef.  */
6273           r = TYPE_NAME (type);
6274           break;
6275         }
6276
6277       /* Fall through.  */
6278
6279     case VAR_DECL:
6280       {
6281         tree argvec = NULL_TREE;
6282         tree gen_tmpl = NULL_TREE;
6283         tree spec;
6284         tree tmpl = NULL_TREE;
6285         tree ctx;
6286         int local_p;
6287
6288         /* Assume this is a non-local variable.  */
6289         local_p = 0;
6290
6291         if (TYPE_P (CP_DECL_CONTEXT (t)))
6292           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, 
6293                                   complain,
6294                                   in_decl, /*entering_scope=*/1);
6295         else if (DECL_NAMESPACE_SCOPE_P (t))
6296           ctx = DECL_CONTEXT (t);
6297         else
6298           {
6299             /* Subsequent calls to pushdecl will fill this in.  */
6300             ctx = NULL_TREE;
6301             local_p = 1;
6302           }
6303
6304         /* Check to see if we already have this specialization.  */
6305         if (!local_p)
6306           {
6307             tmpl = DECL_TI_TEMPLATE (t);
6308             gen_tmpl = most_general_template (tmpl);
6309             argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
6310             spec = retrieve_specialization (gen_tmpl, argvec);
6311           }
6312         else
6313           spec = retrieve_local_specialization (t);
6314
6315         if (spec)
6316           {
6317             r = spec;
6318             break;
6319           }
6320
6321         r = copy_decl (t);
6322         if (TREE_CODE (r) == VAR_DECL)
6323           type = complete_type (type);
6324         TREE_TYPE (r) = type;
6325         c_apply_type_quals_to_decl (cp_type_quals (type), r);
6326         DECL_CONTEXT (r) = ctx;
6327         /* Clear out the mangled name and RTL for the instantiation.  */
6328         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
6329         SET_DECL_RTL (r, NULL_RTX);
6330
6331         /* Don't try to expand the initializer until someone tries to use
6332            this variable; otherwise we run into circular dependencies.  */
6333         DECL_INITIAL (r) = NULL_TREE;
6334         SET_DECL_RTL (r, NULL_RTX);
6335         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
6336
6337         /* Even if the original location is out of scope, the newly
6338            substituted one is not.  */
6339         if (TREE_CODE (r) == VAR_DECL)
6340           {
6341             DECL_DEAD_FOR_LOCAL (r) = 0;
6342             DECL_INITIALIZED_P (r) = 0;
6343           }
6344
6345         if (!local_p)
6346           {
6347             /* A static data member declaration is always marked
6348                external when it is declared in-class, even if an
6349                initializer is present.  We mimic the non-template
6350                processing here.  */
6351             DECL_EXTERNAL (r) = 1;
6352
6353             register_specialization (r, gen_tmpl, argvec);
6354             DECL_TEMPLATE_INFO (r) = tree_cons (tmpl, argvec, NULL_TREE);
6355             SET_DECL_IMPLICIT_INSTANTIATION (r);
6356           }
6357         else
6358           register_local_specialization (r, t);
6359
6360         TREE_CHAIN (r) = NULL_TREE;
6361         if (TREE_CODE (r) == VAR_DECL && VOID_TYPE_P (type))
6362           cp_error_at ("instantiation of `%D' as type `%T'", r, type);
6363         /* Compute the size, alignment, etc. of R.  */
6364         layout_decl (r, 0);
6365       }
6366       break;
6367
6368     default:
6369       abort ();
6370     } 
6371
6372   /* Restore the file and line information.  */
6373   input_location = saved_loc;
6374
6375   return r;
6376 }
6377
6378 /* Substitue into the ARG_TYPES of a function type.  */
6379
6380 static tree
6381 tsubst_arg_types (arg_types, args, complain, in_decl)
6382      tree arg_types;
6383      tree args;
6384      tsubst_flags_t complain;
6385      tree in_decl;
6386 {
6387   tree remaining_arg_types;
6388   tree type;
6389
6390   if (!arg_types || arg_types == void_list_node)
6391     return arg_types;
6392   
6393   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
6394                                           args, complain, in_decl);
6395   if (remaining_arg_types == error_mark_node)
6396     return error_mark_node;
6397
6398   type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
6399   if (type == error_mark_node)
6400     return error_mark_node;
6401   if (VOID_TYPE_P (type))
6402     {
6403       if (complain & tf_error)
6404         {
6405           error ("invalid parameter type `%T'", type);
6406           if (in_decl)
6407             cp_error_at ("in declaration `%D'", in_decl);
6408         }
6409       return error_mark_node;
6410     }
6411
6412   /* Do array-to-pointer, function-to-pointer conversion, and ignore
6413      top-level qualifiers as required.  */
6414   type = TYPE_MAIN_VARIANT (type_decays_to (type));
6415
6416   /* Note that we do not substitute into default arguments here.  The
6417      standard mandates that they be instantiated only when needed,
6418      which is done in build_over_call.  */
6419   return hash_tree_cons (TREE_PURPOSE (arg_types), type,
6420                          remaining_arg_types);
6421                          
6422 }
6423
6424 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
6425    *not* handle the exception-specification for FNTYPE, because the
6426    initial substitution of explicitly provided template parameters
6427    during argument deduction forbids substitution into the
6428    exception-specification:
6429
6430      [temp.deduct]
6431
6432      All references in the function type of the function template to  the
6433      corresponding template parameters are replaced by the specified tem-
6434      plate argument values.  If a substitution in a template parameter or
6435      in  the function type of the function template results in an invalid
6436      type, type deduction fails.  [Note: The equivalent  substitution  in
6437      exception specifications is done only when the function is instanti-
6438      ated, at which point a program is  ill-formed  if  the  substitution
6439      results in an invalid type.]  */
6440
6441 static tree
6442 tsubst_function_type (t, args, complain, in_decl)
6443      tree t;
6444      tree args;
6445      tsubst_flags_t complain;
6446      tree in_decl;
6447 {
6448   tree return_type;
6449   tree arg_types;
6450   tree fntype;
6451
6452   /* The TYPE_CONTEXT is not used for function/method types.  */
6453   my_friendly_assert (TYPE_CONTEXT (t) == NULL_TREE, 0);
6454
6455   /* Substitute the return type.  */
6456   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
6457   if (return_type == error_mark_node)
6458     return error_mark_node;
6459
6460   /* Substitue the argument types.  */
6461   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
6462                                 complain, in_decl); 
6463   if (arg_types == error_mark_node)
6464     return error_mark_node;
6465   
6466   /* Construct a new type node and return it.  */
6467   if (TREE_CODE (t) == FUNCTION_TYPE)
6468     fntype = build_function_type (return_type, arg_types);
6469   else
6470     {
6471       tree r = TREE_TYPE (TREE_VALUE (arg_types));
6472       if (! IS_AGGR_TYPE (r))
6473         {
6474           /* [temp.deduct]
6475              
6476              Type deduction may fail for any of the following
6477              reasons:
6478              
6479              -- Attempting to create "pointer to member of T" when T
6480              is not a class type.  */
6481           if (complain & tf_error)
6482             error ("creating pointer to member function of non-class type `%T'",
6483                       r);
6484           return error_mark_node;
6485         }
6486       
6487       fntype = build_cplus_method_type (r, return_type, TREE_CHAIN
6488                                         (arg_types));
6489     }
6490   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
6491   fntype = build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
6492   
6493   return fntype;  
6494 }
6495
6496 /* Substitute into the PARMS of a call-declarator.  */
6497
6498 static tree
6499 tsubst_call_declarator_parms (parms, args, complain, in_decl)
6500      tree parms;
6501      tree args;
6502      tsubst_flags_t complain;
6503      tree in_decl;
6504 {
6505   tree new_parms;
6506   tree type;
6507   tree defarg;
6508
6509   if (!parms || parms == void_list_node)
6510     return parms;
6511   
6512   new_parms = tsubst_call_declarator_parms (TREE_CHAIN (parms),
6513                                             args, complain, in_decl);
6514
6515   /* Figure out the type of this parameter.  */
6516   type = tsubst (TREE_VALUE (parms), args, complain, in_decl);
6517   
6518   /* Figure out the default argument as well.  Note that we use
6519      tsubst_expr since the default argument is really an expression.  */
6520   defarg = tsubst_expr (TREE_PURPOSE (parms), args, complain, in_decl);
6521
6522   /* Chain this parameter on to the front of those we have already
6523      processed.  We don't use hash_tree_cons because that function
6524      doesn't check TREE_PARMLIST.  */
6525   new_parms = tree_cons (defarg, type, new_parms);
6526
6527   /* And note that these are parameters.  */
6528   TREE_PARMLIST (new_parms) = 1;
6529   
6530   return new_parms;
6531 }
6532
6533 /* Take the tree structure T and replace template parameters used
6534    therein with the argument vector ARGS.  IN_DECL is an associated
6535    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
6536    Issue error and warning messages under control of COMPLAIN.  Note
6537    that we must be relatively non-tolerant of extensions here, in
6538    order to preserve conformance; if we allow substitutions that
6539    should not be allowed, we may allow argument deductions that should
6540    not succeed, and therefore report ambiguous overload situations
6541    where there are none.  In theory, we could allow the substitution,
6542    but indicate that it should have failed, and allow our caller to
6543    make sure that the right thing happens, but we don't try to do this
6544    yet.
6545
6546    This function is used for dealing with types, decls and the like;
6547    for expressions, use tsubst_expr or tsubst_copy.  */
6548
6549 static tree
6550 tsubst (t, args, complain, in_decl)
6551      tree t, args;
6552      tsubst_flags_t complain;
6553      tree in_decl;
6554 {
6555   tree type, r;
6556
6557   if (t == NULL_TREE || t == error_mark_node
6558       || t == integer_type_node
6559       || t == void_type_node
6560       || t == char_type_node
6561       || TREE_CODE (t) == NAMESPACE_DECL)
6562     return t;
6563
6564   if (TREE_CODE (t) == IDENTIFIER_NODE)
6565     type = IDENTIFIER_TYPE_VALUE (t);
6566   else
6567     type = TREE_TYPE (t);
6568   if (type == unknown_type_node)
6569     abort ();
6570
6571   if (type && TREE_CODE (t) != FUNCTION_DECL
6572       && TREE_CODE (t) != TYPENAME_TYPE
6573       && TREE_CODE (t) != TEMPLATE_DECL
6574       && TREE_CODE (t) != IDENTIFIER_NODE
6575       && TREE_CODE (t) != FUNCTION_TYPE
6576       && TREE_CODE (t) != METHOD_TYPE)
6577     type = tsubst (type, args, complain, in_decl);
6578   if (type == error_mark_node)
6579     return error_mark_node;
6580
6581   if (DECL_P (t))
6582     return tsubst_decl (t, args, type, complain);
6583
6584   switch (TREE_CODE (t))
6585     {
6586     case RECORD_TYPE:
6587     case UNION_TYPE:
6588     case ENUMERAL_TYPE:
6589       return tsubst_aggr_type (t, args, complain, in_decl,
6590                                /*entering_scope=*/0);
6591
6592     case ERROR_MARK:
6593     case IDENTIFIER_NODE:
6594     case VOID_TYPE:
6595     case REAL_TYPE:
6596     case COMPLEX_TYPE:
6597     case VECTOR_TYPE:
6598     case BOOLEAN_TYPE:
6599     case INTEGER_CST:
6600     case REAL_CST:
6601     case STRING_CST:
6602       return t;
6603
6604     case INTEGER_TYPE:
6605       if (t == integer_type_node)
6606         return t;
6607
6608       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
6609           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
6610         return t;
6611
6612       {
6613         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
6614
6615         max = tsubst_expr (omax, args, complain, in_decl);
6616         if (max == error_mark_node)
6617           return error_mark_node;
6618
6619         /* See if we can reduce this expression to something simpler.  */
6620         max = maybe_fold_nontype_arg (max);
6621         if (!processing_template_decl)
6622           max = decl_constant_value (max);
6623
6624         if (processing_template_decl 
6625             /* When providing explicit arguments to a template
6626                function, but leaving some arguments for subsequent
6627                deduction, MAX may be template-dependent even if we're
6628                not PROCESSING_TEMPLATE_DECL.  We still need to check for
6629                template parms, though; MAX won't be an INTEGER_CST for
6630                dynamic arrays, either.  */
6631             || (TREE_CODE (max) != INTEGER_CST
6632                 && uses_template_parms (max)))
6633           {
6634             tree itype = make_node (INTEGER_TYPE);
6635             TYPE_MIN_VALUE (itype) = size_zero_node;
6636             TYPE_MAX_VALUE (itype) = build_min (MINUS_EXPR, sizetype, max,
6637                                                 integer_one_node);
6638             return itype;
6639           }
6640
6641         if (integer_zerop (omax))
6642           {
6643             /* Still allow an explicit array of size zero.  */
6644             if (pedantic)
6645               pedwarn ("creating array with size zero");
6646           }
6647         else if (integer_zerop (max) 
6648                  || (TREE_CODE (max) == INTEGER_CST 
6649                      && INT_CST_LT (max, integer_zero_node)))
6650           {
6651             /* [temp.deduct]
6652
6653                Type deduction may fail for any of the following
6654                reasons:  
6655
6656                  Attempting to create an array with a size that is
6657                  zero or negative.  */
6658             if (complain & tf_error)
6659               error ("creating array with size zero (`%E')", max);
6660
6661             return error_mark_node;
6662           }
6663
6664         return compute_array_index_type (NULL_TREE, max);
6665       }
6666
6667     case TEMPLATE_TYPE_PARM:
6668     case TEMPLATE_TEMPLATE_PARM:
6669     case BOUND_TEMPLATE_TEMPLATE_PARM:
6670     case TEMPLATE_PARM_INDEX:
6671       {
6672         int idx;
6673         int level;
6674         int levels;
6675
6676         r = NULL_TREE;
6677
6678         if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
6679             || TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
6680             || TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
6681           {
6682             idx = TEMPLATE_TYPE_IDX (t);
6683             level = TEMPLATE_TYPE_LEVEL (t);
6684           }
6685         else
6686           {
6687             idx = TEMPLATE_PARM_IDX (t);
6688             level = TEMPLATE_PARM_LEVEL (t);
6689           }
6690
6691         if (TREE_VEC_LENGTH (args) > 0)
6692           {
6693             tree arg = NULL_TREE;
6694
6695             levels = TMPL_ARGS_DEPTH (args);
6696             if (level <= levels)
6697               arg = TMPL_ARG (args, level, idx);
6698
6699             if (arg == error_mark_node)
6700               return error_mark_node;
6701             else if (arg != NULL_TREE)
6702               {
6703                 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
6704                   {
6705                     my_friendly_assert (TYPE_P (arg), 0);
6706                     return cp_build_qualified_type_real
6707                       (arg, cp_type_quals (arg) | cp_type_quals (t),
6708                        complain | tf_ignore_bad_quals);
6709                   }
6710                 else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
6711                   {
6712                     /* We are processing a type constructed from
6713                        a template template parameter */
6714                     tree argvec = tsubst (TYPE_TI_ARGS (t),
6715                                           args, complain, in_decl);
6716                     if (argvec == error_mark_node)
6717                       return error_mark_node;
6718                         
6719                     /* We can get a TEMPLATE_TEMPLATE_PARM here when 
6720                        we are resolving nested-types in the signature of 
6721                        a member function templates.
6722                        Otherwise ARG is a TEMPLATE_DECL and is the real 
6723                        template to be instantiated.  */
6724                     if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
6725                       arg = TYPE_NAME (arg);
6726
6727                     r = lookup_template_class (arg, 
6728                                                argvec, in_decl, 
6729                                                DECL_CONTEXT (arg),
6730                                                /*entering_scope=*/0,
6731                                                complain);
6732                     return cp_build_qualified_type_real
6733                       (r, TYPE_QUALS (t), complain);
6734                   }
6735                 else
6736                   /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
6737                   return arg;
6738               }
6739           }
6740         else
6741           abort ();
6742
6743         if (level == 1)
6744           /* This can happen during the attempted tsubst'ing in
6745              unify.  This means that we don't yet have any information
6746              about the template parameter in question.  */
6747           return t;
6748
6749         /* If we get here, we must have been looking at a parm for a
6750            more deeply nested template.  Make a new version of this
6751            template parameter, but with a lower level.  */
6752         switch (TREE_CODE (t))
6753           {
6754           case TEMPLATE_TYPE_PARM:
6755           case TEMPLATE_TEMPLATE_PARM:
6756           case BOUND_TEMPLATE_TEMPLATE_PARM:
6757             if (cp_type_quals (t))
6758               {
6759                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
6760                 r = cp_build_qualified_type_real
6761                   (r, cp_type_quals (t),
6762                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
6763                                ? tf_ignore_bad_quals : 0));
6764               }
6765             else
6766               {
6767                 r = copy_type (t);
6768                 TEMPLATE_TYPE_PARM_INDEX (r)
6769                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
6770                                                 r, levels);
6771                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
6772                 TYPE_MAIN_VARIANT (r) = r;
6773                 TYPE_POINTER_TO (r) = NULL_TREE;
6774                 TYPE_REFERENCE_TO (r) = NULL_TREE;
6775
6776                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
6777                   {
6778                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
6779                                           complain, in_decl); 
6780                     if (argvec == error_mark_node)
6781                       return error_mark_node;
6782
6783                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
6784                       = tree_cons (TYPE_TI_TEMPLATE (t), argvec, NULL_TREE);
6785                   }
6786               }
6787             break;
6788
6789           case TEMPLATE_PARM_INDEX:
6790             r = reduce_template_parm_level (t, type, levels);
6791             break;
6792            
6793           default:
6794             abort ();
6795           }
6796
6797         return r;
6798       }
6799
6800     case TREE_LIST:
6801       {
6802         tree purpose, value, chain, result;
6803
6804         if (t == void_list_node)
6805           return t;
6806
6807         purpose = TREE_PURPOSE (t);
6808         if (purpose)
6809           {
6810             purpose = tsubst (purpose, args, complain, in_decl);
6811             if (purpose == error_mark_node)
6812               return error_mark_node;
6813           }
6814         value = TREE_VALUE (t);
6815         if (value)
6816           {
6817             value = tsubst (value, args, complain, in_decl);
6818             if (value == error_mark_node)
6819               return error_mark_node;
6820           }
6821         chain = TREE_CHAIN (t);
6822         if (chain && chain != void_type_node)
6823           {
6824             chain = tsubst (chain, args, complain, in_decl);
6825             if (chain == error_mark_node)
6826               return error_mark_node;
6827           }
6828         if (purpose == TREE_PURPOSE (t)
6829             && value == TREE_VALUE (t)
6830             && chain == TREE_CHAIN (t))
6831           return t;
6832         if (TREE_PARMLIST (t))
6833           {
6834             result = tree_cons (purpose, value, chain);
6835             TREE_PARMLIST (result) = 1;
6836           }
6837         else
6838           result = hash_tree_cons (purpose, value, chain);
6839         return result;
6840       }
6841     case TREE_VEC:
6842       if (type != NULL_TREE)
6843         {
6844           /* A binfo node.  We always need to make a copy, of the node
6845              itself and of its BINFO_BASETYPES.  */
6846
6847           t = copy_node (t);
6848
6849           /* Make sure type isn't a typedef copy.  */
6850           type = BINFO_TYPE (TYPE_BINFO (type));
6851
6852           TREE_TYPE (t) = complete_type (type);
6853           if (IS_AGGR_TYPE (type))
6854             {
6855               BINFO_VTABLE (t) = TYPE_BINFO_VTABLE (type);
6856               BINFO_VIRTUALS (t) = TYPE_BINFO_VIRTUALS (type);
6857               if (TYPE_BINFO_BASETYPES (type) != NULL_TREE)
6858                 BINFO_BASETYPES (t) = copy_node (TYPE_BINFO_BASETYPES (type));
6859             }
6860           return t;
6861         }
6862
6863       /* Otherwise, a vector of template arguments.  */
6864       return tsubst_template_arg_vector (t, args, complain);
6865
6866     case POINTER_TYPE:
6867     case REFERENCE_TYPE:
6868       {
6869         enum tree_code code;
6870
6871         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
6872           return t;
6873
6874         code = TREE_CODE (t);
6875
6876
6877         /* [temp.deduct]
6878            
6879            Type deduction may fail for any of the following
6880            reasons:  
6881
6882            -- Attempting to create a pointer to reference type.
6883            -- Attempting to create a reference to a reference type or
6884               a reference to void.  */
6885         if (TREE_CODE (type) == REFERENCE_TYPE
6886             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
6887           {
6888             static location_t last_loc;
6889
6890             /* We keep track of the last time we issued this error
6891                message to avoid spewing a ton of messages during a
6892                single bad template instantiation.  */
6893             if (complain & tf_error
6894                 && (last_loc.line != input_line
6895                     || last_loc.file != input_filename))
6896               {
6897                 if (TREE_CODE (type) == VOID_TYPE)
6898                   error ("forming reference to void");
6899                 else
6900                   error ("forming %s to reference type `%T'",
6901                             (code == POINTER_TYPE) ? "pointer" : "reference",
6902                             type);
6903                 last_loc = input_location;
6904               }
6905
6906             return error_mark_node;
6907           }
6908         else if (code == POINTER_TYPE)
6909           {
6910             r = build_pointer_type (type);
6911             if (TREE_CODE (type) == METHOD_TYPE)
6912               r = build_ptrmemfunc_type (r);
6913           }
6914         else
6915           r = build_reference_type (type);
6916         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
6917
6918         if (r != error_mark_node)
6919           /* Will this ever be needed for TYPE_..._TO values?  */
6920           layout_type (r);
6921         
6922         return r;
6923       }
6924     case OFFSET_TYPE:
6925       {
6926         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
6927         if (r == error_mark_node || !IS_AGGR_TYPE (r))
6928           {
6929             /* [temp.deduct]
6930
6931                Type deduction may fail for any of the following
6932                reasons:
6933                
6934                -- Attempting to create "pointer to member of T" when T
6935                   is not a class type.  */
6936             if (complain & tf_error)
6937               error ("creating pointer to member of non-class type `%T'", r);
6938             return error_mark_node;
6939           }
6940         if (TREE_CODE (type) == REFERENCE_TYPE)
6941           {
6942             if (complain & tf_error)
6943               error ("creating pointer to member reference type `%T'", type);
6944             
6945             return error_mark_node;
6946           }
6947         my_friendly_assert (TREE_CODE (type) != METHOD_TYPE, 20011231);
6948         if (TREE_CODE (type) == FUNCTION_TYPE)
6949           /* This is really a method type. The cv qualifiers of the
6950              this pointer should _not_ be determined by the cv
6951              qualifiers of the class type.  They should be held
6952              somewhere in the FUNCTION_TYPE, but we don't do that at
6953              the moment.  Consider
6954                 typedef void (Func) () const;
6955
6956                 template <typename T1> void Foo (Func T1::*);
6957
6958               */
6959           return build_cplus_method_type (TYPE_MAIN_VARIANT (r),
6960                                           TREE_TYPE (type),
6961                                           TYPE_ARG_TYPES (type));
6962         else
6963           return build_offset_type (r, type);
6964       }
6965     case FUNCTION_TYPE:
6966     case METHOD_TYPE:
6967       {
6968         tree fntype;
6969         tree raises;
6970
6971         fntype = tsubst_function_type (t, args, complain, in_decl);
6972         if (fntype == error_mark_node)
6973           return error_mark_node;
6974
6975         /* Substitue the exception specification.  */
6976         raises = TYPE_RAISES_EXCEPTIONS (t);
6977         if (raises)
6978           {
6979             tree   list = NULL_TREE;
6980             
6981             if (! TREE_VALUE (raises))
6982               list = raises;
6983             else
6984               for (; raises != NULL_TREE; raises = TREE_CHAIN (raises))
6985                 {
6986                   tree spec = TREE_VALUE (raises);
6987                   
6988                   spec = tsubst (spec, args, complain, in_decl);
6989                   if (spec == error_mark_node)
6990                     return spec;
6991                   list = add_exception_specifier (list, spec, complain);
6992                 }
6993             fntype = build_exception_variant (fntype, list);
6994           }
6995         return fntype;
6996       }
6997     case ARRAY_TYPE:
6998       {
6999         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
7000         if (domain == error_mark_node)
7001           return error_mark_node;
7002
7003         /* As an optimization, we avoid regenerating the array type if
7004            it will obviously be the same as T.  */
7005         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
7006           return t;
7007
7008         /* These checks should match the ones in grokdeclarator.  
7009
7010            [temp.deduct] 
7011         
7012            The deduction may fail for any of the following reasons: 
7013
7014            -- Attempting to create an array with an element type that
7015               is void, a function type, or a reference type.  */
7016         if (TREE_CODE (type) == VOID_TYPE 
7017             || TREE_CODE (type) == FUNCTION_TYPE
7018             || TREE_CODE (type) == REFERENCE_TYPE)
7019           {
7020             if (complain & tf_error)
7021               error ("creating array of `%T'", type);
7022             return error_mark_node;
7023           }
7024
7025         r = build_cplus_array_type (type, domain);
7026         return r;
7027       }
7028
7029     case PLUS_EXPR:
7030     case MINUS_EXPR:
7031       {
7032         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
7033         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
7034
7035         if (e1 == error_mark_node || e2 == error_mark_node)
7036           return error_mark_node;
7037
7038         return fold (build (TREE_CODE (t), TREE_TYPE (t), e1, e2));
7039       }
7040
7041     case NEGATE_EXPR:
7042     case NOP_EXPR:
7043       {
7044         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
7045         if (e == error_mark_node)
7046           return error_mark_node;
7047
7048         return fold (build (TREE_CODE (t), TREE_TYPE (t), e));
7049       }
7050
7051     case TYPENAME_TYPE:
7052       {
7053         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
7054                                      in_decl, /*entering_scope=*/1);
7055         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
7056                               complain, in_decl); 
7057
7058         if (ctx == error_mark_node || f == error_mark_node)
7059           return error_mark_node;
7060
7061         if (!IS_AGGR_TYPE (ctx))
7062           {
7063             if (complain & tf_error)
7064               error ("`%T' is not a class, struct, or union type",
7065                         ctx);
7066             return error_mark_node;
7067           }
7068         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
7069           {
7070             /* Normally, make_typename_type does not require that the CTX
7071                have complete type in order to allow things like:
7072              
7073                  template <class T> struct S { typename S<T>::X Y; };
7074
7075                But, such constructs have already been resolved by this
7076                point, so here CTX really should have complete type, unless
7077                it's a partial instantiation.  */
7078             ctx = complete_type (ctx);
7079             if (!COMPLETE_TYPE_P (ctx))
7080               {
7081                 if (complain & tf_error)
7082                   cxx_incomplete_type_error (NULL_TREE, ctx);
7083                 return error_mark_node;
7084               }
7085           }
7086
7087         f = make_typename_type (ctx, f,
7088                                 (complain & tf_error) | tf_keep_type_decl);
7089         if (f == error_mark_node)
7090           return f;
7091         if (TREE_CODE (f) == TYPE_DECL)
7092           {
7093             complain |= tf_ignore_bad_quals;
7094             f = TREE_TYPE (f);
7095           }
7096         
7097         return cp_build_qualified_type_real
7098           (f, cp_type_quals (f) | cp_type_quals (t), complain);
7099       }
7100                
7101     case UNBOUND_CLASS_TEMPLATE:
7102       {
7103         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
7104                                      in_decl, /*entering_scope=*/1);
7105         tree name = TYPE_IDENTIFIER (t);
7106
7107         if (ctx == error_mark_node || name == error_mark_node)
7108           return error_mark_node;
7109
7110         return make_unbound_class_template (ctx, name, complain);
7111       }
7112
7113     case INDIRECT_REF:
7114       {
7115         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
7116         if (e == error_mark_node)
7117           return error_mark_node;
7118         return make_pointer_declarator (type, e);
7119       }
7120
7121     case ADDR_EXPR:
7122       {
7123         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
7124         if (e == error_mark_node)
7125           return error_mark_node;
7126         return make_reference_declarator (type, e);
7127       }
7128
7129     case ARRAY_REF:
7130       {
7131         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
7132         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl);
7133         if (e1 == error_mark_node || e2 == error_mark_node)
7134           return error_mark_node;
7135
7136         return build_nt (ARRAY_REF, e1, e2, tsubst_expr);
7137       }
7138
7139     case CALL_EXPR:
7140       {
7141         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
7142         tree e2 = (tsubst_call_declarator_parms
7143                    (CALL_DECLARATOR_PARMS (t), args, complain, in_decl));
7144         tree e3 = tsubst (CALL_DECLARATOR_EXCEPTION_SPEC (t), args,
7145                           complain, in_decl);
7146
7147         if (e1 == error_mark_node || e2 == error_mark_node 
7148             || e3 == error_mark_node)
7149           return error_mark_node;
7150
7151         return make_call_declarator (e1, e2, CALL_DECLARATOR_QUALS (t), e3);
7152       }
7153
7154     case SCOPE_REF:
7155       {
7156         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
7157         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
7158         if (e1 == error_mark_node || e2 == error_mark_node)
7159           return error_mark_node;
7160
7161         return build_nt (TREE_CODE (t), e1, e2);
7162       }
7163
7164     case TYPEOF_TYPE:
7165       {
7166         tree e1 = tsubst_expr (TYPE_FIELDS (t), args, complain, in_decl);
7167         if (e1 == error_mark_node)
7168           return error_mark_node;
7169
7170         return TREE_TYPE (e1); 
7171       }
7172
7173     default:
7174       sorry ("use of `%s' in template",
7175              tree_code_name [(int) TREE_CODE (t)]);
7176       return error_mark_node;
7177     }
7178 }
7179
7180 /* Like tsubst, but deals with expressions.  This function just replaces
7181    template parms; to finish processing the resultant expression, use
7182    tsubst_expr.  */
7183
7184 static tree
7185 tsubst_copy (t, args, complain, in_decl)
7186      tree t, args;
7187      tsubst_flags_t complain;
7188      tree in_decl;
7189 {
7190   enum tree_code code;
7191   tree r;
7192
7193   if (t == NULL_TREE || t == error_mark_node)
7194     return t;
7195
7196   code = TREE_CODE (t);
7197
7198   switch (code)
7199     {
7200     case PARM_DECL:
7201       r = retrieve_local_specialization (t);
7202       my_friendly_assert (r != NULL, 20020903);
7203       return r;
7204
7205     case CONST_DECL:
7206       {
7207         tree enum_type;
7208         tree v;
7209
7210         if (DECL_TEMPLATE_PARM_P (t))
7211           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
7212         if (!DECL_CONTEXT (t))
7213           /* This is a global enumeration constant.  */
7214           return t;
7215
7216         /* Unfortunately, we cannot just call lookup_name here.
7217            Consider:
7218            
7219              template <int I> int f() {
7220              enum E { a = I };
7221              struct S { void g() { E e = a; } };
7222              };
7223            
7224            When we instantiate f<7>::S::g(), say, lookup_name is not
7225            clever enough to find f<7>::a.  */
7226         enum_type 
7227           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl, 
7228                               /*entering_scope=*/0);
7229
7230         for (v = TYPE_VALUES (enum_type); 
7231              v != NULL_TREE; 
7232              v = TREE_CHAIN (v))
7233           if (TREE_PURPOSE (v) == DECL_NAME (t))
7234             return TREE_VALUE (v);
7235
7236           /* We didn't find the name.  That should never happen; if
7237              name-lookup found it during preliminary parsing, we
7238              should find it again here during instantiation.  */
7239         abort ();
7240       }
7241       return t;
7242
7243     case FIELD_DECL:
7244       if (DECL_CONTEXT (t))
7245         {
7246           tree ctx;
7247
7248           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
7249                                   /*entering_scope=*/1);
7250           if (ctx != DECL_CONTEXT (t))
7251             return lookup_field (ctx, DECL_NAME (t), 0, false);
7252         }
7253       return t;
7254
7255     case VAR_DECL:
7256     case FUNCTION_DECL:
7257       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
7258           || local_variable_p (t))
7259         t = tsubst (t, args, complain, in_decl);
7260       mark_used (t);
7261       return t;
7262
7263     case BASELINK:
7264       {
7265         tree name;
7266         tree qualifying_scope;
7267         tree fns;
7268         tree template_args = 0;
7269         bool template_id_p = false;
7270
7271         /* A baselink indicates a function from a base class.  The
7272            BASELINK_ACCESS_BINFO and BASELINK_BINFO are going to have
7273            non-dependent types; otherwise, the lookup could not have
7274            succeeded.  However, they may indicate bases of the template
7275            class, rather than the instantiated class.  
7276            
7277            In addition, lookups that were not ambiguous before may be
7278            ambiguous now.  Therefore, we perform the lookup again. */
7279         qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (t));
7280         fns = BASELINK_FUNCTIONS (t);
7281         if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
7282           {
7283             template_id_p = true;
7284             template_args = TREE_OPERAND (fns, 1);
7285             fns = TREE_OPERAND (fns, 0);
7286             template_args = tsubst_copy (template_args, args,
7287                                          complain, in_decl);
7288             maybe_fold_nontype_args (template_args);
7289           }
7290         name = DECL_NAME (get_first_fn (fns));
7291         t = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
7292         if (BASELINK_P (t) && template_id_p)
7293           BASELINK_FUNCTIONS (t) 
7294             = build_nt (TEMPLATE_ID_EXPR,
7295                         BASELINK_FUNCTIONS (t),
7296                         template_args);
7297         return adjust_result_of_qualified_name_lookup (t, 
7298                                                        qualifying_scope,
7299                                                        current_class_type);
7300       }
7301
7302     case TEMPLATE_DECL:
7303       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
7304         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)), 
7305                        args, complain, in_decl);
7306       else if (is_member_template (t))
7307         return tsubst (t, args, complain, in_decl);
7308       else if (DECL_CLASS_SCOPE_P (t)
7309                && uses_template_parms (DECL_CONTEXT (t)))
7310         {
7311           /* Template template argument like the following example need
7312              special treatment:
7313
7314                template <template <class> class TT> struct C {};
7315                template <class T> struct D {
7316                  template <class U> struct E {};
7317                  C<E> c;                                // #1
7318                };
7319                D<int> d;                                // #2
7320
7321              We are processing the template argument `E' in #1 for
7322              the template instantiation #2.  Originally, `E' is a
7323              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
7324              have to substitute this with one having context `D<int>'.  */
7325
7326           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
7327           return lookup_field (context, DECL_NAME(t), 0, false);
7328         }
7329       else
7330         /* Ordinary template template argument.  */
7331         return t;
7332
7333     case LOOKUP_EXPR:
7334       {
7335         /* We must tsubst into a LOOKUP_EXPR in case the names to
7336            which it refers is a conversion operator; in that case the
7337            name will change.  We avoid making unnecessary copies,
7338            however.  */
7339         
7340         tree id = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
7341
7342         if (id != TREE_OPERAND (t, 0))
7343           {
7344             r = build_nt (LOOKUP_EXPR, id);
7345             LOOKUP_EXPR_GLOBAL (r) = LOOKUP_EXPR_GLOBAL (t);
7346             t = r;
7347           }
7348
7349         return t;
7350       }
7351
7352     case CAST_EXPR:
7353     case REINTERPRET_CAST_EXPR:
7354     case CONST_CAST_EXPR:
7355     case STATIC_CAST_EXPR:
7356     case DYNAMIC_CAST_EXPR:
7357     case NOP_EXPR:
7358       return build1
7359         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
7360          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
7361
7362     case INDIRECT_REF:
7363     case NEGATE_EXPR:
7364     case TRUTH_NOT_EXPR:
7365     case BIT_NOT_EXPR:
7366     case ADDR_EXPR:
7367     case CONVERT_EXPR:      /* Unary + */
7368     case SIZEOF_EXPR:
7369     case ALIGNOF_EXPR:
7370     case ARROW_EXPR:
7371     case THROW_EXPR:
7372     case TYPEID_EXPR:
7373     case REALPART_EXPR:
7374     case IMAGPART_EXPR:
7375       return build1
7376         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
7377          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
7378
7379     case COMPONENT_REF:
7380       {
7381         tree object;
7382         tree name;
7383
7384         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
7385         name = TREE_OPERAND (t, 1);
7386         if (TREE_CODE (name) == BIT_NOT_EXPR) 
7387           {
7388             name = tsubst_copy (TREE_OPERAND (name, 0), args,
7389                                 complain, in_decl);
7390             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
7391           }
7392         else if (TREE_CODE (name) == SCOPE_REF
7393                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
7394           {
7395             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
7396                                      complain, in_decl);
7397             name = TREE_OPERAND (name, 1);
7398             name = tsubst_copy (TREE_OPERAND (name, 0), args,
7399                                 complain, in_decl);
7400             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
7401             name = build_nt (SCOPE_REF, base, name);
7402           }
7403         else
7404           name = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
7405         return build_nt (COMPONENT_REF, object, name);
7406       }
7407
7408     case PLUS_EXPR:
7409     case MINUS_EXPR:
7410     case MULT_EXPR:
7411     case TRUNC_DIV_EXPR:
7412     case CEIL_DIV_EXPR:
7413     case FLOOR_DIV_EXPR:
7414     case ROUND_DIV_EXPR:
7415     case EXACT_DIV_EXPR:
7416     case BIT_AND_EXPR:
7417     case BIT_ANDTC_EXPR:
7418     case BIT_IOR_EXPR:
7419     case BIT_XOR_EXPR:
7420     case TRUNC_MOD_EXPR:
7421     case FLOOR_MOD_EXPR:
7422     case TRUTH_ANDIF_EXPR:
7423     case TRUTH_ORIF_EXPR:
7424     case TRUTH_AND_EXPR:
7425     case TRUTH_OR_EXPR:
7426     case RSHIFT_EXPR:
7427     case LSHIFT_EXPR:
7428     case RROTATE_EXPR:
7429     case LROTATE_EXPR:
7430     case EQ_EXPR:
7431     case NE_EXPR:
7432     case MAX_EXPR:
7433     case MIN_EXPR:
7434     case LE_EXPR:
7435     case GE_EXPR:
7436     case LT_EXPR:
7437     case GT_EXPR:
7438     case ARRAY_REF:
7439     case COMPOUND_EXPR:
7440     case SCOPE_REF:
7441     case DOTSTAR_EXPR:
7442     case MEMBER_REF:
7443     case PREDECREMENT_EXPR:
7444     case PREINCREMENT_EXPR:
7445     case POSTDECREMENT_EXPR:
7446     case POSTINCREMENT_EXPR:
7447       return build_nt
7448         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
7449          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
7450
7451     case CALL_EXPR:
7452       return build_nt (code, 
7453                        tsubst_copy (TREE_OPERAND (t, 0), args,
7454                                     complain, in_decl),
7455                        tsubst_copy (TREE_OPERAND (t, 1), args, complain,
7456                                     in_decl),
7457                        NULL_TREE);
7458
7459     case METHOD_CALL_EXPR:
7460       return build_nt
7461         (code, 
7462          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
7463          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
7464          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl),
7465          NULL_TREE);
7466
7467     case STMT_EXPR:
7468       /* This processing should really occur in tsubst_expr.  However,
7469          tsubst_expr does not recurse into expressions, since it
7470          assumes that there aren't any statements inside them.  So, we
7471          need to expand the STMT_EXPR here.  */
7472       if (!processing_template_decl)
7473         {
7474           tree stmt_expr = begin_stmt_expr ();
7475           tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl);
7476           return finish_stmt_expr (stmt_expr);
7477         }
7478       
7479       return t;
7480
7481     case COND_EXPR:
7482     case MODOP_EXPR:
7483     case PSEUDO_DTOR_EXPR:
7484       {
7485         r = build_nt
7486           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
7487            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
7488            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
7489         return r;
7490       }
7491
7492     case NEW_EXPR:
7493       {
7494         r = build_nt
7495         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
7496          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
7497          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
7498         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
7499         return r;
7500       }
7501
7502     case DELETE_EXPR:
7503       {
7504         r = build_nt
7505         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
7506          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
7507         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
7508         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
7509         return r;
7510       }
7511
7512     case TEMPLATE_ID_EXPR:
7513       {
7514         /* Substituted template arguments */
7515         tree targs = tsubst_copy (TREE_OPERAND (t, 1), args, complain,
7516                                   in_decl);
7517
7518         maybe_fold_nontype_args (targs);
7519         return lookup_template_function
7520           (tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl), targs);
7521       }
7522
7523     case TREE_LIST:
7524       {
7525         tree purpose, value, chain;
7526
7527         if (t == void_list_node)
7528           return t;
7529
7530         purpose = TREE_PURPOSE (t);
7531         if (purpose)
7532           purpose = tsubst_copy (purpose, args, complain, in_decl);
7533         value = TREE_VALUE (t);
7534         if (value)
7535           value = tsubst_copy (value, args, complain, in_decl);
7536         chain = TREE_CHAIN (t);
7537         if (chain && chain != void_type_node)
7538           chain = tsubst_copy (chain, args, complain, in_decl);
7539         if (purpose == TREE_PURPOSE (t)
7540             && value == TREE_VALUE (t)
7541             && chain == TREE_CHAIN (t))
7542           return t;
7543         return tree_cons (purpose, value, chain);
7544       }
7545
7546     case RECORD_TYPE:
7547     case UNION_TYPE:
7548     case ENUMERAL_TYPE:
7549     case INTEGER_TYPE:
7550     case TEMPLATE_TYPE_PARM:
7551     case TEMPLATE_TEMPLATE_PARM:
7552     case BOUND_TEMPLATE_TEMPLATE_PARM:
7553     case TEMPLATE_PARM_INDEX:
7554     case POINTER_TYPE:
7555     case REFERENCE_TYPE:
7556     case OFFSET_TYPE:
7557     case FUNCTION_TYPE:
7558     case METHOD_TYPE:
7559     case ARRAY_TYPE:
7560     case TYPENAME_TYPE:
7561     case UNBOUND_CLASS_TEMPLATE:
7562     case TYPEOF_TYPE:
7563     case TYPE_DECL:
7564       return tsubst (t, args, complain, in_decl);
7565
7566     case IDENTIFIER_NODE:
7567       if (IDENTIFIER_TYPENAME_P (t))
7568         {
7569           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
7570           return mangle_conv_op_name_for_type (new_type);
7571         }
7572       else
7573         return t;
7574
7575     case CONSTRUCTOR:
7576       {
7577         r = build_constructor
7578           (tsubst (TREE_TYPE (t), args, complain, in_decl), 
7579            tsubst_copy (CONSTRUCTOR_ELTS (t), args, complain, in_decl));
7580         TREE_HAS_CONSTRUCTOR (r) = TREE_HAS_CONSTRUCTOR (t);
7581         return r;
7582       }
7583
7584     case VA_ARG_EXPR:
7585       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
7586                                           in_decl),
7587                              tsubst (TREE_TYPE (t), args, complain, in_decl));
7588
7589     default:
7590       return t;
7591     }
7592 }
7593
7594 /* Like tsubst_copy for expressions, etc. but also does semantic
7595    processing.  */
7596
7597 static tree
7598 tsubst_expr (t, args, complain, in_decl)
7599      tree t, args;
7600      tsubst_flags_t complain;
7601      tree in_decl;
7602 {
7603   tree stmt, tmp;
7604
7605   if (t == NULL_TREE || t == error_mark_node)
7606     return t;
7607
7608   if (processing_template_decl)
7609     return tsubst_copy (t, args, complain, in_decl);
7610
7611   if (!STATEMENT_CODE_P (TREE_CODE (t)))
7612     return tsubst_copy_and_build (t, args, complain, in_decl);
7613     
7614   switch (TREE_CODE (t))
7615     {
7616     case CTOR_INITIALIZER:
7617       prep_stmt (t);
7618       finish_mem_initializers (tsubst_initializer_list 
7619                                (TREE_OPERAND (t, 0), args));
7620       break;
7621
7622     case RETURN_STMT:
7623       prep_stmt (t);
7624       finish_return_stmt (tsubst_expr (RETURN_STMT_EXPR (t),
7625                                        args, complain, in_decl));
7626       break;
7627
7628     case EXPR_STMT:
7629       prep_stmt (t);
7630       finish_expr_stmt (tsubst_expr (EXPR_STMT_EXPR (t),
7631                                      args, complain, in_decl));
7632       break;
7633
7634     case USING_STMT:
7635       prep_stmt (t);
7636       do_using_directive (tsubst_expr (USING_STMT_NAMESPACE (t),
7637                                        args, complain, in_decl));
7638       break;
7639       
7640     case DECL_STMT:
7641       {
7642         tree decl;
7643         tree init;
7644
7645         prep_stmt (t);
7646         decl = DECL_STMT_DECL (t);
7647         if (TREE_CODE (decl) == LABEL_DECL)
7648           finish_label_decl (DECL_NAME (decl));
7649         else if (TREE_CODE (decl) == USING_DECL)
7650           {
7651             tree scope = DECL_INITIAL (decl);
7652             tree name = DECL_NAME (decl);
7653             
7654             scope = tsubst_expr (scope, args, complain, in_decl);
7655             do_local_using_decl (lookup_qualified_name (scope,
7656                                                         name, 
7657                                                         /*is_type_p=*/0,
7658                                                         /*flags=*/0));
7659           }
7660         else
7661           {
7662             init = DECL_INITIAL (decl);
7663             decl = tsubst (decl, args, complain, in_decl);
7664             if (decl != error_mark_node)
7665               {
7666                 if (init)
7667                   DECL_INITIAL (decl) = error_mark_node;
7668                 /* By marking the declaration as instantiated, we avoid
7669                    trying to instantiate it.  Since instantiate_decl can't
7670                    handle local variables, and since we've already done
7671                    all that needs to be done, that's the right thing to
7672                    do.  */
7673                 if (TREE_CODE (decl) == VAR_DECL)
7674                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
7675                 if (TREE_CODE (decl) == VAR_DECL
7676                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
7677                   /* Anonymous aggregates are a special case.  */
7678                   finish_anon_union (decl);
7679                 else 
7680                   {
7681                     maybe_push_decl (decl);
7682                     if (DECL_PRETTY_FUNCTION_P (decl))
7683                       {
7684                         /* For __PRETTY_FUNCTION__ we have to adjust the
7685                            initializer.  */
7686                         const char *const name
7687                           = cxx_printable_name (current_function_decl, 2);
7688                         init = cp_fname_init (name);
7689                         TREE_TYPE (decl) = TREE_TYPE (init);
7690                       }
7691                     else
7692                       init = tsubst_expr (init, args, complain, in_decl);
7693                     cp_finish_decl (decl, init, NULL_TREE, 0);
7694                   }
7695               }
7696           }
7697
7698         /* A DECL_STMT can also be used as an expression, in the condition
7699            clause of an if/for/while construct.  If we aren't followed by
7700            another statement, return our decl.  */
7701         if (TREE_CHAIN (t) == NULL_TREE)
7702           return decl;
7703       }
7704       break;
7705
7706     case FOR_STMT:
7707       {
7708         prep_stmt (t);
7709
7710         stmt = begin_for_stmt ();
7711         tsubst_expr (FOR_INIT_STMT (t), args, complain, in_decl);
7712         finish_for_init_stmt (stmt);
7713         finish_for_cond (tsubst_expr (FOR_COND (t),
7714                                       args, complain, in_decl),
7715                          stmt);
7716         tmp = tsubst_expr (FOR_EXPR (t), args, complain, in_decl);
7717         finish_for_expr (tmp, stmt);
7718         tsubst_expr (FOR_BODY (t), args, complain, in_decl);
7719         finish_for_stmt (stmt);
7720       }
7721       break;
7722
7723     case WHILE_STMT:
7724       {
7725         prep_stmt (t);
7726         stmt = begin_while_stmt ();
7727         finish_while_stmt_cond (tsubst_expr (WHILE_COND (t),
7728                                              args, complain, in_decl),
7729                                 stmt);
7730         tsubst_expr (WHILE_BODY (t), args, complain, in_decl);
7731         finish_while_stmt (stmt);
7732       }
7733       break;
7734
7735     case DO_STMT:
7736       {
7737         prep_stmt (t);
7738         stmt = begin_do_stmt ();
7739         tsubst_expr (DO_BODY (t), args, complain, in_decl);
7740         finish_do_body (stmt);
7741         finish_do_stmt (tsubst_expr (DO_COND (t),
7742                                      args, complain, in_decl),
7743                         stmt);
7744       }
7745       break;
7746
7747     case IF_STMT:
7748       {
7749         prep_stmt (t);
7750         stmt = begin_if_stmt ();
7751         finish_if_stmt_cond (tsubst_expr (IF_COND (t),
7752                                           args, complain, in_decl),
7753                              stmt);
7754
7755         if (tmp = THEN_CLAUSE (t), tmp)
7756           {
7757             tsubst_expr (tmp, args, complain, in_decl);
7758             finish_then_clause (stmt);
7759           }
7760
7761         if (tmp = ELSE_CLAUSE (t), tmp)
7762           {
7763             begin_else_clause ();
7764             tsubst_expr (tmp, args, complain, in_decl);
7765             finish_else_clause (stmt);
7766           }
7767
7768         finish_if_stmt ();
7769       }
7770       break;
7771
7772     case COMPOUND_STMT:
7773       {
7774         prep_stmt (t);
7775         if (COMPOUND_STMT_BODY_BLOCK (t))
7776           stmt = begin_function_body ();
7777         else
7778           stmt = begin_compound_stmt (COMPOUND_STMT_NO_SCOPE (t));
7779
7780         tsubst_expr (COMPOUND_BODY (t), args, complain, in_decl);
7781
7782         if (COMPOUND_STMT_BODY_BLOCK (t))
7783           finish_function_body (stmt);
7784         else
7785           finish_compound_stmt (COMPOUND_STMT_NO_SCOPE (t), stmt);
7786       }
7787       break;
7788
7789     case BREAK_STMT:
7790       prep_stmt (t);
7791       finish_break_stmt ();
7792       break;
7793
7794     case CONTINUE_STMT:
7795       prep_stmt (t);
7796       finish_continue_stmt ();
7797       break;
7798
7799     case SWITCH_STMT:
7800       {
7801         tree val;
7802
7803         prep_stmt (t);
7804         stmt = begin_switch_stmt ();
7805         val = tsubst_expr (SWITCH_COND (t), args, complain, in_decl);
7806         finish_switch_cond (val, stmt);
7807         tsubst_expr (SWITCH_BODY (t), args, complain, in_decl);
7808         finish_switch_stmt (stmt);
7809       }
7810       break;
7811
7812     case CASE_LABEL:
7813       prep_stmt (t);
7814       finish_case_label (tsubst_expr (CASE_LOW (t), args, complain, in_decl),
7815                          tsubst_expr (CASE_HIGH (t), args, complain,
7816                                       in_decl));
7817       break;
7818
7819     case LABEL_STMT:
7820       input_line = STMT_LINENO (t);
7821       finish_label_stmt (DECL_NAME (LABEL_STMT_LABEL (t)));
7822       break;
7823
7824     case FILE_STMT:
7825       input_filename = FILE_STMT_FILENAME (t);
7826       add_stmt (build_nt (FILE_STMT, FILE_STMT_FILENAME_NODE (t)));
7827       break;
7828
7829     case GOTO_STMT:
7830       prep_stmt (t);
7831       tmp = GOTO_DESTINATION (t);
7832       if (TREE_CODE (tmp) != LABEL_DECL)
7833         /* Computed goto's must be tsubst'd into.  On the other hand,
7834            non-computed gotos must not be; the identifier in question
7835            will have no binding.  */
7836         tmp = tsubst_expr (tmp, args, complain, in_decl);
7837       else
7838         tmp = DECL_NAME (tmp);
7839       finish_goto_stmt (tmp);
7840       break;
7841
7842     case ASM_STMT:
7843       prep_stmt (t);
7844       tmp = finish_asm_stmt
7845         (ASM_CV_QUAL (t),
7846          tsubst_expr (ASM_STRING (t), args, complain, in_decl),
7847          tsubst_expr (ASM_OUTPUTS (t), args, complain, in_decl),
7848          tsubst_expr (ASM_INPUTS (t), args, complain, in_decl), 
7849          tsubst_expr (ASM_CLOBBERS (t), args, complain, in_decl));
7850       ASM_INPUT_P (tmp) = ASM_INPUT_P (t);
7851       break;
7852
7853     case TRY_BLOCK:
7854       prep_stmt (t);
7855       if (CLEANUP_P (t))
7856         {
7857           stmt = begin_try_block ();
7858           tsubst_expr (TRY_STMTS (t), args, complain, in_decl);
7859           finish_cleanup_try_block (stmt);
7860           finish_cleanup (tsubst_expr (TRY_HANDLERS (t), args,
7861                                        complain, in_decl),
7862                           stmt);
7863         }
7864       else
7865         {
7866           if (FN_TRY_BLOCK_P (t))
7867             stmt = begin_function_try_block ();
7868           else
7869             stmt = begin_try_block ();
7870
7871           tsubst_expr (TRY_STMTS (t), args, complain, in_decl);
7872
7873           if (FN_TRY_BLOCK_P (t))
7874             finish_function_try_block (stmt);
7875           else
7876             finish_try_block (stmt);
7877
7878           tsubst_expr (TRY_HANDLERS (t), args, complain, in_decl);
7879           if (FN_TRY_BLOCK_P (t))
7880             finish_function_handler_sequence (stmt);
7881           else
7882             finish_handler_sequence (stmt);
7883         }
7884       break;
7885       
7886     case HANDLER:
7887       {
7888         tree decl;
7889
7890         prep_stmt (t);
7891         stmt = begin_handler ();
7892         if (HANDLER_PARMS (t))
7893           {
7894             decl = DECL_STMT_DECL (HANDLER_PARMS (t));
7895             decl = tsubst (decl, args, complain, in_decl);
7896             /* Prevent instantiate_decl from trying to instantiate
7897                this variable.  We've already done all that needs to be
7898                done.  */
7899             DECL_TEMPLATE_INSTANTIATED (decl) = 1;
7900           }
7901         else
7902           decl = NULL_TREE;
7903         finish_handler_parms (decl, stmt);
7904         tsubst_expr (HANDLER_BODY (t), args, complain, in_decl);
7905         finish_handler (stmt);
7906       }
7907       break;
7908
7909     case TAG_DEFN:
7910       prep_stmt (t);
7911       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
7912       break;
7913
7914     default:
7915       abort ();
7916     }
7917
7918   return tsubst_expr (TREE_CHAIN (t), args, complain, in_decl);
7919 }
7920
7921 /* Like tsubst but deals with expressions and performs semantic
7922    analysis.  */
7923
7924 static tree
7925 tsubst_copy_and_build (t, args, complain, in_decl)
7926      tree t, args;
7927      tsubst_flags_t complain;
7928      tree in_decl;
7929 {
7930   if (t == NULL_TREE || t == error_mark_node)
7931     return t;
7932
7933   switch (TREE_CODE (t))
7934     {
7935     case IDENTIFIER_NODE:
7936       if (IDENTIFIER_TYPENAME_P (t))
7937         {
7938           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
7939           return do_identifier (mangle_conv_op_name_for_type (new_type),
7940                                 NULL_TREE);
7941         }
7942       else
7943         return do_identifier (t, NULL_TREE);
7944
7945     case LOOKUP_EXPR:
7946       {
7947         if (LOOKUP_EXPR_GLOBAL (t))
7948           {
7949             tree token
7950               = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
7951             return do_scoped_id (token, IDENTIFIER_GLOBAL_VALUE (token));
7952           }
7953         else
7954           {
7955             t = do_identifier
7956               (tsubst_copy
7957                (TREE_OPERAND (t, 0), args, complain, in_decl),
7958                NULL_TREE);
7959             if (TREE_CODE (t) == ALIAS_DECL)
7960               t = DECL_INITIAL (t);
7961             return t;
7962           }
7963       }
7964
7965     case TEMPLATE_ID_EXPR:
7966       {
7967         tree object;
7968         tree template
7969           = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
7970         tree targs
7971           = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
7972         
7973         if (TREE_CODE (template) == COMPONENT_REF)
7974           {
7975             object = TREE_OPERAND (template, 0);
7976             template = TREE_OPERAND (template, 1);
7977           }
7978         else
7979           object = NULL_TREE;
7980         maybe_fold_nontype_args (targs);
7981         template = lookup_template_function (template, targs);
7982         
7983         if (object)
7984           return build (COMPONENT_REF, TREE_TYPE (template), 
7985                         object, template);
7986         else
7987           return template;
7988       }
7989
7990     case INDIRECT_REF:
7991       return build_x_indirect_ref
7992         (tsubst_copy_and_build (TREE_OPERAND (t, 0), args, complain, in_decl),
7993          "unary *");
7994
7995     case CAST_EXPR:
7996       return build_functional_cast
7997         (tsubst (TREE_TYPE (t), args, complain, in_decl),
7998          tsubst_copy_and_build (TREE_OPERAND (t, 0), args, complain, in_decl));
7999
8000     case REINTERPRET_CAST_EXPR:
8001       return build_reinterpret_cast
8002         (tsubst (TREE_TYPE (t), args, complain, in_decl),
8003          tsubst_copy_and_build (TREE_OPERAND (t, 0), args, complain, in_decl));
8004
8005     case CONST_CAST_EXPR:
8006       return build_const_cast
8007         (tsubst (TREE_TYPE (t), args, complain, in_decl),
8008          tsubst_copy_and_build (TREE_OPERAND (t, 0), args, complain, in_decl));
8009
8010     case DYNAMIC_CAST_EXPR:
8011       return build_dynamic_cast
8012         (tsubst (TREE_TYPE (t), args, complain, in_decl),
8013          tsubst_copy_and_build (TREE_OPERAND (t, 0), args, complain, in_decl));
8014
8015     case STATIC_CAST_EXPR:
8016       return build_static_cast
8017         (tsubst (TREE_TYPE (t), args, complain, in_decl),
8018          tsubst_copy_and_build (TREE_OPERAND (t, 0), args, complain, in_decl));
8019
8020     case PREDECREMENT_EXPR:
8021     case PREINCREMENT_EXPR:
8022     case POSTDECREMENT_EXPR:
8023     case POSTINCREMENT_EXPR:
8024       if (TREE_TYPE (t))
8025         return tsubst_copy (t, args, complain, in_decl);
8026       else
8027         return build_x_unary_op
8028           (TREE_CODE (t),
8029            tsubst_copy_and_build (TREE_OPERAND (t, 0), args, complain,
8030                                   in_decl));
8031
8032     case NEGATE_EXPR:
8033     case BIT_NOT_EXPR:
8034       if (TREE_TYPE (t))
8035         return tsubst_copy (t, args, complain, in_decl);
8036       else
8037         return build_x_unary_op
8038           (TREE_CODE (t),
8039            tsubst_copy_and_build (TREE_OPERAND (t, 0), args, complain,
8040                                   in_decl));
8041
8042     case ABS_EXPR:
8043       if (TREE_TYPE (t))
8044         return t;
8045       return build_x_unary_op
8046         (TREE_CODE (t),
8047          tsubst_copy_and_build (TREE_OPERAND (t, 0), args, complain, in_decl));
8048
8049     case TRUTH_NOT_EXPR:
8050     case ADDR_EXPR:
8051     case CONVERT_EXPR:  /* Unary + */
8052     case REALPART_EXPR:
8053     case IMAGPART_EXPR:
8054       if (TREE_TYPE (t))
8055         return tsubst_copy (t, args, complain, in_decl);
8056       else
8057         return build_x_unary_op
8058           (TREE_CODE (t),
8059            tsubst_copy_and_build (TREE_OPERAND (t, 0), args, complain,
8060                                   in_decl));
8061
8062     case PLUS_EXPR:
8063     case MINUS_EXPR:
8064     case MULT_EXPR:
8065     case TRUNC_DIV_EXPR:
8066     case CEIL_DIV_EXPR:
8067     case FLOOR_DIV_EXPR:
8068     case ROUND_DIV_EXPR:
8069     case EXACT_DIV_EXPR:
8070     case BIT_AND_EXPR:
8071     case BIT_ANDTC_EXPR:
8072     case BIT_IOR_EXPR:
8073     case BIT_XOR_EXPR:
8074     case TRUNC_MOD_EXPR:
8075     case FLOOR_MOD_EXPR:
8076     case TRUTH_ANDIF_EXPR:
8077     case TRUTH_ORIF_EXPR:
8078     case TRUTH_AND_EXPR:
8079     case TRUTH_OR_EXPR:
8080     case RSHIFT_EXPR:
8081     case LSHIFT_EXPR:
8082     case RROTATE_EXPR:
8083     case LROTATE_EXPR:
8084     case EQ_EXPR:
8085     case NE_EXPR:
8086     case MAX_EXPR:
8087     case MIN_EXPR:
8088     case LE_EXPR:
8089     case GE_EXPR:
8090     case LT_EXPR:
8091     case GT_EXPR:
8092     case MEMBER_REF:
8093       return build_x_binary_op
8094         (TREE_CODE (t), 
8095          tsubst_copy_and_build (TREE_OPERAND (t, 0), args, complain, in_decl),
8096          tsubst_copy_and_build (TREE_OPERAND (t, 1), args, complain, in_decl));
8097
8098     case DOTSTAR_EXPR:
8099       return build_m_component_ref
8100         (tsubst_copy_and_build (TREE_OPERAND (t, 0), args, complain, in_decl),
8101          tsubst_copy_and_build (TREE_OPERAND (t, 1), args, complain, in_decl));
8102
8103     case SCOPE_REF:
8104       return build_offset_ref
8105         (tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
8106          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
8107
8108     case ARRAY_REF:
8109       {
8110         if (tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl)
8111             == NULL_TREE)
8112           /* new-type-id */
8113           return build_nt
8114             (ARRAY_REF, NULL_TREE,
8115              tsubst_copy_and_build (TREE_OPERAND (t, 1), args, complain,
8116                                     in_decl));
8117         
8118         return grok_array_decl
8119           (tsubst_copy_and_build (TREE_OPERAND (t, 0), args, complain,
8120                                   in_decl),
8121            tsubst_copy_and_build (TREE_OPERAND (t, 1), args, complain,
8122                                   in_decl));
8123       }
8124
8125     case SIZEOF_EXPR:
8126     case ALIGNOF_EXPR:
8127       {
8128         tree r =
8129           tsubst_copy_and_build (TREE_OPERAND (t, 0), args, complain, in_decl);
8130         if (!TYPE_P (r))
8131           return TREE_CODE (t) == SIZEOF_EXPR ?
8132             expr_sizeof (r) : c_alignof_expr (r);
8133         else
8134           return cxx_sizeof_or_alignof_type (r, TREE_CODE (t), true);
8135       }
8136
8137     case MODOP_EXPR:
8138       return build_x_modify_expr
8139         (tsubst_copy_and_build (TREE_OPERAND (t, 0), args, complain, in_decl),
8140          TREE_CODE (TREE_OPERAND (t, 1)),
8141          tsubst_copy_and_build (TREE_OPERAND (t, 2), args, complain, in_decl));
8142
8143     case ARROW_EXPR:
8144       return build_x_arrow
8145         (tsubst_copy_and_build (TREE_OPERAND (t, 0), args, complain, in_decl));
8146
8147     case NEW_EXPR:
8148       return build_new
8149         (tsubst_copy_and_build (TREE_OPERAND (t, 0), args, complain, in_decl),
8150          tsubst_copy_and_build (TREE_OPERAND (t, 1), args, complain, in_decl),
8151          tsubst_copy_and_build (TREE_OPERAND (t, 2), args, complain, in_decl),
8152          NEW_EXPR_USE_GLOBAL (t));
8153
8154     case DELETE_EXPR:
8155      return delete_sanity
8156        (tsubst_copy_and_build (TREE_OPERAND (t, 0), args, complain, in_decl),
8157         tsubst_copy_and_build (TREE_OPERAND (t, 1), args, complain, in_decl),
8158         DELETE_EXPR_USE_VEC (t),
8159         DELETE_EXPR_USE_GLOBAL (t));
8160
8161     case COMPOUND_EXPR:
8162       {
8163         if (tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl)
8164             == NULL_TREE)
8165           return build_x_compound_expr
8166             (tsubst_copy_and_build (TREE_OPERAND (t, 0), args, complain,
8167                                     in_decl));
8168         else
8169           abort ();
8170       }
8171
8172     case METHOD_CALL_EXPR:
8173       {
8174         tree method
8175           = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
8176         
8177         if (TREE_CODE (method) == SCOPE_REF)
8178           {
8179             tree name = TREE_OPERAND (method, 1);
8180           
8181             if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
8182               name = build_nt (TEMPLATE_ID_EXPR,
8183                                TREE_OPERAND (name, 0),
8184                                TREE_OPERAND (name, 1));
8185             
8186             return build_scoped_method_call
8187               (tsubst_copy_and_build
8188                (TREE_OPERAND (t, 1), args, complain, in_decl),
8189                TREE_OPERAND (method, 0),
8190                name,
8191                tsubst_copy_and_build
8192                (TREE_OPERAND (t, 2), args, complain, in_decl));
8193           }
8194         else 
8195           {
8196             /* We can get a TEMPLATE_ID_EXPR here on code like:
8197
8198             x->f<2>();
8199               
8200             so we must resolve that.  However, we can also get things
8201             like a BIT_NOT_EXPR here, when referring to a destructor,
8202             and things like that are not correctly resolved by this
8203             function so just use it when we really need it.  */
8204             if (TREE_CODE (method) == TEMPLATE_ID_EXPR)
8205               method = lookup_template_function
8206                 (TREE_OPERAND (method, 0),
8207                  TREE_OPERAND (method, 1));
8208
8209             return build_method_call
8210               (tsubst_copy_and_build
8211                (TREE_OPERAND (t, 1), args, complain, in_decl),
8212                method,
8213                tsubst_copy_and_build
8214                (TREE_OPERAND (t, 2), args, complain, in_decl),
8215                NULL_TREE, LOOKUP_NORMAL);
8216           }
8217       }
8218
8219     case CALL_EXPR:
8220       {
8221         tree function, copy_args;
8222
8223         function = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
8224         copy_args = tsubst_copy_and_build (TREE_OPERAND (t, 1), args,
8225                                            complain, in_decl);
8226           
8227         if (BASELINK_P (function))
8228           return build_call_from_tree (function, copy_args, 1);
8229         else if (TREE_CODE (function) == SCOPE_REF)
8230           {
8231             tree name = TREE_OPERAND (function, 1);
8232             if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
8233               name = build_nt (TEMPLATE_ID_EXPR,
8234                                TREE_OPERAND (name, 0),
8235                                build_expr_from_tree (TREE_OPERAND (name, 1)));
8236             
8237             function = resolve_scoped_fn_name (TREE_OPERAND (function, 0),
8238                                                name);
8239             
8240             return build_call_from_tree (function, copy_args, 1);
8241           }
8242         else
8243           {
8244             tree name = function;
8245             tree id;
8246             
8247             if (copy_args != NULL_TREE && TREE_CODE (name) == LOOKUP_EXPR
8248                 && !LOOKUP_EXPR_GLOBAL (name)
8249                 && (TREE_CODE ((id = TREE_OPERAND (name, 0)))
8250                     == IDENTIFIER_NODE)
8251                 && (!current_class_type
8252                     || !lookup_member (current_class_type, id, 0, false)))
8253               {
8254                 /* Do Koenig lookup if there are no class members.  */
8255                 name = do_identifier (id, copy_args);
8256               }
8257             else if (TREE_CODE (name) == TEMPLATE_ID_EXPR
8258                      || ! really_overloaded_fn (name))
8259               name = build_expr_from_tree (name);
8260
8261             if (TREE_CODE (name) == OFFSET_REF)
8262               return build_offset_ref_call_from_tree (name, copy_args);
8263             if (TREE_CODE (name) == COMPONENT_REF)
8264               return finish_object_call_expr (TREE_OPERAND (name, 1),
8265                                               TREE_OPERAND (name, 0),
8266                                               copy_args);
8267             name = convert_from_reference (name);
8268             return build_call_from_tree (name, copy_args, 
8269                                          /*disallow_virtual=*/false);
8270           }
8271       }
8272
8273     case COND_EXPR:
8274       return build_x_conditional_expr
8275         (tsubst_copy_and_build (TREE_OPERAND (t, 0), args, complain, in_decl),
8276          tsubst_copy_and_build (TREE_OPERAND (t, 1), args, complain, in_decl),
8277          tsubst_copy_and_build (TREE_OPERAND (t, 2), args, complain, in_decl));
8278
8279     case PSEUDO_DTOR_EXPR:
8280       return finish_pseudo_destructor_expr 
8281         (tsubst_copy_and_build (TREE_OPERAND (t, 0), args, complain, in_decl),
8282          tsubst_copy_and_build (TREE_OPERAND (t, 1), args, complain, in_decl),
8283          tsubst_copy_and_build (TREE_OPERAND (t, 2), args, complain, in_decl));
8284
8285     case TREE_LIST:
8286       {
8287         tree purpose, value, chain;
8288
8289         if (t == void_list_node)
8290           return t;
8291
8292         purpose = TREE_PURPOSE (t);
8293         if (purpose)
8294           purpose = tsubst_copy_and_build (purpose, args, complain, in_decl);
8295         value = TREE_VALUE (t);
8296         if (value)
8297           value = tsubst_copy_and_build (value, args, complain, in_decl);
8298         chain = TREE_CHAIN (t);
8299         if (chain && chain != void_type_node)
8300           chain = tsubst_copy_and_build (chain, args, complain, in_decl);
8301         if (purpose == TREE_PURPOSE (t)
8302             && value == TREE_VALUE (t)
8303             && chain == TREE_CHAIN (t))
8304           return t;
8305         return tree_cons (purpose, value, chain);
8306       }
8307
8308     case COMPONENT_REF:
8309       {
8310         tree object =
8311           tsubst_copy_and_build (TREE_OPERAND (t, 0), args, complain, in_decl);
8312         tree member =
8313           tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
8314
8315         if (!CLASS_TYPE_P (TREE_TYPE (object)))
8316           {
8317             if (TREE_CODE (member) == BIT_NOT_EXPR)
8318               return finish_pseudo_destructor_expr (object, 
8319                                                     NULL_TREE,
8320                                                     TREE_TYPE (object));
8321             else if (TREE_CODE (member) == SCOPE_REF
8322                      && (TREE_CODE (TREE_OPERAND (member, 1)) == BIT_NOT_EXPR))
8323               return finish_pseudo_destructor_expr (object, 
8324                                                     object,
8325                                                     TREE_TYPE (object));
8326           }
8327         else if (TREE_CODE (member) == SCOPE_REF
8328                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
8329           {
8330             tree tmpl;
8331             tree args;
8332         
8333             /* Lookup the template functions now that we know what the
8334                scope is.  */
8335             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
8336             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
8337             member = lookup_qualified_name (TREE_OPERAND (member, 0),
8338                                             tmpl, 
8339                                             /*is_type=*/0,
8340                                             /*flags=*/0);
8341             if (BASELINK_P (member))
8342               BASELINK_FUNCTIONS (member) 
8343                 = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
8344                             args);
8345             else
8346               {
8347                 error ("`%D' is not a member of `%T'",
8348                        tmpl, TREE_TYPE (object));
8349                 return error_mark_node;
8350               }
8351           }
8352
8353         return finish_class_member_access_expr (object, member);
8354       }
8355
8356     case THROW_EXPR:
8357       return build_throw
8358         (tsubst_copy_and_build (TREE_OPERAND (t, 0), args, complain, in_decl));
8359
8360     case CONSTRUCTOR:
8361       {
8362         tree r;
8363         tree elts;
8364         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8365         bool purpose_p;
8366
8367         /* digest_init will do the wrong thing if we let it.  */
8368         if (type && TYPE_PTRMEMFUNC_P (type))
8369           return t;
8370
8371         r = NULL_TREE;
8372         /* We do not want to process the purpose of aggregate
8373            initializers as they are identifier nodes which will be
8374            looked up by digest_init.  */
8375         purpose_p = !(type && IS_AGGR_TYPE (type));
8376         for (elts = CONSTRUCTOR_ELTS (t);
8377              elts;
8378              elts = TREE_CHAIN (elts))
8379           {
8380             tree purpose = TREE_PURPOSE (elts);
8381             tree value = TREE_VALUE (elts);
8382             
8383             if (purpose && purpose_p)
8384               purpose
8385                 = tsubst_copy_and_build (purpose, args, complain, in_decl);
8386             value = tsubst_copy_and_build (value, args, complain, in_decl);
8387             r = tree_cons (purpose, value, r);
8388           }
8389         
8390         r = build_constructor (NULL_TREE, nreverse (r));
8391         TREE_HAS_CONSTRUCTOR (r) = TREE_HAS_CONSTRUCTOR (t);
8392
8393         if (type)
8394           return digest_init (type, r, 0);
8395         return r;
8396       }
8397
8398     case TYPEID_EXPR:
8399       {
8400         tree operand_0
8401           = tsubst_copy_and_build (TREE_OPERAND (t, 0), args, complain,
8402                                    in_decl);
8403         
8404         if (TYPE_P (operand_0))
8405           return get_typeid (operand_0);
8406         return build_typeid (operand_0);
8407       }
8408
8409     case PARM_DECL:
8410       return convert_from_reference (tsubst_copy (t, args, complain, in_decl));
8411
8412     case VAR_DECL:
8413       return convert_from_reference (tsubst_copy (t, args, complain, in_decl));
8414
8415     case VA_ARG_EXPR:
8416         return build_x_va_arg
8417           (tsubst_copy_and_build
8418            (TREE_OPERAND (t, 0), args, complain, in_decl),
8419            tsubst_copy (TREE_TYPE (t), args, complain, in_decl));
8420
8421     default:
8422       return tsubst_copy (t, args, complain, in_decl);
8423     }
8424 }
8425
8426 /* Verify that the instantiated ARGS are valid. For type arguments,
8427    make sure that the type's linkage is ok. For non-type arguments,
8428    make sure they are constants if they are integral or enumarations.
8429    Emit an error under control of COMPLAIN, and return TRUE on error. */
8430
8431 static bool
8432 check_instantiated_args (tmpl, args, complain)
8433      tree tmpl, args;
8434      tsubst_flags_t complain;
8435 {
8436   int ix, len = DECL_NTPARMS (tmpl);
8437   bool result = false;
8438
8439   for (ix = 0; ix != len; ix++)
8440     {
8441       tree t = TREE_VEC_ELT (args, ix);
8442       
8443       if (TYPE_P (t))
8444         {
8445           /* [basic.link]: A name with no linkage (notably, the name
8446              of a class or enumeration declared in a local scope)
8447              shall not be used to declare an entity with linkage.
8448              This implies that names with no linkage cannot be used as
8449              template arguments.  */
8450           tree nt = no_linkage_check (t);
8451
8452           if (nt)
8453             {
8454               if (!(complain & tf_error))
8455                 /*OK*/;
8456               else if (TYPE_ANONYMOUS_P (nt))
8457                 error ("`%T' uses anonymous type", t);
8458               else
8459                 error ("`%T' uses local type `%T'", t, nt);
8460               result = true;
8461             }
8462           /* In order to avoid all sorts of complications, we do not
8463              allow variably-modified types as template arguments.  */
8464           else if (variably_modified_type_p (t))
8465             {
8466               if (complain & tf_error)
8467                 error ("`%T' is a variably modified type", t);
8468               result = true;
8469             }
8470         }
8471       /* A non-type argument of integral or enumerated type must be a
8472          constant.  */
8473       else if (TREE_TYPE (t)
8474                && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
8475                && !TREE_CONSTANT (t))
8476         {
8477           if (complain & tf_error)
8478             error ("integral expression `%E' is not constant", t);
8479           result = true;
8480         }
8481     }
8482   if (result && complain & tf_error)
8483     error ("  trying to instantiate `%D'", tmpl);
8484   return result;
8485 }
8486
8487 /* Instantiate the indicated variable or function template TMPL with
8488    the template arguments in TARG_PTR.  */
8489
8490 tree
8491 instantiate_template (tmpl, targ_ptr, complain)
8492      tree tmpl, targ_ptr;
8493      tsubst_flags_t complain;
8494 {
8495   tree fndecl;
8496   tree gen_tmpl;
8497   tree spec;
8498
8499   if (tmpl == error_mark_node)
8500     return error_mark_node;
8501
8502   my_friendly_assert (TREE_CODE (tmpl) == TEMPLATE_DECL, 283);
8503
8504   /* If this function is a clone, handle it specially.  */
8505   if (DECL_CLONED_FUNCTION_P (tmpl))
8506     {
8507       tree spec = instantiate_template (DECL_CLONED_FUNCTION (tmpl), targ_ptr,
8508                                         complain);
8509       tree clone;
8510       
8511       /* Look for the clone.  */
8512       for (clone = TREE_CHAIN (spec);
8513            clone && DECL_CLONED_FUNCTION_P (clone);
8514            clone = TREE_CHAIN (clone))
8515         if (DECL_NAME (clone) == DECL_NAME (tmpl))
8516           return clone;
8517       /* We should always have found the clone by now.  */
8518       abort ();
8519       return NULL_TREE;
8520     }
8521   
8522   /* Check to see if we already have this specialization.  */
8523   spec = retrieve_specialization (tmpl, targ_ptr);
8524   if (spec != NULL_TREE)
8525     return spec;
8526
8527   gen_tmpl = most_general_template (tmpl);
8528   if (tmpl != gen_tmpl)
8529     {
8530       /* The TMPL is a partial instantiation.  To get a full set of
8531          arguments we must add the arguments used to perform the
8532          partial instantiation.  */
8533       targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
8534                                               targ_ptr);
8535
8536       /* Check to see if we already have this specialization.  */
8537       spec = retrieve_specialization (gen_tmpl, targ_ptr);
8538       if (spec != NULL_TREE)
8539         return spec;
8540     }
8541
8542   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
8543                                complain))
8544     return error_mark_node;
8545   
8546   /* Make sure that we can see identifiers, and compute access
8547      correctly.  The desired FUNCTION_DECL for FNDECL may or may not be
8548      created earlier.  Let push_access_scope_real figure that out.  */
8549   push_access_scope_real
8550     (gen_tmpl, targ_ptr, tsubst (DECL_CONTEXT (gen_tmpl), targ_ptr, 
8551                                  complain, gen_tmpl));
8552
8553   /* substitute template parameters */
8554   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
8555                    targ_ptr, complain, gen_tmpl);
8556
8557   pop_access_scope (gen_tmpl);
8558
8559   /* The DECL_TI_TEMPLATE should always be the immediate parent
8560      template, not the most general template.  */
8561   DECL_TI_TEMPLATE (fndecl) = tmpl;
8562
8563   if (flag_external_templates)
8564     add_pending_template (fndecl);
8565
8566   /* If we've just instantiated the main entry point for a function,
8567      instantiate all the alternate entry points as well.  We do this
8568      by cloning the instantiation of the main entry point, not by
8569      instantiating the template clones.  */
8570   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
8571     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
8572
8573   return fndecl;
8574 }
8575
8576 /* The FN is a TEMPLATE_DECL for a function.  The ARGS are the
8577    arguments that are being used when calling it.  TARGS is a vector
8578    into which the deduced template arguments are placed.  
8579
8580    Return zero for success, 2 for an incomplete match that doesn't resolve
8581    all the types, and 1 for complete failure.  An error message will be
8582    printed only for an incomplete match.
8583
8584    If FN is a conversion operator, or we are trying to produce a specific
8585    specialization, RETURN_TYPE is the return type desired.
8586
8587    The EXPLICIT_TARGS are explicit template arguments provided via a
8588    template-id.
8589
8590    The parameter STRICT is one of:
8591
8592    DEDUCE_CALL: 
8593      We are deducing arguments for a function call, as in
8594      [temp.deduct.call].
8595
8596    DEDUCE_CONV:
8597      We are deducing arguments for a conversion function, as in 
8598      [temp.deduct.conv].
8599
8600    DEDUCE_EXACT:
8601      We are deducing arguments when doing an explicit instantiation
8602      as in [temp.explicit], when determining an explicit specialization
8603      as in [temp.expl.spec], or when taking the address of a function
8604      template, as in [temp.deduct.funcaddr]. 
8605
8606    DEDUCE_ORDER:
8607      We are deducing arguments when calculating the partial
8608      ordering between specializations of function or class
8609      templates, as in [temp.func.order] and [temp.class.order].
8610
8611    LEN is the number of parms to consider before returning success, or -1
8612    for all.  This is used in partial ordering to avoid comparing parms for
8613    which no actual argument was passed, since they are not considered in
8614    overload resolution (and are explicitly excluded from consideration in
8615    partial ordering in [temp.func.order]/6).  */
8616
8617 int
8618 fn_type_unification (fn, explicit_targs, targs, args, return_type,
8619                      strict, len)
8620      tree fn, explicit_targs, targs, args, return_type;
8621      unification_kind_t strict;
8622      int len;
8623 {
8624   tree parms;
8625   tree fntype;
8626   int result;
8627
8628   my_friendly_assert (TREE_CODE (fn) == TEMPLATE_DECL, 0);
8629
8630   fntype = TREE_TYPE (fn);
8631   if (explicit_targs)
8632     {
8633       /* [temp.deduct]
8634           
8635          The specified template arguments must match the template
8636          parameters in kind (i.e., type, nontype, template), and there
8637          must not be more arguments than there are parameters;
8638          otherwise type deduction fails.
8639
8640          Nontype arguments must match the types of the corresponding
8641          nontype template parameters, or must be convertible to the
8642          types of the corresponding nontype parameters as specified in
8643          _temp.arg.nontype_, otherwise type deduction fails.
8644
8645          All references in the function type of the function template
8646          to the corresponding template parameters are replaced by the
8647          specified template argument values.  If a substitution in a
8648          template parameter or in the function type of the function
8649          template results in an invalid type, type deduction fails.  */
8650       int i;
8651       tree converted_args;
8652
8653       converted_args
8654         = (coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn), 
8655                                   explicit_targs, NULL_TREE, tf_none, 
8656                                   /*require_all_arguments=*/0));
8657       if (converted_args == error_mark_node)
8658         return 1;
8659
8660       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
8661       if (fntype == error_mark_node)
8662         return 1;
8663
8664       /* Place the explicitly specified arguments in TARGS.  */
8665       for (i = 0; i < TREE_VEC_LENGTH (targs); i++)
8666         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
8667     }
8668      
8669   parms = TYPE_ARG_TYPES (fntype);
8670   /* Never do unification on the 'this' parameter.  */
8671   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
8672     parms = TREE_CHAIN (parms);
8673   
8674   if (return_type)
8675     {
8676       /* We've been given a return type to match, prepend it.  */
8677       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
8678       args = tree_cons (NULL_TREE, return_type, args);
8679       if (len >= 0)
8680         ++len;
8681     }
8682
8683   /* We allow incomplete unification without an error message here
8684      because the standard doesn't seem to explicitly prohibit it.  Our
8685      callers must be ready to deal with unification failures in any
8686      event.  */
8687   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn), 
8688                                   targs, parms, args, /*subr=*/0,
8689                                   strict, /*allow_incomplete*/1, len);
8690
8691   if (result == 0) 
8692     /* All is well so far.  Now, check:
8693        
8694        [temp.deduct] 
8695        
8696        When all template arguments have been deduced, all uses of
8697        template parameters in nondeduced contexts are replaced with
8698        the corresponding deduced argument values.  If the
8699        substitution results in an invalid type, as described above,
8700        type deduction fails.  */
8701     if (tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE)
8702         == error_mark_node)
8703       return 1;
8704
8705   return result;
8706 }
8707
8708 /* Adjust types before performing type deduction, as described in
8709    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
8710    sections are symmetric.  PARM is the type of a function parameter
8711    or the return type of the conversion function.  ARG is the type of
8712    the argument passed to the call, or the type of the value
8713    initialized with the result of the conversion function.  */
8714
8715 static int
8716 maybe_adjust_types_for_deduction (strict, parm, arg)
8717      unification_kind_t strict;
8718      tree* parm;
8719      tree* arg;
8720 {
8721   int result = 0;
8722   
8723   switch (strict)
8724     {
8725     case DEDUCE_CALL:
8726       break;
8727
8728     case DEDUCE_CONV:
8729       {
8730         /* Swap PARM and ARG throughout the remainder of this
8731            function; the handling is precisely symmetric since PARM
8732            will initialize ARG rather than vice versa.  */
8733         tree* temp = parm;
8734         parm = arg;
8735         arg = temp;
8736         break;
8737       }
8738
8739     case DEDUCE_EXACT:
8740       /* There is nothing to do in this case.  */
8741       return 0;
8742
8743     case DEDUCE_ORDER:
8744       /* DR 214. [temp.func.order] is underspecified, and leads to no
8745          ordering between things like `T *' and `T const &' for `U *'.
8746          The former has T=U and the latter T=U*. The former looks more
8747          specialized and John Spicer considers it well-formed (the EDG
8748          compiler accepts it).
8749
8750          John also confirms that deduction should proceed as in a function
8751          call. Which implies the usual ARG and PARM conversions as DEDUCE_CALL.
8752          However, in ordering, ARG can have REFERENCE_TYPE, but no argument
8753          to an actual call can have such a type.
8754          
8755          If both ARG and PARM are REFERENCE_TYPE, we change neither.
8756          If only ARG is a REFERENCE_TYPE, we look through that and then
8757          proceed as with DEDUCE_CALL (which could further convert it).  */
8758       if (TREE_CODE (*arg) == REFERENCE_TYPE)
8759         {
8760           if (TREE_CODE (*parm) == REFERENCE_TYPE)
8761             return 0;
8762           *arg = TREE_TYPE (*arg);
8763         }
8764       break;
8765     default:
8766       abort ();
8767     }
8768
8769   if (TREE_CODE (*parm) != REFERENCE_TYPE)
8770     {
8771       /* [temp.deduct.call]
8772          
8773          If P is not a reference type:
8774          
8775          --If A is an array type, the pointer type produced by the
8776          array-to-pointer standard conversion (_conv.array_) is
8777          used in place of A for type deduction; otherwise,
8778          
8779          --If A is a function type, the pointer type produced by
8780          the function-to-pointer standard conversion
8781          (_conv.func_) is used in place of A for type deduction;
8782          otherwise,
8783          
8784          --If A is a cv-qualified type, the top level
8785          cv-qualifiers of A's type are ignored for type
8786          deduction.  */
8787       if (TREE_CODE (*arg) == ARRAY_TYPE)
8788         *arg = build_pointer_type (TREE_TYPE (*arg));
8789       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
8790         *arg = build_pointer_type (*arg);
8791       else
8792         *arg = TYPE_MAIN_VARIANT (*arg);
8793     }
8794   
8795   /* [temp.deduct.call]
8796      
8797      If P is a cv-qualified type, the top level cv-qualifiers
8798      of P's type are ignored for type deduction.  If P is a
8799      reference type, the type referred to by P is used for
8800      type deduction.  */
8801   *parm = TYPE_MAIN_VARIANT (*parm);
8802   if (TREE_CODE (*parm) == REFERENCE_TYPE)
8803     {
8804       *parm = TREE_TYPE (*parm);
8805       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
8806     }
8807
8808   /* DR 322. For conversion deduction, remove a reference type on parm
8809      too (which has been swapped into ARG).  */
8810   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
8811     *arg = TREE_TYPE (*arg);
8812   
8813   return result;
8814 }
8815
8816 /* Most parms like fn_type_unification.
8817
8818    If SUBR is 1, we're being called recursively (to unify the
8819    arguments of a function or method parameter of a function
8820    template).  */
8821
8822 static int
8823 type_unification_real (tparms, targs, xparms, xargs, subr,
8824                        strict, allow_incomplete, xlen)
8825      tree tparms, targs, xparms, xargs;
8826      int subr;
8827      unification_kind_t strict;
8828      int allow_incomplete, xlen;
8829 {
8830   tree parm, arg;
8831   int i;
8832   int ntparms = TREE_VEC_LENGTH (tparms);
8833   int sub_strict;
8834   int saw_undeduced = 0;
8835   tree parms, args;
8836   int len;
8837
8838   my_friendly_assert (TREE_CODE (tparms) == TREE_VEC, 289);
8839   my_friendly_assert (xparms == NULL_TREE 
8840                       || TREE_CODE (xparms) == TREE_LIST, 290);
8841   /* ARGS could be NULL.  */
8842   if (xargs)
8843     my_friendly_assert (TREE_CODE (xargs) == TREE_LIST, 291);
8844   my_friendly_assert (ntparms > 0, 292);
8845
8846   switch (strict)
8847     {
8848     case DEDUCE_CALL:
8849       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
8850                     | UNIFY_ALLOW_DERIVED);
8851       break;
8852       
8853     case DEDUCE_CONV:
8854       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
8855       break;
8856
8857     case DEDUCE_EXACT:
8858       sub_strict = UNIFY_ALLOW_NONE;
8859       break;
8860     
8861     case DEDUCE_ORDER:
8862       sub_strict = UNIFY_ALLOW_NONE;
8863       break;
8864       
8865     default:
8866       abort ();
8867     }
8868
8869   if (xlen == 0)
8870     return 0;
8871
8872  again:
8873   parms = xparms;
8874   args = xargs;
8875   len = xlen;
8876
8877   while (parms
8878          && parms != void_list_node
8879          && args
8880          && args != void_list_node)
8881     {
8882       parm = TREE_VALUE (parms);
8883       parms = TREE_CHAIN (parms);
8884       arg = TREE_VALUE (args);
8885       args = TREE_CHAIN (args);
8886
8887       if (arg == error_mark_node)
8888         return 1;
8889       if (arg == unknown_type_node)
8890         /* We can't deduce anything from this, but we might get all the
8891            template args from other function args.  */
8892         continue;
8893
8894       /* Conversions will be performed on a function argument that
8895          corresponds with a function parameter that contains only
8896          non-deducible template parameters and explicitly specified
8897          template parameters.  */
8898       if (! uses_template_parms (parm))
8899         {
8900           tree type;
8901
8902           if (!TYPE_P (arg))
8903             type = TREE_TYPE (arg);
8904           else
8905             {
8906               type = arg;
8907               arg = NULL_TREE;
8908             }
8909
8910           if (strict == DEDUCE_EXACT || strict == DEDUCE_ORDER)
8911             {
8912               if (same_type_p (parm, type))
8913                 continue;
8914             }
8915           else
8916             /* It might work; we shouldn't check now, because we might
8917                get into infinite recursion.  Overload resolution will
8918                handle it.  */
8919             continue;
8920
8921           return 1;
8922         }
8923         
8924       if (!TYPE_P (arg))
8925         {
8926           my_friendly_assert (TREE_TYPE (arg) != NULL_TREE, 293);
8927           if (type_unknown_p (arg))
8928             {
8929               /* [temp.deduct.type] A template-argument can be deduced from
8930                  a pointer to function or pointer to member function
8931                  argument if the set of overloaded functions does not
8932                  contain function templates and at most one of a set of
8933                  overloaded functions provides a unique match.  */
8934
8935               if (resolve_overloaded_unification
8936                   (tparms, targs, parm, arg, strict, sub_strict)
8937                   != 0)
8938                 return 1;
8939               continue;
8940             }
8941           arg = TREE_TYPE (arg);
8942         }
8943       
8944       {
8945         int arg_strict = sub_strict;
8946         
8947         if (!subr)
8948           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg);
8949
8950         if (unify (tparms, targs, parm, arg, arg_strict))
8951           return 1;
8952       }
8953
8954       /* Are we done with the interesting parms?  */
8955       if (--len == 0)
8956         goto done;
8957     }
8958   /* Fail if we've reached the end of the parm list, and more args
8959      are present, and the parm list isn't variadic.  */
8960   if (args && args != void_list_node && parms == void_list_node)
8961     return 1;
8962   /* Fail if parms are left and they don't have default values.  */
8963   if (parms
8964       && parms != void_list_node
8965       && TREE_PURPOSE (parms) == NULL_TREE)
8966     return 1;
8967
8968  done:
8969   if (!subr)
8970     for (i = 0; i < ntparms; i++)
8971       if (TREE_VEC_ELT (targs, i) == NULL_TREE)
8972         {
8973           tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
8974
8975           /* If this is an undeduced nontype parameter that depends on
8976              a type parameter, try another pass; its type may have been
8977              deduced from a later argument than the one from which
8978              this parameter can be deduced.  */
8979           if (TREE_CODE (tparm) == PARM_DECL
8980               && uses_template_parms (TREE_TYPE (tparm))
8981               && !saw_undeduced++)
8982             goto again;
8983
8984           if (!allow_incomplete)
8985             error ("incomplete type unification");
8986           return 2;
8987         }
8988   return 0;
8989 }
8990
8991 /* Subroutine of type_unification_real.  Args are like the variables at the
8992    call site.  ARG is an overloaded function (or template-id); we try
8993    deducing template args from each of the overloads, and if only one
8994    succeeds, we go with that.  Modifies TARGS and returns 0 on success.  */
8995
8996 static int
8997 resolve_overloaded_unification (tparms, targs, parm, arg, strict,
8998                                 sub_strict)
8999      tree tparms, targs, parm, arg;
9000      unification_kind_t strict;
9001      int sub_strict;
9002 {
9003   tree tempargs = copy_node (targs);
9004   int good = 0;
9005
9006   if (TREE_CODE (arg) == ADDR_EXPR)
9007     arg = TREE_OPERAND (arg, 0);
9008
9009   if (TREE_CODE (arg) == COMPONENT_REF)
9010     /* Handle `&x' where `x' is some static or non-static member
9011        function name.  */
9012     arg = TREE_OPERAND (arg, 1);
9013
9014   if (TREE_CODE (arg) == OFFSET_REF)
9015     arg = TREE_OPERAND (arg, 1);
9016
9017   /* Strip baselink information.  */
9018   if (BASELINK_P (arg))
9019     arg = BASELINK_FUNCTIONS (arg);
9020
9021   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
9022     {
9023       /* If we got some explicit template args, we need to plug them into
9024          the affected templates before we try to unify, in case the
9025          explicit args will completely resolve the templates in question.  */
9026
9027       tree expl_subargs = TREE_OPERAND (arg, 1);
9028       arg = TREE_OPERAND (arg, 0);
9029
9030       for (; arg; arg = OVL_NEXT (arg))
9031         {
9032           tree fn = OVL_CURRENT (arg);
9033           tree subargs, elem;
9034
9035           if (TREE_CODE (fn) != TEMPLATE_DECL)
9036             continue;
9037
9038           subargs = get_bindings_overload (fn, DECL_TEMPLATE_RESULT (fn),
9039                                            expl_subargs);
9040           if (subargs)
9041             {
9042               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
9043               if (TREE_CODE (elem) == METHOD_TYPE)
9044                 elem = build_ptrmemfunc_type (build_pointer_type (elem));
9045               good += try_one_overload (tparms, targs, tempargs, parm, elem,
9046                                         strict, sub_strict);
9047             }
9048         }
9049     }
9050   else if (TREE_CODE (arg) == OVERLOAD
9051            || TREE_CODE (arg) == FUNCTION_DECL)
9052     {
9053       for (; arg; arg = OVL_NEXT (arg))
9054         {
9055           tree type = TREE_TYPE (OVL_CURRENT (arg));
9056           if (TREE_CODE (type) == METHOD_TYPE)
9057             type = build_ptrmemfunc_type (build_pointer_type (type));
9058           good += try_one_overload (tparms, targs, tempargs, parm,
9059                                     type,
9060                                     strict, sub_strict);
9061         }
9062     }
9063   else
9064     abort ();
9065
9066   /* [temp.deduct.type] A template-argument can be deduced from a pointer
9067      to function or pointer to member function argument if the set of
9068      overloaded functions does not contain function templates and at most
9069      one of a set of overloaded functions provides a unique match.
9070
9071      So if we found multiple possibilities, we return success but don't
9072      deduce anything.  */
9073
9074   if (good == 1)
9075     {
9076       int i = TREE_VEC_LENGTH (targs);
9077       for (; i--; )
9078         if (TREE_VEC_ELT (tempargs, i))
9079           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
9080     }
9081   if (good)
9082     return 0;
9083
9084   return 1;
9085 }
9086
9087 /* Subroutine of resolve_overloaded_unification; does deduction for a single
9088    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
9089    different overloads deduce different arguments for a given parm.
9090    Returns 1 on success.  */
9091
9092 static int
9093 try_one_overload (tparms, orig_targs, targs, parm, arg, strict,
9094                   sub_strict)
9095      tree tparms, orig_targs, targs, parm, arg;
9096      unification_kind_t strict;
9097      int sub_strict;
9098 {
9099   int nargs;
9100   tree tempargs;
9101   int i;
9102
9103   /* [temp.deduct.type] A template-argument can be deduced from a pointer
9104      to function or pointer to member function argument if the set of
9105      overloaded functions does not contain function templates and at most
9106      one of a set of overloaded functions provides a unique match.
9107
9108      So if this is a template, just return success.  */
9109
9110   if (uses_template_parms (arg))
9111     return 1;
9112
9113   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg);
9114
9115   /* We don't copy orig_targs for this because if we have already deduced
9116      some template args from previous args, unify would complain when we
9117      try to deduce a template parameter for the same argument, even though
9118      there isn't really a conflict.  */
9119   nargs = TREE_VEC_LENGTH (targs);
9120   tempargs = make_tree_vec (nargs);
9121
9122   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
9123     return 0;
9124
9125   /* First make sure we didn't deduce anything that conflicts with
9126      explicitly specified args.  */
9127   for (i = nargs; i--; )
9128     {
9129       tree elt = TREE_VEC_ELT (tempargs, i);
9130       tree oldelt = TREE_VEC_ELT (orig_targs, i);
9131
9132       if (elt == NULL_TREE)
9133         continue;
9134       else if (uses_template_parms (elt))
9135         {
9136           /* Since we're unifying against ourselves, we will fill in template
9137              args used in the function parm list with our own template parms.
9138              Discard them.  */
9139           TREE_VEC_ELT (tempargs, i) = NULL_TREE;
9140           continue;
9141         }
9142       else if (oldelt && ! template_args_equal (oldelt, elt))
9143         return 0;
9144     }
9145
9146   for (i = nargs; i--; )
9147     {
9148       tree elt = TREE_VEC_ELT (tempargs, i);
9149
9150       if (elt)
9151         TREE_VEC_ELT (targs, i) = elt;
9152     }
9153
9154   return 1;
9155 }
9156
9157 /* Verify that nondeduce template argument agrees with the type
9158    obtained from argument deduction.  Return nonzero if the
9159    verification fails.
9160
9161    For example:
9162
9163      struct A { typedef int X; };
9164      template <class T, class U> struct C {};
9165      template <class T> struct C<T, typename T::X> {};
9166
9167    Then with the instantiation `C<A, int>', we can deduce that
9168    `T' is `A' but unify () does not check whether `typename T::X'
9169    is `int'.  This function ensure that they agree.
9170
9171    TARGS, PARMS are the same as the arguments of unify.
9172    ARGS contains template arguments from all levels.  */
9173
9174 static int
9175 verify_class_unification (targs, parms, args)
9176      tree targs, parms, args;
9177 {
9178   parms = tsubst (parms, add_outermost_template_args (args, targs),
9179                   tf_none, NULL_TREE);
9180   if (parms == error_mark_node)
9181     return 1;
9182
9183   return !comp_template_args (parms, INNERMOST_TEMPLATE_ARGS (args));
9184 }
9185
9186 /* PARM is a template class (perhaps with unbound template
9187    parameters).  ARG is a fully instantiated type.  If ARG can be
9188    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
9189    TARGS are as for unify.  */
9190
9191 static tree
9192 try_class_unification (tparms, targs, parm, arg)
9193      tree tparms;
9194      tree targs;
9195      tree parm;
9196      tree arg;
9197 {
9198   tree copy_of_targs;
9199
9200   if (!CLASSTYPE_TEMPLATE_INFO (arg)
9201       || CLASSTYPE_TI_TEMPLATE (arg) != CLASSTYPE_TI_TEMPLATE (parm))
9202     return NULL_TREE;
9203
9204   /* We need to make a new template argument vector for the call to
9205      unify.  If we used TARGS, we'd clutter it up with the result of
9206      the attempted unification, even if this class didn't work out.
9207      We also don't want to commit ourselves to all the unifications
9208      we've already done, since unification is supposed to be done on
9209      an argument-by-argument basis.  In other words, consider the
9210      following pathological case:
9211
9212        template <int I, int J, int K>
9213        struct S {};
9214        
9215        template <int I, int J>
9216        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
9217        
9218        template <int I, int J, int K>
9219        void f(S<I, J, K>, S<I, I, I>);
9220        
9221        void g() {
9222          S<0, 0, 0> s0;
9223          S<0, 1, 2> s2;
9224        
9225          f(s0, s2);
9226        }
9227
9228      Now, by the time we consider the unification involving `s2', we
9229      already know that we must have `f<0, 0, 0>'.  But, even though
9230      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
9231      because there are two ways to unify base classes of S<0, 1, 2>
9232      with S<I, I, I>.  If we kept the already deduced knowledge, we
9233      would reject the possibility I=1.  */
9234   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
9235   
9236   /* If unification failed, we're done.  */
9237   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
9238              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
9239     return NULL_TREE;
9240
9241   return arg;
9242 }
9243
9244 /* Subroutine of get_template_base.  RVAL, if non-NULL, is a base we
9245    have already discovered to be satisfactory.  ARG_BINFO is the binfo
9246    for the base class of ARG that we are currently examining.  */
9247
9248 static tree
9249 get_template_base_recursive (tparms, targs, parm,
9250                              arg_binfo, rval, flags)
9251      tree tparms;
9252      tree targs;
9253      tree arg_binfo;
9254      tree rval;
9255      tree parm;
9256      int flags;
9257 {
9258   tree binfos;
9259   int i, n_baselinks;
9260   tree arg = BINFO_TYPE (arg_binfo);
9261
9262   if (!(flags & GTB_IGNORE_TYPE))
9263     {
9264       tree r = try_class_unification (tparms, targs,
9265                                       parm, arg);
9266
9267       /* If there is more than one satisfactory baseclass, then:
9268
9269            [temp.deduct.call]
9270
9271            If they yield more than one possible deduced A, the type
9272            deduction fails.
9273
9274            applies.  */
9275       if (r && rval && !same_type_p (r, rval))
9276         return error_mark_node;
9277       else if (r)
9278         rval = r;
9279     }
9280
9281   binfos = BINFO_BASETYPES (arg_binfo);
9282   n_baselinks = binfos ? TREE_VEC_LENGTH (binfos) : 0;
9283
9284   /* Process base types.  */
9285   for (i = 0; i < n_baselinks; i++)
9286     {
9287       tree base_binfo = TREE_VEC_ELT (binfos, i);
9288       int this_virtual;
9289
9290       /* Skip this base, if we've already seen it.  */
9291       if (BINFO_MARKED (base_binfo))
9292         continue;
9293
9294       this_virtual = 
9295         (flags & GTB_VIA_VIRTUAL) || TREE_VIA_VIRTUAL (base_binfo);
9296       
9297       /* When searching for a non-virtual, we cannot mark virtually
9298          found binfos.  */
9299       if (! this_virtual)
9300         BINFO_MARKED (base_binfo) = 1;
9301       
9302       rval = get_template_base_recursive (tparms, targs,
9303                                           parm,
9304                                           base_binfo, 
9305                                           rval,
9306                                           GTB_VIA_VIRTUAL * this_virtual);
9307       
9308       /* If we discovered more than one matching base class, we can
9309          stop now.  */
9310       if (rval == error_mark_node)
9311         return error_mark_node;
9312     }
9313
9314   return rval;
9315 }
9316
9317 /* Given a template type PARM and a class type ARG, find the unique
9318    base type in ARG that is an instance of PARM.  We do not examine
9319    ARG itself; only its base-classes.  If there is no appropriate base
9320    class, return NULL_TREE.  If there is more than one, return
9321    error_mark_node.  PARM may be the type of a partial specialization,
9322    as well as a plain template type.  Used by unify.  */
9323
9324 static tree
9325 get_template_base (tparms, targs, parm, arg)
9326      tree tparms;
9327      tree targs;
9328      tree parm;
9329      tree arg;
9330 {
9331   tree rval;
9332   tree arg_binfo;
9333
9334   my_friendly_assert (IS_AGGR_TYPE_CODE (TREE_CODE (arg)), 92);
9335   
9336   arg_binfo = TYPE_BINFO (complete_type (arg));
9337   rval = get_template_base_recursive (tparms, targs,
9338                                       parm, arg_binfo, 
9339                                       NULL_TREE,
9340                                       GTB_IGNORE_TYPE);
9341
9342   /* Since get_template_base_recursive marks the bases classes, we
9343      must unmark them here.  */
9344   dfs_walk (arg_binfo, dfs_unmark, markedp, 0);
9345
9346   return rval;
9347 }
9348
9349 /* Returns the level of DECL, which declares a template parameter.  */
9350
9351 static int
9352 template_decl_level (decl)
9353      tree decl;
9354 {
9355   switch (TREE_CODE (decl))
9356     {
9357     case TYPE_DECL:
9358     case TEMPLATE_DECL:
9359       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
9360
9361     case PARM_DECL:
9362       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
9363
9364     default:
9365       abort ();
9366       return 0;
9367     }
9368 }
9369
9370 /* Decide whether ARG can be unified with PARM, considering only the
9371    cv-qualifiers of each type, given STRICT as documented for unify.
9372    Returns nonzero iff the unification is OK on that basis.*/
9373
9374 static int
9375 check_cv_quals_for_unify (strict, arg, parm)
9376      int strict;
9377      tree arg;
9378      tree parm;
9379 {
9380   int arg_quals = cp_type_quals (arg);
9381   int parm_quals = cp_type_quals (parm);
9382
9383   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM)
9384     {
9385       /* If the cvr quals of parm will not unify with ARG, they'll be
9386          ignored in instantiation, so we have to do the same here.  */
9387       if (TREE_CODE (arg) == REFERENCE_TYPE)
9388         parm_quals &= ~(TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE);
9389       if (!POINTER_TYPE_P (arg) &&
9390           TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
9391         parm_quals &= ~TYPE_QUAL_RESTRICT;
9392     }
9393   
9394   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
9395       && (arg_quals & parm_quals) != parm_quals)
9396     return 0;
9397
9398   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
9399       && (parm_quals & arg_quals) != arg_quals)
9400     return 0;
9401
9402   return 1;
9403 }
9404
9405 /* Takes parameters as for type_unification.  Returns 0 if the
9406    type deduction succeeds, 1 otherwise.  The parameter STRICT is a
9407    bitwise or of the following flags:
9408
9409      UNIFY_ALLOW_NONE:
9410        Require an exact match between PARM and ARG.
9411      UNIFY_ALLOW_MORE_CV_QUAL:
9412        Allow the deduced ARG to be more cv-qualified (by qualification
9413        conversion) than ARG.
9414      UNIFY_ALLOW_LESS_CV_QUAL:
9415        Allow the deduced ARG to be less cv-qualified than ARG.
9416      UNIFY_ALLOW_DERIVED:
9417        Allow the deduced ARG to be a template base class of ARG,
9418        or a pointer to a template base class of the type pointed to by
9419        ARG.
9420      UNIFY_ALLOW_INTEGER:
9421        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
9422        case for more information. 
9423      UNIFY_ALLOW_OUTER_LEVEL:
9424        This is the outermost level of a deduction. Used to determine validity
9425        of qualification conversions. A valid qualification conversion must
9426        have const qualified pointers leading up to the inner type which
9427        requires additional CV quals, except at the outer level, where const
9428        is not required [conv.qual]. It would be normal to set this flag in
9429        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
9430      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
9431        This is the outermost level of a deduction, and PARM can be more CV
9432        qualified at this point.
9433      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
9434        This is the outermost level of a deduction, and PARM can be less CV
9435        qualified at this point.
9436      UNIFY_ALLOW_MAX_CORRECTION:
9437        This is an INTEGER_TYPE's maximum value.  Used if the range may
9438        have been derived from a size specification, such as an array size.
9439        If the size was given by a nontype template parameter N, the maximum
9440        value will have the form N-1.  The flag says that we can (and indeed
9441        must) unify N with (ARG + 1), an exception to the normal rules on
9442        folding PARM.  */
9443
9444 static int
9445 unify (tparms, targs, parm, arg, strict)
9446      tree tparms, targs, parm, arg;
9447      int strict;
9448 {
9449   int idx;
9450   tree targ;
9451   tree tparm;
9452   int strict_in = strict;
9453
9454   /* I don't think this will do the right thing with respect to types.
9455      But the only case I've seen it in so far has been array bounds, where
9456      signedness is the only information lost, and I think that will be
9457      okay.  */
9458   while (TREE_CODE (parm) == NOP_EXPR)
9459     parm = TREE_OPERAND (parm, 0);
9460
9461   if (arg == error_mark_node)
9462     return 1;
9463   if (arg == unknown_type_node)
9464     /* We can't deduce anything from this, but we might get all the
9465        template args from other function args.  */
9466     return 0;
9467
9468   /* If PARM uses template parameters, then we can't bail out here,
9469      even if ARG == PARM, since we won't record unifications for the
9470      template parameters.  We might need them if we're trying to
9471      figure out which of two things is more specialized.  */
9472   if (arg == parm && !uses_template_parms (parm))
9473     return 0;
9474
9475   /* Immediately reject some pairs that won't unify because of
9476      cv-qualification mismatches.  */
9477   if (TREE_CODE (arg) == TREE_CODE (parm)
9478       && TYPE_P (arg)
9479       /* It is the elements of the array which hold the cv quals of an array
9480          type, and the elements might be template type parms. We'll check
9481          when we recurse.  */
9482       && TREE_CODE (arg) != ARRAY_TYPE
9483       /* We check the cv-qualifiers when unifying with template type
9484          parameters below.  We want to allow ARG `const T' to unify with
9485          PARM `T' for example, when computing which of two templates
9486          is more specialized, for example.  */
9487       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
9488       && !check_cv_quals_for_unify (strict_in, arg, parm))
9489     return 1;
9490
9491   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
9492       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
9493     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
9494   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
9495   strict &= ~UNIFY_ALLOW_DERIVED;
9496   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
9497   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
9498   strict &= ~UNIFY_ALLOW_MAX_CORRECTION;
9499   
9500   switch (TREE_CODE (parm))
9501     {
9502     case TYPENAME_TYPE:
9503     case SCOPE_REF:
9504     case UNBOUND_CLASS_TEMPLATE:
9505       /* In a type which contains a nested-name-specifier, template
9506          argument values cannot be deduced for template parameters used
9507          within the nested-name-specifier.  */
9508       return 0;
9509
9510     case TEMPLATE_TYPE_PARM:
9511     case TEMPLATE_TEMPLATE_PARM:
9512     case BOUND_TEMPLATE_TEMPLATE_PARM:
9513       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
9514
9515       if (TEMPLATE_TYPE_LEVEL (parm)
9516           != template_decl_level (tparm))
9517         /* The PARM is not one we're trying to unify.  Just check
9518            to see if it matches ARG.  */
9519         return (TREE_CODE (arg) == TREE_CODE (parm)
9520                 && same_type_p (parm, arg)) ? 0 : 1;
9521       idx = TEMPLATE_TYPE_IDX (parm);
9522       targ = TREE_VEC_ELT (targs, idx);
9523       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
9524
9525       /* Check for mixed types and values.  */
9526       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
9527            && TREE_CODE (tparm) != TYPE_DECL)
9528           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM 
9529               && TREE_CODE (tparm) != TEMPLATE_DECL))
9530         return 1;
9531
9532       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
9533         {
9534           /* ARG must be constructed from a template class or a template
9535              template parameter.  */
9536           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
9537               && (TREE_CODE (arg) != RECORD_TYPE || !CLASSTYPE_TEMPLATE_INFO (arg)))
9538             return 1;
9539
9540           {
9541             tree parmtmpl = TYPE_TI_TEMPLATE (parm);
9542             tree parmvec = TYPE_TI_ARGS (parm);
9543             tree argvec = TYPE_TI_ARGS (arg);
9544             tree argtmplvec
9545               = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_TI_TEMPLATE (arg));
9546             int i;
9547
9548             /* The parameter and argument roles have to be switched here 
9549                in order to handle default arguments properly.  For example, 
9550                template<template <class> class TT> void f(TT<int>) 
9551                should be able to accept vector<int> which comes from 
9552                template <class T, class Allocator = allocator> 
9553                class vector.  */
9554
9555             if (coerce_template_parms (argtmplvec, parmvec, parmtmpl, 0, 1)
9556                 == error_mark_node)
9557               return 1;
9558           
9559             /* Deduce arguments T, i from TT<T> or TT<i>.  
9560                We check each element of PARMVEC and ARGVEC individually
9561                rather than the whole TREE_VEC since they can have
9562                different number of elements.  */
9563
9564             for (i = 0; i < TREE_VEC_LENGTH (parmvec); ++i)
9565               {
9566                 tree t = TREE_VEC_ELT (parmvec, i);
9567
9568                 if (unify (tparms, targs, t, 
9569                            TREE_VEC_ELT (argvec, i), 
9570                            UNIFY_ALLOW_NONE))
9571                   return 1;
9572               }
9573           }
9574           arg = TYPE_TI_TEMPLATE (arg);
9575
9576           /* Fall through to deduce template name.  */
9577         }
9578
9579       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
9580           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
9581         {
9582           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
9583
9584           /* Simple cases: Value already set, does match or doesn't.  */
9585           if (targ != NULL_TREE && template_args_equal (targ, arg))
9586             return 0;
9587           else if (targ)
9588             return 1;
9589         }
9590       else
9591         {
9592           /* If ARG is an offset type, we're trying to unify '*T' with
9593              'U C::*', which is ill-formed. See the comment in the
9594              POINTER_TYPE case about this ugliness. */
9595           if (TREE_CODE (arg) == OFFSET_TYPE)
9596             return 1;
9597           
9598           /* If PARM is `const T' and ARG is only `int', we don't have
9599              a match unless we are allowing additional qualification.
9600              If ARG is `const int' and PARM is just `T' that's OK;
9601              that binds `const int' to `T'.  */
9602           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL, 
9603                                          arg, parm))
9604             return 1;
9605
9606           /* Consider the case where ARG is `const volatile int' and
9607              PARM is `const T'.  Then, T should be `volatile int'.  */
9608           arg = cp_build_qualified_type_real
9609             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
9610           if (arg == error_mark_node)
9611             return 1;
9612
9613           /* Simple cases: Value already set, does match or doesn't.  */
9614           if (targ != NULL_TREE && same_type_p (targ, arg))
9615             return 0;
9616           else if (targ)
9617             return 1;
9618
9619           /* Make sure that ARG is not a variable-sized array.  (Note
9620              that were talking about variable-sized arrays (like
9621              `int[n]'), rather than arrays of unknown size (like
9622              `int[]').)  We'll get very confused by such a type since
9623              the bound of the array will not be computable in an
9624              instantiation.  Besides, such types are not allowed in
9625              ISO C++, so we can do as we please here.  */
9626           if (variably_modified_type_p (arg))
9627             return 1;
9628         }
9629
9630       TREE_VEC_ELT (targs, idx) = arg;
9631       return 0;
9632
9633     case TEMPLATE_PARM_INDEX:
9634       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
9635
9636       if (TEMPLATE_PARM_LEVEL (parm) 
9637           != template_decl_level (tparm))
9638         /* The PARM is not one we're trying to unify.  Just check
9639            to see if it matches ARG.  */
9640         return (TREE_CODE (arg) == TREE_CODE (parm)
9641                 && cp_tree_equal (parm, arg) > 0) ? 0 : 1;
9642
9643       idx = TEMPLATE_PARM_IDX (parm);
9644       targ = TREE_VEC_ELT (targs, idx);
9645
9646       if (targ)
9647         {
9648           int i = (cp_tree_equal (targ, arg) > 0);
9649           if (i == 1)
9650             return 0;
9651           else if (i == 0)
9652             return 1;
9653           else
9654             abort ();
9655         }
9656
9657       /* [temp.deduct.type] If, in the declaration of a function template
9658          with a non-type template-parameter, the non-type
9659          template-parameter is used in an expression in the function
9660          parameter-list and, if the corresponding template-argument is
9661          deduced, the template-argument type shall match the type of the
9662          template-parameter exactly, except that a template-argument
9663          deduced from an array bound may be of any integral type. 
9664          The non-type parameter might use already deduced type parameters.  */
9665       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
9666       if (!TREE_TYPE (arg))
9667         /* Template-parameter dependent expression.  Just accept it for now.
9668            It will later be processed in convert_template_argument.  */
9669         ;
9670       else if (same_type_p (TREE_TYPE (arg), tparm))
9671         /* OK */;
9672       else if ((strict & UNIFY_ALLOW_INTEGER)
9673                && (TREE_CODE (tparm) == INTEGER_TYPE
9674                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
9675         /* OK */;
9676       else if (uses_template_parms (tparm))
9677         /* We haven't deduced the type of this parameter yet.  Try again
9678            later.  */
9679         return 0;
9680       else
9681         return 1;
9682
9683       TREE_VEC_ELT (targs, idx) = arg;
9684       return 0;
9685
9686     case POINTER_TYPE:
9687       {
9688         if (TREE_CODE (arg) != POINTER_TYPE)
9689           return 1;
9690         
9691         /* [temp.deduct.call]
9692
9693            A can be another pointer or pointer to member type that can
9694            be converted to the deduced A via a qualification
9695            conversion (_conv.qual_).
9696
9697            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
9698            This will allow for additional cv-qualification of the
9699            pointed-to types if appropriate.  */
9700         
9701         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
9702           /* The derived-to-base conversion only persists through one
9703              level of pointers.  */
9704           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
9705
9706         if (TREE_CODE (TREE_TYPE (parm)) == OFFSET_TYPE
9707             && TREE_CODE (TREE_TYPE (arg)) == OFFSET_TYPE)
9708           {
9709             /* Avoid getting confused about cv-quals; don't recurse here.
9710                Pointers to members should really be just OFFSET_TYPE, not
9711                this two-level nonsense...  */
9712
9713             parm = TREE_TYPE (parm);
9714             arg = TREE_TYPE (arg);
9715             goto offset;
9716           }
9717
9718         return unify (tparms, targs, TREE_TYPE (parm), 
9719                       TREE_TYPE (arg), strict);
9720       }
9721
9722     case REFERENCE_TYPE:
9723       if (TREE_CODE (arg) != REFERENCE_TYPE)
9724         return 1;
9725       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
9726                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
9727
9728     case ARRAY_TYPE:
9729       if (TREE_CODE (arg) != ARRAY_TYPE)
9730         return 1;
9731       if ((TYPE_DOMAIN (parm) == NULL_TREE)
9732           != (TYPE_DOMAIN (arg) == NULL_TREE))
9733         return 1;
9734       if (TYPE_DOMAIN (parm) != NULL_TREE
9735           && unify (tparms, targs, TYPE_DOMAIN (parm),
9736                     TYPE_DOMAIN (arg), UNIFY_ALLOW_NONE) != 0)
9737         return 1;
9738       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
9739                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
9740
9741     case REAL_TYPE:
9742     case COMPLEX_TYPE:
9743     case VECTOR_TYPE:
9744     case INTEGER_TYPE:
9745     case BOOLEAN_TYPE:
9746     case VOID_TYPE:
9747       if (TREE_CODE (arg) != TREE_CODE (parm))
9748         return 1;
9749
9750       if (TREE_CODE (parm) == INTEGER_TYPE
9751           && TREE_CODE (TYPE_MAX_VALUE (parm)) != INTEGER_CST)
9752         {
9753           if (TYPE_MIN_VALUE (parm) && TYPE_MIN_VALUE (arg)
9754               && unify (tparms, targs, TYPE_MIN_VALUE (parm),
9755                         TYPE_MIN_VALUE (arg), UNIFY_ALLOW_INTEGER))
9756             return 1;
9757           if (TYPE_MAX_VALUE (parm) && TYPE_MAX_VALUE (arg)
9758               && unify (tparms, targs, TYPE_MAX_VALUE (parm),
9759                         TYPE_MAX_VALUE (arg),
9760                         UNIFY_ALLOW_INTEGER | UNIFY_ALLOW_MAX_CORRECTION))
9761             return 1;
9762         }
9763       /* We have already checked cv-qualification at the top of the
9764          function.  */
9765       else if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
9766         return 1;
9767
9768       /* As far as unification is concerned, this wins.  Later checks
9769          will invalidate it if necessary.  */
9770       return 0;
9771
9772       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
9773       /* Type INTEGER_CST can come from ordinary constant template args.  */
9774     case INTEGER_CST:
9775       while (TREE_CODE (arg) == NOP_EXPR)
9776         arg = TREE_OPERAND (arg, 0);
9777
9778       if (TREE_CODE (arg) != INTEGER_CST)
9779         return 1;
9780       return !tree_int_cst_equal (parm, arg);
9781
9782     case TREE_VEC:
9783       {
9784         int i;
9785         if (TREE_CODE (arg) != TREE_VEC)
9786           return 1;
9787         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
9788           return 1;
9789         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
9790           if (unify (tparms, targs,
9791                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
9792                      UNIFY_ALLOW_NONE))
9793             return 1;
9794         return 0;
9795       }
9796
9797     case RECORD_TYPE:
9798     case UNION_TYPE:
9799       if (TREE_CODE (arg) != TREE_CODE (parm))
9800         return 1;
9801   
9802       if (TYPE_PTRMEMFUNC_P (parm))
9803         {
9804           if (!TYPE_PTRMEMFUNC_P (arg))
9805             return 1;
9806
9807           return unify (tparms, targs, 
9808                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
9809                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
9810                         strict);
9811         }
9812
9813       if (CLASSTYPE_TEMPLATE_INFO (parm))
9814         {
9815           tree t = NULL_TREE;
9816
9817           if (strict_in & UNIFY_ALLOW_DERIVED)
9818             {
9819               /* First, we try to unify the PARM and ARG directly.  */
9820               t = try_class_unification (tparms, targs,
9821                                          parm, arg);
9822
9823               if (!t)
9824                 {
9825                   /* Fallback to the special case allowed in
9826                      [temp.deduct.call]:
9827                      
9828                        If P is a class, and P has the form
9829                        template-id, then A can be a derived class of
9830                        the deduced A.  Likewise, if P is a pointer to
9831                        a class of the form template-id, A can be a
9832                        pointer to a derived class pointed to by the
9833                        deduced A.  */
9834                   t = get_template_base (tparms, targs,
9835                                          parm, arg);
9836
9837                   if (! t || t == error_mark_node)
9838                     return 1;
9839                 }
9840             }
9841           else if (CLASSTYPE_TEMPLATE_INFO (arg) 
9842                    && (CLASSTYPE_TI_TEMPLATE (parm) 
9843                        == CLASSTYPE_TI_TEMPLATE (arg)))
9844             /* Perhaps PARM is something like S<U> and ARG is S<int>.
9845                Then, we should unify `int' and `U'.  */
9846             t = arg;
9847           else
9848             /* There's no chance of unification succeeding.  */
9849             return 1;
9850
9851           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
9852                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
9853         }
9854       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
9855         return 1;
9856       return 0;
9857
9858     case METHOD_TYPE:
9859     case FUNCTION_TYPE:
9860       if (TREE_CODE (arg) != TREE_CODE (parm))
9861         return 1;
9862
9863       if (unify (tparms, targs, TREE_TYPE (parm),
9864                  TREE_TYPE (arg), UNIFY_ALLOW_NONE))
9865         return 1;
9866       return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
9867                                     TYPE_ARG_TYPES (arg), 1, 
9868                                     DEDUCE_EXACT, 0, -1);
9869
9870     case OFFSET_TYPE:
9871     offset:
9872       if (TREE_CODE (arg) != OFFSET_TYPE)
9873         return 1;
9874       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
9875                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
9876         return 1;
9877       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
9878                     strict);
9879
9880     case CONST_DECL:
9881       if (DECL_TEMPLATE_PARM_P (parm))
9882         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
9883       if (arg != decl_constant_value (parm)) 
9884         return 1;
9885       return 0;
9886
9887     case TEMPLATE_DECL:
9888       /* Matched cases are handled by the ARG == PARM test above.  */
9889       return 1;
9890
9891     case MINUS_EXPR:
9892       if (tree_int_cst_equal (TREE_OPERAND (parm, 1), integer_one_node)
9893           && (strict_in & UNIFY_ALLOW_MAX_CORRECTION))
9894         {
9895           /* We handle this case specially, since it comes up with
9896              arrays.  In particular, something like:
9897
9898              template <int N> void f(int (&x)[N]);
9899
9900              Here, we are trying to unify the range type, which
9901              looks like [0 ... (N - 1)].  */
9902           tree t, t1, t2;
9903           t1 = TREE_OPERAND (parm, 0);
9904           t2 = TREE_OPERAND (parm, 1);
9905
9906           t = fold (build (PLUS_EXPR, integer_type_node, arg, t2));
9907
9908           return unify (tparms, targs, t1, t, strict);
9909         }
9910       /* else fall through */
9911
9912     default:
9913       if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (TREE_CODE (parm))))
9914         {
9915
9916           /* We're looking at an expression.  This can happen with
9917              something like: 
9918            
9919                template <int I>
9920                void foo(S<I>, S<I + 2>);
9921
9922              This is a "nondeduced context":
9923
9924                [deduct.type]
9925            
9926                The nondeduced contexts are:
9927
9928                --A type that is a template-id in which one or more of
9929                  the template-arguments is an expression that references
9930                  a template-parameter.  
9931
9932              In these cases, we assume deduction succeeded, but don't
9933              actually infer any unifications.  */
9934
9935           if (!uses_template_parms (parm)
9936               && !template_args_equal (parm, arg))
9937             return 1;
9938           else
9939             return 0;
9940         }
9941       else
9942         sorry ("use of `%s' in template type unification",
9943                tree_code_name [(int) TREE_CODE (parm)]);
9944
9945       return 1;
9946     }
9947 }
9948 \f
9949 /* Called if RESULT is explicitly instantiated, or is a member of an
9950    explicitly instantiated class, or if using -frepo and the
9951    instantiation of RESULT has been assigned to this file.  */
9952
9953 void
9954 mark_decl_instantiated (result, extern_p)
9955      tree result;
9956      int extern_p;
9957 {
9958   /* We used to set this unconditionally; we moved that to
9959      do_decl_instantiation so it wouldn't get set on members of
9960      explicit class template instantiations.  But we still need to set
9961      it here for the 'extern template' case in order to suppress
9962      implicit instantiations.  */
9963   if (extern_p)
9964     SET_DECL_EXPLICIT_INSTANTIATION (result);
9965
9966   /* If this entity has already been written out, it's too late to
9967      make any modifications.  */
9968   if (TREE_ASM_WRITTEN (result))
9969     return;
9970
9971   if (TREE_CODE (result) != FUNCTION_DECL)
9972     /* The TREE_PUBLIC flag for function declarations will have been
9973        set correctly by tsubst.  */
9974     TREE_PUBLIC (result) = 1;
9975
9976   if (! extern_p)
9977     {
9978       DECL_INTERFACE_KNOWN (result) = 1;
9979       DECL_NOT_REALLY_EXTERN (result) = 1;
9980
9981       /* Always make artificials weak.  */
9982       if (DECL_ARTIFICIAL (result) && flag_weak)
9983         comdat_linkage (result);
9984       /* For WIN32 we also want to put explicit instantiations in
9985          linkonce sections.  */
9986       else if (TREE_PUBLIC (result))
9987         maybe_make_one_only (result);
9988     }
9989
9990   if (TREE_CODE (result) == FUNCTION_DECL)
9991     defer_fn (result);
9992 }
9993
9994 /* Given two function templates PAT1 and PAT2, return:
9995
9996    DEDUCE should be DEDUCE_EXACT or DEDUCE_ORDER.
9997    
9998    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
9999    -1 if PAT2 is more specialized than PAT1.
10000    0 if neither is more specialized.
10001
10002    LEN is passed through to fn_type_unification.  */
10003    
10004 int
10005 more_specialized (pat1, pat2, deduce, len)
10006      tree pat1, pat2;
10007      int deduce;
10008      int len;
10009 {
10010   tree targs;
10011   int winner = 0;
10012
10013   targs = get_bindings_real (pat1, DECL_TEMPLATE_RESULT (pat2),
10014                              NULL_TREE, 0, deduce, len);
10015   if (targs)
10016     --winner;
10017
10018   targs = get_bindings_real (pat2, DECL_TEMPLATE_RESULT (pat1),
10019                              NULL_TREE, 0, deduce, len);
10020   if (targs)
10021     ++winner;
10022
10023   return winner;
10024 }
10025
10026 /* Given two class template specialization list nodes PAT1 and PAT2, return:
10027
10028    1 if PAT1 is more specialized than PAT2 as described in [temp.class.order].
10029    -1 if PAT2 is more specialized than PAT1.
10030    0 if neither is more specialized.  */
10031    
10032 int
10033 more_specialized_class (pat1, pat2)
10034      tree pat1, pat2;
10035 {
10036   tree targs;
10037   int winner = 0;
10038
10039   targs = get_class_bindings (TREE_VALUE (pat1), TREE_PURPOSE (pat1),
10040                               TREE_PURPOSE (pat2));
10041   if (targs)
10042     --winner;
10043
10044   targs = get_class_bindings (TREE_VALUE (pat2), TREE_PURPOSE (pat2),
10045                               TREE_PURPOSE (pat1));
10046   if (targs)
10047     ++winner;
10048
10049   return winner;
10050 }
10051
10052 /* Return the template arguments that will produce the function signature
10053    DECL from the function template FN, with the explicit template
10054    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is 1, the return type must
10055    also match.  Return NULL_TREE if no satisfactory arguments could be
10056    found.  DEDUCE and LEN are passed through to fn_type_unification.  */
10057    
10058 static tree
10059 get_bindings_real (fn, decl, explicit_args, check_rettype, deduce, len)
10060      tree fn, decl, explicit_args;
10061      int check_rettype, deduce, len;
10062 {
10063   int ntparms = DECL_NTPARMS (fn);
10064   tree targs = make_tree_vec (ntparms);
10065   tree decl_type;
10066   tree decl_arg_types;
10067   int i;
10068
10069   /* Substitute the explicit template arguments into the type of DECL.
10070      The call to fn_type_unification will handle substitution into the
10071      FN.  */
10072   decl_type = TREE_TYPE (decl);
10073   if (explicit_args && uses_template_parms (decl_type))
10074     {
10075       tree tmpl;
10076       tree converted_args;
10077
10078       if (DECL_TEMPLATE_INFO (decl))
10079         tmpl = DECL_TI_TEMPLATE (decl);
10080       else
10081         /* We can get here for some invalid specializations.  */
10082         return NULL_TREE;
10083
10084       converted_args
10085         = (coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
10086                                   explicit_args, NULL_TREE,
10087                                   tf_none, /*require_all_arguments=*/0));
10088       if (converted_args == error_mark_node)
10089         return NULL_TREE;
10090       
10091       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE); 
10092       if (decl_type == error_mark_node)
10093         return NULL_TREE;
10094     }
10095
10096   decl_arg_types = TYPE_ARG_TYPES (decl_type);
10097   /* Never do unification on the 'this' parameter.  */
10098   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
10099     decl_arg_types = TREE_CHAIN (decl_arg_types);
10100
10101   i = fn_type_unification (fn, explicit_args, targs, 
10102                            decl_arg_types,
10103                            (check_rettype || DECL_CONV_FN_P (fn)
10104                             ? TREE_TYPE (decl_type) : NULL_TREE),
10105                            deduce, len);
10106
10107   if (i != 0)
10108     return NULL_TREE;
10109
10110   return targs;
10111 }
10112
10113 /* For most uses, we want to check the return type.  */
10114
10115 tree 
10116 get_bindings (fn, decl, explicit_args)
10117      tree fn, decl, explicit_args;
10118 {
10119   return get_bindings_real (fn, decl, explicit_args, 1, DEDUCE_EXACT, -1);
10120 }
10121
10122 /* But for resolve_overloaded_unification, we only care about the parameter
10123    types.  */
10124
10125 static tree
10126 get_bindings_overload (fn, decl, explicit_args)
10127      tree fn, decl, explicit_args;
10128 {
10129   return get_bindings_real (fn, decl, explicit_args, 0, DEDUCE_EXACT, -1);
10130 }
10131
10132 /* Return the innermost template arguments that, when applied to a
10133    template specialization whose innermost template parameters are
10134    TPARMS, and whose specialization arguments are PARMS, yield the
10135    ARGS.  
10136
10137    For example, suppose we have:
10138
10139      template <class T, class U> struct S {};
10140      template <class T> struct S<T*, int> {};
10141
10142    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
10143    {T}, the PARMS will be {T*, int} and the ARGS will be {double*,
10144    int}.  The resulting vector will be {double}, indicating that `T'
10145    is bound to `double'.  */
10146
10147 static tree
10148 get_class_bindings (tparms, parms, args)
10149      tree tparms, parms, args;
10150 {
10151   int i, ntparms = TREE_VEC_LENGTH (tparms);
10152   tree vec = make_tree_vec (ntparms);
10153
10154   if (unify (tparms, vec, parms, INNERMOST_TEMPLATE_ARGS (args),
10155              UNIFY_ALLOW_NONE))
10156     return NULL_TREE;
10157
10158   for (i =  0; i < ntparms; ++i)
10159     if (! TREE_VEC_ELT (vec, i))
10160       return NULL_TREE;
10161
10162   if (verify_class_unification (vec, parms, args))
10163     return NULL_TREE;
10164
10165   return vec;
10166 }
10167
10168 /* In INSTANTIATIONS is a list of <INSTANTIATION, TEMPLATE> pairs.
10169    Pick the most specialized template, and return the corresponding
10170    instantiation, or if there is no corresponding instantiation, the
10171    template itself.  If there is no most specialized template,
10172    error_mark_node is returned.  If there are no templates at all,
10173    NULL_TREE is returned.  */
10174
10175 tree
10176 most_specialized_instantiation (instantiations)
10177      tree instantiations;
10178 {
10179   tree fn, champ;
10180   int fate;
10181
10182   if (!instantiations)
10183     return NULL_TREE;
10184
10185   champ = instantiations;
10186   for (fn = TREE_CHAIN (instantiations); fn; fn = TREE_CHAIN (fn))
10187     {
10188       fate = more_specialized (TREE_VALUE (champ), TREE_VALUE (fn),
10189                                DEDUCE_EXACT, -1);
10190       if (fate == 1)
10191         ;
10192       else
10193         {
10194           if (fate == 0)
10195             {
10196               fn = TREE_CHAIN (fn);
10197               if (! fn)
10198                 return error_mark_node;
10199             }
10200           champ = fn;
10201         }
10202     }
10203
10204   for (fn = instantiations; fn && fn != champ; fn = TREE_CHAIN (fn))
10205     {
10206       fate = more_specialized (TREE_VALUE (champ), TREE_VALUE (fn),
10207                                DEDUCE_EXACT, -1);
10208       if (fate != 1)
10209         return error_mark_node;
10210     }
10211
10212   return TREE_PURPOSE (champ) ? TREE_PURPOSE (champ) : TREE_VALUE (champ);
10213 }
10214
10215 /* Return the most specialized of the list of templates in FNS that can
10216    produce an instantiation matching DECL, given the explicit template
10217    arguments EXPLICIT_ARGS.  */
10218
10219 static tree
10220 most_specialized (fns, decl, explicit_args)
10221      tree fns, decl, explicit_args;
10222 {
10223   tree candidates = NULL_TREE;
10224   tree fn, args;
10225
10226   for (fn = fns; fn; fn = TREE_CHAIN (fn))
10227     {
10228       tree candidate = TREE_VALUE (fn);
10229
10230       args = get_bindings (candidate, decl, explicit_args);
10231       if (args)
10232         candidates = tree_cons (NULL_TREE, candidate, candidates);
10233     }
10234
10235   return most_specialized_instantiation (candidates);
10236 }
10237
10238 /* If DECL is a specialization of some template, return the most
10239    general such template.  Otherwise, returns NULL_TREE.
10240
10241    For example, given:
10242
10243      template <class T> struct S { template <class U> void f(U); };
10244
10245    if TMPL is `template <class U> void S<int>::f(U)' this will return
10246    the full template.  This function will not trace past partial
10247    specializations, however.  For example, given in addition:
10248
10249      template <class T> struct S<T*> { template <class U> void f(U); };
10250
10251    if TMPL is `template <class U> void S<int*>::f(U)' this will return
10252    `template <class T> template <class U> S<T*>::f(U)'.  */
10253
10254 tree
10255 most_general_template (decl)
10256      tree decl;
10257 {
10258   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
10259      an immediate specialization.  */
10260   if (TREE_CODE (decl) == FUNCTION_DECL)
10261     {
10262       if (DECL_TEMPLATE_INFO (decl)) {
10263         decl = DECL_TI_TEMPLATE (decl);
10264
10265         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
10266            template friend.  */
10267         if (TREE_CODE (decl) != TEMPLATE_DECL)
10268           return NULL_TREE;
10269       } else
10270         return NULL_TREE;
10271     }
10272
10273   /* Look for more and more general templates.  */
10274   while (DECL_TEMPLATE_INFO (decl))
10275     {
10276       /* The DECL_TI_TEMPLATE can be a LOOKUP_EXPR or IDENTIFIER_NODE
10277          in some cases.  (See cp-tree.h for details.)  */
10278       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
10279         break;
10280
10281       if (CLASS_TYPE_P (TREE_TYPE (decl))
10282           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
10283         break;
10284
10285       /* Stop if we run into an explicitly specialized class template.  */
10286       if (!DECL_NAMESPACE_SCOPE_P (decl)
10287           && DECL_CONTEXT (decl)
10288           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
10289         break;
10290
10291       decl = DECL_TI_TEMPLATE (decl);
10292     }
10293
10294   return decl;
10295 }
10296
10297 /* Return the most specialized of the class template specializations
10298    of TMPL which can produce an instantiation matching ARGS, or
10299    error_mark_node if the choice is ambiguous.  */
10300
10301 static tree
10302 most_specialized_class (tmpl, args)
10303      tree tmpl;
10304      tree args;
10305 {
10306   tree list = NULL_TREE;
10307   tree t;
10308   tree champ;
10309   int fate;
10310
10311   tmpl = most_general_template (tmpl);
10312   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
10313     {
10314       tree spec_args 
10315         = get_class_bindings (TREE_VALUE (t), TREE_PURPOSE (t), args);
10316       if (spec_args)
10317         {
10318           list = tree_cons (TREE_PURPOSE (t), TREE_VALUE (t), list);
10319           TREE_TYPE (list) = TREE_TYPE (t);
10320         }
10321     }
10322
10323   if (! list)
10324     return NULL_TREE;
10325
10326   t = list;
10327   champ = t;
10328   t = TREE_CHAIN (t);
10329   for (; t; t = TREE_CHAIN (t))
10330     {
10331       fate = more_specialized_class (champ, t);
10332       if (fate == 1)
10333         ;
10334       else
10335         {
10336           if (fate == 0)
10337             {
10338               t = TREE_CHAIN (t);
10339               if (! t)
10340                 return error_mark_node;
10341             }
10342           champ = t;
10343         }
10344     }
10345
10346   for (t = list; t && t != champ; t = TREE_CHAIN (t))
10347     {
10348       fate = more_specialized_class (champ, t);
10349       if (fate != 1)
10350         return error_mark_node;
10351     }
10352
10353   return champ;
10354 }
10355
10356 /* Explicitly instantiate DECL.  */
10357
10358 void
10359 do_decl_instantiation (tree decl, tree storage)
10360 {
10361   tree result = NULL_TREE;
10362   int extern_p = 0;
10363
10364   if (!decl)
10365     /* An error occurred, for which grokdeclarator has already issued
10366        an appropriate message.  */
10367     return;
10368   else if (! DECL_LANG_SPECIFIC (decl))
10369     {
10370       error ("explicit instantiation of non-template `%#D'", decl);
10371       return;
10372     }
10373   else if (TREE_CODE (decl) == VAR_DECL)
10374     {
10375       /* There is an asymmetry here in the way VAR_DECLs and
10376          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
10377          the latter, the DECL we get back will be marked as a
10378          template instantiation, and the appropriate
10379          DECL_TEMPLATE_INFO will be set up.  This does not happen for
10380          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
10381          should handle VAR_DECLs as it currently handles
10382          FUNCTION_DECLs.  */
10383       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
10384       if (!result || TREE_CODE (result) != VAR_DECL)
10385         {
10386           error ("no matching template for `%D' found", decl);
10387           return;
10388         }
10389     }
10390   else if (TREE_CODE (decl) != FUNCTION_DECL)
10391     {
10392       error ("explicit instantiation of `%#D'", decl);
10393       return;
10394     }
10395   else
10396     result = decl;
10397
10398   /* Check for various error cases.  Note that if the explicit
10399      instantiation is valid the RESULT will currently be marked as an
10400      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
10401      until we get here.  */
10402
10403   if (DECL_TEMPLATE_SPECIALIZATION (result))
10404     {
10405       /* DR 259 [temp.spec].
10406
10407          Both an explicit instantiation and a declaration of an explicit
10408          specialization shall not appear in a program unless the explicit
10409          instantiation follows a declaration of the explicit specialization.
10410
10411          For a given set of template parameters, if an explicit
10412          instantiation of a template appears after a declaration of an
10413          explicit specialization for that template, the explicit
10414          instantiation has no effect.  */
10415       return;
10416     }
10417   else if (DECL_EXPLICIT_INSTANTIATION (result))
10418     {
10419       /* [temp.spec]
10420
10421          No program shall explicitly instantiate any template more
10422          than once.  
10423
10424          We check DECL_INTERFACE_KNOWN so as not to complain when the first
10425          instantiation was `extern' and the second is not, and EXTERN_P for
10426          the opposite case.  If -frepo, chances are we already got marked
10427          as an explicit instantiation because of the repo file.  */
10428       if (DECL_INTERFACE_KNOWN (result) && !extern_p && !flag_use_repository)
10429         pedwarn ("duplicate explicit instantiation of `%#D'", result);
10430
10431       /* If we've already instantiated the template, just return now.  */
10432       if (DECL_INTERFACE_KNOWN (result))
10433         return;
10434     }
10435   else if (!DECL_IMPLICIT_INSTANTIATION (result))
10436     {
10437       error ("no matching template for `%D' found", result);
10438       return;
10439     }
10440   else if (!DECL_TEMPLATE_INFO (result))
10441     {
10442       pedwarn ("explicit instantiation of non-template `%#D'", result);
10443       return;
10444     }
10445
10446   if (flag_external_templates)
10447     return;
10448
10449   if (storage == NULL_TREE)
10450     ;
10451   else if (storage == ridpointers[(int) RID_EXTERN])
10452     {
10453       if (pedantic && !in_system_header)
10454         pedwarn ("ISO C++ forbids the use of `extern' on explicit instantiations");
10455       extern_p = 1;
10456     }
10457   else
10458     error ("storage class `%D' applied to template instantiation",
10459               storage);
10460
10461   SET_DECL_EXPLICIT_INSTANTIATION (result);
10462   mark_decl_instantiated (result, extern_p);
10463   repo_template_instantiated (result, extern_p);
10464   if (! extern_p)
10465     instantiate_decl (result, /*defer_ok=*/1);
10466 }
10467
10468 void
10469 mark_class_instantiated (t, extern_p)
10470      tree t;
10471      int extern_p;
10472 {
10473   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
10474   SET_CLASSTYPE_INTERFACE_KNOWN (t);
10475   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
10476   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
10477   if (! extern_p)
10478     {
10479       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
10480       rest_of_type_compilation (t, 1);
10481     }
10482 }     
10483
10484 /* Called from do_type_instantiation through binding_table_foreach to
10485    do recursive instantiation for the type bound in ENTRY.   */
10486 static void
10487 bt_instantiate_type_proc (binding_entry entry, void *data)
10488 {
10489   tree storage = *(tree *) data;
10490
10491   if (IS_AGGR_TYPE (entry->type)
10492       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
10493     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
10494 }
10495
10496 /* Perform an explicit instantiation of template class T.  STORAGE, if
10497    non-null, is the RID for extern, inline or static.  COMPLAIN is
10498    nonzero if this is called from the parser, zero if called recursively,
10499    since the standard is unclear (as detailed below).  */
10500  
10501 void
10502 do_type_instantiation (t, storage, complain)
10503      tree t, storage;
10504      tsubst_flags_t complain;
10505 {
10506   int extern_p = 0;
10507   int nomem_p = 0;
10508   int static_p = 0;
10509
10510   if (TREE_CODE (t) == TYPE_DECL)
10511     t = TREE_TYPE (t);
10512
10513   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
10514     {
10515       error ("explicit instantiation of non-template type `%T'", t);
10516       return;
10517     }
10518
10519   complete_type (t);
10520
10521   /* With -fexternal-templates, explicit instantiations are treated the same
10522      as implicit ones.  */
10523   if (flag_external_templates)
10524     return;
10525
10526   if (!COMPLETE_TYPE_P (t))
10527     {
10528       if (complain & tf_error)
10529         error ("explicit instantiation of `%#T' before definition of template",
10530                   t);
10531       return;
10532     }
10533
10534   if (storage != NULL_TREE)
10535     {
10536       if (pedantic && !in_system_header)
10537         pedwarn("ISO C++ forbids the use of `%s' on explicit instantiations", 
10538                    IDENTIFIER_POINTER (storage));
10539
10540       if (storage == ridpointers[(int) RID_INLINE])
10541         nomem_p = 1;
10542       else if (storage == ridpointers[(int) RID_EXTERN])
10543         extern_p = 1;
10544       else if (storage == ridpointers[(int) RID_STATIC])
10545         static_p = 1;
10546       else
10547         {
10548           error ("storage class `%D' applied to template instantiation",
10549                     storage);
10550           extern_p = 0;
10551         }
10552     }
10553
10554   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
10555     {
10556       /* DR 259 [temp.spec].
10557
10558          Both an explicit instantiation and a declaration of an explicit
10559          specialization shall not appear in a program unless the explicit
10560          instantiation follows a declaration of the explicit specialization.
10561
10562          For a given set of template parameters, if an explicit
10563          instantiation of a template appears after a declaration of an
10564          explicit specialization for that template, the explicit
10565          instantiation has no effect.  */
10566       return;
10567     }
10568   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
10569     {
10570       /* [temp.spec]
10571
10572          No program shall explicitly instantiate any template more
10573          than once.  
10574
10575          If CLASSTYPE_INTERFACE_ONLY, then the first explicit instantiation
10576          was `extern'.  If EXTERN_P then the second is.  If -frepo, chances
10577          are we already got marked as an explicit instantiation because of the
10578          repo file.  All these cases are OK.  */
10579       if (!CLASSTYPE_INTERFACE_ONLY (t) && !extern_p && !flag_use_repository
10580           && (complain & tf_error))
10581         pedwarn ("duplicate explicit instantiation of `%#T'", t);
10582       
10583       /* If we've already instantiated the template, just return now.  */
10584       if (!CLASSTYPE_INTERFACE_ONLY (t))
10585         return;
10586     }
10587
10588   mark_class_instantiated (t, extern_p);
10589   repo_template_instantiated (t, extern_p);
10590
10591   if (nomem_p)
10592     return;
10593
10594   {
10595     tree tmp;
10596
10597     /* In contrast to implicit instantiation, where only the
10598        declarations, and not the definitions, of members are
10599        instantiated, we have here:
10600
10601          [temp.explicit]
10602
10603          The explicit instantiation of a class template specialization
10604          implies the instantiation of all of its members not
10605          previously explicitly specialized in the translation unit
10606          containing the explicit instantiation.  
10607
10608        Of course, we can't instantiate member template classes, since
10609        we don't have any arguments for them.  Note that the standard
10610        is unclear on whether the instantiation of the members are
10611        *explicit* instantiations or not.  We choose to be generous,
10612        and not set DECL_EXPLICIT_INSTANTIATION.  Therefore, we allow
10613        the explicit instantiation of a class where some of the members
10614        have no definition in the current translation unit.  */
10615
10616     if (! static_p)
10617       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
10618         if (TREE_CODE (tmp) == FUNCTION_DECL
10619             && DECL_TEMPLATE_INSTANTIATION (tmp))
10620           {
10621             mark_decl_instantiated (tmp, extern_p);
10622             repo_template_instantiated (tmp, extern_p);
10623             if (! extern_p)
10624               instantiate_decl (tmp, /*defer_ok=*/1);
10625           }
10626
10627     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
10628       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
10629         {
10630           mark_decl_instantiated (tmp, extern_p);
10631           repo_template_instantiated (tmp, extern_p);
10632           if (! extern_p)
10633             instantiate_decl (tmp, /*defer_ok=*/1);
10634         }
10635
10636     if (CLASSTYPE_NESTED_UTDS (t))
10637       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
10638                              bt_instantiate_type_proc, &storage);
10639   }
10640 }
10641
10642 /* Given a function DECL, which is a specialization of TMPL, modify
10643    DECL to be a re-instantiation of TMPL with the same template
10644    arguments.  TMPL should be the template into which tsubst'ing
10645    should occur for DECL, not the most general template.
10646
10647    One reason for doing this is a scenario like this:
10648
10649      template <class T>
10650      void f(const T&, int i);
10651
10652      void g() { f(3, 7); }
10653
10654      template <class T>
10655      void f(const T& t, const int i) { }
10656
10657    Note that when the template is first instantiated, with
10658    instantiate_template, the resulting DECL will have no name for the
10659    first parameter, and the wrong type for the second.  So, when we go
10660    to instantiate the DECL, we regenerate it.  */
10661
10662 static void
10663 regenerate_decl_from_template (decl, tmpl)
10664      tree decl;
10665      tree tmpl;
10666 {
10667   /* The most general version of TMPL.  */
10668   tree gen_tmpl;
10669   /* The arguments used to instantiate DECL, from the most general
10670      template.  */
10671   tree args;
10672   tree code_pattern;
10673   tree new_decl;
10674   int unregistered;
10675
10676   args = DECL_TI_ARGS (decl);
10677   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
10678
10679   /* Unregister the specialization so that when we tsubst we will not
10680      just return DECL.  We don't have to unregister DECL from TMPL
10681      because if would only be registered there if it were a partial
10682      instantiation of a specialization, which it isn't: it's a full
10683      instantiation.  */
10684   gen_tmpl = most_general_template (tmpl);
10685   push_access_scope_real (gen_tmpl, args, DECL_CONTEXT (decl));
10686   unregistered = unregister_specialization (decl, gen_tmpl);
10687
10688   /* If the DECL was not unregistered then something peculiar is
10689      happening: we created a specialization but did not call
10690      register_specialization for it.  */
10691   my_friendly_assert (unregistered, 0);
10692
10693   /* Do the substitution to get the new declaration.  */
10694   new_decl = tsubst (code_pattern, args, tf_error, NULL_TREE);
10695
10696   if (TREE_CODE (decl) == VAR_DECL)
10697     {
10698       /* Set up DECL_INITIAL, since tsubst doesn't.  */
10699       if (!DECL_INITIALIZED_IN_CLASS_P (decl))
10700         DECL_INITIAL (new_decl) = 
10701           tsubst_expr (DECL_INITIAL (code_pattern), args, 
10702                        tf_error, DECL_TI_TEMPLATE (decl));
10703     }
10704   else if (TREE_CODE (decl) == FUNCTION_DECL)
10705     {
10706       /* Convince duplicate_decls to use the DECL_ARGUMENTS from the
10707          new decl.  */ 
10708       DECL_INITIAL (new_decl) = error_mark_node;
10709       /* And don't complain about a duplicate definition.  */
10710       DECL_INITIAL (decl) = NULL_TREE;
10711     }
10712
10713   pop_access_scope (decl);
10714
10715   /* The immediate parent of the new template is still whatever it was
10716      before, even though tsubst sets DECL_TI_TEMPLATE up as the most
10717      general template.  We also reset the DECL_ASSEMBLER_NAME since
10718      tsubst always calculates the name as if the function in question
10719      were really a template instance, and sometimes, with friend
10720      functions, this is not so.  See tsubst_friend_function for
10721      details.  */
10722   DECL_TI_TEMPLATE (new_decl) = DECL_TI_TEMPLATE (decl);
10723   COPY_DECL_ASSEMBLER_NAME (decl, new_decl);
10724   COPY_DECL_RTL (decl, new_decl);
10725   DECL_USE_TEMPLATE (new_decl) = DECL_USE_TEMPLATE (decl);
10726
10727   /* Call duplicate decls to merge the old and new declarations.  */
10728   duplicate_decls (new_decl, decl);
10729
10730   /* Now, re-register the specialization.  */
10731   register_specialization (decl, gen_tmpl, args);
10732 }
10733
10734 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
10735    substituted to get DECL.  */
10736
10737 static tree
10738 template_for_substitution (tree decl)
10739 {
10740   tree tmpl = DECL_TI_TEMPLATE (decl);
10741
10742   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
10743      for the instantiation.  This is not always the most general
10744      template.  Consider, for example:
10745
10746         template <class T>
10747         struct S { template <class U> void f();
10748                    template <> void f<int>(); };
10749
10750      and an instantiation of S<double>::f<int>.  We want TD to be the
10751      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
10752   while (/* An instantiation cannot have a definition, so we need a
10753             more general template.  */
10754          DECL_TEMPLATE_INSTANTIATION (tmpl)
10755            /* We must also deal with friend templates.  Given:
10756
10757                 template <class T> struct S { 
10758                   template <class U> friend void f() {};
10759                 };
10760
10761               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
10762               so far as the language is concerned, but that's still
10763               where we get the pattern for the instantiation from.  On
10764               other hand, if the definition comes outside the class, say:
10765
10766                 template <class T> struct S { 
10767                   template <class U> friend void f();
10768                 };
10769                 template <class U> friend void f() {}
10770
10771               we don't need to look any further.  That's what the check for
10772               DECL_INITIAL is for.  */
10773           || (TREE_CODE (decl) == FUNCTION_DECL
10774               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
10775               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
10776     {
10777       /* The present template, TD, should not be a definition.  If it
10778          were a definition, we should be using it!  Note that we
10779          cannot restructure the loop to just keep going until we find
10780          a template with a definition, since that might go too far if
10781          a specialization was declared, but not defined.  */
10782       my_friendly_assert (!(TREE_CODE (decl) == VAR_DECL
10783                             && !DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl))), 
10784                           0); 
10785       
10786       /* Fetch the more general template.  */
10787       tmpl = DECL_TI_TEMPLATE (tmpl);
10788     }
10789
10790   return tmpl;
10791 }
10792
10793 /* Produce the definition of D, a _DECL generated from a template.  If
10794    DEFER_OK is nonzero, then we don't have to actually do the
10795    instantiation now; we just have to do it sometime.  */
10796
10797 tree
10798 instantiate_decl (d, defer_ok)
10799      tree d;
10800      int defer_ok;
10801 {
10802   tree tmpl = DECL_TI_TEMPLATE (d);
10803   tree gen_args;
10804   tree args;
10805   tree td;
10806   tree code_pattern;
10807   tree spec;
10808   tree gen_tmpl;
10809   int pattern_defined;
10810   int need_push;
10811   location_t saved_loc = input_location;
10812   
10813   /* This function should only be used to instantiate templates for
10814      functions and static member variables.  */
10815   my_friendly_assert (TREE_CODE (d) == FUNCTION_DECL
10816                       || TREE_CODE (d) == VAR_DECL, 0);
10817
10818   /* Variables are never deferred; if instantiation is required, they
10819      are instantiated right away.  That allows for better code in the
10820      case that an expression refers to the value of the variable --
10821      if the variable has a constant value the referring expression can
10822      take advantage of that fact.  */
10823   if (TREE_CODE (d) == VAR_DECL)
10824     defer_ok = 0;
10825
10826   /* Don't instantiate cloned functions.  Instead, instantiate the
10827      functions they cloned.  */
10828   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
10829     d = DECL_CLONED_FUNCTION (d);
10830
10831   if (DECL_TEMPLATE_INSTANTIATED (d))
10832     /* D has already been instantiated.  It might seem reasonable to
10833        check whether or not D is an explicit instantiation, and, if so,
10834        stop here.  But when an explicit instantiation is deferred
10835        until the end of the compilation, DECL_EXPLICIT_INSTANTIATION
10836        is set, even though we still need to do the instantiation.  */
10837     return d;
10838
10839   /* If we already have a specialization of this declaration, then
10840      there's no reason to instantiate it.  Note that
10841      retrieve_specialization gives us both instantiations and
10842      specializations, so we must explicitly check
10843      DECL_TEMPLATE_SPECIALIZATION.  */
10844   gen_tmpl = most_general_template (tmpl);
10845   gen_args = DECL_TI_ARGS (d);
10846   spec = retrieve_specialization (gen_tmpl, gen_args);
10847   if (spec != NULL_TREE && DECL_TEMPLATE_SPECIALIZATION (spec))
10848     return spec;
10849
10850   /* This needs to happen before any tsubsting.  */
10851   if (! push_tinst_level (d))
10852     return d;
10853
10854   timevar_push (TV_PARSE);
10855
10856   /* We may be in the middle of deferred access check.  Disable
10857      it now.  */
10858   push_deferring_access_checks (dk_no_deferred);
10859
10860   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
10861      for the instantiation.  */
10862   td = template_for_substitution (d);
10863   code_pattern = DECL_TEMPLATE_RESULT (td);
10864
10865   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
10866       || DECL_TEMPLATE_SPECIALIZATION (td))
10867     /* In the case of a friend template whose definition is provided
10868        outside the class, we may have too many arguments.  Drop the
10869        ones we don't need.  The same is true for specializations.  */
10870     args = get_innermost_template_args
10871       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
10872   else
10873     args = gen_args;
10874
10875   if (TREE_CODE (d) == FUNCTION_DECL)
10876     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
10877   else
10878     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
10879
10880   input_location = DECL_SOURCE_LOCATION (d);
10881
10882   if (pattern_defined)
10883     {
10884       /* Let the repository code that this template definition is
10885          available.
10886
10887          The repository doesn't need to know about cloned functions
10888          because they never actually show up in the object file.  It
10889          does need to know about the clones; those are the symbols
10890          that the linker will be emitting error messages about.  */
10891       if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (d)
10892           || DECL_MAYBE_IN_CHARGE_DESTRUCTOR_P (d))
10893         {
10894           tree t;
10895
10896           for (t = TREE_CHAIN (d);
10897                t && DECL_CLONED_FUNCTION_P (t); 
10898                t = TREE_CHAIN (t))
10899             repo_template_used (t);
10900         }
10901       else
10902         repo_template_used (d);
10903
10904       if (flag_external_templates && ! DECL_INTERFACE_KNOWN (d))
10905         {
10906           if (flag_alt_external_templates)
10907             {
10908               if (interface_unknown)
10909                 warn_if_unknown_interface (d);
10910             }
10911           else if (DECL_INTERFACE_KNOWN (code_pattern))
10912             {
10913               DECL_INTERFACE_KNOWN (d) = 1;
10914               DECL_NOT_REALLY_EXTERN (d) = ! DECL_EXTERNAL (code_pattern);
10915             }
10916           else
10917             warn_if_unknown_interface (code_pattern);
10918         }
10919
10920       if (at_eof)
10921         import_export_decl (d);
10922     }
10923
10924   if (!defer_ok)
10925     {
10926       /* Recheck the substitutions to obtain any warning messages
10927          about ignoring cv qualifiers.  */
10928       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
10929       tree type = TREE_TYPE (gen);
10930
10931       /* Make sure that we can see identifiers, and compute access
10932          correctly.  D is already the target FUNCTION_DECL with the
10933          right context.  */
10934       push_access_scope (d);
10935
10936       if (TREE_CODE (gen) == FUNCTION_DECL)
10937         {
10938           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_error | tf_warning, d);
10939           tsubst (TYPE_RAISES_EXCEPTIONS (type), gen_args,
10940                   tf_error | tf_warning, d);
10941           /* Don't simply tsubst the function type, as that will give
10942              duplicate warnings about poor parameter qualifications.
10943              The function arguments are the same as the decl_arguments
10944              without the top level cv qualifiers.  */
10945           type = TREE_TYPE (type);
10946         }
10947       tsubst (type, gen_args, tf_error | tf_warning, d);
10948
10949       pop_access_scope (d);
10950     }
10951   
10952   if (TREE_CODE (d) == VAR_DECL && DECL_INITIALIZED_IN_CLASS_P (d)
10953       && DECL_INITIAL (d) == NULL_TREE)
10954     /* We should have set up DECL_INITIAL in instantiate_class_template.  */
10955     abort ();
10956   /* Reject all external templates except inline functions.  */
10957   else if (DECL_INTERFACE_KNOWN (d)
10958            && ! DECL_NOT_REALLY_EXTERN (d)
10959            && ! (TREE_CODE (d) == FUNCTION_DECL 
10960                  && DECL_INLINE (d)))
10961     goto out;
10962   /* Defer all other templates, unless we have been explicitly
10963      forbidden from doing so.  We restore the source position here
10964      because it's used by add_pending_template.  */
10965   else if (! pattern_defined || defer_ok)
10966     {
10967       input_location = saved_loc;
10968
10969       if (at_eof && !pattern_defined 
10970           && DECL_EXPLICIT_INSTANTIATION (d))
10971         /* [temp.explicit]
10972
10973            The definition of a non-exported function template, a
10974            non-exported member function template, or a non-exported
10975            member function or static data member of a class template
10976            shall be present in every translation unit in which it is
10977            explicitly instantiated.  */
10978         pedwarn
10979           ("explicit instantiation of `%D' but no definition available", d);
10980
10981       add_pending_template (d);
10982       goto out;
10983     }
10984
10985   need_push = !global_bindings_p ();
10986   if (need_push)
10987     push_to_top_level ();
10988
10989   /* Regenerate the declaration in case the template has been modified
10990      by a subsequent redeclaration.  */
10991   regenerate_decl_from_template (d, td);
10992   
10993   /* We already set the file and line above.  Reset them now in case
10994      they changed as a result of calling
10995      regenerate_decl_from_template.  */
10996   input_location = DECL_SOURCE_LOCATION (d);
10997
10998   if (TREE_CODE (d) == VAR_DECL)
10999     {
11000       /* Clear out DECL_RTL; whatever was there before may not be right
11001          since we've reset the type of the declaration.  */
11002       SET_DECL_RTL (d, NULL_RTX);
11003
11004       DECL_IN_AGGR_P (d) = 0;
11005       import_export_decl (d);
11006       DECL_EXTERNAL (d) = ! DECL_NOT_REALLY_EXTERN (d);
11007
11008       if (DECL_EXTERNAL (d))
11009         {
11010           /* The fact that this code is executing indicates that:
11011              
11012              (1) D is a template static data member, for which a
11013                  definition is available.
11014
11015              (2) An implicit or explicit instantiation has occured.
11016
11017              (3) We are not going to emit a definition of the static
11018                  data member at this time.
11019
11020              This situation is peculiar, but it occurs on platforms
11021              without weak symbols when performing an implicit
11022              instantiation.  There, we cannot implicitly instantiate a
11023              defined static data member in more than one translation
11024              unit, so import_export_decl marks the declaration as
11025              external; we must rely on explicit instantiation.  */
11026         }
11027       else
11028         {
11029           /* Mark D as instantiated so that recursive calls to
11030              instantiate_decl do not try to instantiate it again.  */
11031           DECL_TEMPLATE_INSTANTIATED (d) = 1;
11032           cp_finish_decl (d, 
11033                           (!DECL_INITIALIZED_IN_CLASS_P (d) 
11034                            ? DECL_INITIAL (d) : NULL_TREE),
11035                           NULL_TREE, 0);
11036         }
11037     }
11038   else if (TREE_CODE (d) == FUNCTION_DECL)
11039     {
11040       htab_t saved_local_specializations;
11041       tree subst_decl;
11042       tree tmpl_parm;
11043       tree spec_parm;
11044
11045       /* Mark D as instantiated so that recursive calls to
11046          instantiate_decl do not try to instantiate it again.  */
11047       DECL_TEMPLATE_INSTANTIATED (d) = 1;
11048
11049       /* Save away the current list, in case we are instantiating one
11050          template from within the body of another.  */
11051       saved_local_specializations = local_specializations;
11052
11053       /* Set up the list of local specializations.  */
11054       local_specializations = htab_create (37, 
11055                                            hash_local_specialization,
11056                                            eq_local_specializations,
11057                                            NULL);
11058
11059       /* Set up context.  */
11060       import_export_decl (d);
11061       start_function (NULL_TREE, d, NULL_TREE, SF_PRE_PARSED);
11062
11063       /* Create substitution entries for the parameters.  */
11064       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
11065       tmpl_parm = DECL_ARGUMENTS (subst_decl);
11066       spec_parm = DECL_ARGUMENTS (d);
11067       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
11068         {
11069           register_local_specialization (spec_parm, tmpl_parm);
11070           spec_parm = skip_artificial_parms_for (d, spec_parm);
11071           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
11072         }
11073       while (tmpl_parm)
11074         {
11075           register_local_specialization (spec_parm, tmpl_parm);
11076           tmpl_parm = TREE_CHAIN (tmpl_parm);
11077           spec_parm = TREE_CHAIN (spec_parm);
11078         }
11079       my_friendly_assert (!spec_parm, 20020813);
11080
11081       /* Substitute into the body of the function.  */
11082       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
11083                    tf_error | tf_warning, tmpl);
11084
11085       /* We don't need the local specializations any more.  */
11086       htab_delete (local_specializations);
11087       local_specializations = saved_local_specializations;
11088
11089       /* Finish the function.  */
11090       d = finish_function (0);
11091       expand_body (d);
11092     }
11093
11094   /* We're not deferring instantiation any more.  */
11095   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
11096
11097   if (need_push)
11098     pop_from_top_level ();
11099
11100 out:
11101   input_location = saved_loc;
11102   pop_deferring_access_checks ();
11103   pop_tinst_level ();
11104
11105   timevar_pop (TV_PARSE);
11106
11107   return d;
11108 }
11109
11110 /* Run through the list of templates that we wish we could
11111    instantiate, and instantiate any we can.  */
11112
11113 int
11114 instantiate_pending_templates ()
11115 {
11116   tree *t;
11117   tree last = NULL_TREE;
11118   int instantiated_something = 0;
11119   int reconsider;
11120   
11121   do 
11122     {
11123       reconsider = 0;
11124
11125       t = &pending_templates;
11126       while (*t)
11127         {
11128           tree instantiation = TREE_VALUE (*t);
11129
11130           reopen_tinst_level (TREE_PURPOSE (*t));
11131
11132           if (TYPE_P (instantiation))
11133             {
11134               tree fn;
11135
11136               if (!COMPLETE_TYPE_P (instantiation))
11137                 {
11138                   instantiate_class_template (instantiation);
11139                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
11140                     for (fn = TYPE_METHODS (instantiation); 
11141                          fn;
11142                          fn = TREE_CHAIN (fn))
11143                       if (! DECL_ARTIFICIAL (fn))
11144                         instantiate_decl (fn, /*defer_ok=*/0);
11145                   if (COMPLETE_TYPE_P (instantiation))
11146                     {
11147                       instantiated_something = 1;
11148                       reconsider = 1;
11149                     }
11150                 }
11151
11152               if (COMPLETE_TYPE_P (instantiation))
11153                 /* If INSTANTIATION has been instantiated, then we don't
11154                    need to consider it again in the future.  */
11155                 *t = TREE_CHAIN (*t);
11156               else
11157                 {
11158                   last = *t;
11159                   t = &TREE_CHAIN (*t);
11160                 }
11161             }
11162           else
11163             {
11164               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
11165                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
11166                 {
11167                   instantiation = instantiate_decl (instantiation,
11168                                                     /*defer_ok=*/0);
11169                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
11170                     {
11171                       instantiated_something = 1;
11172                       reconsider = 1;
11173                     }
11174                 }
11175
11176               if (DECL_TEMPLATE_SPECIALIZATION (instantiation)
11177                   || DECL_TEMPLATE_INSTANTIATED (instantiation))
11178                 /* If INSTANTIATION has been instantiated, then we don't
11179                    need to consider it again in the future.  */
11180                 *t = TREE_CHAIN (*t);
11181               else
11182                 {
11183                   last = *t;
11184                   t = &TREE_CHAIN (*t);
11185                 }
11186             }
11187           tinst_depth = 0;
11188           current_tinst_level = NULL_TREE;
11189         }
11190       last_pending_template = last;
11191     } 
11192   while (reconsider);
11193
11194   return instantiated_something;
11195 }
11196
11197 /* Substitute ARGVEC into T, which is a list of initializers for
11198    either base class or a non-static data member.  The TREE_PURPOSEs
11199    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
11200    instantiate_decl.  */
11201
11202 static tree
11203 tsubst_initializer_list (t, argvec)
11204      tree t, argvec;
11205 {
11206   tree inits = NULL_TREE;
11207
11208   for (; t; t = TREE_CHAIN (t))
11209     {
11210       tree decl;
11211       tree init;
11212       tree val;
11213
11214       decl = tsubst_copy (TREE_PURPOSE (t), argvec, tf_error | tf_warning,
11215                           NULL_TREE);
11216       decl = expand_member_init (decl);
11217       if (decl && !DECL_P (decl))
11218         in_base_initializer = 1;
11219       
11220       init = tsubst_expr (TREE_VALUE (t), argvec, tf_error | tf_warning,
11221                           NULL_TREE);
11222       if (!init)
11223         ;
11224       else if (TREE_CODE (init) == TREE_LIST)
11225         for (val = init; val; val = TREE_CHAIN (val))
11226           TREE_VALUE (val) = convert_from_reference (TREE_VALUE (val));
11227       else if (init != void_type_node)
11228         init = convert_from_reference (init);
11229
11230       in_base_initializer = 0;
11231
11232       if (decl)
11233         {
11234           init = build_tree_list (decl, init);
11235           TREE_CHAIN (init) = inits;
11236           inits = init;
11237         }
11238     }
11239   return inits;
11240 }
11241
11242 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
11243
11244 static void
11245 set_current_access_from_decl (decl)
11246      tree decl;
11247 {
11248   if (TREE_PRIVATE (decl))
11249     current_access_specifier = access_private_node;
11250   else if (TREE_PROTECTED (decl))
11251     current_access_specifier = access_protected_node;
11252   else
11253     current_access_specifier = access_public_node;
11254 }
11255
11256 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
11257    is the instantiation (which should have been created with
11258    start_enum) and ARGS are the template arguments to use.  */
11259
11260 static void
11261 tsubst_enum (tag, newtag, args)
11262      tree tag;
11263      tree newtag;
11264      tree args;
11265 {
11266   tree e;
11267
11268   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
11269     {
11270       tree value;
11271       
11272       /* Note that in a template enum, the TREE_VALUE is the
11273          CONST_DECL, not the corresponding INTEGER_CST.  */
11274       value = tsubst_expr (DECL_INITIAL (TREE_VALUE (e)), 
11275                            args, tf_error | tf_warning,
11276                            NULL_TREE);
11277
11278       /* Give this enumeration constant the correct access.  */
11279       set_current_access_from_decl (TREE_VALUE (e));
11280
11281       /* Actually build the enumerator itself.  */
11282       build_enumerator (TREE_PURPOSE (e), value, newtag); 
11283     }
11284
11285   finish_enum (newtag);
11286   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
11287     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
11288 }
11289
11290 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
11291    its type -- but without substituting the innermost set of template
11292    arguments.  So, innermost set of template parameters will appear in
11293    the type.  */
11294
11295 tree 
11296 get_mostly_instantiated_function_type (decl)
11297      tree decl;
11298 {
11299   tree fn_type;
11300   tree tmpl;
11301   tree targs;
11302   tree tparms;
11303   int parm_depth;
11304
11305   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
11306   targs = DECL_TI_ARGS (decl);
11307   tparms = DECL_TEMPLATE_PARMS (tmpl);
11308   parm_depth = TMPL_PARMS_DEPTH (tparms);
11309
11310   /* There should be as many levels of arguments as there are levels
11311      of parameters.  */
11312   my_friendly_assert (parm_depth == TMPL_ARGS_DEPTH (targs), 0);
11313
11314   fn_type = TREE_TYPE (tmpl);
11315
11316   if (parm_depth == 1)
11317     /* No substitution is necessary.  */
11318     ;
11319   else
11320     {
11321       int i;
11322       tree partial_args;
11323
11324       /* Replace the innermost level of the TARGS with NULL_TREEs to
11325          let tsubst know not to substitute for those parameters.  */
11326       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
11327       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
11328         SET_TMPL_ARGS_LEVEL (partial_args, i,
11329                              TMPL_ARGS_LEVEL (targs, i));
11330       SET_TMPL_ARGS_LEVEL (partial_args,
11331                            TMPL_ARGS_DEPTH (targs),
11332                            make_tree_vec (DECL_NTPARMS (tmpl)));
11333
11334       /* Make sure that we can see identifiers, and compute access
11335          correctly.  We can just use the context of DECL for the
11336          partial substitution here.  It depends only on outer template
11337          parameters, regardless of whether the innermost level is
11338          specialized or not.  */
11339       push_access_scope (decl);
11340
11341       /* Now, do the (partial) substitution to figure out the
11342          appropriate function type.  */
11343       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
11344
11345       /* Substitute into the template parameters to obtain the real
11346          innermost set of parameters.  This step is important if the
11347          innermost set of template parameters contains value
11348          parameters whose types depend on outer template parameters.  */
11349       TREE_VEC_LENGTH (partial_args)--;
11350       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
11351
11352       pop_access_scope (decl);
11353     }
11354
11355   return fn_type;
11356 }
11357
11358 /* Return truthvalue if we're processing a template different from
11359    the last one involved in diagnostics.  */
11360 int
11361 problematic_instantiation_changed ()
11362 {
11363   return last_template_error_tick != tinst_level_tick;
11364 }
11365
11366 /* Remember current template involved in diagnostics.  */
11367 void
11368 record_last_problematic_instantiation ()
11369 {
11370   last_template_error_tick = tinst_level_tick;
11371 }
11372
11373 tree
11374 current_instantiation ()
11375 {
11376   return current_tinst_level;
11377 }
11378
11379 /* [temp.param] Check that template non-type parm TYPE is of an allowable
11380    type. Return zero for ok, nonzero for disallowed. Issue error and
11381    warning messages under control of COMPLAIN.  */
11382
11383 static int
11384 invalid_nontype_parm_type_p (type, complain)
11385      tree type;
11386      tsubst_flags_t complain;
11387 {
11388   if (INTEGRAL_TYPE_P (type))
11389     return 0;
11390   else if (POINTER_TYPE_P (type))
11391     return 0;
11392   else if (TYPE_PTRMEM_P (type))
11393     return 0;
11394   else if (TYPE_PTRMEMFUNC_P (type))
11395     return 0;
11396   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
11397     return 0;
11398   else if (TREE_CODE (type) == TYPENAME_TYPE)
11399     return 0;
11400            
11401   if (complain & tf_error)
11402     error ("`%#T' is not a valid type for a template constant parameter",
11403               type);
11404   return 1;
11405 }
11406
11407 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
11408    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
11409
11410 static bool
11411 dependent_type_p_r (tree type)
11412 {
11413   tree scope;
11414
11415   /* [temp.dep.type]
11416
11417      A type is dependent if it is:
11418
11419      -- a template parameter.  */
11420   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
11421     return true;
11422   /* -- a qualified-id with a nested-name-specifier which contains a
11423         class-name that names a dependent type or whose unqualified-id
11424         names a dependent type.  */
11425   if (TREE_CODE (type) == TYPENAME_TYPE)
11426     return true;
11427   /* -- a cv-qualified type where the cv-unqualified type is
11428         dependent.  */
11429   type = TYPE_MAIN_VARIANT (type);
11430   /* -- a compound type constructed from any dependent type.  */
11431   if (TYPE_PTRMEM_P (type) || TYPE_PTRMEMFUNC_P (type))
11432     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
11433             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE 
11434                                            (type)));
11435   else if (TREE_CODE (type) == POINTER_TYPE
11436            || TREE_CODE (type) == REFERENCE_TYPE)
11437     return dependent_type_p (TREE_TYPE (type));
11438   else if (TREE_CODE (type) == FUNCTION_TYPE
11439            || TREE_CODE (type) == METHOD_TYPE)
11440     {
11441       tree arg_type;
11442
11443       if (dependent_type_p (TREE_TYPE (type)))
11444         return true;
11445       for (arg_type = TYPE_ARG_TYPES (type); 
11446            arg_type; 
11447            arg_type = TREE_CHAIN (arg_type))
11448         if (dependent_type_p (TREE_VALUE (arg_type)))
11449           return true;
11450       return false;
11451     }
11452   /* -- an array type constructed from any dependent type or whose
11453         size is specified by a constant expression that is
11454         value-dependent.  */
11455   if (TREE_CODE (type) == ARRAY_TYPE)
11456     {
11457       if (TYPE_DOMAIN (type)
11458           && ((value_dependent_expression_p 
11459                (TYPE_MAX_VALUE (TYPE_DOMAIN (type))))
11460               || (type_dependent_expression_p
11461                   (TYPE_MAX_VALUE (TYPE_DOMAIN (type))))))
11462         return true;
11463       return dependent_type_p (TREE_TYPE (type));
11464     }
11465   /* -- a template-id in which either the template name is a template
11466         parameter or any of the template arguments is a dependent type or
11467         an expression that is type-dependent or value-dependent.  
11468
11469      This language seems somewhat confused; for example, it does not
11470      discuss template template arguments.  Therefore, we use the
11471      definition for dependent template arguments in [temp.dep.temp].  */
11472   if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
11473       && (dependent_template_id_p
11474           (CLASSTYPE_TI_TEMPLATE (type),
11475            CLASSTYPE_TI_ARGS (type))))
11476     return true;
11477   else if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
11478     return true;
11479   /* All TYPEOF_TYPEs are dependent; if the argument of the `typeof'
11480      expression is not type-dependent, then it should already been
11481      have resolved.  */
11482   if (TREE_CODE (type) == TYPEOF_TYPE)
11483     return true;
11484   /* The standard does not specifically mention types that are local
11485      to template functions or local classes, but they should be
11486      considered dependent too.  For example:
11487
11488        template <int I> void f() { 
11489          enum E { a = I }; 
11490          S<sizeof (E)> s;
11491        }
11492
11493      The size of `E' cannot be known until the value of `I' has been
11494      determined.  Therefore, `E' must be considered dependent.  */
11495   scope = TYPE_CONTEXT (type);
11496   if (scope && TYPE_P (scope))
11497     return dependent_type_p (scope);
11498   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
11499     return type_dependent_expression_p (scope);
11500
11501   /* Other types are non-dependent.  */
11502   return false;
11503 }
11504
11505 /* Returns TRUE if TYPE is dependent, in the sense of
11506    [temp.dep.type].  */
11507
11508 bool
11509 dependent_type_p (tree type)
11510 {
11511   /* If there are no template parameters in scope, then there can't be
11512      any dependent types.  */
11513   if (!processing_template_decl)
11514     return false;
11515
11516   /* If the type is NULL, we have not computed a type for the entity
11517      in question; in that case, the type is dependent.  */
11518   if (!type)
11519     return true;
11520
11521   /* Erroneous types can be considered non-dependent.  */
11522   if (type == error_mark_node)
11523     return false;
11524
11525   /* If we have not already computed the appropriate value for TYPE,
11526      do so now.  */
11527   if (!TYPE_DEPENDENT_P_VALID (type))
11528     {
11529       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
11530       TYPE_DEPENDENT_P_VALID (type) = 1;
11531     }
11532
11533   return TYPE_DEPENDENT_P (type);
11534 }
11535
11536 /* Returns TRUE if the EXPRESSION is value-dependent.  */
11537
11538 bool
11539 value_dependent_expression_p (tree expression)
11540 {
11541   if (!processing_template_decl)
11542     return false;
11543
11544   /* A name declared with a dependent type.  */
11545   if (TREE_CODE (expression) == LOOKUP_EXPR
11546       || (DECL_P (expression)
11547           && dependent_type_p (TREE_TYPE (expression))))
11548     return true;
11549   /* A non-type template parameter.  */
11550   if ((TREE_CODE (expression) == CONST_DECL
11551        && DECL_TEMPLATE_PARM_P (expression))
11552       || TREE_CODE (expression) == TEMPLATE_PARM_INDEX)
11553     return true;
11554   /* A constant with integral or enumeration type and is initialized 
11555      with an expression that is value-dependent.  */
11556   if (TREE_CODE (expression) == VAR_DECL
11557       && DECL_INITIAL (expression)
11558       && (CP_INTEGRAL_TYPE_P (TREE_TYPE (expression))
11559           || TREE_CODE (TREE_TYPE (expression)) == ENUMERAL_TYPE)
11560       && value_dependent_expression_p (DECL_INITIAL (expression)))
11561     return true;
11562   /* These expressions are value-dependent if the type to which the
11563      cast occurs is dependent.  */
11564   if ((TREE_CODE (expression) == DYNAMIC_CAST_EXPR
11565        || TREE_CODE (expression) == STATIC_CAST_EXPR
11566        || TREE_CODE (expression) == CONST_CAST_EXPR
11567        || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
11568        || TREE_CODE (expression) == CAST_EXPR)
11569       && dependent_type_p (TREE_TYPE (expression)))
11570     return true;
11571   /* A `sizeof' expression where the sizeof operand is a type is
11572      value-dependent if the type is dependent.  If the type was not
11573      dependent, we would no longer have a SIZEOF_EXPR, so any
11574      SIZEOF_EXPR is dependent.  */
11575   if (TREE_CODE (expression) == SIZEOF_EXPR)
11576     return true;
11577   /* A constant expression is value-dependent if any subexpression is
11578      value-dependent.  */
11579   if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (TREE_CODE (expression))))
11580     {
11581       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
11582         {
11583         case '1':
11584           return (value_dependent_expression_p 
11585                   (TREE_OPERAND (expression, 0)));
11586         case '<':
11587         case '2':
11588           return ((value_dependent_expression_p 
11589                    (TREE_OPERAND (expression, 0)))
11590                   || (value_dependent_expression_p 
11591                       (TREE_OPERAND (expression, 1))));
11592         case 'e':
11593           {
11594             int i;
11595             for (i = 0; i < first_rtl_op (TREE_CODE (expression)); ++i)
11596               /* In some cases, some of the operands may be missing.
11597                  (For example, in the case of PREDECREMENT_EXPR, the
11598                  amount to increment by may be missing.)  That doesn't
11599                  make the expression dependent.  */
11600               if (TREE_OPERAND (expression, i)
11601                   && (value_dependent_expression_p
11602                       (TREE_OPERAND (expression, i))))
11603                 return true;
11604             return false;
11605           }
11606         }
11607     }
11608
11609   /* The expression is not value-dependent.  */
11610   return false;
11611 }
11612
11613 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
11614    [temp.dep.expr].  */
11615
11616 bool
11617 type_dependent_expression_p (expression)
11618      tree expression;
11619 {
11620   if (!processing_template_decl)
11621     return false;
11622
11623   /* Some expression forms are never type-dependent.  */
11624   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
11625       || TREE_CODE (expression) == SIZEOF_EXPR
11626       || TREE_CODE (expression) == ALIGNOF_EXPR
11627       || TREE_CODE (expression) == TYPEID_EXPR
11628       || TREE_CODE (expression) == DELETE_EXPR
11629       || TREE_CODE (expression) == VEC_DELETE_EXPR
11630       || TREE_CODE (expression) == THROW_EXPR)
11631     return false;
11632
11633   /* The types of these expressions depends only on the type to which
11634      the cast occurs.  */
11635   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
11636       || TREE_CODE (expression) == STATIC_CAST_EXPR
11637       || TREE_CODE (expression) == CONST_CAST_EXPR
11638       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
11639       || TREE_CODE (expression) == CAST_EXPR)
11640     return dependent_type_p (TREE_TYPE (expression));
11641   /* The types of these expressions depends only on the type created
11642      by the expression.  */
11643   else if (TREE_CODE (expression) == NEW_EXPR
11644            || TREE_CODE (expression) == VEC_NEW_EXPR)
11645     {
11646       /* For NEW_EXPR tree nodes created inside a template, either
11647          the object type itself or a TREE_LIST may appear as the
11648          operand 1.  */
11649       tree type = TREE_OPERAND (expression, 1);
11650       if (TREE_CODE (type) == TREE_LIST)
11651         /* This is an array type.  We need to check array dimensions
11652            as well.  */
11653         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
11654                || value_dependent_expression_p
11655                     (TREE_OPERAND (TREE_VALUE (type), 1));
11656       else
11657         return dependent_type_p (type);
11658     }
11659
11660   if (TREE_CODE (expression) == FUNCTION_DECL
11661       && DECL_LANG_SPECIFIC (expression)
11662       && DECL_TEMPLATE_INFO (expression)
11663       && (dependent_template_id_p
11664           (DECL_TI_TEMPLATE (expression),
11665            INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
11666     return true;
11667
11668   return (dependent_type_p (TREE_TYPE (expression)));
11669 }
11670
11671 /* Returns TRUE if the ARG (a template argument) is dependent.  */
11672
11673 bool
11674 dependent_template_arg_p (tree arg)
11675 {
11676   if (!processing_template_decl)
11677     return false;
11678
11679   if (TREE_CODE (arg) == TEMPLATE_DECL
11680       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
11681     return dependent_template_p (arg);
11682   else if (TYPE_P (arg))
11683     return dependent_type_p (arg);
11684   else
11685     return (type_dependent_expression_p (arg)
11686             || value_dependent_expression_p (arg));
11687 }
11688
11689 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
11690
11691 static bool
11692 dependent_template_id_p (tree tmpl, tree args)
11693 {
11694   int i;
11695
11696   if (dependent_template_p (tmpl))
11697     return true;
11698   for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
11699     if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
11700       return true;
11701   return false;
11702 }
11703
11704 /* Returns TRUE if the template TMPL is dependent.  */
11705
11706 bool
11707 dependent_template_p (tree tmpl)
11708 {
11709   /* Template template parameters are dependent.  */
11710   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
11711       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
11712     return true;
11713   /* So are member templates of dependent classes.  */
11714   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
11715     return dependent_type_p (DECL_CONTEXT (tmpl));
11716   return false;
11717 }
11718
11719 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
11720    TYPENAME_TYPE corresponds.  Returns ERROR_MARK_NODE if no such TYPE
11721    can be found.  Note that this function peers inside uninstantiated
11722    templates and therefore should be used only in extremely limited
11723    situations.  */
11724
11725 tree
11726 resolve_typename_type (tree type, bool only_current_p)
11727 {
11728   tree scope;
11729   tree name;
11730   tree decl;
11731   int quals;
11732
11733   my_friendly_assert (TREE_CODE (type) == TYPENAME_TYPE,
11734                       20010702);
11735
11736   scope = TYPE_CONTEXT (type);
11737   name = TYPE_IDENTIFIER (type);
11738
11739   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
11740      it first before we can figure out what NAME refers to.  */
11741   if (TREE_CODE (scope) == TYPENAME_TYPE)
11742     scope = resolve_typename_type (scope, only_current_p);
11743   /* If we don't know what SCOPE refers to, then we cannot resolve the
11744      TYPENAME_TYPE.  */
11745   if (scope == error_mark_node || TREE_CODE (scope) == TYPENAME_TYPE)
11746     return error_mark_node;
11747   /* If the SCOPE is a template type parameter, we have no way of
11748      resolving the name.  */
11749   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
11750     return type;
11751   /* If the SCOPE is not the current instantiation, there's no reason
11752      to look inside it.  */
11753   if (only_current_p && !currently_open_class (scope))
11754     return error_mark_node;
11755   /* If SCOPE is a partial instantiation, it will not have a valid
11756      TYPE_FIELDS list, so use the original template.  */
11757   scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
11758   /* Enter the SCOPE so that name lookup will be resolved as if we
11759      were in the class definition.  In particular, SCOPE will no
11760      longer be considered a dependent type.  */
11761   push_scope (scope);
11762   /* Look up the declaration.  */
11763   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
11764   /* Obtain the set of qualifiers applied to the TYPE.  */
11765   quals = cp_type_quals (type);
11766   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
11767      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
11768   if (!decl)
11769     type = error_mark_node;
11770   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
11771            && TREE_CODE (decl) == TYPE_DECL)
11772     type = TREE_TYPE (decl);
11773   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
11774            && DECL_CLASS_TEMPLATE_P (decl))
11775     {
11776       tree tmpl;
11777       tree args;
11778       /* Obtain the template and the arguments.  */
11779       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
11780       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
11781       /* Instantiate the template.  */
11782       type = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
11783                                     /*entering_scope=*/0, 
11784                                     tf_error);
11785     }
11786   else
11787     type = error_mark_node;
11788   /* Qualify the resulting type.  */
11789   if (type != error_mark_node && quals)
11790     type = cp_build_qualified_type (type, quals);
11791   /* Leave the SCOPE.  */
11792   pop_scope (scope);
11793
11794   return type;
11795 }
11796
11797 tree
11798 resolve_typename_type_in_current_instantiation (tree type)
11799 {
11800   tree t;
11801
11802   t = resolve_typename_type (type, /*only_current_p=*/true);
11803   return (t != error_mark_node) ? t : type;
11804 }
11805
11806 #include "gt-cp-pt.h"