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