OSDN Git Service

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