OSDN Git Service

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