OSDN Git Service

* c-common.c (vector_types_convertible_p,
[pf3gnuchains/gcc-fork.git] / gcc / cp / pt.c
1 /* Handle parameterized types (templates) for GNU C++.
2    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3    2001, 2002, 2003, 2004, 2005, 2007  Free Software Foundation, Inc.
4    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
5    Rewritten by Jason Merrill (jason@cygnus.com).
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3, or (at your option)
12 any later version.
13
14 GCC is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.  */
22
23 /* Known bugs or deficiencies include:
24
25      all methods must be provided in header files; can't use a source
26      file that contains only the method templates and "just win".  */
27
28 #include "config.h"
29 #include "system.h"
30 #include "coretypes.h"
31 #include "tm.h"
32 #include "obstack.h"
33 #include "tree.h"
34 #include "pointer-set.h"
35 #include "flags.h"
36 #include "c-common.h"
37 #include "cp-tree.h"
38 #include "cp-objcp-common.h"
39 #include "tree-inline.h"
40 #include "decl.h"
41 #include "output.h"
42 #include "except.h"
43 #include "toplev.h"
44 #include "rtl.h"
45 #include "timevar.h"
46 #include "tree-iterator.h"
47 #include "vecprim.h"
48
49 /* The type of functions taking a tree, and some additional data, and
50    returning an int.  */
51 typedef int (*tree_fn_t) (tree, void*);
52
53 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
54    instantiations have been deferred, either because their definitions
55    were not yet available, or because we were putting off doing the work.  */
56 struct pending_template GTY (()) {
57   struct pending_template *next;
58   struct tinst_level *tinst;
59 };
60
61 static GTY(()) struct pending_template *pending_templates;
62 static GTY(()) struct pending_template *last_pending_template;
63
64 int processing_template_parmlist;
65 static int template_header_count;
66
67 static GTY(()) tree saved_trees;
68 static VEC(int,heap) *inline_parm_levels;
69
70 static GTY(()) struct tinst_level *current_tinst_level;
71
72 static GTY(()) tree saved_access_scope;
73
74 /* Live only within one (recursive) call to tsubst_expr.  We use
75    this to pass the statement expression node from the STMT_EXPR
76    to the EXPR_STMT that is its result.  */
77 static tree cur_stmt_expr;
78
79 /* A map from local variable declarations in the body of the template
80    presently being instantiated to the corresponding instantiated
81    local variables.  */
82 static htab_t local_specializations;
83
84 /* Contains canonical template parameter types. The vector is indexed by
85    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
86    TREE_LIST, whose TREE_VALUEs contain the canonical template
87    parameters of various types and levels.  */
88 static GTY(()) VEC(tree,gc) *canonical_template_parms;
89
90 #define UNIFY_ALLOW_NONE 0
91 #define UNIFY_ALLOW_MORE_CV_QUAL 1
92 #define UNIFY_ALLOW_LESS_CV_QUAL 2
93 #define UNIFY_ALLOW_DERIVED 4
94 #define UNIFY_ALLOW_INTEGER 8
95 #define UNIFY_ALLOW_OUTER_LEVEL 16
96 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
97 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
98
99 static void push_access_scope (tree);
100 static void pop_access_scope (tree);
101 static bool resolve_overloaded_unification (tree, tree, tree, tree,
102                                             unification_kind_t, int);
103 static int try_one_overload (tree, tree, tree, tree, tree,
104                              unification_kind_t, int, bool);
105 static int unify (tree, tree, tree, tree, int);
106 static void add_pending_template (tree);
107 static int push_tinst_level (tree);
108 static void pop_tinst_level (void);
109 static tree reopen_tinst_level (struct tinst_level *);
110 static tree tsubst_initializer_list (tree, tree);
111 static tree get_class_bindings (tree, tree, tree);
112 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
113                                    bool, bool);
114 static void tsubst_enum (tree, tree, tree);
115 static tree add_to_template_args (tree, tree);
116 static tree add_outermost_template_args (tree, tree);
117 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
118 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
119                                              tree);
120 static int  type_unification_real (tree, tree, tree, tree,
121                                    int, unification_kind_t, int);
122 static void note_template_header (int);
123 static tree convert_nontype_argument_function (tree, tree);
124 static tree convert_nontype_argument (tree, tree);
125 static tree convert_template_argument (tree, tree, tree,
126                                        tsubst_flags_t, int, tree);
127 static int for_each_template_parm (tree, tree_fn_t, void*,
128                                    struct pointer_set_t*);
129 static tree expand_template_argument_pack (tree);
130 static tree build_template_parm_index (int, int, int, tree, tree);
131 static bool inline_needs_template_parms (tree);
132 static void push_inline_template_parms_recursive (tree, int);
133 static tree retrieve_local_specialization (tree);
134 static void register_local_specialization (tree, tree);
135 static tree reduce_template_parm_level (tree, tree, int);
136 static int mark_template_parm (tree, void *);
137 static int template_parm_this_level_p (tree, void *);
138 static tree tsubst_friend_function (tree, tree);
139 static tree tsubst_friend_class (tree, tree);
140 static int can_complete_type_without_circularity (tree);
141 static tree get_bindings (tree, tree, tree, bool);
142 static int template_decl_level (tree);
143 static int check_cv_quals_for_unify (int, tree, tree);
144 static void template_parm_level_and_index (tree, int*, int*);
145 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
146 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
147 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
148 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
149 static void regenerate_decl_from_template (tree, tree);
150 static tree most_specialized_class (tree, tree);
151 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
152 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
153 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
154 static bool check_specialization_scope (void);
155 static tree process_partial_specialization (tree);
156 static void set_current_access_from_decl (tree);
157 static tree get_template_base (tree, tree, tree, tree);
158 static tree try_class_unification (tree, tree, tree, tree);
159 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
160                                            tree, tree);
161 static int template_args_equal (tree, tree);
162 static void tsubst_default_arguments (tree);
163 static tree for_each_template_parm_r (tree *, int *, void *);
164 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
165 static void copy_default_args_to_explicit_spec (tree);
166 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
167 static int eq_local_specializations (const void *, const void *);
168 static bool dependent_template_arg_p (tree);
169 static bool any_template_arguments_need_structural_equality_p (tree);
170 static bool dependent_type_p_r (tree);
171 static tree tsubst (tree, tree, tsubst_flags_t, tree);
172 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
173 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
174 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
175
176 /* Make the current scope suitable for access checking when we are
177    processing T.  T can be FUNCTION_DECL for instantiated function
178    template, or VAR_DECL for static member variable (need by
179    instantiate_decl).  */
180
181 static void
182 push_access_scope (tree t)
183 {
184   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
185               || TREE_CODE (t) == VAR_DECL);
186
187   if (DECL_FRIEND_CONTEXT (t))
188     push_nested_class (DECL_FRIEND_CONTEXT (t));
189   else if (DECL_CLASS_SCOPE_P (t))
190     push_nested_class (DECL_CONTEXT (t));
191   else
192     push_to_top_level ();
193
194   if (TREE_CODE (t) == FUNCTION_DECL)
195     {
196       saved_access_scope = tree_cons
197         (NULL_TREE, current_function_decl, saved_access_scope);
198       current_function_decl = t;
199     }
200 }
201
202 /* Restore the scope set up by push_access_scope.  T is the node we
203    are processing.  */
204
205 static void
206 pop_access_scope (tree t)
207 {
208   if (TREE_CODE (t) == FUNCTION_DECL)
209     {
210       current_function_decl = TREE_VALUE (saved_access_scope);
211       saved_access_scope = TREE_CHAIN (saved_access_scope);
212     }
213
214   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
215     pop_nested_class ();
216   else
217     pop_from_top_level ();
218 }
219
220 /* Do any processing required when DECL (a member template
221    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
222    to DECL, unless it is a specialization, in which case the DECL
223    itself is returned.  */
224
225 tree
226 finish_member_template_decl (tree decl)
227 {
228   if (decl == error_mark_node)
229     return error_mark_node;
230
231   gcc_assert (DECL_P (decl));
232
233   if (TREE_CODE (decl) == TYPE_DECL)
234     {
235       tree type;
236
237       type = TREE_TYPE (decl);
238       if (IS_AGGR_TYPE (type)
239           && CLASSTYPE_TEMPLATE_INFO (type)
240           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
241         {
242           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
243           check_member_template (tmpl);
244           return tmpl;
245         }
246       return NULL_TREE;
247     }
248   else if (TREE_CODE (decl) == FIELD_DECL)
249     error ("data member %qD cannot be a member template", decl);
250   else if (DECL_TEMPLATE_INFO (decl))
251     {
252       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
253         {
254           check_member_template (DECL_TI_TEMPLATE (decl));
255           return DECL_TI_TEMPLATE (decl);
256         }
257       else
258         return decl;
259     }
260   else
261     error ("invalid member template declaration %qD", decl);
262
263   return error_mark_node;
264 }
265
266 /* Returns the template nesting level of the indicated class TYPE.
267
268    For example, in:
269      template <class T>
270      struct A
271      {
272        template <class U>
273        struct B {};
274      };
275
276    A<T>::B<U> has depth two, while A<T> has depth one.
277    Both A<T>::B<int> and A<int>::B<U> have depth one, if
278    they are instantiations, not specializations.
279
280    This function is guaranteed to return 0 if passed NULL_TREE so
281    that, for example, `template_class_depth (current_class_type)' is
282    always safe.  */
283
284 int
285 template_class_depth (tree type)
286 {
287   int depth;
288
289   for (depth = 0;
290        type && TREE_CODE (type) != NAMESPACE_DECL;
291        type = (TREE_CODE (type) == FUNCTION_DECL)
292          ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
293     {
294       if (TREE_CODE (type) != FUNCTION_DECL)
295         {
296           if (CLASSTYPE_TEMPLATE_INFO (type)
297               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type))
298               && uses_template_parms (CLASSTYPE_TI_ARGS (type)))
299             ++depth;
300         }
301       else
302         {
303           if (DECL_TEMPLATE_INFO (type)
304               && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (type))
305               && uses_template_parms (DECL_TI_ARGS (type)))
306             ++depth;
307         }
308     }
309
310   return depth;
311 }
312
313 /* Subroutine of maybe_begin_member_template_processing.
314    Returns true if processing DECL needs us to push template parms.  */
315
316 static bool
317 inline_needs_template_parms (tree decl)
318 {
319   if (! DECL_TEMPLATE_INFO (decl))
320     return false;
321
322   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
323           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
324 }
325
326 /* Subroutine of maybe_begin_member_template_processing.
327    Push the template parms in PARMS, starting from LEVELS steps into the
328    chain, and ending at the beginning, since template parms are listed
329    innermost first.  */
330
331 static void
332 push_inline_template_parms_recursive (tree parmlist, int levels)
333 {
334   tree parms = TREE_VALUE (parmlist);
335   int i;
336
337   if (levels > 1)
338     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
339
340   ++processing_template_decl;
341   current_template_parms
342     = tree_cons (size_int (processing_template_decl),
343                  parms, current_template_parms);
344   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
345
346   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
347                NULL);
348   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
349     {
350       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
351
352       if (parm == error_mark_node)
353         continue;
354
355       gcc_assert (DECL_P (parm));
356
357       switch (TREE_CODE (parm))
358         {
359         case TYPE_DECL:
360         case TEMPLATE_DECL:
361           pushdecl (parm);
362           break;
363
364         case PARM_DECL:
365           {
366             /* Make a CONST_DECL as is done in process_template_parm.
367                It is ugly that we recreate this here; the original
368                version built in process_template_parm is no longer
369                available.  */
370             tree decl = build_decl (CONST_DECL, DECL_NAME (parm),
371                                     TREE_TYPE (parm));
372             DECL_ARTIFICIAL (decl) = 1;
373             TREE_CONSTANT (decl) = 1;
374             TREE_INVARIANT (decl) = 1;
375             TREE_READONLY (decl) = 1;
376             DECL_INITIAL (decl) = DECL_INITIAL (parm);
377             SET_DECL_TEMPLATE_PARM_P (decl);
378             pushdecl (decl);
379           }
380           break;
381
382         default:
383           gcc_unreachable ();
384         }
385     }
386 }
387
388 /* Restore the template parameter context for a member template or
389    a friend template defined in a class definition.  */
390
391 void
392 maybe_begin_member_template_processing (tree decl)
393 {
394   tree parms;
395   int levels = 0;
396
397   if (inline_needs_template_parms (decl))
398     {
399       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
400       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
401
402       if (DECL_TEMPLATE_SPECIALIZATION (decl))
403         {
404           --levels;
405           parms = TREE_CHAIN (parms);
406         }
407
408       push_inline_template_parms_recursive (parms, levels);
409     }
410
411   /* Remember how many levels of template parameters we pushed so that
412      we can pop them later.  */
413   VEC_safe_push (int, heap, inline_parm_levels, levels);
414 }
415
416 /* Undo the effects of maybe_begin_member_template_processing.  */
417
418 void
419 maybe_end_member_template_processing (void)
420 {
421   int i;
422   int last;
423
424   if (VEC_length (int, inline_parm_levels) == 0)
425     return;
426
427   last = VEC_pop (int, inline_parm_levels);
428   for (i = 0; i < last; ++i)
429     {
430       --processing_template_decl;
431       current_template_parms = TREE_CHAIN (current_template_parms);
432       poplevel (0, 0, 0);
433     }
434 }
435
436 /* Return a new template argument vector which contains all of ARGS,
437    but has as its innermost set of arguments the EXTRA_ARGS.  */
438
439 static tree
440 add_to_template_args (tree args, tree extra_args)
441 {
442   tree new_args;
443   int extra_depth;
444   int i;
445   int j;
446
447   extra_depth = TMPL_ARGS_DEPTH (extra_args);
448   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
449
450   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
451     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
452
453   for (j = 1; j <= extra_depth; ++j, ++i)
454     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
455
456   return new_args;
457 }
458
459 /* Like add_to_template_args, but only the outermost ARGS are added to
460    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
461    (EXTRA_ARGS) levels are added.  This function is used to combine
462    the template arguments from a partial instantiation with the
463    template arguments used to attain the full instantiation from the
464    partial instantiation.  */
465
466 static tree
467 add_outermost_template_args (tree args, tree extra_args)
468 {
469   tree new_args;
470
471   /* If there are more levels of EXTRA_ARGS than there are ARGS,
472      something very fishy is going on.  */
473   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
474
475   /* If *all* the new arguments will be the EXTRA_ARGS, just return
476      them.  */
477   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
478     return extra_args;
479
480   /* For the moment, we make ARGS look like it contains fewer levels.  */
481   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
482
483   new_args = add_to_template_args (args, extra_args);
484
485   /* Now, we restore ARGS to its full dimensions.  */
486   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
487
488   return new_args;
489 }
490
491 /* Return the N levels of innermost template arguments from the ARGS.  */
492
493 tree
494 get_innermost_template_args (tree args, int n)
495 {
496   tree new_args;
497   int extra_levels;
498   int i;
499
500   gcc_assert (n >= 0);
501
502   /* If N is 1, just return the innermost set of template arguments.  */
503   if (n == 1)
504     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
505
506   /* If we're not removing anything, just return the arguments we were
507      given.  */
508   extra_levels = TMPL_ARGS_DEPTH (args) - n;
509   gcc_assert (extra_levels >= 0);
510   if (extra_levels == 0)
511     return args;
512
513   /* Make a new set of arguments, not containing the outer arguments.  */
514   new_args = make_tree_vec (n);
515   for (i = 1; i <= n; ++i)
516     SET_TMPL_ARGS_LEVEL (new_args, i,
517                          TMPL_ARGS_LEVEL (args, i + extra_levels));
518
519   return new_args;
520 }
521
522 /* We've got a template header coming up; push to a new level for storing
523    the parms.  */
524
525 void
526 begin_template_parm_list (void)
527 {
528   /* We use a non-tag-transparent scope here, which causes pushtag to
529      put tags in this scope, rather than in the enclosing class or
530      namespace scope.  This is the right thing, since we want
531      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
532      global template class, push_template_decl handles putting the
533      TEMPLATE_DECL into top-level scope.  For a nested template class,
534      e.g.:
535
536        template <class T> struct S1 {
537          template <class T> struct S2 {};
538        };
539
540      pushtag contains special code to call pushdecl_with_scope on the
541      TEMPLATE_DECL for S2.  */
542   begin_scope (sk_template_parms, NULL);
543   ++processing_template_decl;
544   ++processing_template_parmlist;
545   note_template_header (0);
546 }
547
548 /* This routine is called when a specialization is declared.  If it is
549    invalid to declare a specialization here, an error is reported and
550    false is returned, otherwise this routine will return true.  */
551
552 static bool
553 check_specialization_scope (void)
554 {
555   tree scope = current_scope ();
556
557   /* [temp.expl.spec]
558
559      An explicit specialization shall be declared in the namespace of
560      which the template is a member, or, for member templates, in the
561      namespace of which the enclosing class or enclosing class
562      template is a member.  An explicit specialization of a member
563      function, member class or static data member of a class template
564      shall be declared in the namespace of which the class template
565      is a member.  */
566   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
567     {
568       error ("explicit specialization in non-namespace scope %qD", scope);
569       return false;
570     }
571
572   /* [temp.expl.spec]
573
574      In an explicit specialization declaration for a member of a class
575      template or a member template that appears in namespace scope,
576      the member template and some of its enclosing class templates may
577      remain unspecialized, except that the declaration shall not
578      explicitly specialize a class member template if its enclosing
579      class templates are not explicitly specialized as well.  */
580   if (current_template_parms)
581     {
582       error ("enclosing class templates are not explicitly specialized");
583       return false;
584     }
585
586   return true;
587 }
588
589 /* We've just seen template <>.  */
590
591 bool
592 begin_specialization (void)
593 {
594   begin_scope (sk_template_spec, NULL);
595   note_template_header (1);
596   return check_specialization_scope ();
597 }
598
599 /* Called at then end of processing a declaration preceded by
600    template<>.  */
601
602 void
603 end_specialization (void)
604 {
605   finish_scope ();
606   reset_specialization ();
607 }
608
609 /* Any template <>'s that we have seen thus far are not referring to a
610    function specialization.  */
611
612 void
613 reset_specialization (void)
614 {
615   processing_specialization = 0;
616   template_header_count = 0;
617 }
618
619 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
620    it was of the form template <>.  */
621
622 static void
623 note_template_header (int specialization)
624 {
625   processing_specialization = specialization;
626   template_header_count++;
627 }
628
629 /* We're beginning an explicit instantiation.  */
630
631 void
632 begin_explicit_instantiation (void)
633 {
634   gcc_assert (!processing_explicit_instantiation);
635   processing_explicit_instantiation = true;
636 }
637
638
639 void
640 end_explicit_instantiation (void)
641 {
642   gcc_assert (processing_explicit_instantiation);
643   processing_explicit_instantiation = false;
644 }
645
646 /* An explicit specialization or partial specialization TMPL is being
647    declared.  Check that the namespace in which the specialization is
648    occurring is permissible.  Returns false iff it is invalid to
649    specialize TMPL in the current namespace.  */
650
651 static bool
652 check_specialization_namespace (tree tmpl)
653 {
654   tree tpl_ns = decl_namespace_context (tmpl);
655
656   /* [tmpl.expl.spec]
657
658      An explicit specialization shall be declared in the namespace of
659      which the template is a member, or, for member templates, in the
660      namespace of which the enclosing class or enclosing class
661      template is a member.  An explicit specialization of a member
662      function, member class or static data member of a class template
663      shall be declared in the namespace of which the class template is
664      a member.  */
665   if (is_associated_namespace (current_namespace, tpl_ns))
666     /* Same or super-using namespace.  */
667     return true;
668   else
669     {
670       pedwarn ("specialization of %qD in different namespace", tmpl);
671       pedwarn ("  from definition of %q+#D", tmpl);
672       return false;
673     }
674 }
675
676 /* SPEC is an explicit instantiation.  Check that it is valid to
677    perform this explicit instantiation in the current namespace.  */
678
679 static void
680 check_explicit_instantiation_namespace (tree spec)
681 {
682   tree ns;
683
684   /* DR 275: An explicit instantiation shall appear in an enclosing
685      namespace of its template.  */
686   ns = decl_namespace_context (spec);
687   if (!is_ancestor (current_namespace, ns))
688     pedwarn ("explicit instantiation of %qD in namespace %qD "
689              "(which does not enclose namespace %qD)",
690              spec, current_namespace, ns);
691 }
692
693 /* The TYPE is being declared.  If it is a template type, that means it
694    is a partial specialization.  Do appropriate error-checking.  */
695
696 tree
697 maybe_process_partial_specialization (tree type)
698 {
699   tree context;
700
701   if (type == error_mark_node)
702     return error_mark_node;
703
704   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
705     {
706       error ("name of class shadows template template parameter %qD",
707              TYPE_NAME (type));
708       return error_mark_node;
709     }
710
711   context = TYPE_CONTEXT (type);
712
713   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
714     {
715       /* This is for ordinary explicit specialization and partial
716          specialization of a template class such as:
717
718            template <> class C<int>;
719
720          or:
721
722            template <class T> class C<T*>;
723
724          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
725
726       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
727           && !COMPLETE_TYPE_P (type))
728         {
729           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
730           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
731           if (processing_template_decl)
732             push_template_decl (TYPE_MAIN_DECL (type));
733         }
734       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
735         error ("specialization of %qT after instantiation", type);
736     }
737   else if (CLASS_TYPE_P (type)
738            && !CLASSTYPE_USE_TEMPLATE (type)
739            && CLASSTYPE_TEMPLATE_INFO (type)
740            && context && CLASS_TYPE_P (context)
741            && CLASSTYPE_TEMPLATE_INFO (context))
742     {
743       /* This is for an explicit specialization of member class
744          template according to [temp.expl.spec/18]:
745
746            template <> template <class U> class C<int>::D;
747
748          The context `C<int>' must be an implicit instantiation.
749          Otherwise this is just a member class template declared
750          earlier like:
751
752            template <> class C<int> { template <class U> class D; };
753            template <> template <class U> class C<int>::D;
754
755          In the first case, `C<int>::D' is a specialization of `C<T>::D'
756          while in the second case, `C<int>::D' is a primary template
757          and `C<T>::D' may not exist.  */
758
759       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
760           && !COMPLETE_TYPE_P (type))
761         {
762           tree t;
763
764           if (current_namespace
765               != decl_namespace_context (CLASSTYPE_TI_TEMPLATE (type)))
766             {
767               pedwarn ("specializing %q#T in different namespace", type);
768               pedwarn ("  from definition of %q+#D",
769                        CLASSTYPE_TI_TEMPLATE (type));
770             }
771
772           /* Check for invalid specialization after instantiation:
773
774                template <> template <> class C<int>::D<int>;
775                template <> template <class U> class C<int>::D;  */
776
777           for (t = DECL_TEMPLATE_INSTANTIATIONS
778                  (most_general_template (CLASSTYPE_TI_TEMPLATE (type)));
779                t; t = TREE_CHAIN (t))
780             if (TREE_VALUE (t) != type
781                 && TYPE_CONTEXT (TREE_VALUE (t)) == context)
782               error ("specialization %qT after instantiation %qT",
783                      type, TREE_VALUE (t));
784
785           /* Mark TYPE as a specialization.  And as a result, we only
786              have one level of template argument for the innermost
787              class template.  */
788           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
789           CLASSTYPE_TI_ARGS (type)
790             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
791         }
792     }
793   else if (processing_specialization)
794     {
795       error ("explicit specialization of non-template %qT", type);
796       return error_mark_node;
797     }
798
799   return type;
800 }
801
802 /* Returns nonzero if we can optimize the retrieval of specializations
803    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
804    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
805
806 static inline bool
807 optimize_specialization_lookup_p (tree tmpl)
808 {
809   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
810           && DECL_CLASS_SCOPE_P (tmpl)
811           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
812              parameter.  */
813           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
814           /* The optimized lookup depends on the fact that the
815              template arguments for the member function template apply
816              purely to the containing class, which is not true if the
817              containing class is an explicit or partial
818              specialization.  */
819           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
820           && !DECL_MEMBER_TEMPLATE_P (tmpl)
821           && !DECL_CONV_FN_P (tmpl)
822           /* It is possible to have a template that is not a member
823              template and is not a member of a template class:
824
825              template <typename T>
826              struct S { friend A::f(); };
827
828              Here, the friend function is a template, but the context does
829              not have template information.  The optimized lookup relies
830              on having ARGS be the template arguments for both the class
831              and the function template.  */
832           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
833 }
834
835 /* Retrieve the specialization (in the sense of [temp.spec] - a
836    specialization is either an instantiation or an explicit
837    specialization) of TMPL for the given template ARGS.  If there is
838    no such specialization, return NULL_TREE.  The ARGS are a vector of
839    arguments, or a vector of vectors of arguments, in the case of
840    templates with more than one level of parameters.
841
842    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
843    then we search for a partial specialization matching ARGS.  This
844    parameter is ignored if TMPL is not a class template.  */
845
846 static tree
847 retrieve_specialization (tree tmpl, tree args,
848                          bool class_specializations_p)
849 {
850   if (args == error_mark_node)
851     return NULL_TREE;
852
853   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
854
855   /* There should be as many levels of arguments as there are
856      levels of parameters.  */
857   gcc_assert (TMPL_ARGS_DEPTH (args)
858               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
859
860   if (optimize_specialization_lookup_p (tmpl))
861     {
862       tree class_template;
863       tree class_specialization;
864       VEC(tree,gc) *methods;
865       tree fns;
866       int idx;
867
868       /* The template arguments actually apply to the containing
869          class.  Find the class specialization with those
870          arguments.  */
871       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
872       class_specialization
873         = retrieve_specialization (class_template, args,
874                                    /*class_specializations_p=*/false);
875       if (!class_specialization)
876         return NULL_TREE;
877       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
878          for the specialization.  */
879       idx = class_method_index_for_fn (class_specialization, tmpl);
880       if (idx == -1)
881         return NULL_TREE;
882       /* Iterate through the methods with the indicated name, looking
883          for the one that has an instance of TMPL.  */
884       methods = CLASSTYPE_METHOD_VEC (class_specialization);
885       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
886         {
887           tree fn = OVL_CURRENT (fns);
888           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl)
889             return fn;
890         }
891       return NULL_TREE;
892     }
893   else
894     {
895       tree *sp;
896       tree *head;
897
898       /* Class templates store their instantiations on the
899          DECL_TEMPLATE_INSTANTIATIONS list; other templates use the
900          DECL_TEMPLATE_SPECIALIZATIONS list.  */
901       if (!class_specializations_p
902           && TREE_CODE (DECL_TEMPLATE_RESULT (tmpl)) == TYPE_DECL)
903         sp = &DECL_TEMPLATE_INSTANTIATIONS (tmpl);
904       else
905         sp = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
906       head = sp;
907       /* Iterate through the list until we find a matching template.  */
908       while (*sp != NULL_TREE)
909         {
910           tree spec = *sp;
911
912           if (comp_template_args (TREE_PURPOSE (spec), args))
913             {
914               /* Use the move-to-front heuristic to speed up future
915                  searches.  */
916               if (spec != *head)
917                 {
918                   *sp = TREE_CHAIN (*sp);
919                   TREE_CHAIN (spec) = *head;
920                   *head = spec;
921                 }
922               return TREE_VALUE (spec);
923             }
924           sp = &TREE_CHAIN (spec);
925         }
926     }
927
928   return NULL_TREE;
929 }
930
931 /* Like retrieve_specialization, but for local declarations.  */
932
933 static tree
934 retrieve_local_specialization (tree tmpl)
935 {
936   tree spec = (tree) htab_find_with_hash (local_specializations, tmpl,
937                                           htab_hash_pointer (tmpl));
938   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
939 }
940
941 /* Returns nonzero iff DECL is a specialization of TMPL.  */
942
943 int
944 is_specialization_of (tree decl, tree tmpl)
945 {
946   tree t;
947
948   if (TREE_CODE (decl) == FUNCTION_DECL)
949     {
950       for (t = decl;
951            t != NULL_TREE;
952            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
953         if (t == tmpl)
954           return 1;
955     }
956   else
957     {
958       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
959
960       for (t = TREE_TYPE (decl);
961            t != NULL_TREE;
962            t = CLASSTYPE_USE_TEMPLATE (t)
963              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
964         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
965           return 1;
966     }
967
968   return 0;
969 }
970
971 /* Returns nonzero iff DECL is a specialization of friend declaration
972    FRIEND according to [temp.friend].  */
973
974 bool
975 is_specialization_of_friend (tree decl, tree friend)
976 {
977   bool need_template = true;
978   int template_depth;
979
980   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
981               || TREE_CODE (decl) == TYPE_DECL);
982
983   /* For [temp.friend/6] when FRIEND is an ordinary member function
984      of a template class, we want to check if DECL is a specialization
985      if this.  */
986   if (TREE_CODE (friend) == FUNCTION_DECL
987       && DECL_TEMPLATE_INFO (friend)
988       && !DECL_USE_TEMPLATE (friend))
989     {
990       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
991       friend = DECL_TI_TEMPLATE (friend);
992       need_template = false;
993     }
994   else if (TREE_CODE (friend) == TEMPLATE_DECL
995            && !PRIMARY_TEMPLATE_P (friend))
996     need_template = false;
997
998   /* There is nothing to do if this is not a template friend.  */
999   if (TREE_CODE (friend) != TEMPLATE_DECL)
1000     return false;
1001
1002   if (is_specialization_of (decl, friend))
1003     return true;
1004
1005   /* [temp.friend/6]
1006      A member of a class template may be declared to be a friend of a
1007      non-template class.  In this case, the corresponding member of
1008      every specialization of the class template is a friend of the
1009      class granting friendship.
1010
1011      For example, given a template friend declaration
1012
1013        template <class T> friend void A<T>::f();
1014
1015      the member function below is considered a friend
1016
1017        template <> struct A<int> {
1018          void f();
1019        };
1020
1021      For this type of template friend, TEMPLATE_DEPTH below will be
1022      nonzero.  To determine if DECL is a friend of FRIEND, we first
1023      check if the enclosing class is a specialization of another.  */
1024
1025   template_depth = template_class_depth (DECL_CONTEXT (friend));
1026   if (template_depth
1027       && DECL_CLASS_SCOPE_P (decl)
1028       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1029                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend))))
1030     {
1031       /* Next, we check the members themselves.  In order to handle
1032          a few tricky cases, such as when FRIEND's are
1033
1034            template <class T> friend void A<T>::g(T t);
1035            template <class T> template <T t> friend void A<T>::h();
1036
1037          and DECL's are
1038
1039            void A<int>::g(int);
1040            template <int> void A<int>::h();
1041
1042          we need to figure out ARGS, the template arguments from
1043          the context of DECL.  This is required for template substitution
1044          of `T' in the function parameter of `g' and template parameter
1045          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1046
1047       tree context = DECL_CONTEXT (decl);
1048       tree args = NULL_TREE;
1049       int current_depth = 0;
1050
1051       while (current_depth < template_depth)
1052         {
1053           if (CLASSTYPE_TEMPLATE_INFO (context))
1054             {
1055               if (current_depth == 0)
1056                 args = TYPE_TI_ARGS (context);
1057               else
1058                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1059               current_depth++;
1060             }
1061           context = TYPE_CONTEXT (context);
1062         }
1063
1064       if (TREE_CODE (decl) == FUNCTION_DECL)
1065         {
1066           bool is_template;
1067           tree friend_type;
1068           tree decl_type;
1069           tree friend_args_type;
1070           tree decl_args_type;
1071
1072           /* Make sure that both DECL and FRIEND are templates or
1073              non-templates.  */
1074           is_template = DECL_TEMPLATE_INFO (decl)
1075                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1076           if (need_template ^ is_template)
1077             return false;
1078           else if (is_template)
1079             {
1080               /* If both are templates, check template parameter list.  */
1081               tree friend_parms
1082                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend),
1083                                          args, tf_none);
1084               if (!comp_template_parms
1085                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1086                       friend_parms))
1087                 return false;
1088
1089               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1090             }
1091           else
1092             decl_type = TREE_TYPE (decl);
1093
1094           friend_type = tsubst_function_type (TREE_TYPE (friend), args,
1095                                               tf_none, NULL_TREE);
1096           if (friend_type == error_mark_node)
1097             return false;
1098
1099           /* Check if return types match.  */
1100           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1101             return false;
1102
1103           /* Check if function parameter types match, ignoring the
1104              `this' parameter.  */
1105           friend_args_type = TYPE_ARG_TYPES (friend_type);
1106           decl_args_type = TYPE_ARG_TYPES (decl_type);
1107           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend))
1108             friend_args_type = TREE_CHAIN (friend_args_type);
1109           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1110             decl_args_type = TREE_CHAIN (decl_args_type);
1111
1112           return compparms (decl_args_type, friend_args_type);
1113         }
1114       else
1115         {
1116           /* DECL is a TYPE_DECL */
1117           bool is_template;
1118           tree decl_type = TREE_TYPE (decl);
1119
1120           /* Make sure that both DECL and FRIEND are templates or
1121              non-templates.  */
1122           is_template
1123             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1124               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1125
1126           if (need_template ^ is_template)
1127             return false;
1128           else if (is_template)
1129             {
1130               tree friend_parms;
1131               /* If both are templates, check the name of the two
1132                  TEMPLATE_DECL's first because is_friend didn't.  */
1133               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1134                   != DECL_NAME (friend))
1135                 return false;
1136
1137               /* Now check template parameter list.  */
1138               friend_parms
1139                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend),
1140                                          args, tf_none);
1141               return comp_template_parms
1142                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1143                  friend_parms);
1144             }
1145           else
1146             return (DECL_NAME (decl)
1147                     == DECL_NAME (friend));
1148         }
1149     }
1150   return false;
1151 }
1152
1153 /* Register the specialization SPEC as a specialization of TMPL with
1154    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1155    is actually just a friend declaration.  Returns SPEC, or an
1156    equivalent prior declaration, if available.  */
1157
1158 static tree
1159 register_specialization (tree spec, tree tmpl, tree args, bool is_friend)
1160 {
1161   tree fn;
1162
1163   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
1164
1165   if (TREE_CODE (spec) == FUNCTION_DECL
1166       && uses_template_parms (DECL_TI_ARGS (spec)))
1167     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1168        register it; we want the corresponding TEMPLATE_DECL instead.
1169        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1170        the more obvious `uses_template_parms (spec)' to avoid problems
1171        with default function arguments.  In particular, given
1172        something like this:
1173
1174           template <class T> void f(T t1, T t = T())
1175
1176        the default argument expression is not substituted for in an
1177        instantiation unless and until it is actually needed.  */
1178     return spec;
1179
1180   fn = retrieve_specialization (tmpl, args,
1181                                 /*class_specializations_p=*/false);
1182   /* We can sometimes try to re-register a specialization that we've
1183      already got.  In particular, regenerate_decl_from_template calls
1184      duplicate_decls which will update the specialization list.  But,
1185      we'll still get called again here anyhow.  It's more convenient
1186      to simply allow this than to try to prevent it.  */
1187   if (fn == spec)
1188     return spec;
1189   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1190     {
1191       if (DECL_TEMPLATE_INSTANTIATION (fn))
1192         {
1193           if (TREE_USED (fn)
1194               || DECL_EXPLICIT_INSTANTIATION (fn))
1195             {
1196               error ("specialization of %qD after instantiation",
1197                      fn);
1198               return error_mark_node;
1199             }
1200           else
1201             {
1202               tree clone;
1203               /* This situation should occur only if the first
1204                  specialization is an implicit instantiation, the
1205                  second is an explicit specialization, and the
1206                  implicit instantiation has not yet been used.  That
1207                  situation can occur if we have implicitly
1208                  instantiated a member function and then specialized
1209                  it later.
1210
1211                  We can also wind up here if a friend declaration that
1212                  looked like an instantiation turns out to be a
1213                  specialization:
1214
1215                    template <class T> void foo(T);
1216                    class S { friend void foo<>(int) };
1217                    template <> void foo(int);
1218
1219                  We transform the existing DECL in place so that any
1220                  pointers to it become pointers to the updated
1221                  declaration.
1222
1223                  If there was a definition for the template, but not
1224                  for the specialization, we want this to look as if
1225                  there were no definition, and vice versa.  */
1226               DECL_INITIAL (fn) = NULL_TREE;
1227               duplicate_decls (spec, fn, is_friend);
1228               /* The call to duplicate_decls will have applied
1229                  [temp.expl.spec]:
1230
1231                    An explicit specialization of a function template
1232                    is inline only if it is explicitly declared to be,
1233                    and independently of whether its function template
1234                    is.
1235
1236                 to the primary function; now copy the inline bits to
1237                 the various clones.  */
1238               FOR_EACH_CLONE (clone, fn)
1239                 {
1240                   DECL_DECLARED_INLINE_P (clone)
1241                     = DECL_DECLARED_INLINE_P (fn);
1242                   DECL_INLINE (clone)
1243                     = DECL_INLINE (fn);
1244                 }
1245               check_specialization_namespace (fn);
1246
1247               return fn;
1248             }
1249         }
1250       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1251         {
1252           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1253             /* Dup decl failed, but this is a new definition. Set the
1254                line number so any errors match this new
1255                definition.  */
1256             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1257
1258           return fn;
1259         }
1260     }
1261
1262   /* A specialization must be declared in the same namespace as the
1263      template it is specializing.  */
1264   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1265       && !check_specialization_namespace (tmpl))
1266     DECL_CONTEXT (spec) = FROB_CONTEXT (decl_namespace_context (tmpl));
1267
1268   if (!optimize_specialization_lookup_p (tmpl))
1269     DECL_TEMPLATE_SPECIALIZATIONS (tmpl)
1270       = tree_cons (args, spec, DECL_TEMPLATE_SPECIALIZATIONS (tmpl));
1271
1272   return spec;
1273 }
1274
1275 /* Unregister the specialization SPEC as a specialization of TMPL.
1276    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1277    if the SPEC was listed as a specialization of TMPL.  */
1278
1279 bool
1280 reregister_specialization (tree spec, tree tmpl, tree new_spec)
1281 {
1282   tree* s;
1283
1284   for (s = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
1285        *s != NULL_TREE;
1286        s = &TREE_CHAIN (*s))
1287     if (TREE_VALUE (*s) == spec)
1288       {
1289         if (!new_spec)
1290           *s = TREE_CHAIN (*s);
1291         else
1292           TREE_VALUE (*s) = new_spec;
1293         return 1;
1294       }
1295
1296   return 0;
1297 }
1298
1299 /* Compare an entry in the local specializations hash table P1 (which
1300    is really a pointer to a TREE_LIST) with P2 (which is really a
1301    DECL).  */
1302
1303 static int
1304 eq_local_specializations (const void *p1, const void *p2)
1305 {
1306   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1307 }
1308
1309 /* Hash P1, an entry in the local specializations table.  */
1310
1311 static hashval_t
1312 hash_local_specialization (const void* p1)
1313 {
1314   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1315 }
1316
1317 /* Like register_specialization, but for local declarations.  We are
1318    registering SPEC, an instantiation of TMPL.  */
1319
1320 static void
1321 register_local_specialization (tree spec, tree tmpl)
1322 {
1323   void **slot;
1324
1325   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1326                                    htab_hash_pointer (tmpl), INSERT);
1327   *slot = build_tree_list (spec, tmpl);
1328 }
1329
1330 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1331    specialized class.  */
1332
1333 bool
1334 explicit_class_specialization_p (tree type)
1335 {
1336   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1337     return false;
1338   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1339 }
1340
1341 /* Print the list of candidate FNS in an error message.  */
1342
1343 void
1344 print_candidates (tree fns)
1345 {
1346   tree fn;
1347
1348   const char *str = "candidates are:";
1349
1350   for (fn = fns; fn != NULL_TREE; fn = TREE_CHAIN (fn))
1351     {
1352       tree f;
1353
1354       for (f = TREE_VALUE (fn); f; f = OVL_NEXT (f))
1355         error ("%s %+#D", str, OVL_CURRENT (f));
1356       str = "               ";
1357     }
1358 }
1359
1360 /* Returns the template (one of the functions given by TEMPLATE_ID)
1361    which can be specialized to match the indicated DECL with the
1362    explicit template args given in TEMPLATE_ID.  The DECL may be
1363    NULL_TREE if none is available.  In that case, the functions in
1364    TEMPLATE_ID are non-members.
1365
1366    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1367    specialization of a member template.
1368
1369    The TEMPLATE_COUNT is the number of references to qualifying
1370    template classes that appeared in the name of the function. See
1371    check_explicit_specialization for a more accurate description.
1372
1373    TSK indicates what kind of template declaration (if any) is being
1374    declared.  TSK_TEMPLATE indicates that the declaration given by
1375    DECL, though a FUNCTION_DECL, has template parameters, and is
1376    therefore a template function.
1377
1378    The template args (those explicitly specified and those deduced)
1379    are output in a newly created vector *TARGS_OUT.
1380
1381    If it is impossible to determine the result, an error message is
1382    issued.  The error_mark_node is returned to indicate failure.  */
1383
1384 static tree
1385 determine_specialization (tree template_id,
1386                           tree decl,
1387                           tree* targs_out,
1388                           int need_member_template,
1389                           int template_count,
1390                           tmpl_spec_kind tsk)
1391 {
1392   tree fns;
1393   tree targs;
1394   tree explicit_targs;
1395   tree candidates = NULL_TREE;
1396   /* A TREE_LIST of templates of which DECL may be a specialization.
1397      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1398      corresponding TREE_PURPOSE is the set of template arguments that,
1399      when used to instantiate the template, would produce a function
1400      with the signature of DECL.  */
1401   tree templates = NULL_TREE;
1402   int header_count;
1403   struct cp_binding_level *b;
1404
1405   *targs_out = NULL_TREE;
1406
1407   if (template_id == error_mark_node || decl == error_mark_node)
1408     return error_mark_node;
1409
1410   fns = TREE_OPERAND (template_id, 0);
1411   explicit_targs = TREE_OPERAND (template_id, 1);
1412
1413   if (fns == error_mark_node)
1414     return error_mark_node;
1415
1416   /* Check for baselinks.  */
1417   if (BASELINK_P (fns))
1418     fns = BASELINK_FUNCTIONS (fns);
1419
1420   if (!is_overloaded_fn (fns))
1421     {
1422       error ("%qD is not a function template", fns);
1423       return error_mark_node;
1424     }
1425
1426   /* Count the number of template headers specified for this
1427      specialization.  */
1428   header_count = 0;
1429   for (b = current_binding_level;
1430        b->kind == sk_template_parms;
1431        b = b->level_chain)
1432     ++header_count;
1433
1434   for (; fns; fns = OVL_NEXT (fns))
1435     {
1436       tree fn = OVL_CURRENT (fns);
1437
1438       if (TREE_CODE (fn) == TEMPLATE_DECL)
1439         {
1440           tree decl_arg_types;
1441           tree fn_arg_types;
1442
1443           /* In case of explicit specialization, we need to check if
1444              the number of template headers appearing in the specialization
1445              is correct. This is usually done in check_explicit_specialization,
1446              but the check done there cannot be exhaustive when specializing
1447              member functions. Consider the following code:
1448
1449              template <> void A<int>::f(int);
1450              template <> template <> void A<int>::f(int);
1451
1452              Assuming that A<int> is not itself an explicit specialization
1453              already, the first line specializes "f" which is a non-template
1454              member function, whilst the second line specializes "f" which
1455              is a template member function. So both lines are syntactically
1456              correct, and check_explicit_specialization does not reject
1457              them.
1458
1459              Here, we can do better, as we are matching the specialization
1460              against the declarations. We count the number of template
1461              headers, and we check if they match TEMPLATE_COUNT + 1
1462              (TEMPLATE_COUNT is the number of qualifying template classes,
1463              plus there must be another header for the member template
1464              itself).
1465
1466              Notice that if header_count is zero, this is not a
1467              specialization but rather a template instantiation, so there
1468              is no check we can perform here.  */
1469           if (header_count && header_count != template_count + 1)
1470             continue;
1471
1472           /* Check that the number of template arguments at the
1473              innermost level for DECL is the same as for FN.  */
1474           if (current_binding_level->kind == sk_template_parms
1475               && !current_binding_level->explicit_spec_p
1476               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1477                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1478                                       (current_template_parms))))
1479             continue;
1480
1481           /* DECL might be a specialization of FN.  */
1482           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1483           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1484
1485           /* For a non-static member function, we need to make sure
1486              that the const qualification is the same.  Since
1487              get_bindings does not try to merge the "this" parameter,
1488              we must do the comparison explicitly.  */
1489           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1490               && !same_type_p (TREE_VALUE (fn_arg_types),
1491                                TREE_VALUE (decl_arg_types)))
1492             continue;
1493
1494           /* Skip the "this" parameter and, for constructors of
1495              classes with virtual bases, the VTT parameter.  A
1496              full specialization of a constructor will have a VTT
1497              parameter, but a template never will.  */ 
1498           decl_arg_types 
1499             = skip_artificial_parms_for (decl, decl_arg_types);
1500           fn_arg_types 
1501             = skip_artificial_parms_for (fn, fn_arg_types);
1502
1503           /* Check that the number of function parameters matches.
1504              For example,
1505                template <class T> void f(int i = 0);
1506                template <> void f<int>();
1507              The specialization f<int> is invalid but is not caught
1508              by get_bindings below.  */
1509           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1510             continue;
1511
1512           /* Function templates cannot be specializations; there are
1513              no partial specializations of functions.  Therefore, if
1514              the type of DECL does not match FN, there is no
1515              match.  */
1516           if (tsk == tsk_template)
1517             {
1518               if (compparms (fn_arg_types, decl_arg_types))
1519                 candidates = tree_cons (NULL_TREE, fn, candidates);
1520               continue;
1521             }
1522
1523           /* See whether this function might be a specialization of this
1524              template.  */
1525           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1526
1527           if (!targs)
1528             /* We cannot deduce template arguments that when used to
1529                specialize TMPL will produce DECL.  */
1530             continue;
1531
1532           /* Save this template, and the arguments deduced.  */
1533           templates = tree_cons (targs, fn, templates);
1534         }
1535       else if (need_member_template)
1536         /* FN is an ordinary member function, and we need a
1537            specialization of a member template.  */
1538         ;
1539       else if (TREE_CODE (fn) != FUNCTION_DECL)
1540         /* We can get IDENTIFIER_NODEs here in certain erroneous
1541            cases.  */
1542         ;
1543       else if (!DECL_FUNCTION_MEMBER_P (fn))
1544         /* This is just an ordinary non-member function.  Nothing can
1545            be a specialization of that.  */
1546         ;
1547       else if (DECL_ARTIFICIAL (fn))
1548         /* Cannot specialize functions that are created implicitly.  */
1549         ;
1550       else
1551         {
1552           tree decl_arg_types;
1553
1554           /* This is an ordinary member function.  However, since
1555              we're here, we can assume it's enclosing class is a
1556              template class.  For example,
1557
1558                template <typename T> struct S { void f(); };
1559                template <> void S<int>::f() {}
1560
1561              Here, S<int>::f is a non-template, but S<int> is a
1562              template class.  If FN has the same type as DECL, we
1563              might be in business.  */
1564
1565           if (!DECL_TEMPLATE_INFO (fn))
1566             /* Its enclosing class is an explicit specialization
1567                of a template class.  This is not a candidate.  */
1568             continue;
1569
1570           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1571                             TREE_TYPE (TREE_TYPE (fn))))
1572             /* The return types differ.  */
1573             continue;
1574
1575           /* Adjust the type of DECL in case FN is a static member.  */
1576           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1577           if (DECL_STATIC_FUNCTION_P (fn)
1578               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1579             decl_arg_types = TREE_CHAIN (decl_arg_types);
1580
1581           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1582                          decl_arg_types))
1583             /* They match!  */
1584             candidates = tree_cons (NULL_TREE, fn, candidates);
1585         }
1586     }
1587
1588   if (templates && TREE_CHAIN (templates))
1589     {
1590       /* We have:
1591
1592            [temp.expl.spec]
1593
1594            It is possible for a specialization with a given function
1595            signature to be instantiated from more than one function
1596            template.  In such cases, explicit specification of the
1597            template arguments must be used to uniquely identify the
1598            function template specialization being specialized.
1599
1600          Note that here, there's no suggestion that we're supposed to
1601          determine which of the candidate templates is most
1602          specialized.  However, we, also have:
1603
1604            [temp.func.order]
1605
1606            Partial ordering of overloaded function template
1607            declarations is used in the following contexts to select
1608            the function template to which a function template
1609            specialization refers:
1610
1611            -- when an explicit specialization refers to a function
1612               template.
1613
1614          So, we do use the partial ordering rules, at least for now.
1615          This extension can only serve to make invalid programs valid,
1616          so it's safe.  And, there is strong anecdotal evidence that
1617          the committee intended the partial ordering rules to apply;
1618          the EDG front end has that behavior, and John Spicer claims
1619          that the committee simply forgot to delete the wording in
1620          [temp.expl.spec].  */
1621       tree tmpl = most_specialized_instantiation (templates);
1622       if (tmpl != error_mark_node)
1623         {
1624           templates = tmpl;
1625           TREE_CHAIN (templates) = NULL_TREE;
1626         }
1627     }
1628
1629   if (templates == NULL_TREE && candidates == NULL_TREE)
1630     {
1631       error ("template-id %qD for %q+D does not match any template "
1632              "declaration", template_id, decl);
1633       return error_mark_node;
1634     }
1635   else if ((templates && TREE_CHAIN (templates))
1636            || (candidates && TREE_CHAIN (candidates))
1637            || (templates && candidates))
1638     {
1639       error ("ambiguous template specialization %qD for %q+D",
1640              template_id, decl);
1641       chainon (candidates, templates);
1642       print_candidates (candidates);
1643       return error_mark_node;
1644     }
1645
1646   /* We have one, and exactly one, match.  */
1647   if (candidates)
1648     {
1649       tree fn = TREE_VALUE (candidates);
1650       /* DECL is a re-declaration of a template function.  */
1651       if (TREE_CODE (fn) == TEMPLATE_DECL)
1652         return fn;
1653       /* It was a specialization of an ordinary member function in a
1654          template class.  */
1655       *targs_out = copy_node (DECL_TI_ARGS (fn));
1656       return DECL_TI_TEMPLATE (fn);
1657     }
1658
1659   /* It was a specialization of a template.  */
1660   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
1661   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
1662     {
1663       *targs_out = copy_node (targs);
1664       SET_TMPL_ARGS_LEVEL (*targs_out,
1665                            TMPL_ARGS_DEPTH (*targs_out),
1666                            TREE_PURPOSE (templates));
1667     }
1668   else
1669     *targs_out = TREE_PURPOSE (templates);
1670   return TREE_VALUE (templates);
1671 }
1672
1673 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
1674    but with the default argument values filled in from those in the
1675    TMPL_TYPES.  */
1676
1677 static tree
1678 copy_default_args_to_explicit_spec_1 (tree spec_types,
1679                                       tree tmpl_types)
1680 {
1681   tree new_spec_types;
1682
1683   if (!spec_types)
1684     return NULL_TREE;
1685
1686   if (spec_types == void_list_node)
1687     return void_list_node;
1688
1689   /* Substitute into the rest of the list.  */
1690   new_spec_types =
1691     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
1692                                           TREE_CHAIN (tmpl_types));
1693
1694   /* Add the default argument for this parameter.  */
1695   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
1696                          TREE_VALUE (spec_types),
1697                          new_spec_types);
1698 }
1699
1700 /* DECL is an explicit specialization.  Replicate default arguments
1701    from the template it specializes.  (That way, code like:
1702
1703      template <class T> void f(T = 3);
1704      template <> void f(double);
1705      void g () { f (); }
1706
1707    works, as required.)  An alternative approach would be to look up
1708    the correct default arguments at the call-site, but this approach
1709    is consistent with how implicit instantiations are handled.  */
1710
1711 static void
1712 copy_default_args_to_explicit_spec (tree decl)
1713 {
1714   tree tmpl;
1715   tree spec_types;
1716   tree tmpl_types;
1717   tree new_spec_types;
1718   tree old_type;
1719   tree new_type;
1720   tree t;
1721   tree object_type = NULL_TREE;
1722   tree in_charge = NULL_TREE;
1723   tree vtt = NULL_TREE;
1724
1725   /* See if there's anything we need to do.  */
1726   tmpl = DECL_TI_TEMPLATE (decl);
1727   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
1728   for (t = tmpl_types; t; t = TREE_CHAIN (t))
1729     if (TREE_PURPOSE (t))
1730       break;
1731   if (!t)
1732     return;
1733
1734   old_type = TREE_TYPE (decl);
1735   spec_types = TYPE_ARG_TYPES (old_type);
1736
1737   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1738     {
1739       /* Remove the this pointer, but remember the object's type for
1740          CV quals.  */
1741       object_type = TREE_TYPE (TREE_VALUE (spec_types));
1742       spec_types = TREE_CHAIN (spec_types);
1743       tmpl_types = TREE_CHAIN (tmpl_types);
1744
1745       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
1746         {
1747           /* DECL may contain more parameters than TMPL due to the extra
1748              in-charge parameter in constructors and destructors.  */
1749           in_charge = spec_types;
1750           spec_types = TREE_CHAIN (spec_types);
1751         }
1752       if (DECL_HAS_VTT_PARM_P (decl))
1753         {
1754           vtt = spec_types;
1755           spec_types = TREE_CHAIN (spec_types);
1756         }
1757     }
1758
1759   /* Compute the merged default arguments.  */
1760   new_spec_types =
1761     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
1762
1763   /* Compute the new FUNCTION_TYPE.  */
1764   if (object_type)
1765     {
1766       if (vtt)
1767         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
1768                                          TREE_VALUE (vtt),
1769                                          new_spec_types);
1770
1771       if (in_charge)
1772         /* Put the in-charge parameter back.  */
1773         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
1774                                          TREE_VALUE (in_charge),
1775                                          new_spec_types);
1776
1777       new_type = build_method_type_directly (object_type,
1778                                              TREE_TYPE (old_type),
1779                                              new_spec_types);
1780     }
1781   else
1782     new_type = build_function_type (TREE_TYPE (old_type),
1783                                     new_spec_types);
1784   new_type = cp_build_type_attribute_variant (new_type,
1785                                               TYPE_ATTRIBUTES (old_type));
1786   new_type = build_exception_variant (new_type,
1787                                       TYPE_RAISES_EXCEPTIONS (old_type));
1788   TREE_TYPE (decl) = new_type;
1789 }
1790
1791 /* Check to see if the function just declared, as indicated in
1792    DECLARATOR, and in DECL, is a specialization of a function
1793    template.  We may also discover that the declaration is an explicit
1794    instantiation at this point.
1795
1796    Returns DECL, or an equivalent declaration that should be used
1797    instead if all goes well.  Issues an error message if something is
1798    amiss.  Returns error_mark_node if the error is not easily
1799    recoverable.
1800
1801    FLAGS is a bitmask consisting of the following flags:
1802
1803    2: The function has a definition.
1804    4: The function is a friend.
1805
1806    The TEMPLATE_COUNT is the number of references to qualifying
1807    template classes that appeared in the name of the function.  For
1808    example, in
1809
1810      template <class T> struct S { void f(); };
1811      void S<int>::f();
1812
1813    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
1814    classes are not counted in the TEMPLATE_COUNT, so that in
1815
1816      template <class T> struct S {};
1817      template <> struct S<int> { void f(); }
1818      template <> void S<int>::f();
1819
1820    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
1821    invalid; there should be no template <>.)
1822
1823    If the function is a specialization, it is marked as such via
1824    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
1825    is set up correctly, and it is added to the list of specializations
1826    for that template.  */
1827
1828 tree
1829 check_explicit_specialization (tree declarator,
1830                                tree decl,
1831                                int template_count,
1832                                int flags)
1833 {
1834   int have_def = flags & 2;
1835   int is_friend = flags & 4;
1836   int specialization = 0;
1837   int explicit_instantiation = 0;
1838   int member_specialization = 0;
1839   tree ctype = DECL_CLASS_CONTEXT (decl);
1840   tree dname = DECL_NAME (decl);
1841   tmpl_spec_kind tsk;
1842
1843   if (is_friend)
1844     {
1845       if (!processing_specialization)
1846         tsk = tsk_none;
1847       else
1848         tsk = tsk_excessive_parms;
1849     }
1850   else
1851     tsk = current_tmpl_spec_kind (template_count);
1852
1853   switch (tsk)
1854     {
1855     case tsk_none:
1856       if (processing_specialization)
1857         {
1858           specialization = 1;
1859           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1860         }
1861       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1862         {
1863           if (is_friend)
1864             /* This could be something like:
1865
1866                template <class T> void f(T);
1867                class S { friend void f<>(int); }  */
1868             specialization = 1;
1869           else
1870             {
1871               /* This case handles bogus declarations like template <>
1872                  template <class T> void f<int>(); */
1873
1874               error ("template-id %qD in declaration of primary template",
1875                      declarator);
1876               return decl;
1877             }
1878         }
1879       break;
1880
1881     case tsk_invalid_member_spec:
1882       /* The error has already been reported in
1883          check_specialization_scope.  */
1884       return error_mark_node;
1885
1886     case tsk_invalid_expl_inst:
1887       error ("template parameter list used in explicit instantiation");
1888
1889       /* Fall through.  */
1890
1891     case tsk_expl_inst:
1892       if (have_def)
1893         error ("definition provided for explicit instantiation");
1894
1895       explicit_instantiation = 1;
1896       break;
1897
1898     case tsk_excessive_parms:
1899     case tsk_insufficient_parms:
1900       if (tsk == tsk_excessive_parms)
1901         error ("too many template parameter lists in declaration of %qD",
1902                decl);
1903       else if (template_header_count)
1904         error("too few template parameter lists in declaration of %qD", decl);
1905       else
1906         error("explicit specialization of %qD must be introduced by "
1907               "%<template <>%>", decl);
1908
1909       /* Fall through.  */
1910     case tsk_expl_spec:
1911       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1912       if (ctype)
1913         member_specialization = 1;
1914       else
1915         specialization = 1;
1916       break;
1917
1918     case tsk_template:
1919       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1920         {
1921           /* This case handles bogus declarations like template <>
1922              template <class T> void f<int>(); */
1923
1924           if (uses_template_parms (declarator))
1925             error ("function template partial specialization %qD "
1926                    "is not allowed", declarator);
1927           else
1928             error ("template-id %qD in declaration of primary template",
1929                    declarator);
1930           return decl;
1931         }
1932
1933       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
1934         /* This is a specialization of a member template, without
1935            specialization the containing class.  Something like:
1936
1937              template <class T> struct S {
1938                template <class U> void f (U);
1939              };
1940              template <> template <class U> void S<int>::f(U) {}
1941
1942            That's a specialization -- but of the entire template.  */
1943         specialization = 1;
1944       break;
1945
1946     default:
1947       gcc_unreachable ();
1948     }
1949
1950   if (specialization || member_specialization)
1951     {
1952       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
1953       for (; t; t = TREE_CHAIN (t))
1954         if (TREE_PURPOSE (t))
1955           {
1956             pedwarn
1957               ("default argument specified in explicit specialization");
1958             break;
1959           }
1960     }
1961
1962   if (specialization || member_specialization || explicit_instantiation)
1963     {
1964       tree tmpl = NULL_TREE;
1965       tree targs = NULL_TREE;
1966
1967       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
1968       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
1969         {
1970           tree fns;
1971
1972           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
1973           if (ctype)
1974             fns = dname;
1975           else
1976             {
1977               /* If there is no class context, the explicit instantiation
1978                  must be at namespace scope.  */
1979               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
1980
1981               /* Find the namespace binding, using the declaration
1982                  context.  */
1983               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
1984                                            false, true);
1985               if (fns == error_mark_node || !is_overloaded_fn (fns))
1986                 {
1987                   error ("%qD is not a template function", dname);
1988                   fns = error_mark_node;
1989                 }
1990               else
1991                 {
1992                   tree fn = OVL_CURRENT (fns);
1993                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
1994                                                 CP_DECL_CONTEXT (fn)))
1995                     error ("%qD is not declared in %qD",
1996                            decl, current_namespace);
1997                 }
1998             }
1999
2000           declarator = lookup_template_function (fns, NULL_TREE);
2001         }
2002
2003       if (declarator == error_mark_node)
2004         return error_mark_node;
2005
2006       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2007         {
2008           if (!explicit_instantiation)
2009             /* A specialization in class scope.  This is invalid,
2010                but the error will already have been flagged by
2011                check_specialization_scope.  */
2012             return error_mark_node;
2013           else
2014             {
2015               /* It's not valid to write an explicit instantiation in
2016                  class scope, e.g.:
2017
2018                    class C { template void f(); }
2019
2020                    This case is caught by the parser.  However, on
2021                    something like:
2022
2023                    template class C { void f(); };
2024
2025                    (which is invalid) we can get here.  The error will be
2026                    issued later.  */
2027               ;
2028             }
2029
2030           return decl;
2031         }
2032       else if (ctype != NULL_TREE
2033                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2034                    IDENTIFIER_NODE))
2035         {
2036           /* Find the list of functions in ctype that have the same
2037              name as the declared function.  */
2038           tree name = TREE_OPERAND (declarator, 0);
2039           tree fns = NULL_TREE;
2040           int idx;
2041
2042           if (constructor_name_p (name, ctype))
2043             {
2044               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2045
2046               if (is_constructor ? !TYPE_HAS_CONSTRUCTOR (ctype)
2047                   : !CLASSTYPE_DESTRUCTORS (ctype))
2048                 {
2049                   /* From [temp.expl.spec]:
2050
2051                      If such an explicit specialization for the member
2052                      of a class template names an implicitly-declared
2053                      special member function (clause _special_), the
2054                      program is ill-formed.
2055
2056                      Similar language is found in [temp.explicit].  */
2057                   error ("specialization of implicitly-declared special member function");
2058                   return error_mark_node;
2059                 }
2060
2061               name = is_constructor ? ctor_identifier : dtor_identifier;
2062             }
2063
2064           if (!DECL_CONV_FN_P (decl))
2065             {
2066               idx = lookup_fnfields_1 (ctype, name);
2067               if (idx >= 0)
2068                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2069             }
2070           else
2071             {
2072               VEC(tree,gc) *methods;
2073               tree ovl;
2074
2075               /* For a type-conversion operator, we cannot do a
2076                  name-based lookup.  We might be looking for `operator
2077                  int' which will be a specialization of `operator T'.
2078                  So, we find *all* the conversion operators, and then
2079                  select from them.  */
2080               fns = NULL_TREE;
2081
2082               methods = CLASSTYPE_METHOD_VEC (ctype);
2083               if (methods)
2084                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2085                      VEC_iterate (tree, methods, idx, ovl);
2086                      ++idx)
2087                   {
2088                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2089                       /* There are no more conversion functions.  */
2090                       break;
2091
2092                     /* Glue all these conversion functions together
2093                        with those we already have.  */
2094                     for (; ovl; ovl = OVL_NEXT (ovl))
2095                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2096                   }
2097             }
2098
2099           if (fns == NULL_TREE)
2100             {
2101               error ("no member function %qD declared in %qT", name, ctype);
2102               return error_mark_node;
2103             }
2104           else
2105             TREE_OPERAND (declarator, 0) = fns;
2106         }
2107
2108       /* Figure out what exactly is being specialized at this point.
2109          Note that for an explicit instantiation, even one for a
2110          member function, we cannot tell apriori whether the
2111          instantiation is for a member template, or just a member
2112          function of a template class.  Even if a member template is
2113          being instantiated, the member template arguments may be
2114          elided if they can be deduced from the rest of the
2115          declaration.  */
2116       tmpl = determine_specialization (declarator, decl,
2117                                        &targs,
2118                                        member_specialization,
2119                                        template_count,
2120                                        tsk);
2121
2122       if (!tmpl || tmpl == error_mark_node)
2123         /* We couldn't figure out what this declaration was
2124            specializing.  */
2125         return error_mark_node;
2126       else
2127         {
2128           tree gen_tmpl = most_general_template (tmpl);
2129
2130           if (explicit_instantiation)
2131             {
2132               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2133                  is done by do_decl_instantiation later.  */
2134
2135               int arg_depth = TMPL_ARGS_DEPTH (targs);
2136               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2137
2138               if (arg_depth > parm_depth)
2139                 {
2140                   /* If TMPL is not the most general template (for
2141                      example, if TMPL is a friend template that is
2142                      injected into namespace scope), then there will
2143                      be too many levels of TARGS.  Remove some of them
2144                      here.  */
2145                   int i;
2146                   tree new_targs;
2147
2148                   new_targs = make_tree_vec (parm_depth);
2149                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2150                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2151                       = TREE_VEC_ELT (targs, i);
2152                   targs = new_targs;
2153                 }
2154
2155               return instantiate_template (tmpl, targs, tf_error);
2156             }
2157
2158           /* If we thought that the DECL was a member function, but it
2159              turns out to be specializing a static member function,
2160              make DECL a static member function as well.  */
2161           if (DECL_STATIC_FUNCTION_P (tmpl)
2162               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2163             revert_static_member_fn (decl);
2164
2165           /* If this is a specialization of a member template of a
2166              template class, we want to return the TEMPLATE_DECL, not
2167              the specialization of it.  */
2168           if (tsk == tsk_template)
2169             {
2170               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2171               DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl)) = NULL_TREE;
2172               if (have_def)
2173                 {
2174                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2175                   DECL_SOURCE_LOCATION (DECL_TEMPLATE_RESULT (tmpl))
2176                     = DECL_SOURCE_LOCATION (decl);
2177                   /* We want to use the argument list specified in the
2178                      definition, not in the original declaration.  */
2179                   DECL_ARGUMENTS (DECL_TEMPLATE_RESULT (tmpl))
2180                     = DECL_ARGUMENTS (decl);
2181                 }
2182               return tmpl;
2183             }
2184
2185           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2186           DECL_TEMPLATE_INFO (decl) = tree_cons (tmpl, targs, NULL_TREE);
2187
2188           /* Inherit default function arguments from the template
2189              DECL is specializing.  */
2190           copy_default_args_to_explicit_spec (decl);
2191
2192           /* This specialization has the same protection as the
2193              template it specializes.  */
2194           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2195           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2196
2197           /* 7.1.1-1 [dcl.stc]
2198
2199              A storage-class-specifier shall not be specified in an
2200              explicit specialization...
2201
2202              The parser rejects these, so unless action is taken here,
2203              explicit function specializations will always appear with
2204              global linkage.
2205
2206              The action recommended by the C++ CWG in response to C++
2207              defect report 605 is to make the storage class and linkage
2208              of the explicit specialization match the templated function:
2209
2210              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2211            */
2212           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2213             {
2214               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2215               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2216
2217               /* This specialization has the same linkage and visibility as
2218                  the function template it specializes.  */
2219               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2220               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2221               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2222                 {
2223                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2224                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2225                 }
2226             }
2227
2228           /* If DECL is a friend declaration, declared using an
2229              unqualified name, the namespace associated with DECL may
2230              have been set incorrectly.  For example, in:
2231
2232                template <typename T> void f(T);
2233                namespace N {
2234                  struct S { friend void f<int>(int); }
2235                }
2236
2237              we will have set the DECL_CONTEXT for the friend
2238              declaration to N, rather than to the global namespace.  */
2239           if (DECL_NAMESPACE_SCOPE_P (decl))
2240             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2241
2242           if (is_friend && !have_def)
2243             /* This is not really a declaration of a specialization.
2244                It's just the name of an instantiation.  But, it's not
2245                a request for an instantiation, either.  */
2246             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2247           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2248             /* This is indeed a specialization.  In case of constructors
2249                and destructors, we need in-charge and not-in-charge
2250                versions in V3 ABI.  */
2251             clone_function_decl (decl, /*update_method_vec_p=*/0);
2252
2253           /* Register this specialization so that we can find it
2254              again.  */
2255           decl = register_specialization (decl, gen_tmpl, targs, is_friend);
2256         }
2257     }
2258
2259   return decl;
2260 }
2261
2262 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2263    parameters.  These are represented in the same format used for
2264    DECL_TEMPLATE_PARMS.  */
2265
2266 int
2267 comp_template_parms (const_tree parms1, const_tree parms2)
2268 {
2269   const_tree p1;
2270   const_tree p2;
2271
2272   if (parms1 == parms2)
2273     return 1;
2274
2275   for (p1 = parms1, p2 = parms2;
2276        p1 != NULL_TREE && p2 != NULL_TREE;
2277        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2278     {
2279       tree t1 = TREE_VALUE (p1);
2280       tree t2 = TREE_VALUE (p2);
2281       int i;
2282
2283       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2284       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2285
2286       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2287         return 0;
2288
2289       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2290         {
2291           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2292           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2293
2294           /* If either of the template parameters are invalid, assume
2295              they match for the sake of error recovery. */
2296           if (parm1 == error_mark_node || parm2 == error_mark_node)
2297             return 1;
2298
2299           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2300             return 0;
2301
2302           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2303               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2304                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2305             continue;
2306           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2307             return 0;
2308         }
2309     }
2310
2311   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2312     /* One set of parameters has more parameters lists than the
2313        other.  */
2314     return 0;
2315
2316   return 1;
2317 }
2318
2319 /* Determine whether PARM is a parameter pack.  */
2320 bool 
2321 template_parameter_pack_p (const_tree parm)
2322 {
2323   /* Determine if we have a non-type template parameter pack.  */
2324   if (TREE_CODE (parm) == PARM_DECL)
2325     return (DECL_TEMPLATE_PARM_P (parm) 
2326             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2327
2328   /* If this is a list of template parameters, we could get a
2329      TYPE_DECL or a TEMPLATE_DECL.  */ 
2330   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2331     parm = TREE_TYPE (parm);
2332
2333   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2334            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2335           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2336 }
2337
2338 /* Determine whether ARGS describes a variadic template args list,
2339    i.e., one that is terminated by a template argument pack.  */
2340 static bool 
2341 template_args_variadic_p (tree args)
2342 {
2343   int nargs;
2344   tree last_parm;
2345
2346   if (args == NULL_TREE)
2347     return false;
2348
2349   args = INNERMOST_TEMPLATE_ARGS (args);
2350   nargs = TREE_VEC_LENGTH (args);
2351
2352   if (nargs == 0)
2353     return false;
2354
2355   last_parm = TREE_VEC_ELT (args, nargs - 1);
2356
2357   return ARGUMENT_PACK_P (last_parm);
2358 }
2359
2360 /* Generate a new name for the parameter pack name NAME (an
2361    IDENTIFIER_NODE) that incorporates its */
2362 static tree
2363 make_ith_pack_parameter_name (tree name, int i)
2364 {
2365   /* Munge the name to include the parameter index.  */
2366   char numbuf[128];
2367   char* newname;
2368   
2369   sprintf(numbuf, "%i", i);
2370   newname = (char*)alloca (IDENTIFIER_LENGTH (name) + strlen(numbuf) + 2);
2371   sprintf(newname, "%s#%i", IDENTIFIER_POINTER (name), i);
2372   return get_identifier (newname);
2373 }
2374
2375 /* Structure used to track the progress of find_parameter_pack_r.  */
2376 struct find_parameter_pack_data 
2377 {
2378   tree* parameter_packs;
2379   struct pointer_set_t *visited;
2380 };
2381
2382 /* Identifiers all of the argument packs that occur in a template
2383    argument and appends them to the TREE_LIST inside DATA, which is a
2384    find_parameter_pack_Data structure. This is a subroutine of
2385    make_pack_expansion and uses_parameter_packs.  */
2386 static tree
2387 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2388 {
2389   tree t = *tp;
2390   struct find_parameter_pack_data* ppd = 
2391     (struct find_parameter_pack_data*)data;
2392
2393   if (TYPE_P (t))
2394     {
2395       tree context = TYPE_CONTEXT (t);
2396       cp_walk_tree (&context, &find_parameter_packs_r, ppd, ppd->visited);
2397     }
2398
2399   /* This switch statement will return immediately if we don't find a
2400      parameter pack.  */
2401   switch (TREE_CODE (t)) 
2402     {
2403     case TEMPLATE_PARM_INDEX:
2404       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2405         break;
2406       return NULL_TREE;
2407
2408     case BOUND_TEMPLATE_TEMPLATE_PARM:
2409       /* Check the template arguments.  */
2410       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2411                     ppd->visited);
2412
2413       /* Dig out the underlying TEMPLATE_TEMPLATE_PARM.  */
2414       t = TYPE_TI_TEMPLATE (t);
2415       if (DECL_P (t) && TREE_TYPE (t))
2416         t = TREE_TYPE (t);
2417       *walk_subtrees = 0;
2418       
2419       /* Fall through.  */
2420
2421     case TEMPLATE_TYPE_PARM:
2422     case TEMPLATE_TEMPLATE_PARM:
2423       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2424         break;
2425       return NULL_TREE;
2426
2427     case PARM_DECL:
2428       if (FUNCTION_PARAMETER_PACK_P (t))
2429         {
2430           /* We don't want to walk into the type of a PARM_DECL,
2431              because we don't want to see the type parameter pack.*/
2432           *walk_subtrees = 0;
2433           break;
2434         }
2435       return NULL_TREE;
2436
2437     case RECORD_TYPE:
2438       if (TYPE_PTRMEMFUNC_P (t))
2439         return NULL_TREE;
2440       /* Fall through.  */
2441
2442     case UNION_TYPE:
2443     case ENUMERAL_TYPE:
2444       if (TYPE_TEMPLATE_INFO (t))
2445         {
2446           tree args = TREE_VALUE (TYPE_TEMPLATE_INFO (t));
2447           cp_walk_tree (&args, &find_parameter_packs_r, ppd, ppd->visited);
2448         }
2449
2450       *walk_subtrees = 0;
2451       return NULL_TREE;
2452
2453     case TEMPLATE_DECL:
2454       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
2455           && TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (t)))
2456         break;
2457       
2458       *walk_subtrees = 0;
2459       return NULL_TREE;
2460        
2461     case TYPE_PACK_EXPANSION:
2462     case EXPR_PACK_EXPANSION:
2463       *walk_subtrees = 0;
2464       return NULL_TREE;
2465
2466     case INTEGER_TYPE:
2467       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
2468                     ppd, ppd->visited);
2469       *walk_subtrees = 0;
2470       return NULL_TREE;
2471
2472     default:
2473       return NULL_TREE;
2474     }
2475   
2476   /* Add this parameter pack to the list.  */
2477   *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2478
2479   return NULL_TREE;
2480 }
2481
2482 /* Determines if the expression or type T uses any parameter packs.  */
2483 bool
2484 uses_parameter_packs (tree t)
2485 {
2486   tree parameter_packs = NULL_TREE;
2487   struct find_parameter_pack_data ppd;
2488   ppd.parameter_packs = &parameter_packs;
2489   ppd.visited = pointer_set_create ();
2490   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2491   pointer_set_destroy (ppd.visited);
2492   return parameter_packs != NULL_TREE;
2493 }
2494
2495 /* Turn ARG, which may be an expression, type, or a TREE_LIST
2496    representation a base-class initializer into a parameter pack
2497    expansion. If all goes well, the resulting node will be an
2498    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
2499    respectively.  */
2500 tree 
2501 make_pack_expansion (tree arg)
2502 {
2503   tree result;
2504   tree parameter_packs = NULL_TREE;
2505   bool for_types = false;
2506   struct find_parameter_pack_data ppd;
2507
2508   if (!arg || arg == error_mark_node)
2509     return arg;
2510
2511   if (TREE_CODE (arg) == TREE_LIST)
2512     {
2513       /* The only time we will see a TREE_LIST here is for a base
2514          class initializer.  In this case, the TREE_PURPOSE will be a
2515          _TYPE node (representing the base class expansion we're
2516          initializing) and the TREE_VALUE will be a TREE_LIST
2517          containing the initialization arguments. 
2518
2519          The resulting expansion looks somewhat different from most
2520          expansions. Rather than returning just one _EXPANSION, we
2521          return a TREE_LIST whose TREE_PURPOSE is a
2522          TYPE_PACK_EXPANSION containing the bases that will be
2523          initialized.  The TREE_VALUE will be identical to the
2524          original TREE_VALUE, which is a list of arguments that will
2525          be passed to each base.  We do not introduce any new pack
2526          expansion nodes into the TREE_VALUE (although it is possible
2527          that some already exist), because the TREE_PURPOSE and
2528          TREE_VALUE all need to be expanded together with the same
2529          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
2530          resulting TREE_PURPOSE will mention the parameter packs in
2531          both the bases and the arguments to the bases.  */
2532       tree purpose;
2533       tree value;
2534       tree parameter_packs = NULL_TREE;
2535
2536       /* Determine which parameter packs will be used by the base
2537          class expansion.  */
2538       ppd.visited = pointer_set_create ();
2539       ppd.parameter_packs = &parameter_packs;
2540       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
2541                     &ppd, ppd.visited);
2542
2543       if (parameter_packs == NULL_TREE)
2544         {
2545           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
2546           pointer_set_destroy (ppd.visited);
2547           return error_mark_node;
2548         }
2549
2550       if (TREE_VALUE (arg) != void_type_node)
2551         {
2552           /* Collect the sets of parameter packs used in each of the
2553              initialization arguments.  */
2554           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
2555             {
2556               /* Determine which parameter packs will be expanded in this
2557                  argument.  */
2558               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
2559                             &ppd, ppd.visited);
2560             }
2561         }
2562
2563       pointer_set_destroy (ppd.visited);
2564
2565       /* Create the pack expansion type for the base type.  */
2566       purpose = make_node (TYPE_PACK_EXPANSION);
2567       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
2568       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
2569
2570       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2571          they will rarely be compared to anything.  */
2572       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
2573
2574       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
2575     }
2576
2577   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
2578     for_types = true;
2579
2580   /* Build the PACK_EXPANSION_* node.  */
2581   result = make_node (for_types ? TYPE_PACK_EXPANSION : EXPR_PACK_EXPANSION);
2582   SET_PACK_EXPANSION_PATTERN (result, arg);
2583   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
2584     {
2585       /* Propagate type and const-expression information.  */
2586       TREE_TYPE (result) = TREE_TYPE (arg);
2587       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
2588     }
2589   else
2590     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2591        they will rarely be compared to anything.  */
2592     SET_TYPE_STRUCTURAL_EQUALITY (result);
2593
2594   /* Determine which parameter packs will be expanded.  */
2595   ppd.parameter_packs = &parameter_packs;
2596   ppd.visited = pointer_set_create ();
2597   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
2598   pointer_set_destroy (ppd.visited);
2599
2600   /* Make sure we found some parameter packs.  */
2601   if (parameter_packs == NULL_TREE)
2602     {
2603       if (TYPE_P (arg))
2604         error ("expansion pattern %<%T%> contains no argument packs", arg);
2605       else
2606         error ("expansion pattern %<%E%> contains no argument packs", arg);
2607       return error_mark_node;
2608     }
2609   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
2610
2611   return result;
2612 }
2613
2614 /* Checks T for any "bare" parameter packs, which have not yet been
2615    expanded, and issues an error if any are found. This operation can
2616    only be done on full expressions or types (e.g., an expression
2617    statement, "if" condition, etc.), because we could have expressions like:
2618
2619      foo(f(g(h(args)))...)
2620
2621    where "args" is a parameter pack. check_for_bare_parameter_packs
2622    should not be called for the subexpressions args, h(args),
2623    g(h(args)), or f(g(h(args))), because we would produce erroneous
2624    error messages. 
2625
2626    Returns TRUE if there were no bare parameter packs, returns FALSE
2627    (and emits an error) if there were bare parameter packs.*/
2628 bool 
2629 check_for_bare_parameter_packs (tree t)
2630 {
2631   tree parameter_packs = NULL_TREE;
2632   struct find_parameter_pack_data ppd;
2633
2634   if (!processing_template_decl || !t || t == error_mark_node)
2635     return true;
2636
2637   if (TREE_CODE (t) == TYPE_DECL)
2638     t = TREE_TYPE (t);
2639
2640   ppd.parameter_packs = &parameter_packs;
2641   ppd.visited = pointer_set_create ();
2642   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2643   pointer_set_destroy (ppd.visited);
2644
2645   if (parameter_packs) 
2646     {
2647       error ("parameter packs not expanded with `...':");
2648       while (parameter_packs)
2649         {
2650           tree pack = TREE_VALUE (parameter_packs);
2651           tree name = NULL_TREE;
2652
2653           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
2654               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
2655             name = TYPE_NAME (pack);
2656           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
2657             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
2658           else
2659             name = DECL_NAME (pack);
2660           inform ("        %qD", name);
2661
2662           parameter_packs = TREE_CHAIN (parameter_packs);
2663         }
2664
2665       return false;
2666     }
2667
2668   return true;
2669 }
2670
2671 /* Expand any parameter packs that occur in the template arguments in
2672    ARGS.  */
2673 tree
2674 expand_template_argument_pack (tree args)
2675 {
2676   tree result_args = NULL_TREE;
2677   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
2678   int num_result_args = -1;
2679
2680   /* First, determine if we need to expand anything, and the number of
2681      slots we'll need.  */
2682   for (in_arg = 0; in_arg < nargs; ++in_arg)
2683     {
2684       tree arg = TREE_VEC_ELT (args, in_arg);
2685       if (ARGUMENT_PACK_P (arg))
2686         {
2687           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
2688           if (num_result_args < 0)
2689             num_result_args = in_arg + num_packed;
2690           else
2691             num_result_args += num_packed;
2692         }
2693       else
2694         {
2695           if (num_result_args >= 0)
2696             num_result_args++;
2697         }
2698     }
2699
2700   /* If no expansion is necessary, we're done.  */
2701   if (num_result_args < 0)
2702     return args;
2703
2704   /* Expand arguments.  */
2705   result_args = make_tree_vec (num_result_args);
2706   for (in_arg = 0; in_arg < nargs; ++in_arg)
2707     {
2708       tree arg = TREE_VEC_ELT (args, in_arg);
2709       if (ARGUMENT_PACK_P (arg))
2710         {
2711           tree packed = ARGUMENT_PACK_ARGS (arg);
2712           int i, num_packed = TREE_VEC_LENGTH (packed);
2713           for (i = 0; i < num_packed; ++i, ++out_arg)
2714             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
2715         }
2716       else
2717         {
2718           TREE_VEC_ELT (result_args, out_arg) = arg;
2719           ++out_arg;
2720         }
2721     }
2722
2723   return result_args;
2724 }
2725
2726 /* Complain if DECL shadows a template parameter.
2727
2728    [temp.local]: A template-parameter shall not be redeclared within its
2729    scope (including nested scopes).  */
2730
2731 void
2732 check_template_shadow (tree decl)
2733 {
2734   tree olddecl;
2735
2736   /* If we're not in a template, we can't possibly shadow a template
2737      parameter.  */
2738   if (!current_template_parms)
2739     return;
2740
2741   /* Figure out what we're shadowing.  */
2742   if (TREE_CODE (decl) == OVERLOAD)
2743     decl = OVL_CURRENT (decl);
2744   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
2745
2746   /* If there's no previous binding for this name, we're not shadowing
2747      anything, let alone a template parameter.  */
2748   if (!olddecl)
2749     return;
2750
2751   /* If we're not shadowing a template parameter, we're done.  Note
2752      that OLDDECL might be an OVERLOAD (or perhaps even an
2753      ERROR_MARK), so we can't just blithely assume it to be a _DECL
2754      node.  */
2755   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
2756     return;
2757
2758   /* We check for decl != olddecl to avoid bogus errors for using a
2759      name inside a class.  We check TPFI to avoid duplicate errors for
2760      inline member templates.  */
2761   if (decl == olddecl
2762       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
2763     return;
2764
2765   error ("declaration of %q+#D", decl);
2766   error (" shadows template parm %q+#D", olddecl);
2767 }
2768
2769 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
2770    ORIG_LEVEL, DECL, and TYPE.  */
2771
2772 static tree
2773 build_template_parm_index (int index,
2774                            int level,
2775                            int orig_level,
2776                            tree decl,
2777                            tree type)
2778 {
2779   tree t = make_node (TEMPLATE_PARM_INDEX);
2780   TEMPLATE_PARM_IDX (t) = index;
2781   TEMPLATE_PARM_LEVEL (t) = level;
2782   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
2783   TEMPLATE_PARM_DECL (t) = decl;
2784   TREE_TYPE (t) = type;
2785   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
2786   TREE_INVARIANT (t) = TREE_INVARIANT (decl);
2787   TREE_READONLY (t) = TREE_READONLY (decl);
2788
2789   return t;
2790 }
2791
2792 /* Find the canonical type parameter for the given template type
2793    parameter.  Returns the canonical type parameter, which may be TYPE
2794    if no such parameter existed.  */
2795 static tree
2796 canonical_type_parameter (tree type)
2797 {
2798   tree list;
2799   int idx = TEMPLATE_TYPE_IDX (type);
2800   if (!canonical_template_parms)
2801     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
2802
2803   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
2804     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
2805
2806   list = VEC_index (tree, canonical_template_parms, idx);
2807   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
2808     list = TREE_CHAIN (list);
2809
2810   if (list)
2811     return TREE_VALUE (list);
2812   else
2813     {
2814       VEC_replace(tree, canonical_template_parms, idx,
2815                   tree_cons (NULL_TREE, type, 
2816                              VEC_index (tree, canonical_template_parms, idx)));
2817       return type;
2818     }
2819 }
2820
2821 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
2822    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
2823    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
2824    new one is created.  */
2825
2826 static tree
2827 reduce_template_parm_level (tree index, tree type, int levels)
2828 {
2829   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
2830       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
2831           != TEMPLATE_PARM_LEVEL (index) - levels))
2832     {
2833       tree orig_decl = TEMPLATE_PARM_DECL (index);
2834       tree decl, t;
2835
2836       decl = build_decl (TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
2837       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
2838       TREE_INVARIANT (decl) = TREE_INVARIANT (orig_decl);
2839       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
2840       DECL_ARTIFICIAL (decl) = 1;
2841       SET_DECL_TEMPLATE_PARM_P (decl);
2842
2843       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
2844                                      TEMPLATE_PARM_LEVEL (index) - levels,
2845                                      TEMPLATE_PARM_ORIG_LEVEL (index),
2846                                      decl, type);
2847       TEMPLATE_PARM_DESCENDANTS (index) = t;
2848       TEMPLATE_PARM_PARAMETER_PACK (t) 
2849         = TEMPLATE_PARM_PARAMETER_PACK (index);
2850
2851         /* Template template parameters need this.  */
2852       if (TREE_CODE (decl) != CONST_DECL)
2853         DECL_TEMPLATE_PARMS (decl)
2854           = DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index));
2855     }
2856
2857   return TEMPLATE_PARM_DESCENDANTS (index);
2858 }
2859
2860 /* Process information from new template parameter PARM and append it to the
2861    LIST being built.  This new parameter is a non-type parameter iff
2862    IS_NON_TYPE is true. This new parameter is a parameter
2863    pack iff IS_PARAMETER_PACK is true.  */
2864
2865 tree
2866 process_template_parm (tree list, tree parm, bool is_non_type, 
2867                        bool is_parameter_pack)
2868 {
2869   tree decl = 0;
2870   tree defval;
2871   tree err_parm_list;
2872   int idx = 0;
2873
2874   gcc_assert (TREE_CODE (parm) == TREE_LIST);
2875   defval = TREE_PURPOSE (parm);
2876
2877   if (list)
2878     {
2879       tree p = tree_last (list);
2880
2881       if (p && TREE_VALUE (p) != error_mark_node)
2882         {
2883           p = TREE_VALUE (p);
2884           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
2885             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
2886           else
2887             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
2888         }
2889
2890       ++idx;
2891     }
2892   else
2893     idx = 0;
2894
2895   if (is_non_type)
2896     {
2897       parm = TREE_VALUE (parm);
2898
2899       SET_DECL_TEMPLATE_PARM_P (parm);
2900
2901       if (TREE_TYPE (parm) == error_mark_node)
2902         {
2903           err_parm_list = build_tree_list (defval, parm);
2904           TREE_VALUE (err_parm_list) = error_mark_node;
2905            return chainon (list, err_parm_list);
2906         }
2907       else
2908       {
2909         /* [temp.param]
2910
2911            The top-level cv-qualifiers on the template-parameter are
2912            ignored when determining its type.  */
2913         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
2914         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
2915           {
2916             err_parm_list = build_tree_list (defval, parm);
2917             TREE_VALUE (err_parm_list) = error_mark_node;
2918              return chainon (list, err_parm_list);
2919           }
2920
2921         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
2922           {
2923             /* This template parameter is not a parameter pack, but it
2924                should be. Complain about "bare" parameter packs.  */
2925             check_for_bare_parameter_packs (TREE_TYPE (parm));
2926             
2927             /* Recover by calling this a parameter pack.  */
2928             is_parameter_pack = true;
2929           }
2930       }
2931
2932       /* A template parameter is not modifiable.  */
2933       TREE_CONSTANT (parm) = 1;
2934       TREE_INVARIANT (parm) = 1;
2935       TREE_READONLY (parm) = 1;
2936       decl = build_decl (CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
2937       TREE_CONSTANT (decl) = 1;
2938       TREE_INVARIANT (decl) = 1;
2939       TREE_READONLY (decl) = 1;
2940       DECL_INITIAL (parm) = DECL_INITIAL (decl)
2941         = build_template_parm_index (idx, processing_template_decl,
2942                                      processing_template_decl,
2943                                      decl, TREE_TYPE (parm));
2944
2945       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
2946         = is_parameter_pack;
2947     }
2948   else
2949     {
2950       tree t;
2951       parm = TREE_VALUE (TREE_VALUE (parm));
2952
2953       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
2954         {
2955           t = make_aggr_type (TEMPLATE_TEMPLATE_PARM);
2956           /* This is for distinguishing between real templates and template
2957              template parameters */
2958           TREE_TYPE (parm) = t;
2959           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
2960           decl = parm;
2961         }
2962       else
2963         {
2964           t = make_aggr_type (TEMPLATE_TYPE_PARM);
2965           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
2966           decl = build_decl (TYPE_DECL, parm, t);
2967         }
2968
2969       TYPE_NAME (t) = decl;
2970       TYPE_STUB_DECL (t) = decl;
2971       parm = decl;
2972       TEMPLATE_TYPE_PARM_INDEX (t)
2973         = build_template_parm_index (idx, processing_template_decl,
2974                                      processing_template_decl,
2975                                      decl, TREE_TYPE (parm));
2976       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
2977       TYPE_CANONICAL (t) = canonical_type_parameter (t);
2978     }
2979   DECL_ARTIFICIAL (decl) = 1;
2980   SET_DECL_TEMPLATE_PARM_P (decl);
2981   pushdecl (decl);
2982   parm = build_tree_list (defval, parm);
2983   return chainon (list, parm);
2984 }
2985
2986 /* The end of a template parameter list has been reached.  Process the
2987    tree list into a parameter vector, converting each parameter into a more
2988    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
2989    as PARM_DECLs.  */
2990
2991 tree
2992 end_template_parm_list (tree parms)
2993 {
2994   int nparms;
2995   tree parm, next;
2996   tree saved_parmlist = make_tree_vec (list_length (parms));
2997
2998   current_template_parms
2999     = tree_cons (size_int (processing_template_decl),
3000                  saved_parmlist, current_template_parms);
3001
3002   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3003     {
3004       next = TREE_CHAIN (parm);
3005       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3006       TREE_CHAIN (parm) = NULL_TREE;
3007     }
3008
3009   --processing_template_parmlist;
3010
3011   return saved_parmlist;
3012 }
3013
3014 /* end_template_decl is called after a template declaration is seen.  */
3015
3016 void
3017 end_template_decl (void)
3018 {
3019   reset_specialization ();
3020
3021   if (! processing_template_decl)
3022     return;
3023
3024   /* This matches the pushlevel in begin_template_parm_list.  */
3025   finish_scope ();
3026
3027   --processing_template_decl;
3028   current_template_parms = TREE_CHAIN (current_template_parms);
3029 }
3030
3031 /* Within the declaration of a template, return all levels of template
3032    parameters that apply.  The template parameters are represented as
3033    a TREE_VEC, in the form documented in cp-tree.h for template
3034    arguments.  */
3035
3036 static tree
3037 current_template_args (void)
3038 {
3039   tree header;
3040   tree args = NULL_TREE;
3041   int length = TMPL_PARMS_DEPTH (current_template_parms);
3042   int l = length;
3043
3044   /* If there is only one level of template parameters, we do not
3045      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3046      TREE_VEC containing the arguments.  */
3047   if (length > 1)
3048     args = make_tree_vec (length);
3049
3050   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3051     {
3052       tree a = copy_node (TREE_VALUE (header));
3053       int i;
3054
3055       TREE_TYPE (a) = NULL_TREE;
3056       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3057         {
3058           tree t = TREE_VEC_ELT (a, i);
3059
3060           /* T will be a list if we are called from within a
3061              begin/end_template_parm_list pair, but a vector directly
3062              if within a begin/end_member_template_processing pair.  */
3063           if (TREE_CODE (t) == TREE_LIST)
3064             {
3065               t = TREE_VALUE (t);
3066
3067               if (t != error_mark_node)
3068                 {
3069                   if (TREE_CODE (t) == TYPE_DECL
3070                       || TREE_CODE (t) == TEMPLATE_DECL)
3071                     {
3072                       t = TREE_TYPE (t);
3073                       
3074                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3075                         {
3076                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3077                              with a single element, which expands T.  */
3078                           tree vec = make_tree_vec (1);
3079                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3080                           
3081                           t = make_node (TYPE_ARGUMENT_PACK);
3082                           SET_ARGUMENT_PACK_ARGS (t, vec);
3083                         }
3084                     }
3085                   else
3086                     {
3087                       t = DECL_INITIAL (t);
3088                       
3089                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3090                         {
3091                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3092                              with a single element, which expands T.  */
3093                           tree vec = make_tree_vec (1);
3094                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3095                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3096                           
3097                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3098                           SET_ARGUMENT_PACK_ARGS (t, vec);
3099                           TREE_TYPE (t) = type;
3100                         }
3101                     }
3102                 }
3103               TREE_VEC_ELT (a, i) = t;
3104             }
3105         }
3106
3107       if (length > 1)
3108         TREE_VEC_ELT (args, --l) = a;
3109       else
3110         args = a;
3111     }
3112
3113   return args;
3114 }
3115
3116 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3117    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3118    a member template.  Used by push_template_decl below.  */
3119
3120 static tree
3121 build_template_decl (tree decl, tree parms, bool member_template_p)
3122 {
3123   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3124   DECL_TEMPLATE_PARMS (tmpl) = parms;
3125   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3126   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3127   if (DECL_LANG_SPECIFIC (decl))
3128     {
3129       DECL_STATIC_FUNCTION_P (tmpl) = DECL_STATIC_FUNCTION_P (decl);
3130       DECL_CONSTRUCTOR_P (tmpl) = DECL_CONSTRUCTOR_P (decl);
3131       DECL_DESTRUCTOR_P (tmpl) = DECL_DESTRUCTOR_P (decl);
3132       DECL_NONCONVERTING_P (tmpl) = DECL_NONCONVERTING_P (decl);
3133       DECL_ASSIGNMENT_OPERATOR_P (tmpl) = DECL_ASSIGNMENT_OPERATOR_P (decl);
3134       if (DECL_OVERLOADED_OPERATOR_P (decl))
3135         SET_OVERLOADED_OPERATOR_CODE (tmpl,
3136                                       DECL_OVERLOADED_OPERATOR_P (decl));
3137     }
3138
3139   return tmpl;
3140 }
3141
3142 struct template_parm_data
3143 {
3144   /* The level of the template parameters we are currently
3145      processing.  */
3146   int level;
3147
3148   /* The index of the specialization argument we are currently
3149      processing.  */
3150   int current_arg;
3151
3152   /* An array whose size is the number of template parameters.  The
3153      elements are nonzero if the parameter has been used in any one
3154      of the arguments processed so far.  */
3155   int* parms;
3156
3157   /* An array whose size is the number of template arguments.  The
3158      elements are nonzero if the argument makes use of template
3159      parameters of this level.  */
3160   int* arg_uses_template_parms;
3161 };
3162
3163 /* Subroutine of push_template_decl used to see if each template
3164    parameter in a partial specialization is used in the explicit
3165    argument list.  If T is of the LEVEL given in DATA (which is
3166    treated as a template_parm_data*), then DATA->PARMS is marked
3167    appropriately.  */
3168
3169 static int
3170 mark_template_parm (tree t, void* data)
3171 {
3172   int level;
3173   int idx;
3174   struct template_parm_data* tpd = (struct template_parm_data*) data;
3175
3176   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3177     {
3178       level = TEMPLATE_PARM_LEVEL (t);
3179       idx = TEMPLATE_PARM_IDX (t);
3180     }
3181   else
3182     {
3183       level = TEMPLATE_TYPE_LEVEL (t);
3184       idx = TEMPLATE_TYPE_IDX (t);
3185     }
3186
3187   if (level == tpd->level)
3188     {
3189       tpd->parms[idx] = 1;
3190       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3191     }
3192
3193   /* Return zero so that for_each_template_parm will continue the
3194      traversal of the tree; we want to mark *every* template parm.  */
3195   return 0;
3196 }
3197
3198 /* Process the partial specialization DECL.  */
3199
3200 static tree
3201 process_partial_specialization (tree decl)
3202 {
3203   tree type = TREE_TYPE (decl);
3204   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3205   tree specargs = CLASSTYPE_TI_ARGS (type);
3206   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3207   tree inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3208   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3209   int nargs = TREE_VEC_LENGTH (inner_args);
3210   int ntparms = TREE_VEC_LENGTH (inner_parms);
3211   int  i;
3212   int did_error_intro = 0;
3213   struct template_parm_data tpd;
3214   struct template_parm_data tpd2;
3215
3216   /* We check that each of the template parameters given in the
3217      partial specialization is used in the argument list to the
3218      specialization.  For example:
3219
3220        template <class T> struct S;
3221        template <class T> struct S<T*>;
3222
3223      The second declaration is OK because `T*' uses the template
3224      parameter T, whereas
3225
3226        template <class T> struct S<int>;
3227
3228      is no good.  Even trickier is:
3229
3230        template <class T>
3231        struct S1
3232        {
3233           template <class U>
3234           struct S2;
3235           template <class U>
3236           struct S2<T>;
3237        };
3238
3239      The S2<T> declaration is actually invalid; it is a
3240      full-specialization.  Of course,
3241
3242           template <class U>
3243           struct S2<T (*)(U)>;
3244
3245      or some such would have been OK.  */
3246   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3247   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3248   memset (tpd.parms, 0, sizeof (int) * ntparms);
3249
3250   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3251   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3252   for (i = 0; i < nargs; ++i)
3253     {
3254       tpd.current_arg = i;
3255       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3256                               &mark_template_parm,
3257                               &tpd,
3258                               NULL);
3259     }
3260   for (i = 0; i < ntparms; ++i)
3261     if (tpd.parms[i] == 0)
3262       {
3263         /* One of the template parms was not used in the
3264            specialization.  */
3265         if (!did_error_intro)
3266           {
3267             error ("template parameters not used in partial specialization:");
3268             did_error_intro = 1;
3269           }
3270
3271         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3272       }
3273
3274   /* [temp.class.spec]
3275
3276      The argument list of the specialization shall not be identical to
3277      the implicit argument list of the primary template.  */
3278   if (comp_template_args
3279       (inner_args,
3280        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3281                                                    (maintmpl)))))
3282     error ("partial specialization %qT does not specialize any template arguments", type);
3283
3284   /* [temp.class.spec]
3285
3286      A partially specialized non-type argument expression shall not
3287      involve template parameters of the partial specialization except
3288      when the argument expression is a simple identifier.
3289
3290      The type of a template parameter corresponding to a specialized
3291      non-type argument shall not be dependent on a parameter of the
3292      specialization. 
3293
3294      Also, we verify that pack expansions only occur at the
3295      end of the argument list.  */
3296   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3297   tpd2.parms = 0;
3298   for (i = 0; i < nargs; ++i)
3299     {
3300       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3301       tree arg = TREE_VEC_ELT (inner_args, i);
3302       tree packed_args = NULL_TREE;
3303       int j, len = 1;
3304
3305       if (ARGUMENT_PACK_P (arg))
3306         {
3307           /* Extract the arguments from the argument pack. We'll be
3308              iterating over these in the following loop.  */
3309           packed_args = ARGUMENT_PACK_ARGS (arg);
3310           len = TREE_VEC_LENGTH (packed_args);
3311         }
3312
3313       for (j = 0; j < len; j++)
3314         {
3315           if (packed_args)
3316             /* Get the Jth argument in the parameter pack.  */
3317             arg = TREE_VEC_ELT (packed_args, j);
3318
3319           if (PACK_EXPANSION_P (arg))
3320             {
3321               /* Pack expansions must come at the end of the
3322                  argument list.  */
3323               if ((packed_args && j < len - 1)
3324                   || (!packed_args && i < nargs - 1))
3325                 {
3326                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3327                     error ("parameter pack argument %qE must be at the end of the template argument list", arg);
3328                   else
3329                     error ("parameter pack argument %qT must be at the end of the template argument list", arg);                   
3330                 }
3331             }
3332
3333           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3334             /* We only care about the pattern.  */
3335             arg = PACK_EXPANSION_PATTERN (arg);
3336
3337           if (/* These first two lines are the `non-type' bit.  */
3338               !TYPE_P (arg)
3339               && TREE_CODE (arg) != TEMPLATE_DECL
3340               /* This next line is the `argument expression is not just a
3341                  simple identifier' condition and also the `specialized
3342                  non-type argument' bit.  */
3343               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3344             {
3345               if ((!packed_args && tpd.arg_uses_template_parms[i])
3346                   || (packed_args && uses_template_parms (arg)))
3347                 error ("template argument %qE involves template parameter(s)",
3348                        arg);
3349               else 
3350                 {
3351                   /* Look at the corresponding template parameter,
3352                      marking which template parameters its type depends
3353                      upon.  */
3354                   tree type = TREE_TYPE (parm);
3355
3356                   if (!tpd2.parms)
3357                     {
3358                       /* We haven't yet initialized TPD2.  Do so now.  */
3359                       tpd2.arg_uses_template_parms 
3360                         = (int *) alloca (sizeof (int) * nargs);
3361                       /* The number of parameters here is the number in the
3362                          main template, which, as checked in the assertion
3363                          above, is NARGS.  */
3364                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3365                       tpd2.level = 
3366                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3367                     }
3368
3369                   /* Mark the template parameters.  But this time, we're
3370                      looking for the template parameters of the main
3371                      template, not in the specialization.  */
3372                   tpd2.current_arg = i;
3373                   tpd2.arg_uses_template_parms[i] = 0;
3374                   memset (tpd2.parms, 0, sizeof (int) * nargs);
3375                   for_each_template_parm (type,
3376                                           &mark_template_parm,
3377                                           &tpd2,
3378                                           NULL);
3379
3380                   if (tpd2.arg_uses_template_parms [i])
3381                     {
3382                       /* The type depended on some template parameters.
3383                          If they are fully specialized in the
3384                          specialization, that's OK.  */
3385                       int j;
3386                       for (j = 0; j < nargs; ++j)
3387                         if (tpd2.parms[j] != 0
3388                             && tpd.arg_uses_template_parms [j])
3389                           {
3390                             error ("type %qT of template argument %qE depends "
3391                                    "on template parameter(s)", 
3392                                    type,
3393                                    arg);
3394                             break;
3395                           }
3396                     }
3397                 }
3398             }
3399         }
3400     }
3401
3402   if (retrieve_specialization (maintmpl, specargs,
3403                                /*class_specializations_p=*/true))
3404     /* We've already got this specialization.  */
3405     return decl;
3406
3407   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
3408     = tree_cons (specargs, inner_parms,
3409                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
3410   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
3411   return decl;
3412 }
3413
3414 /* Check that a template declaration's use of default arguments is not
3415    invalid.  Here, PARMS are the template parameters.  IS_PRIMARY is
3416    nonzero if DECL is the thing declared by a primary template.
3417    IS_PARTIAL is nonzero if DECL is a partial specialization.
3418    
3419
3420    IS_FRIEND_DECL is nonzero if DECL is a friend function template
3421    declaration (but not a definition); 1 indicates a declaration, 2
3422    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
3423    emitted for extraneous default arguments.
3424
3425    Returns TRUE if there were no errors found, FALSE otherwise. */
3426
3427 bool
3428 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
3429                          int is_partial, int is_friend_decl)
3430 {
3431   const char *msg;
3432   int last_level_to_check;
3433   tree parm_level;
3434   bool no_errors = true;
3435
3436   /* [temp.param]
3437
3438      A default template-argument shall not be specified in a
3439      function template declaration or a function template definition, nor
3440      in the template-parameter-list of the definition of a member of a
3441      class template.  */
3442
3443   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
3444     /* You can't have a function template declaration in a local
3445        scope, nor you can you define a member of a class template in a
3446        local scope.  */
3447     return true;
3448
3449   if (current_class_type
3450       && !TYPE_BEING_DEFINED (current_class_type)
3451       && DECL_LANG_SPECIFIC (decl)
3452       /* If this is either a friend defined in the scope of the class
3453          or a member function.  */
3454       && (DECL_FUNCTION_MEMBER_P (decl)
3455           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
3456           : DECL_FRIEND_CONTEXT (decl)
3457           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
3458           : false)
3459       /* And, if it was a member function, it really was defined in
3460          the scope of the class.  */
3461       && (!DECL_FUNCTION_MEMBER_P (decl)
3462           || DECL_INITIALIZED_IN_CLASS_P (decl)))
3463     /* We already checked these parameters when the template was
3464        declared, so there's no need to do it again now.  This function
3465        was defined in class scope, but we're processing it's body now
3466        that the class is complete.  */
3467     return true;
3468
3469   /* Core issue 226 (C++0x only): the following only applies to class
3470      templates.  */
3471   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
3472     {
3473       /* [temp.param]
3474
3475          If a template-parameter has a default template-argument, all
3476          subsequent template-parameters shall have a default
3477          template-argument supplied.  */
3478       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
3479         {
3480           tree inner_parms = TREE_VALUE (parm_level);
3481           int ntparms = TREE_VEC_LENGTH (inner_parms);
3482           int seen_def_arg_p = 0;
3483           int i;
3484
3485           for (i = 0; i < ntparms; ++i)
3486             {
3487               tree parm = TREE_VEC_ELT (inner_parms, i);
3488
3489               if (parm == error_mark_node)
3490                 continue;
3491
3492               if (TREE_PURPOSE (parm))
3493                 seen_def_arg_p = 1;
3494               else if (seen_def_arg_p)
3495                 {
3496                   error ("no default argument for %qD", TREE_VALUE (parm));
3497                   /* For better subsequent error-recovery, we indicate that
3498                      there should have been a default argument.  */
3499                   TREE_PURPOSE (parm) = error_mark_node;
3500                   no_errors = false;
3501                 }
3502             }
3503         }
3504     }
3505
3506   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
3507       || is_partial 
3508       || !is_primary
3509       || is_friend_decl)
3510     /* For an ordinary class template, default template arguments are
3511        allowed at the innermost level, e.g.:
3512          template <class T = int>
3513          struct S {};
3514        but, in a partial specialization, they're not allowed even
3515        there, as we have in [temp.class.spec]:
3516
3517          The template parameter list of a specialization shall not
3518          contain default template argument values.
3519
3520        So, for a partial specialization, or for a function template
3521        (in C++98/C++03), we look at all of them.  */
3522     ;
3523   else
3524     /* But, for a primary class template that is not a partial
3525        specialization we look at all template parameters except the
3526        innermost ones.  */
3527     parms = TREE_CHAIN (parms);
3528
3529   /* Figure out what error message to issue.  */
3530   if (is_friend_decl == 2)
3531     msg = "default template arguments may not be used in function template friend re-declaration";
3532   else if (is_friend_decl)
3533     msg = "default template arguments may not be used in function template friend declarations";
3534   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
3535     msg = "default template arguments may not be used in function templates";
3536   else if (is_partial)
3537     msg = "default template arguments may not be used in partial specializations";
3538   else
3539     msg = "default argument for template parameter for class enclosing %qD";
3540
3541   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
3542     /* If we're inside a class definition, there's no need to
3543        examine the parameters to the class itself.  On the one
3544        hand, they will be checked when the class is defined, and,
3545        on the other, default arguments are valid in things like:
3546          template <class T = double>
3547          struct S { template <class U> void f(U); };
3548        Here the default argument for `S' has no bearing on the
3549        declaration of `f'.  */
3550     last_level_to_check = template_class_depth (current_class_type) + 1;
3551   else
3552     /* Check everything.  */
3553     last_level_to_check = 0;
3554
3555   for (parm_level = parms;
3556        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
3557        parm_level = TREE_CHAIN (parm_level))
3558     {
3559       tree inner_parms = TREE_VALUE (parm_level);
3560       int i;
3561       int ntparms;
3562
3563       ntparms = TREE_VEC_LENGTH (inner_parms);
3564       for (i = 0; i < ntparms; ++i)
3565         {
3566           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
3567             continue;
3568
3569           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
3570             {
3571               if (msg)
3572                 {
3573                   no_errors = false;
3574                   if (is_friend_decl == 2)
3575                     return no_errors;
3576
3577                   error (msg, decl);
3578                   msg = 0;
3579                 }
3580
3581               /* Clear out the default argument so that we are not
3582                  confused later.  */
3583               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
3584             }
3585         }
3586
3587       /* At this point, if we're still interested in issuing messages,
3588          they must apply to classes surrounding the object declared.  */
3589       if (msg)
3590         msg = "default argument for template parameter for class enclosing %qD";
3591     }
3592
3593   return no_errors;
3594 }
3595
3596 /* Worker for push_template_decl_real, called via
3597    for_each_template_parm.  DATA is really an int, indicating the
3598    level of the parameters we are interested in.  If T is a template
3599    parameter of that level, return nonzero.  */
3600
3601 static int
3602 template_parm_this_level_p (tree t, void* data)
3603 {
3604   int this_level = *(int *)data;
3605   int level;
3606
3607   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3608     level = TEMPLATE_PARM_LEVEL (t);
3609   else
3610     level = TEMPLATE_TYPE_LEVEL (t);
3611   return level == this_level;
3612 }
3613
3614 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
3615    parameters given by current_template_args, or reuses a
3616    previously existing one, if appropriate.  Returns the DECL, or an
3617    equivalent one, if it is replaced via a call to duplicate_decls.
3618
3619    If IS_FRIEND is true, DECL is a friend declaration.  */
3620
3621 tree
3622 push_template_decl_real (tree decl, bool is_friend)
3623 {
3624   tree tmpl;
3625   tree args;
3626   tree info;
3627   tree ctx;
3628   int primary;
3629   int is_partial;
3630   int new_template_p = 0;
3631   /* True if the template is a member template, in the sense of
3632      [temp.mem].  */
3633   bool member_template_p = false;
3634
3635   if (decl == error_mark_node)
3636     return decl;
3637
3638   /* See if this is a partial specialization.  */
3639   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
3640                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
3641                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
3642
3643   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
3644     is_friend = true;
3645
3646   if (is_friend)
3647     /* For a friend, we want the context of the friend function, not
3648        the type of which it is a friend.  */
3649     ctx = DECL_CONTEXT (decl);
3650   else if (CP_DECL_CONTEXT (decl)
3651            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
3652     /* In the case of a virtual function, we want the class in which
3653        it is defined.  */
3654     ctx = CP_DECL_CONTEXT (decl);
3655   else
3656     /* Otherwise, if we're currently defining some class, the DECL
3657        is assumed to be a member of the class.  */
3658     ctx = current_scope ();
3659
3660   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
3661     ctx = NULL_TREE;
3662
3663   if (!DECL_CONTEXT (decl))
3664     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
3665
3666   /* See if this is a primary template.  */
3667   if (is_friend && ctx)
3668     /* A friend template that specifies a class context, i.e.
3669          template <typename T> friend void A<T>::f();
3670        is not primary.  */
3671     primary = 0;
3672   else
3673     primary = template_parm_scope_p ();
3674
3675   if (primary)
3676     {
3677       if (DECL_CLASS_SCOPE_P (decl))
3678         member_template_p = true;
3679       if (TREE_CODE (decl) == TYPE_DECL
3680           && ANON_AGGRNAME_P (DECL_NAME (decl)))
3681         error ("template class without a name");
3682       else if (TREE_CODE (decl) == FUNCTION_DECL)
3683         {
3684           if (DECL_DESTRUCTOR_P (decl))
3685             {
3686               /* [temp.mem]
3687
3688                  A destructor shall not be a member template.  */
3689               error ("destructor %qD declared as member template", decl);
3690               return error_mark_node;
3691             }
3692           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
3693               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
3694                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
3695                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
3696                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
3697                       == void_list_node)))
3698             {
3699               /* [basic.stc.dynamic.allocation]
3700
3701                  An allocation function can be a function
3702                  template. ... Template allocation functions shall
3703                  have two or more parameters.  */
3704               error ("invalid template declaration of %qD", decl);
3705               return error_mark_node;
3706             }
3707         }
3708       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3709                && CLASS_TYPE_P (TREE_TYPE (decl)))
3710         /* OK */;
3711       else
3712         {
3713           error ("template declaration of %q#D", decl);
3714           return error_mark_node;
3715         }
3716     }
3717
3718   /* Check to see that the rules regarding the use of default
3719      arguments are not being violated.  */
3720   check_default_tmpl_args (decl, current_template_parms,
3721                            primary, is_partial, /*is_friend_decl=*/0);
3722
3723   /* Ensure that there are no parameter packs in the type of this
3724      declaration that have not been expanded.  */
3725   if (TREE_CODE (decl) == FUNCTION_DECL)
3726     {
3727       /* Check each of the arguments individually to see if there are
3728          any bare parameter packs.  */
3729       tree type = TREE_TYPE (decl);
3730       tree arg = DECL_ARGUMENTS (decl);
3731       tree argtype = TYPE_ARG_TYPES (type);
3732
3733       while (arg && argtype)
3734         {
3735           if (!FUNCTION_PARAMETER_PACK_P (arg)
3736               && !check_for_bare_parameter_packs (TREE_TYPE (arg)))
3737             {
3738             /* This is a PARM_DECL that contains unexpanded parameter
3739                packs. We have already complained about this in the
3740                check_for_bare_parameter_packs call, so just replace
3741                these types with ERROR_MARK_NODE.  */
3742               TREE_TYPE (arg) = error_mark_node;
3743               TREE_VALUE (argtype) = error_mark_node;
3744             }
3745
3746           arg = TREE_CHAIN (arg);
3747           argtype = TREE_CHAIN (argtype);
3748         }
3749
3750       /* Check for bare parameter packs in the return type and the
3751          exception specifiers.  */
3752       check_for_bare_parameter_packs (TREE_TYPE (type));
3753       check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type));
3754     }
3755   else
3756     check_for_bare_parameter_packs (TREE_TYPE (decl));
3757
3758   if (is_partial)
3759     return process_partial_specialization (decl);
3760
3761   /* A primary class template can only have one parameter pack, at the
3762      end of the template parameter list.  */
3763   if (primary && TREE_CODE (decl) == TYPE_DECL)
3764     {
3765       tree inner_parms 
3766         = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3767       int i, len = TREE_VEC_LENGTH (inner_parms);
3768       for (i = 0; i < len - 1; i++)
3769         {
3770           tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
3771
3772           if (template_parameter_pack_p (parm))
3773             {
3774               if (TREE_CODE (parm) == PARM_DECL)
3775                 error ("parameter pack %qE must be at the end of the"
3776                        " template parameter list", parm);
3777               else
3778                 error ("parameter pack %qT must be at the end of the"
3779                        " template parameter list", TREE_TYPE (parm));
3780             }
3781         }
3782     }
3783
3784   args = current_template_args ();
3785
3786   if (!ctx
3787       || TREE_CODE (ctx) == FUNCTION_DECL
3788       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
3789       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
3790     {
3791       if (DECL_LANG_SPECIFIC (decl)
3792           && DECL_TEMPLATE_INFO (decl)
3793           && DECL_TI_TEMPLATE (decl))
3794         tmpl = DECL_TI_TEMPLATE (decl);
3795       /* If DECL is a TYPE_DECL for a class-template, then there won't
3796          be DECL_LANG_SPECIFIC.  The information equivalent to
3797          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
3798       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3799                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
3800                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
3801         {
3802           /* Since a template declaration already existed for this
3803              class-type, we must be redeclaring it here.  Make sure
3804              that the redeclaration is valid.  */
3805           redeclare_class_template (TREE_TYPE (decl),
3806                                     current_template_parms);
3807           /* We don't need to create a new TEMPLATE_DECL; just use the
3808              one we already had.  */
3809           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
3810         }
3811       else
3812         {
3813           tmpl = build_template_decl (decl, current_template_parms,
3814                                       member_template_p);
3815           new_template_p = 1;
3816
3817           if (DECL_LANG_SPECIFIC (decl)
3818               && DECL_TEMPLATE_SPECIALIZATION (decl))
3819             {
3820               /* A specialization of a member template of a template
3821                  class.  */
3822               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3823               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
3824               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
3825             }
3826         }
3827     }
3828   else
3829     {
3830       tree a, t, current, parms;
3831       int i;
3832
3833       if (TREE_CODE (decl) == TYPE_DECL)
3834         {
3835           if ((IS_AGGR_TYPE_CODE (TREE_CODE (TREE_TYPE (decl)))
3836                || TREE_CODE (TREE_TYPE (decl)) == ENUMERAL_TYPE)
3837               && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
3838               && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
3839             tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
3840           else
3841             {
3842               error ("%qD does not declare a template type", decl);
3843               return decl;
3844             }
3845         }
3846       else if (!DECL_LANG_SPECIFIC (decl) || !DECL_TEMPLATE_INFO (decl))
3847         {
3848           error ("template definition of non-template %q#D", decl);
3849           return decl;
3850         }
3851       else
3852         tmpl = DECL_TI_TEMPLATE (decl);
3853
3854       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3855           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
3856           && DECL_TEMPLATE_SPECIALIZATION (decl)
3857           && DECL_MEMBER_TEMPLATE_P (tmpl))
3858         {
3859           tree new_tmpl;
3860
3861           /* The declaration is a specialization of a member
3862              template, declared outside the class.  Therefore, the
3863              innermost template arguments will be NULL, so we
3864              replace them with the arguments determined by the
3865              earlier call to check_explicit_specialization.  */
3866           args = DECL_TI_ARGS (decl);
3867
3868           new_tmpl
3869             = build_template_decl (decl, current_template_parms,
3870                                    member_template_p);
3871           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
3872           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
3873           DECL_TI_TEMPLATE (decl) = new_tmpl;
3874           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
3875           DECL_TEMPLATE_INFO (new_tmpl)
3876             = tree_cons (tmpl, args, NULL_TREE);
3877
3878           register_specialization (new_tmpl,
3879                                    most_general_template (tmpl),
3880                                    args,
3881                                    is_friend);
3882           return decl;
3883         }
3884
3885       /* Make sure the template headers we got make sense.  */
3886
3887       parms = DECL_TEMPLATE_PARMS (tmpl);
3888       i = TMPL_PARMS_DEPTH (parms);
3889       if (TMPL_ARGS_DEPTH (args) != i)
3890         {
3891           error ("expected %d levels of template parms for %q#D, got %d",
3892                  i, decl, TMPL_ARGS_DEPTH (args));
3893         }
3894       else
3895         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
3896           {
3897             a = TMPL_ARGS_LEVEL (args, i);
3898             t = INNERMOST_TEMPLATE_PARMS (parms);
3899
3900             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
3901               {
3902                 if (current == decl)
3903                   error ("got %d template parameters for %q#D",
3904                          TREE_VEC_LENGTH (a), decl);
3905                 else
3906                   error ("got %d template parameters for %q#T",
3907                          TREE_VEC_LENGTH (a), current);
3908                 error ("  but %d required", TREE_VEC_LENGTH (t));
3909                 return error_mark_node;
3910               }
3911
3912             /* Perhaps we should also check that the parms are used in the
3913                appropriate qualifying scopes in the declarator?  */
3914
3915             if (current == decl)
3916               current = ctx;
3917             else
3918               current = (TYPE_P (current)
3919                          ? TYPE_CONTEXT (current)
3920                          : DECL_CONTEXT (current));
3921           }
3922     }
3923
3924   DECL_TEMPLATE_RESULT (tmpl) = decl;
3925   TREE_TYPE (tmpl) = TREE_TYPE (decl);
3926
3927   /* Push template declarations for global functions and types.  Note
3928      that we do not try to push a global template friend declared in a
3929      template class; such a thing may well depend on the template
3930      parameters of the class.  */
3931   if (new_template_p && !ctx
3932       && !(is_friend && template_class_depth (current_class_type) > 0))
3933     {
3934       tmpl = pushdecl_namespace_level (tmpl, is_friend);
3935       if (tmpl == error_mark_node)
3936         return error_mark_node;
3937
3938       /* Hide template friend classes that haven't been declared yet.  */
3939       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
3940         {
3941           DECL_ANTICIPATED (tmpl) = 1;
3942           DECL_FRIEND_P (tmpl) = 1;
3943         }
3944     }
3945
3946   if (primary)
3947     {
3948       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
3949       if (DECL_CONV_FN_P (tmpl))
3950         {
3951           int depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
3952
3953           /* It is a conversion operator. See if the type converted to
3954              depends on innermost template operands.  */
3955
3956           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
3957                                          depth))
3958             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
3959         }
3960     }
3961
3962   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
3963      back to its most general template.  If TMPL is a specialization,
3964      ARGS may only have the innermost set of arguments.  Add the missing
3965      argument levels if necessary.  */
3966   if (DECL_TEMPLATE_INFO (tmpl))
3967     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
3968
3969   info = tree_cons (tmpl, args, NULL_TREE);
3970
3971   if (DECL_IMPLICIT_TYPEDEF_P (decl))
3972     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
3973   else if (DECL_LANG_SPECIFIC (decl))
3974     DECL_TEMPLATE_INFO (decl) = info;
3975
3976   return DECL_TEMPLATE_RESULT (tmpl);
3977 }
3978
3979 tree
3980 push_template_decl (tree decl)
3981 {
3982   return push_template_decl_real (decl, false);
3983 }
3984
3985 /* Called when a class template TYPE is redeclared with the indicated
3986    template PARMS, e.g.:
3987
3988      template <class T> struct S;
3989      template <class T> struct S {};  */
3990
3991 bool
3992 redeclare_class_template (tree type, tree parms)
3993 {
3994   tree tmpl;
3995   tree tmpl_parms;
3996   int i;
3997
3998   if (!TYPE_TEMPLATE_INFO (type))
3999     {
4000       error ("%qT is not a template type", type);
4001       return false;
4002     }
4003
4004   tmpl = TYPE_TI_TEMPLATE (type);
4005   if (!PRIMARY_TEMPLATE_P (tmpl))
4006     /* The type is nested in some template class.  Nothing to worry
4007        about here; there are no new template parameters for the nested
4008        type.  */
4009     return true;
4010
4011   if (!parms)
4012     {
4013       error ("template specifiers not specified in declaration of %qD",
4014              tmpl);
4015       return false;
4016     }
4017
4018   parms = INNERMOST_TEMPLATE_PARMS (parms);
4019   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4020
4021   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4022     {
4023       error ("previous declaration %q+D", tmpl);
4024       error ("used %d template parameter(s) instead of %d",
4025              TREE_VEC_LENGTH (tmpl_parms),
4026              TREE_VEC_LENGTH (parms));
4027       return false;
4028     }
4029
4030   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4031     {
4032       tree tmpl_parm;
4033       tree parm;
4034       tree tmpl_default;
4035       tree parm_default;
4036
4037       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4038           || TREE_VEC_ELT (parms, i) == error_mark_node)
4039         continue;
4040
4041       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4042       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4043       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4044       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4045
4046       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4047          TEMPLATE_DECL.  */
4048       if (tmpl_parm != error_mark_node
4049            && (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4050            || (TREE_CODE (tmpl_parm) != TYPE_DECL
4051                && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))))
4052         {
4053           error ("template parameter %q+#D", tmpl_parm);
4054           error ("redeclared here as %q#D", parm);
4055           return false;
4056         }
4057
4058       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4059         {
4060           /* We have in [temp.param]:
4061
4062              A template-parameter may not be given default arguments
4063              by two different declarations in the same scope.  */
4064           error ("redefinition of default argument for %q#D", parm);
4065           error ("%J  original definition appeared here", tmpl_parm);
4066           return false;
4067         }
4068
4069       if (parm_default != NULL_TREE)
4070         /* Update the previous template parameters (which are the ones
4071            that will really count) with the new default value.  */
4072         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4073       else if (tmpl_default != NULL_TREE)
4074         /* Update the new parameters, too; they'll be used as the
4075            parameters for any members.  */
4076         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4077     }
4078
4079     return true;
4080 }
4081
4082 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4083    (possibly simplified) expression.  */
4084
4085 tree
4086 fold_non_dependent_expr (tree expr)
4087 {
4088   if (expr == NULL_TREE)
4089     return NULL_TREE;
4090
4091   /* If we're in a template, but EXPR isn't value dependent, simplify
4092      it.  We're supposed to treat:
4093
4094        template <typename T> void f(T[1 + 1]);
4095        template <typename T> void f(T[2]);
4096
4097      as two declarations of the same function, for example.  */
4098   if (processing_template_decl
4099       && !type_dependent_expression_p (expr)
4100       && !value_dependent_expression_p (expr))
4101     {
4102       HOST_WIDE_INT saved_processing_template_decl;
4103
4104       saved_processing_template_decl = processing_template_decl;
4105       processing_template_decl = 0;
4106       expr = tsubst_copy_and_build (expr,
4107                                     /*args=*/NULL_TREE,
4108                                     tf_error,
4109                                     /*in_decl=*/NULL_TREE,
4110                                     /*function_p=*/false,
4111                                     /*integral_constant_expression_p=*/true);
4112       processing_template_decl = saved_processing_template_decl;
4113     }
4114   return expr;
4115 }
4116
4117 /* EXPR is an expression which is used in a constant-expression context.
4118    For instance, it could be a VAR_DECL with a constant initializer.
4119    Extract the innest constant expression.
4120
4121    This is basically a more powerful version of
4122    integral_constant_value, which can be used also in templates where
4123    initializers can maintain a syntactic rather than semantic form
4124    (even if they are non-dependent, for access-checking purposes).  */
4125
4126 static tree
4127 fold_decl_constant_value (tree expr)
4128 {
4129   tree const_expr = expr;
4130   do
4131     {
4132       expr = fold_non_dependent_expr (const_expr);
4133       const_expr = integral_constant_value (expr);
4134     }
4135   while (expr != const_expr);
4136
4137   return expr;
4138 }
4139
4140 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4141    must be a function or a pointer-to-function type, as specified
4142    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4143    and check that the resulting function has external linkage.  */
4144
4145 static tree
4146 convert_nontype_argument_function (tree type, tree expr)
4147 {
4148   tree fns = expr;
4149   tree fn, fn_no_ptr;
4150
4151   fn = instantiate_type (type, fns, tf_none);
4152   if (fn == error_mark_node)
4153     return error_mark_node;
4154
4155   fn_no_ptr = fn;
4156   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4157     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4158   if (TREE_CODE (fn_no_ptr) == BASELINK)
4159     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4160  
4161   /* [temp.arg.nontype]/1
4162
4163      A template-argument for a non-type, non-template template-parameter
4164      shall be one of:
4165      [...]
4166      -- the address of an object or function with external linkage.  */
4167   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4168     {
4169       error ("%qE is not a valid template argument for type %qT "
4170              "because function %qD has not external linkage",
4171              expr, type, fn_no_ptr);
4172       return NULL_TREE;
4173     }
4174
4175   return fn;
4176 }
4177
4178 /* Attempt to convert the non-type template parameter EXPR to the
4179    indicated TYPE.  If the conversion is successful, return the
4180    converted value.  If the conversion is unsuccessful, return
4181    NULL_TREE if we issued an error message, or error_mark_node if we
4182    did not.  We issue error messages for out-and-out bad template
4183    parameters, but not simply because the conversion failed, since we
4184    might be just trying to do argument deduction.  Both TYPE and EXPR
4185    must be non-dependent.
4186
4187    The conversion follows the special rules described in
4188    [temp.arg.nontype], and it is much more strict than an implicit
4189    conversion.
4190
4191    This function is called twice for each template argument (see
4192    lookup_template_class for a more accurate description of this
4193    problem). This means that we need to handle expressions which
4194    are not valid in a C++ source, but can be created from the
4195    first call (for instance, casts to perform conversions). These
4196    hacks can go away after we fix the double coercion problem.  */
4197
4198 static tree
4199 convert_nontype_argument (tree type, tree expr)
4200 {
4201   tree expr_type;
4202
4203   /* Detect immediately string literals as invalid non-type argument.
4204      This special-case is not needed for correctness (we would easily
4205      catch this later), but only to provide better diagnostic for this
4206      common user mistake. As suggested by DR 100, we do not mention
4207      linkage issues in the diagnostic as this is not the point.  */
4208   if (TREE_CODE (expr) == STRING_CST)
4209     {
4210       error ("%qE is not a valid template argument for type %qT "
4211              "because string literals can never be used in this context",
4212              expr, type);
4213       return NULL_TREE;
4214     }
4215
4216   /* If we are in a template, EXPR may be non-dependent, but still
4217      have a syntactic, rather than semantic, form.  For example, EXPR
4218      might be a SCOPE_REF, rather than the VAR_DECL to which the
4219      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4220      so that access checking can be performed when the template is
4221      instantiated -- but here we need the resolved form so that we can
4222      convert the argument.  */
4223   expr = fold_non_dependent_expr (expr);
4224   if (error_operand_p (expr))
4225     return error_mark_node;
4226   expr_type = TREE_TYPE (expr);
4227
4228   /* HACK: Due to double coercion, we can get a
4229      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4230      which is the tree that we built on the first call (see
4231      below when coercing to reference to object or to reference to
4232      function). We just strip everything and get to the arg.
4233      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4234      for examples.  */
4235   if (TREE_CODE (expr) == NOP_EXPR)
4236     {
4237       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4238         {
4239           /* ??? Maybe we could use convert_from_reference here, but we
4240              would need to relax its constraints because the NOP_EXPR
4241              could actually change the type to something more cv-qualified,
4242              and this is not folded by convert_from_reference.  */
4243           tree addr = TREE_OPERAND (expr, 0);
4244           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4245           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4246           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4247           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4248                       (TREE_TYPE (expr_type),
4249                        TREE_TYPE (TREE_TYPE (addr))));
4250
4251           expr = TREE_OPERAND (addr, 0);
4252           expr_type = TREE_TYPE (expr);
4253         }
4254
4255       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4256          parameter is a pointer to object, through decay and
4257          qualification conversion. Let's strip everything.  */
4258       else if (TYPE_PTROBV_P (type))
4259         {
4260           STRIP_NOPS (expr);
4261           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4262           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4263           /* Skip the ADDR_EXPR only if it is part of the decay for
4264              an array. Otherwise, it is part of the original argument
4265              in the source code.  */
4266           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4267             expr = TREE_OPERAND (expr, 0);
4268           expr_type = TREE_TYPE (expr);
4269         }
4270     }
4271
4272   /* [temp.arg.nontype]/5, bullet 1
4273
4274      For a non-type template-parameter of integral or enumeration type,
4275      integral promotions (_conv.prom_) and integral conversions
4276      (_conv.integral_) are applied.  */
4277   if (INTEGRAL_TYPE_P (type))
4278     {
4279       if (!INTEGRAL_TYPE_P (expr_type))
4280         return error_mark_node;
4281
4282       expr = fold_decl_constant_value (expr);
4283       /* Notice that there are constant expressions like '4 % 0' which
4284          do not fold into integer constants.  */
4285       if (TREE_CODE (expr) != INTEGER_CST)
4286         {
4287           error ("%qE is not a valid template argument for type %qT "
4288                  "because it is a non-constant expression", expr, type);
4289           return NULL_TREE;
4290         }
4291
4292       /* At this point, an implicit conversion does what we want,
4293          because we already know that the expression is of integral
4294          type.  */
4295       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4296       if (expr == error_mark_node)
4297         return error_mark_node;
4298
4299       /* Conversion was allowed: fold it to a bare integer constant.  */
4300       expr = fold (expr);
4301     }
4302   /* [temp.arg.nontype]/5, bullet 2
4303
4304      For a non-type template-parameter of type pointer to object,
4305      qualification conversions (_conv.qual_) and the array-to-pointer
4306      conversion (_conv.array_) are applied.  */
4307   else if (TYPE_PTROBV_P (type))
4308     {
4309       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
4310
4311          A template-argument for a non-type, non-template template-parameter
4312          shall be one of: [...]
4313
4314          -- the name of a non-type template-parameter;
4315          -- the address of an object or function with external linkage, [...]
4316             expressed as "& id-expression" where the & is optional if the name
4317             refers to a function or array, or if the corresponding
4318             template-parameter is a reference.
4319
4320         Here, we do not care about functions, as they are invalid anyway
4321         for a parameter of type pointer-to-object.  */
4322
4323       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
4324         /* Non-type template parameters are OK.  */
4325         ;
4326       else if (TREE_CODE (expr) != ADDR_EXPR
4327                && TREE_CODE (expr_type) != ARRAY_TYPE)
4328         {
4329           if (TREE_CODE (expr) == VAR_DECL)
4330             {
4331               error ("%qD is not a valid template argument "
4332                      "because %qD is a variable, not the address of "
4333                      "a variable",
4334                      expr, expr);
4335               return NULL_TREE;
4336             }
4337           /* Other values, like integer constants, might be valid
4338              non-type arguments of some other type.  */
4339           return error_mark_node;
4340         }
4341       else
4342         {
4343           tree decl;
4344
4345           decl = ((TREE_CODE (expr) == ADDR_EXPR)
4346                   ? TREE_OPERAND (expr, 0) : expr);
4347           if (TREE_CODE (decl) != VAR_DECL)
4348             {
4349               error ("%qE is not a valid template argument of type %qT "
4350                      "because %qE is not a variable",
4351                      expr, type, decl);
4352               return NULL_TREE;
4353             }
4354           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
4355             {
4356               error ("%qE is not a valid template argument of type %qT "
4357                      "because %qD does not have external linkage",
4358                      expr, type, decl);
4359               return NULL_TREE;
4360             }
4361         }
4362
4363       expr = decay_conversion (expr);
4364       if (expr == error_mark_node)
4365         return error_mark_node;
4366
4367       expr = perform_qualification_conversions (type, expr);
4368       if (expr == error_mark_node)
4369         return error_mark_node;
4370     }
4371   /* [temp.arg.nontype]/5, bullet 3
4372
4373      For a non-type template-parameter of type reference to object, no
4374      conversions apply. The type referred to by the reference may be more
4375      cv-qualified than the (otherwise identical) type of the
4376      template-argument. The template-parameter is bound directly to the
4377      template-argument, which must be an lvalue.  */
4378   else if (TYPE_REF_OBJ_P (type))
4379     {
4380       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
4381                                                       expr_type))
4382         return error_mark_node;
4383
4384       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
4385         {
4386           error ("%qE is not a valid template argument for type %qT "
4387                  "because of conflicts in cv-qualification", expr, type);
4388           return NULL_TREE;
4389         }
4390
4391       if (!real_lvalue_p (expr))
4392         {
4393           error ("%qE is not a valid template argument for type %qT "
4394                  "because it is not an lvalue", expr, type);
4395           return NULL_TREE;
4396         }
4397
4398       /* [temp.arg.nontype]/1
4399
4400          A template-argument for a non-type, non-template template-parameter
4401          shall be one of: [...]
4402
4403          -- the address of an object or function with external linkage.  */
4404       if (!DECL_EXTERNAL_LINKAGE_P (expr))
4405         {
4406           error ("%qE is not a valid template argument for type %qT "
4407                  "because object %qD has not external linkage",
4408                  expr, type, expr);
4409           return NULL_TREE;
4410         }
4411
4412       expr = build_nop (type, build_address (expr));
4413     }
4414   /* [temp.arg.nontype]/5, bullet 4
4415
4416      For a non-type template-parameter of type pointer to function, only
4417      the function-to-pointer conversion (_conv.func_) is applied. If the
4418      template-argument represents a set of overloaded functions (or a
4419      pointer to such), the matching function is selected from the set
4420      (_over.over_).  */
4421   else if (TYPE_PTRFN_P (type))
4422     {
4423       /* If the argument is a template-id, we might not have enough
4424          context information to decay the pointer.  */
4425       if (!type_unknown_p (expr_type))
4426         {
4427           expr = decay_conversion (expr);
4428           if (expr == error_mark_node)
4429             return error_mark_node;
4430         }
4431
4432       expr = convert_nontype_argument_function (type, expr);
4433       if (!expr || expr == error_mark_node)
4434         return expr;
4435     }
4436   /* [temp.arg.nontype]/5, bullet 5
4437
4438      For a non-type template-parameter of type reference to function, no
4439      conversions apply. If the template-argument represents a set of
4440      overloaded functions, the matching function is selected from the set
4441      (_over.over_).  */
4442   else if (TYPE_REFFN_P (type))
4443     {
4444       if (TREE_CODE (expr) == ADDR_EXPR)
4445         {
4446           error ("%qE is not a valid template argument for type %qT "
4447                  "because it is a pointer", expr, type);
4448           inform ("try using %qE instead", TREE_OPERAND (expr, 0));
4449           return NULL_TREE;
4450         }
4451
4452       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
4453       if (!expr || expr == error_mark_node)
4454         return expr;
4455
4456       expr = build_nop (type, build_address (expr));
4457     }
4458   /* [temp.arg.nontype]/5, bullet 6
4459
4460      For a non-type template-parameter of type pointer to member function,
4461      no conversions apply. If the template-argument represents a set of
4462      overloaded member functions, the matching member function is selected
4463      from the set (_over.over_).  */
4464   else if (TYPE_PTRMEMFUNC_P (type))
4465     {
4466       expr = instantiate_type (type, expr, tf_none);
4467       if (expr == error_mark_node)
4468         return error_mark_node;
4469
4470       /* There is no way to disable standard conversions in
4471          resolve_address_of_overloaded_function (called by
4472          instantiate_type). It is possible that the call succeeded by
4473          converting &B::I to &D::I (where B is a base of D), so we need
4474          to reject this conversion here.
4475
4476          Actually, even if there was a way to disable standard conversions,
4477          it would still be better to reject them here so that we can
4478          provide a superior diagnostic.  */
4479       if (!same_type_p (TREE_TYPE (expr), type))
4480         {
4481           /* Make sure we are just one standard conversion off.  */
4482           gcc_assert (can_convert (type, TREE_TYPE (expr)));
4483           error ("%qE is not a valid template argument for type %qT "
4484                  "because it is of type %qT", expr, type,
4485                  TREE_TYPE (expr));
4486           inform ("standard conversions are not allowed in this context");
4487           return NULL_TREE;
4488         }
4489     }
4490   /* [temp.arg.nontype]/5, bullet 7
4491
4492      For a non-type template-parameter of type pointer to data member,
4493      qualification conversions (_conv.qual_) are applied.  */
4494   else if (TYPE_PTRMEM_P (type))
4495     {
4496       expr = perform_qualification_conversions (type, expr);
4497       if (expr == error_mark_node)
4498         return expr;
4499     }
4500   /* A template non-type parameter must be one of the above.  */
4501   else
4502     gcc_unreachable ();
4503
4504   /* Sanity check: did we actually convert the argument to the
4505      right type?  */
4506   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
4507   return expr;
4508 }
4509
4510
4511 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
4512    template template parameters.  Both PARM_PARMS and ARG_PARMS are
4513    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
4514    or PARM_DECL.
4515
4516    Consider the example:
4517      template <class T> class A;
4518      template<template <class U> class TT> class B;
4519
4520    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
4521    the parameters to A, and OUTER_ARGS contains A.  */
4522
4523 static int
4524 coerce_template_template_parms (tree parm_parms,
4525                                 tree arg_parms,
4526                                 tsubst_flags_t complain,
4527                                 tree in_decl,
4528                                 tree outer_args)
4529 {
4530   int nparms, nargs, i;
4531   tree parm, arg;
4532
4533   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
4534   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
4535
4536   nparms = TREE_VEC_LENGTH (parm_parms);
4537   nargs = TREE_VEC_LENGTH (arg_parms);
4538
4539   if (nargs != nparms)
4540     return 0;
4541
4542   for (i = 0; i < nparms; ++i)
4543     {
4544       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
4545           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
4546         continue;
4547
4548       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
4549       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
4550
4551       if (arg == NULL_TREE || arg == error_mark_node
4552           || parm == NULL_TREE || parm == error_mark_node)
4553         return 0;
4554
4555       if (TREE_CODE (arg) != TREE_CODE (parm))
4556         return 0;
4557
4558       switch (TREE_CODE (parm))
4559         {
4560         case TEMPLATE_DECL:
4561           /* We encounter instantiations of templates like
4562                template <template <template <class> class> class TT>
4563                class C;  */
4564           {
4565             tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
4566             tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
4567
4568             if (!coerce_template_template_parms
4569                 (parmparm, argparm, complain, in_decl, outer_args))
4570               return 0;
4571           }
4572           /* Fall through.  */
4573
4574         case TYPE_DECL:
4575           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))
4576               != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg)))
4577             /* One is a parameter pack, the other is not.  */
4578             return 0;
4579           break;
4580
4581         case PARM_DECL:
4582           /* The tsubst call is used to handle cases such as
4583
4584                template <int> class C {};
4585                template <class T, template <T> class TT> class D {};
4586                D<int, C> d;
4587
4588              i.e. the parameter list of TT depends on earlier parameters.  */
4589           if (!dependent_type_p (TREE_TYPE (arg))
4590               && !same_type_p
4591                     (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
4592                              TREE_TYPE (arg)))
4593             return 0;
4594
4595           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4596               != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg)))
4597             /* One is a parameter pack, the other is not.  */
4598             return 0;
4599           break;
4600
4601         default:
4602           gcc_unreachable ();
4603         }
4604     }
4605   return 1;
4606 }
4607
4608 /* Convert the indicated template ARG as necessary to match the
4609    indicated template PARM.  Returns the converted ARG, or
4610    error_mark_node if the conversion was unsuccessful.  Error and
4611    warning messages are issued under control of COMPLAIN.  This
4612    conversion is for the Ith parameter in the parameter list.  ARGS is
4613    the full set of template arguments deduced so far.  */
4614
4615 static tree
4616 convert_template_argument (tree parm,
4617                            tree arg,
4618                            tree args,
4619                            tsubst_flags_t complain,
4620                            int i,
4621                            tree in_decl)
4622 {
4623   tree val;
4624   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
4625   tree check_arg = arg;
4626
4627   if (TREE_CODE (arg) == TREE_LIST
4628       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
4629     {
4630       /* The template argument was the name of some
4631          member function.  That's usually
4632          invalid, but static members are OK.  In any
4633          case, grab the underlying fields/functions
4634          and issue an error later if required.  */
4635       arg = TREE_VALUE (arg);
4636       TREE_TYPE (arg) = unknown_type_node;
4637     }
4638
4639   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
4640   requires_type = (TREE_CODE (parm) == TYPE_DECL
4641                    || requires_tmpl_type);
4642
4643   /* When determining whether an argument pack expansion is a template,
4644      look at the pattern.  */
4645   if (TREE_CODE (check_arg) == TYPE_PACK_EXPANSION)
4646     check_arg = PACK_EXPANSION_PATTERN (check_arg);
4647
4648   is_tmpl_type = 
4649     ((TREE_CODE (check_arg) == TEMPLATE_DECL
4650       && TREE_CODE (DECL_TEMPLATE_RESULT (check_arg)) == TYPE_DECL)
4651      || TREE_CODE (check_arg) == TEMPLATE_TEMPLATE_PARM
4652      || TREE_CODE (check_arg) == UNBOUND_CLASS_TEMPLATE);
4653
4654   if (is_tmpl_type
4655       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4656           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
4657     arg = TYPE_STUB_DECL (arg);
4658
4659   is_type = TYPE_P (arg) || is_tmpl_type;
4660
4661   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
4662       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
4663     {
4664       pedwarn ("to refer to a type member of a template parameter, "
4665                "use %<typename %E%>", arg);
4666
4667       arg = make_typename_type (TREE_OPERAND (arg, 0),
4668                                 TREE_OPERAND (arg, 1),
4669                                 typename_type,
4670                                 complain & tf_error);
4671       is_type = 1;
4672     }
4673   if (is_type != requires_type)
4674     {
4675       if (in_decl)
4676         {
4677           if (complain & tf_error)
4678             {
4679               error ("type/value mismatch at argument %d in template "
4680                      "parameter list for %qD",
4681                      i + 1, in_decl);
4682               if (is_type)
4683                 error ("  expected a constant of type %qT, got %qT",
4684                        TREE_TYPE (parm),
4685                        (is_tmpl_type ? DECL_NAME (arg) : arg));
4686               else if (requires_tmpl_type)
4687                 error ("  expected a class template, got %qE", arg);
4688               else
4689                 error ("  expected a type, got %qE", arg);
4690             }
4691         }
4692       return error_mark_node;
4693     }
4694   if (is_tmpl_type ^ requires_tmpl_type)
4695     {
4696       if (in_decl && (complain & tf_error))
4697         {
4698           error ("type/value mismatch at argument %d in template "
4699                  "parameter list for %qD",
4700                  i + 1, in_decl);
4701           if (is_tmpl_type)
4702             error ("  expected a type, got %qT", DECL_NAME (arg));
4703           else
4704             error ("  expected a class template, got %qT", arg);
4705         }
4706       return error_mark_node;
4707     }
4708
4709   if (is_type)
4710     {
4711       if (requires_tmpl_type)
4712         {
4713           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
4714             /* The number of argument required is not known yet.
4715                Just accept it for now.  */
4716             val = TREE_TYPE (arg);
4717           else
4718             {
4719               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
4720               tree argparm;
4721
4722               check_arg = arg;
4723               /* When determining whether a pack expansion is a template,
4724                  look at the pattern.  */
4725               if (TREE_CODE (check_arg) == TYPE_PACK_EXPANSION)
4726                 check_arg = PACK_EXPANSION_PATTERN (check_arg);
4727
4728               argparm = DECL_INNERMOST_TEMPLATE_PARMS (check_arg);
4729
4730               if (coerce_template_template_parms (parmparm, argparm,
4731                                                   complain, in_decl,
4732                                                   args))
4733                 {
4734                   val = arg;
4735
4736                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
4737                      TEMPLATE_DECL.  */
4738                   if (val != error_mark_node)
4739                     {
4740                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
4741                         val = TREE_TYPE (val);
4742                       else if (TREE_CODE (val) == TYPE_PACK_EXPANSION
4743                                && DECL_TEMPLATE_TEMPLATE_PARM_P (check_arg))
4744                         {
4745                           val = TREE_TYPE (check_arg);
4746                           val = make_pack_expansion (val);
4747                         }
4748                     }
4749                 }
4750               else
4751                 {
4752                   if (in_decl && (complain & tf_error))
4753                     {
4754                       error ("type/value mismatch at argument %d in "
4755                              "template parameter list for %qD",
4756                              i + 1, in_decl);
4757                       error ("  expected a template of type %qD, got %qD",
4758                              parm, arg);
4759                     }
4760
4761                   val = error_mark_node;
4762                 }
4763             }
4764         }
4765       else
4766         val = arg;
4767       /* We only form one instance of each template specialization.
4768          Therefore, if we use a non-canonical variant (i.e., a
4769          typedef), any future messages referring to the type will use
4770          the typedef, which is confusing if those future uses do not
4771          themselves also use the typedef.  */
4772       if (TYPE_P (val))
4773         val = canonical_type_variant (val);
4774     }
4775   else
4776     {
4777       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
4778
4779       if (invalid_nontype_parm_type_p (t, complain))
4780         return error_mark_node;
4781
4782       if (!uses_template_parms (arg) && !uses_template_parms (t))
4783         /* We used to call digest_init here.  However, digest_init
4784            will report errors, which we don't want when complain
4785            is zero.  More importantly, digest_init will try too
4786            hard to convert things: for example, `0' should not be
4787            converted to pointer type at this point according to
4788            the standard.  Accepting this is not merely an
4789            extension, since deciding whether or not these
4790            conversions can occur is part of determining which
4791            function template to call, or whether a given explicit
4792            argument specification is valid.  */
4793         val = convert_nontype_argument (t, arg);
4794       else
4795         val = arg;
4796
4797       if (val == NULL_TREE)
4798         val = error_mark_node;
4799       else if (val == error_mark_node && (complain & tf_error))
4800         error ("could not convert template argument %qE to %qT",  arg, t);
4801     }
4802
4803   return val;
4804 }
4805
4806 /* Coerces the remaining template arguments in INNER_ARGS (from
4807    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
4808    Returns the coerced argument pack. PARM_IDX is the position of this
4809    parameter in the template parameter list. ARGS is the original
4810    template argument list.  */
4811 static tree
4812 coerce_template_parameter_pack (tree parms,
4813                                 int parm_idx,
4814                                 tree args,
4815                                 tree inner_args,
4816                                 int arg_idx,
4817                                 tree new_args,
4818                                 int* lost,
4819                                 tree in_decl,
4820                                 tsubst_flags_t complain)
4821 {
4822   tree parm = TREE_VEC_ELT (parms, parm_idx);
4823   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
4824   tree packed_args;
4825   tree argument_pack;
4826   tree packed_types = NULL_TREE;
4827
4828   if (arg_idx > nargs)
4829     arg_idx = nargs;
4830
4831   packed_args = make_tree_vec (nargs - arg_idx);
4832
4833   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
4834       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
4835     {
4836       /* When the template parameter is a non-type template
4837          parameter pack whose type uses parameter packs, we need
4838          to look at each of the template arguments
4839          separately. Build a vector of the types for these
4840          non-type template parameters in PACKED_TYPES.  */
4841       tree expansion 
4842         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
4843       packed_types = tsubst_pack_expansion (expansion, args,
4844                                             complain, in_decl);
4845
4846       if (packed_types == error_mark_node)
4847         return error_mark_node;
4848
4849       /* Check that we have the right number of arguments.  */
4850       if (arg_idx < nargs
4851           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
4852           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
4853         {
4854           int needed_parms 
4855             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
4856           error ("wrong number of template arguments (%d, should be %d)",
4857                  nargs, needed_parms);
4858           return error_mark_node;
4859         }
4860
4861       /* If we aren't able to check the actual arguments now
4862          (because they haven't been expanded yet), we can at least
4863          verify that all of the types used for the non-type
4864          template parameter pack are, in fact, valid for non-type
4865          template parameters.  */
4866       if (arg_idx < nargs 
4867           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
4868         {
4869           int j, len = TREE_VEC_LENGTH (packed_types);
4870           for (j = 0; j < len; ++j)
4871             {
4872               tree t = TREE_VEC_ELT (packed_types, j);
4873               if (invalid_nontype_parm_type_p (t, complain))
4874                 return error_mark_node;
4875             }
4876         }
4877     }
4878
4879   /* Convert the remaining arguments, which will be a part of the
4880      parameter pack "parm".  */
4881   for (; arg_idx < nargs; ++arg_idx)
4882     {
4883       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
4884       tree actual_parm = TREE_VALUE (parm);
4885
4886       if (packed_types && !PACK_EXPANSION_P (arg))
4887         {
4888           /* When we have a vector of types (corresponding to the
4889              non-type template parameter pack that uses parameter
4890              packs in its type, as mention above), and the
4891              argument is not an expansion (which expands to a
4892              currently unknown number of arguments), clone the
4893              parm and give it the next type in PACKED_TYPES.  */
4894           actual_parm = copy_node (actual_parm);
4895           TREE_TYPE (actual_parm) = 
4896             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
4897         }
4898
4899       arg = convert_template_argument (actual_parm, 
4900                                        arg, new_args, complain, parm_idx,
4901                                        in_decl);
4902       if (arg == error_mark_node)
4903         (*lost)++;
4904       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
4905     }
4906
4907   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
4908       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
4909     argument_pack = make_node (TYPE_ARGUMENT_PACK);
4910   else
4911     {
4912       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
4913       TREE_TYPE (argument_pack) = TREE_TYPE (TREE_VALUE (parm));
4914       TREE_CONSTANT (argument_pack) = 1;
4915     }
4916
4917   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
4918   return argument_pack;
4919 }
4920
4921 /* Convert all template arguments to their appropriate types, and
4922    return a vector containing the innermost resulting template
4923    arguments.  If any error occurs, return error_mark_node. Error and
4924    warning messages are issued under control of COMPLAIN.
4925
4926    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
4927    for arguments not specified in ARGS.  Otherwise, if
4928    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
4929    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
4930    USE_DEFAULT_ARGS is false, then all arguments must be specified in
4931    ARGS.  */
4932
4933 static tree
4934 coerce_template_parms (tree parms,
4935                        tree args,
4936                        tree in_decl,
4937                        tsubst_flags_t complain,
4938                        bool require_all_args,
4939                        bool use_default_args)
4940 {
4941   int nparms, nargs, parm_idx, arg_idx, lost = 0;
4942   tree inner_args;
4943   tree new_args;
4944   tree new_inner_args;
4945   bool saved_skip_evaluation;
4946
4947   /* When used as a boolean value, indicates whether this is a
4948      variadic template parameter list. Since it's an int, we can also
4949      subtract it from nparms to get the number of non-variadic
4950      parameters.  */
4951   int variadic_p = 0;
4952
4953   inner_args 
4954     = expand_template_argument_pack (INNERMOST_TEMPLATE_ARGS (args));
4955
4956   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
4957   nparms = TREE_VEC_LENGTH (parms);
4958
4959   /* Determine if there are any parameter packs.  */
4960   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
4961     {
4962       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
4963       if (template_parameter_pack_p (tparm))
4964         {
4965           variadic_p = 1;
4966           break;
4967         }
4968     }
4969
4970   if ((nargs > nparms - variadic_p && !variadic_p)
4971       || (nargs < nparms - variadic_p
4972           && require_all_args
4973           && (!use_default_args
4974               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
4975                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
4976     {
4977       if (complain & tf_error)
4978         {
4979           const char *or_more = "";
4980           if (variadic_p)
4981             {
4982               or_more = " or more";
4983               --nparms;
4984             }
4985
4986           error ("wrong number of template arguments (%d, should be %d%s)",
4987                  nargs, nparms, or_more);
4988
4989           if (in_decl)
4990             error ("provided for %q+D", in_decl);
4991         }
4992
4993       return error_mark_node;
4994     }
4995
4996   /* We need to evaluate the template arguments, even though this
4997      template-id may be nested within a "sizeof".  */
4998   saved_skip_evaluation = skip_evaluation;
4999   skip_evaluation = false;
5000   new_inner_args = make_tree_vec (nparms);
5001   new_args = add_outermost_template_args (args, new_inner_args);
5002   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5003     {
5004       tree arg;
5005       tree parm;
5006
5007       /* Get the Ith template parameter.  */
5008       parm = TREE_VEC_ELT (parms, parm_idx);
5009  
5010       if (parm == error_mark_node)
5011       {
5012         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5013         continue;
5014       }
5015
5016       /* Calculate the next argument.  */
5017       if (template_parameter_pack_p (TREE_VALUE (parm)))
5018         {
5019           /* All remaining arguments will be placed in the
5020              template parameter pack PARM.  */
5021           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5022                                                 inner_args, arg_idx,
5023                                                 new_args, &lost,
5024                                                 in_decl, complain);
5025           
5026           /* Store this argument.  */
5027           if (arg == error_mark_node)
5028             lost++;
5029           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5030
5031           /* We are done with all of the arguments.  */
5032           arg_idx = nargs;
5033
5034           continue;
5035         }
5036       else if (arg_idx < nargs)
5037         {
5038           arg = TREE_VEC_ELT (inner_args, arg_idx);
5039
5040           if (arg && PACK_EXPANSION_P (arg))
5041             {
5042               /* If ARG is a pack expansion, but PARM is not a
5043                  template parameter pack (if it were, we would have
5044                  handled it above), we're trying to expand into a
5045                  fixed-length argument list.  */
5046               if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5047                 error ("cannot expand %<%E%> into a fixed-length "
5048                        "argument list", arg);
5049               else
5050                 error ("cannot expand %<%T%> into a fixed-length "
5051                        "argument list", arg);
5052             }
5053         }
5054       else if (require_all_args)
5055         /* There must be a default arg in this case.  */
5056         arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
5057                                    complain, in_decl);
5058       else
5059         break;
5060
5061       if (arg == error_mark_node)
5062         {
5063           if (complain & tf_error)
5064             error ("template argument %d is invalid", arg_idx + 1);
5065         }
5066       else if (!arg)
5067         /* This only occurs if there was an error in the template
5068            parameter list itself (which we would already have
5069            reported) that we are trying to recover from, e.g., a class
5070            template with a parameter list such as
5071            template<typename..., typename>.  */
5072         return error_mark_node;
5073       else
5074         arg = convert_template_argument (TREE_VALUE (parm),
5075                                          arg, new_args, complain, 
5076                                          parm_idx, in_decl);
5077
5078       if (arg == error_mark_node)
5079         lost++;
5080       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
5081     }
5082   skip_evaluation = saved_skip_evaluation;
5083
5084   if (lost)
5085     return error_mark_node;
5086
5087   return new_inner_args;
5088 }
5089
5090 /* Returns 1 if template args OT and NT are equivalent.  */
5091
5092 static int
5093 template_args_equal (tree ot, tree nt)
5094 {
5095   if (nt == ot)
5096     return 1;
5097
5098   if (TREE_CODE (nt) == TREE_VEC)
5099     /* For member templates */
5100     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
5101   else if (PACK_EXPANSION_P (ot))
5102     return PACK_EXPANSION_P (nt) 
5103       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
5104                               PACK_EXPANSION_PATTERN (nt));
5105   else if (TYPE_P (nt))
5106     return TYPE_P (ot) && same_type_p (ot, nt);
5107   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
5108     return 0;
5109   else
5110     return cp_tree_equal (ot, nt);
5111 }
5112
5113 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
5114    of template arguments.  Returns 0 otherwise.  */
5115
5116 int
5117 comp_template_args (tree oldargs, tree newargs)
5118 {
5119   int i;
5120
5121   oldargs = expand_template_argument_pack (oldargs);
5122   newargs = expand_template_argument_pack (newargs);
5123
5124   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
5125     return 0;
5126
5127   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
5128     {
5129       tree nt = TREE_VEC_ELT (newargs, i);
5130       tree ot = TREE_VEC_ELT (oldargs, i);
5131
5132       if (! template_args_equal (ot, nt))
5133         return 0;
5134     }
5135   return 1;
5136 }
5137
5138 static void
5139 add_pending_template (tree d)
5140 {
5141   tree ti = (TYPE_P (d)
5142              ? CLASSTYPE_TEMPLATE_INFO (d)
5143              : DECL_TEMPLATE_INFO (d));
5144   struct pending_template *pt;
5145   int level;
5146
5147   if (TI_PENDING_TEMPLATE_FLAG (ti))
5148     return;
5149
5150   /* We are called both from instantiate_decl, where we've already had a
5151      tinst_level pushed, and instantiate_template, where we haven't.
5152      Compensate.  */
5153   level = !current_tinst_level || current_tinst_level->decl != d;
5154
5155   if (level)
5156     push_tinst_level (d);
5157
5158   pt = GGC_NEW (struct pending_template);
5159   pt->next = NULL;
5160   pt->tinst = current_tinst_level;
5161   if (last_pending_template)
5162     last_pending_template->next = pt;
5163   else
5164     pending_templates = pt;
5165
5166   last_pending_template = pt;
5167
5168   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
5169
5170   if (level)
5171     pop_tinst_level ();
5172 }
5173
5174
5175 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
5176    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
5177    documentation for TEMPLATE_ID_EXPR.  */
5178
5179 tree
5180 lookup_template_function (tree fns, tree arglist)
5181 {
5182   tree type;
5183
5184   if (fns == error_mark_node || arglist == error_mark_node)
5185     return error_mark_node;
5186
5187   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
5188   gcc_assert (fns && (is_overloaded_fn (fns)
5189                       || TREE_CODE (fns) == IDENTIFIER_NODE));
5190
5191   if (BASELINK_P (fns))
5192     {
5193       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
5194                                          unknown_type_node,
5195                                          BASELINK_FUNCTIONS (fns),
5196                                          arglist);
5197       return fns;
5198     }
5199
5200   type = TREE_TYPE (fns);
5201   if (TREE_CODE (fns) == OVERLOAD || !type)
5202     type = unknown_type_node;
5203
5204   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
5205 }
5206
5207 /* Within the scope of a template class S<T>, the name S gets bound
5208    (in build_self_reference) to a TYPE_DECL for the class, not a
5209    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
5210    or one of its enclosing classes, and that type is a template,
5211    return the associated TEMPLATE_DECL.  Otherwise, the original
5212    DECL is returned.  */
5213
5214 tree
5215 maybe_get_template_decl_from_type_decl (tree decl)
5216 {
5217   return (decl != NULL_TREE
5218           && TREE_CODE (decl) == TYPE_DECL
5219           && DECL_ARTIFICIAL (decl)
5220           && CLASS_TYPE_P (TREE_TYPE (decl))
5221           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
5222     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
5223 }
5224
5225 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
5226    parameters, find the desired type.
5227
5228    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
5229
5230    IN_DECL, if non-NULL, is the template declaration we are trying to
5231    instantiate.
5232
5233    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
5234    the class we are looking up.
5235
5236    Issue error and warning messages under control of COMPLAIN.
5237
5238    If the template class is really a local class in a template
5239    function, then the FUNCTION_CONTEXT is the function in which it is
5240    being instantiated.
5241
5242    ??? Note that this function is currently called *twice* for each
5243    template-id: the first time from the parser, while creating the
5244    incomplete type (finish_template_type), and the second type during the
5245    real instantiation (instantiate_template_class). This is surely something
5246    that we want to avoid. It also causes some problems with argument
5247    coercion (see convert_nontype_argument for more information on this).  */
5248
5249 tree
5250 lookup_template_class (tree d1,
5251                        tree arglist,
5252                        tree in_decl,
5253                        tree context,
5254                        int entering_scope,
5255                        tsubst_flags_t complain)
5256 {
5257   tree template = NULL_TREE, parmlist;
5258   tree t;
5259
5260   timevar_push (TV_NAME_LOOKUP);
5261
5262   if (TREE_CODE (d1) == IDENTIFIER_NODE)
5263     {
5264       tree value = innermost_non_namespace_value (d1);
5265       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
5266         template = value;
5267       else
5268         {
5269           if (context)
5270             push_decl_namespace (context);
5271           template = lookup_name (d1);
5272           template = maybe_get_template_decl_from_type_decl (template);
5273           if (context)
5274             pop_decl_namespace ();
5275         }
5276       if (template)
5277         context = DECL_CONTEXT (template);
5278     }
5279   else if (TREE_CODE (d1) == TYPE_DECL && IS_AGGR_TYPE (TREE_TYPE (d1)))
5280     {
5281       tree type = TREE_TYPE (d1);
5282
5283       /* If we are declaring a constructor, say A<T>::A<T>, we will get
5284          an implicit typename for the second A.  Deal with it.  */
5285       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
5286         type = TREE_TYPE (type);
5287
5288       if (CLASSTYPE_TEMPLATE_INFO (type))
5289         {
5290           template = CLASSTYPE_TI_TEMPLATE (type);
5291           d1 = DECL_NAME (template);
5292         }
5293     }
5294   else if (TREE_CODE (d1) == ENUMERAL_TYPE
5295            || (TYPE_P (d1) && IS_AGGR_TYPE (d1)))
5296     {
5297       template = TYPE_TI_TEMPLATE (d1);
5298       d1 = DECL_NAME (template);
5299     }
5300   else if (TREE_CODE (d1) == TEMPLATE_DECL
5301            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
5302     {
5303       template = d1;
5304       d1 = DECL_NAME (template);
5305       context = DECL_CONTEXT (template);
5306     }
5307
5308   /* Issue an error message if we didn't find a template.  */
5309   if (! template)
5310     {
5311       if (complain & tf_error)
5312         error ("%qT is not a template", d1);
5313       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5314     }
5315
5316   if (TREE_CODE (template) != TEMPLATE_DECL
5317          /* Make sure it's a user visible template, if it was named by
5318             the user.  */
5319       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (template)
5320           && !PRIMARY_TEMPLATE_P (template)))
5321     {
5322       if (complain & tf_error)
5323         {
5324           error ("non-template type %qT used as a template", d1);
5325           if (in_decl)
5326             error ("for template declaration %q+D", in_decl);
5327         }
5328       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5329     }
5330
5331   complain &= ~tf_user;
5332
5333   if (DECL_TEMPLATE_TEMPLATE_PARM_P (template))
5334     {
5335       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
5336          template arguments */
5337
5338       tree parm;
5339       tree arglist2;
5340
5341       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (template);
5342
5343       /* Consider an example where a template template parameter declared as
5344
5345            template <class T, class U = std::allocator<T> > class TT
5346
5347          The template parameter level of T and U are one level larger than
5348          of TT.  To proper process the default argument of U, say when an
5349          instantiation `TT<int>' is seen, we need to build the full
5350          arguments containing {int} as the innermost level.  Outer levels,
5351          available when not appearing as default template argument, can be
5352          obtained from `current_template_args ()'.
5353
5354          Suppose that TT is later substituted with std::vector.  The above
5355          instantiation is `TT<int, std::allocator<T> >' with TT at
5356          level 1, and T at level 2, while the template arguments at level 1
5357          becomes {std::vector} and the inner level 2 is {int}.  */
5358
5359       if (current_template_parms)
5360         arglist = add_to_template_args (current_template_args (), arglist);
5361
5362       arglist2 = coerce_template_parms (parmlist, arglist, template,
5363                                         complain,
5364                                         /*require_all_args=*/true,
5365                                         /*use_default_args=*/true);
5366       if (arglist2 == error_mark_node
5367           || (!uses_template_parms (arglist2)
5368               && check_instantiated_args (template, arglist2, complain)))
5369         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5370
5371       parm = bind_template_template_parm (TREE_TYPE (template), arglist2);
5372       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
5373     }
5374   else
5375     {
5376       tree template_type = TREE_TYPE (template);
5377       tree gen_tmpl;
5378       tree type_decl;
5379       tree found = NULL_TREE;
5380       int arg_depth;
5381       int parm_depth;
5382       int is_partial_instantiation;
5383
5384       gen_tmpl = most_general_template (template);
5385       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
5386       parm_depth = TMPL_PARMS_DEPTH (parmlist);
5387       arg_depth = TMPL_ARGS_DEPTH (arglist);
5388
5389       if (arg_depth == 1 && parm_depth > 1)
5390         {
5391           /* We've been given an incomplete set of template arguments.
5392              For example, given:
5393
5394                template <class T> struct S1 {
5395                  template <class U> struct S2 {};
5396                  template <class U> struct S2<U*> {};
5397                 };
5398
5399              we will be called with an ARGLIST of `U*', but the
5400              TEMPLATE will be `template <class T> template
5401              <class U> struct S1<T>::S2'.  We must fill in the missing
5402              arguments.  */
5403           arglist
5404             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (template)),
5405                                            arglist);
5406           arg_depth = TMPL_ARGS_DEPTH (arglist);
5407         }
5408
5409       /* Now we should have enough arguments.  */
5410       gcc_assert (parm_depth == arg_depth);
5411
5412       /* From here on, we're only interested in the most general
5413          template.  */
5414       template = gen_tmpl;
5415
5416       /* Calculate the BOUND_ARGS.  These will be the args that are
5417          actually tsubst'd into the definition to create the
5418          instantiation.  */
5419       if (parm_depth > 1)
5420         {
5421           /* We have multiple levels of arguments to coerce, at once.  */
5422           int i;
5423           int saved_depth = TMPL_ARGS_DEPTH (arglist);
5424
5425           tree bound_args = make_tree_vec (parm_depth);
5426
5427           for (i = saved_depth,
5428                  t = DECL_TEMPLATE_PARMS (template);
5429                i > 0 && t != NULL_TREE;
5430                --i, t = TREE_CHAIN (t))
5431             {
5432               tree a = coerce_template_parms (TREE_VALUE (t),
5433                                               arglist, template,
5434                                               complain,
5435                                               /*require_all_args=*/true,
5436                                               /*use_default_args=*/true);
5437
5438               /* Don't process further if one of the levels fails.  */
5439               if (a == error_mark_node)
5440                 {
5441                   /* Restore the ARGLIST to its full size.  */
5442                   TREE_VEC_LENGTH (arglist) = saved_depth;
5443                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5444                 }
5445
5446               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
5447
5448               /* We temporarily reduce the length of the ARGLIST so
5449                  that coerce_template_parms will see only the arguments
5450                  corresponding to the template parameters it is
5451                  examining.  */
5452               TREE_VEC_LENGTH (arglist)--;
5453             }
5454
5455           /* Restore the ARGLIST to its full size.  */
5456           TREE_VEC_LENGTH (arglist) = saved_depth;
5457
5458           arglist = bound_args;
5459         }
5460       else
5461         arglist
5462           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
5463                                    INNERMOST_TEMPLATE_ARGS (arglist),
5464                                    template,
5465                                    complain,
5466                                    /*require_all_args=*/true,
5467                                    /*use_default_args=*/true);
5468
5469       if (arglist == error_mark_node)
5470         /* We were unable to bind the arguments.  */
5471         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5472
5473       /* In the scope of a template class, explicit references to the
5474          template class refer to the type of the template, not any
5475          instantiation of it.  For example, in:
5476
5477            template <class T> class C { void f(C<T>); }
5478
5479          the `C<T>' is just the same as `C'.  Outside of the
5480          class, however, such a reference is an instantiation.  */
5481       if (comp_template_args (TYPE_TI_ARGS (template_type),
5482                               arglist))
5483         {
5484           found = template_type;
5485
5486           if (!entering_scope && PRIMARY_TEMPLATE_P (template))
5487             {
5488               tree ctx;
5489
5490               for (ctx = current_class_type;
5491                    ctx && TREE_CODE (ctx) != NAMESPACE_DECL;
5492                    ctx = (TYPE_P (ctx)
5493                           ? TYPE_CONTEXT (ctx)
5494                           : DECL_CONTEXT (ctx)))
5495                 if (TYPE_P (ctx) && same_type_p (ctx, template_type))
5496                   goto found_ctx;
5497
5498               /* We're not in the scope of the class, so the
5499                  TEMPLATE_TYPE is not the type we want after all.  */
5500               found = NULL_TREE;
5501             found_ctx:;
5502             }
5503         }
5504       if (found)
5505         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5506
5507       /* If we already have this specialization, return it.  */
5508       found = retrieve_specialization (template, arglist,
5509                                        /*class_specializations_p=*/false);
5510       if (found)
5511         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5512
5513       /* This type is a "partial instantiation" if any of the template
5514          arguments still involve template parameters.  Note that we set
5515          IS_PARTIAL_INSTANTIATION for partial specializations as
5516          well.  */
5517       is_partial_instantiation = uses_template_parms (arglist);
5518
5519       /* If the deduced arguments are invalid, then the binding
5520          failed.  */
5521       if (!is_partial_instantiation
5522           && check_instantiated_args (template,
5523                                       INNERMOST_TEMPLATE_ARGS (arglist),
5524                                       complain))
5525         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5526
5527       if (!is_partial_instantiation
5528           && !PRIMARY_TEMPLATE_P (template)
5529           && TREE_CODE (CP_DECL_CONTEXT (template)) == NAMESPACE_DECL)
5530         {
5531           found = xref_tag_from_type (TREE_TYPE (template),
5532                                       DECL_NAME (template),
5533                                       /*tag_scope=*/ts_global);
5534           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5535         }
5536
5537       context = tsubst (DECL_CONTEXT (template), arglist,
5538                         complain, in_decl);
5539       if (!context)
5540         context = global_namespace;
5541
5542       /* Create the type.  */
5543       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
5544         {
5545           if (!is_partial_instantiation)
5546             {
5547               set_current_access_from_decl (TYPE_NAME (template_type));
5548               t = start_enum (TYPE_IDENTIFIER (template_type));
5549             }
5550           else
5551             /* We don't want to call start_enum for this type, since
5552                the values for the enumeration constants may involve
5553                template parameters.  And, no one should be interested
5554                in the enumeration constants for such a type.  */
5555             t = make_node (ENUMERAL_TYPE);
5556         }
5557       else
5558         {
5559           t = make_aggr_type (TREE_CODE (template_type));
5560           CLASSTYPE_DECLARED_CLASS (t)
5561             = CLASSTYPE_DECLARED_CLASS (template_type);
5562           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
5563           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
5564
5565           /* A local class.  Make sure the decl gets registered properly.  */
5566           if (context == current_function_decl)
5567             pushtag (DECL_NAME (template), t, /*tag_scope=*/ts_current);
5568
5569           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
5570             /* This instantiation is another name for the primary
5571                template type. Set the TYPE_CANONICAL field
5572                appropriately. */
5573             TYPE_CANONICAL (t) = template_type;
5574           else if (any_template_arguments_need_structural_equality_p (arglist))
5575             /* Some of the template arguments require structural
5576                equality testing, so this template class requires
5577                structural equality testing. */
5578             SET_TYPE_STRUCTURAL_EQUALITY (t);
5579         }
5580
5581       /* If we called start_enum or pushtag above, this information
5582          will already be set up.  */
5583       if (!TYPE_NAME (t))
5584         {
5585           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
5586
5587           type_decl = create_implicit_typedef (DECL_NAME (template), t);
5588           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
5589           TYPE_STUB_DECL (t) = type_decl;
5590           DECL_SOURCE_LOCATION (type_decl)
5591             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
5592         }
5593       else
5594         type_decl = TYPE_NAME (t);
5595
5596       TREE_PRIVATE (type_decl)
5597         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
5598       TREE_PROTECTED (type_decl)
5599         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
5600       DECL_IN_SYSTEM_HEADER (type_decl)
5601         = DECL_IN_SYSTEM_HEADER (template);
5602       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
5603         {
5604           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
5605           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
5606         }
5607
5608       /* Set up the template information.  We have to figure out which
5609          template is the immediate parent if this is a full
5610          instantiation.  */
5611       if (parm_depth == 1 || is_partial_instantiation
5612           || !PRIMARY_TEMPLATE_P (template))
5613         /* This case is easy; there are no member templates involved.  */
5614         found = template;
5615       else
5616         {
5617           /* This is a full instantiation of a member template.  Look
5618              for a partial instantiation of which this is an instance.  */
5619
5620           for (found = DECL_TEMPLATE_INSTANTIATIONS (template);
5621                found; found = TREE_CHAIN (found))
5622             {
5623               int success;
5624               tree tmpl = CLASSTYPE_TI_TEMPLATE (TREE_VALUE (found));
5625
5626               /* We only want partial instantiations, here, not
5627                  specializations or full instantiations.  */
5628               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_VALUE (found))
5629                   || !uses_template_parms (TREE_VALUE (found)))
5630                 continue;
5631
5632               /* Temporarily reduce by one the number of levels in the
5633                  ARGLIST and in FOUND so as to avoid comparing the
5634                  last set of arguments.  */
5635               TREE_VEC_LENGTH (arglist)--;
5636               TREE_VEC_LENGTH (TREE_PURPOSE (found)) --;
5637
5638               /* See if the arguments match.  If they do, then TMPL is
5639                  the partial instantiation we want.  */
5640               success = comp_template_args (TREE_PURPOSE (found), arglist);
5641
5642               /* Restore the argument vectors to their full size.  */
5643               TREE_VEC_LENGTH (arglist)++;
5644               TREE_VEC_LENGTH (TREE_PURPOSE (found))++;
5645
5646               if (success)
5647                 {
5648                   found = tmpl;
5649                   break;
5650                 }
5651             }
5652
5653           if (!found)
5654             {
5655               /* There was no partial instantiation. This happens
5656                  where C<T> is a member template of A<T> and it's used
5657                  in something like
5658
5659                   template <typename T> struct B { A<T>::C<int> m; };
5660                   B<float>;
5661
5662                  Create the partial instantiation.
5663                */
5664               TREE_VEC_LENGTH (arglist)--;
5665               found = tsubst (template, arglist, complain, NULL_TREE);
5666               TREE_VEC_LENGTH (arglist)++;
5667             }
5668         }
5669
5670       SET_TYPE_TEMPLATE_INFO (t, tree_cons (found, arglist, NULL_TREE));
5671       DECL_TEMPLATE_INSTANTIATIONS (template)
5672         = tree_cons (arglist, t,
5673                      DECL_TEMPLATE_INSTANTIATIONS (template));
5674
5675       if (TREE_CODE (t) == ENUMERAL_TYPE
5676           && !is_partial_instantiation)
5677         /* Now that the type has been registered on the instantiations
5678            list, we set up the enumerators.  Because the enumeration
5679            constants may involve the enumeration type itself, we make
5680            sure to register the type first, and then create the
5681            constants.  That way, doing tsubst_expr for the enumeration
5682            constants won't result in recursive calls here; we'll find
5683            the instantiation and exit above.  */
5684         tsubst_enum (template_type, t, arglist);
5685
5686       if (is_partial_instantiation)
5687         /* If the type makes use of template parameters, the
5688            code that generates debugging information will crash.  */
5689         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
5690
5691       /* Possibly limit visibility based on template args.  */
5692       TREE_PUBLIC (type_decl) = 1;
5693       determine_visibility (type_decl);
5694
5695       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
5696     }
5697   timevar_pop (TV_NAME_LOOKUP);
5698 }
5699 \f
5700 struct pair_fn_data
5701 {
5702   tree_fn_t fn;
5703   void *data;
5704   struct pointer_set_t *visited;
5705 };
5706
5707 /* Called from for_each_template_parm via walk_tree.  */
5708
5709 static tree
5710 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
5711 {
5712   tree t = *tp;
5713   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
5714   tree_fn_t fn = pfd->fn;
5715   void *data = pfd->data;
5716
5717   if (TYPE_P (t)
5718       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited))
5719     return error_mark_node;
5720
5721   switch (TREE_CODE (t))
5722     {
5723     case RECORD_TYPE:
5724       if (TYPE_PTRMEMFUNC_P (t))
5725         break;
5726       /* Fall through.  */
5727
5728     case UNION_TYPE:
5729     case ENUMERAL_TYPE:
5730       if (!TYPE_TEMPLATE_INFO (t))
5731         *walk_subtrees = 0;
5732       else if (for_each_template_parm (TREE_VALUE (TYPE_TEMPLATE_INFO (t)),
5733                                        fn, data, pfd->visited))
5734         return error_mark_node;
5735       break;
5736
5737     case INTEGER_TYPE:
5738       if (for_each_template_parm (TYPE_MIN_VALUE (t),
5739                                   fn, data, pfd->visited)
5740           || for_each_template_parm (TYPE_MAX_VALUE (t),
5741                                      fn, data, pfd->visited))
5742         return error_mark_node;
5743       break;
5744
5745     case METHOD_TYPE:
5746       /* Since we're not going to walk subtrees, we have to do this
5747          explicitly here.  */
5748       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
5749                                   pfd->visited))
5750         return error_mark_node;
5751       /* Fall through.  */
5752
5753     case FUNCTION_TYPE:
5754       /* Check the return type.  */
5755       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited))
5756         return error_mark_node;
5757
5758       /* Check the parameter types.  Since default arguments are not
5759          instantiated until they are needed, the TYPE_ARG_TYPES may
5760          contain expressions that involve template parameters.  But,
5761          no-one should be looking at them yet.  And, once they're
5762          instantiated, they don't contain template parameters, so
5763          there's no point in looking at them then, either.  */
5764       {
5765         tree parm;
5766
5767         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
5768           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
5769                                       pfd->visited))
5770             return error_mark_node;
5771
5772         /* Since we've already handled the TYPE_ARG_TYPES, we don't
5773            want walk_tree walking into them itself.  */
5774         *walk_subtrees = 0;
5775       }
5776       break;
5777
5778     case TYPEOF_TYPE:
5779       if (for_each_template_parm (TYPE_FIELDS (t), fn, data,
5780                                   pfd->visited))
5781         return error_mark_node;
5782       break;
5783
5784     case FUNCTION_DECL:
5785     case VAR_DECL:
5786       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
5787           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
5788                                      pfd->visited))
5789         return error_mark_node;
5790       /* Fall through.  */
5791
5792     case PARM_DECL:
5793     case CONST_DECL:
5794       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
5795           && for_each_template_parm (DECL_INITIAL (t), fn, data,
5796                                      pfd->visited))
5797         return error_mark_node;
5798       if (DECL_CONTEXT (t)
5799           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
5800                                      pfd->visited))
5801         return error_mark_node;
5802       break;
5803
5804     case BOUND_TEMPLATE_TEMPLATE_PARM:
5805       /* Record template parameters such as `T' inside `TT<T>'.  */
5806       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited))
5807         return error_mark_node;
5808       /* Fall through.  */
5809
5810     case TEMPLATE_TEMPLATE_PARM:
5811     case TEMPLATE_TYPE_PARM:
5812     case TEMPLATE_PARM_INDEX:
5813       if (fn && (*fn)(t, data))
5814         return error_mark_node;
5815       else if (!fn)
5816         return error_mark_node;
5817       break;
5818
5819     case TEMPLATE_DECL:
5820       /* A template template parameter is encountered.  */
5821       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
5822           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited))
5823         return error_mark_node;
5824
5825       /* Already substituted template template parameter */
5826       *walk_subtrees = 0;
5827       break;
5828
5829     case TYPENAME_TYPE:
5830       if (!fn
5831           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
5832                                      data, pfd->visited))
5833         return error_mark_node;
5834       break;
5835
5836     case CONSTRUCTOR:
5837       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
5838           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
5839                                      (TREE_TYPE (t)), fn, data,
5840                                      pfd->visited))
5841         return error_mark_node;
5842       break;
5843
5844     case INDIRECT_REF:
5845     case COMPONENT_REF:
5846       /* If there's no type, then this thing must be some expression
5847          involving template parameters.  */
5848       if (!fn && !TREE_TYPE (t))
5849         return error_mark_node;
5850       break;
5851
5852     case MODOP_EXPR:
5853     case CAST_EXPR:
5854     case REINTERPRET_CAST_EXPR:
5855     case CONST_CAST_EXPR:
5856     case STATIC_CAST_EXPR:
5857     case DYNAMIC_CAST_EXPR:
5858     case ARROW_EXPR:
5859     case DOTSTAR_EXPR:
5860     case TYPEID_EXPR:
5861     case PSEUDO_DTOR_EXPR:
5862       if (!fn)
5863         return error_mark_node;
5864       break;
5865
5866     default:
5867       break;
5868     }
5869
5870   /* We didn't find any template parameters we liked.  */
5871   return NULL_TREE;
5872 }
5873
5874 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
5875    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
5876    call FN with the parameter and the DATA.
5877    If FN returns nonzero, the iteration is terminated, and
5878    for_each_template_parm returns 1.  Otherwise, the iteration
5879    continues.  If FN never returns a nonzero value, the value
5880    returned by for_each_template_parm is 0.  If FN is NULL, it is
5881    considered to be the function which always returns 1.  */
5882
5883 static int
5884 for_each_template_parm (tree t, tree_fn_t fn, void* data,
5885                         struct pointer_set_t *visited)
5886 {
5887   struct pair_fn_data pfd;
5888   int result;
5889
5890   /* Set up.  */
5891   pfd.fn = fn;
5892   pfd.data = data;
5893
5894   /* Walk the tree.  (Conceptually, we would like to walk without
5895      duplicates, but for_each_template_parm_r recursively calls
5896      for_each_template_parm, so we would need to reorganize a fair
5897      bit to use walk_tree_without_duplicates, so we keep our own
5898      visited list.)  */
5899   if (visited)
5900     pfd.visited = visited;
5901   else
5902     pfd.visited = pointer_set_create ();
5903   result = cp_walk_tree (&t,
5904                          for_each_template_parm_r,
5905                          &pfd,
5906                          pfd.visited) != NULL_TREE;
5907
5908   /* Clean up.  */
5909   if (!visited)
5910     {
5911       pointer_set_destroy (pfd.visited);
5912       pfd.visited = 0;
5913     }
5914
5915   return result;
5916 }
5917
5918 /* Returns true if T depends on any template parameter.  */
5919
5920 int
5921 uses_template_parms (tree t)
5922 {
5923   bool dependent_p;
5924   int saved_processing_template_decl;
5925
5926   saved_processing_template_decl = processing_template_decl;
5927   if (!saved_processing_template_decl)
5928     processing_template_decl = 1;
5929   if (TYPE_P (t))
5930     dependent_p = dependent_type_p (t);
5931   else if (TREE_CODE (t) == TREE_VEC)
5932     dependent_p = any_dependent_template_arguments_p (t);
5933   else if (TREE_CODE (t) == TREE_LIST)
5934     dependent_p = (uses_template_parms (TREE_VALUE (t))
5935                    || uses_template_parms (TREE_CHAIN (t)));
5936   else if (TREE_CODE (t) == TYPE_DECL)
5937     dependent_p = dependent_type_p (TREE_TYPE (t));
5938   else if (DECL_P (t)
5939            || EXPR_P (t)
5940            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
5941            || TREE_CODE (t) == OVERLOAD
5942            || TREE_CODE (t) == BASELINK
5943            || TREE_CODE (t) == IDENTIFIER_NODE
5944            || TREE_CODE (t) == TRAIT_EXPR
5945            || CONSTANT_CLASS_P (t))
5946     dependent_p = (type_dependent_expression_p (t)
5947                    || value_dependent_expression_p (t));
5948   else
5949     {
5950       gcc_assert (t == error_mark_node);
5951       dependent_p = false;
5952     }
5953
5954   processing_template_decl = saved_processing_template_decl;
5955
5956   return dependent_p;
5957 }
5958
5959 /* Returns true if T depends on any template parameter with level LEVEL.  */
5960
5961 int
5962 uses_template_parms_level (tree t, int level)
5963 {
5964   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL);
5965 }
5966
5967 static int tinst_depth;
5968 extern int max_tinst_depth;
5969 #ifdef GATHER_STATISTICS
5970 int depth_reached;
5971 #endif
5972 static int tinst_level_tick;
5973 static int last_template_error_tick;
5974
5975 /* We're starting to instantiate D; record the template instantiation context
5976    for diagnostics and to restore it later.  */
5977
5978 static int
5979 push_tinst_level (tree d)
5980 {
5981   struct tinst_level *new;
5982
5983   if (tinst_depth >= max_tinst_depth)
5984     {
5985       /* If the instantiation in question still has unbound template parms,
5986          we don't really care if we can't instantiate it, so just return.
5987          This happens with base instantiation for implicit `typename'.  */
5988       if (uses_template_parms (d))
5989         return 0;
5990
5991       last_template_error_tick = tinst_level_tick;
5992       error ("template instantiation depth exceeds maximum of %d (use "
5993              "-ftemplate-depth-NN to increase the maximum) instantiating %qD",
5994              max_tinst_depth, d);
5995
5996       print_instantiation_context ();
5997
5998       return 0;
5999     }
6000
6001   new = GGC_NEW (struct tinst_level);
6002   new->decl = d;
6003   new->locus = input_location;
6004   new->in_system_header_p = in_system_header;
6005   new->next = current_tinst_level;
6006   current_tinst_level = new;
6007
6008   ++tinst_depth;
6009 #ifdef GATHER_STATISTICS
6010   if (tinst_depth > depth_reached)
6011     depth_reached = tinst_depth;
6012 #endif
6013
6014   ++tinst_level_tick;
6015   return 1;
6016 }
6017
6018 /* We're done instantiating this template; return to the instantiation
6019    context.  */
6020
6021 static void
6022 pop_tinst_level (void)
6023 {
6024   /* Restore the filename and line number stashed away when we started
6025      this instantiation.  */
6026   input_location = current_tinst_level->locus;
6027   in_system_header = current_tinst_level->in_system_header_p;
6028   current_tinst_level = current_tinst_level->next;
6029   --tinst_depth;
6030   ++tinst_level_tick;
6031 }
6032
6033 /* We're instantiating a deferred template; restore the template
6034    instantiation context in which the instantiation was requested, which
6035    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
6036
6037 static tree
6038 reopen_tinst_level (struct tinst_level *level)
6039 {
6040   struct tinst_level *t;
6041
6042   tinst_depth = 0;
6043   for (t = level; t; t = t->next)
6044     ++tinst_depth;
6045
6046   current_tinst_level = level;
6047   pop_tinst_level ();
6048   return level->decl;
6049 }
6050
6051 /* Returns the TINST_LEVEL which gives the original instantiation
6052    context.  */
6053
6054 struct tinst_level *
6055 outermost_tinst_level (void)
6056 {
6057   struct tinst_level *level = current_tinst_level;
6058   if (level)
6059     while (level->next)
6060       level = level->next;
6061   return level;
6062 }
6063
6064 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
6065    vector of template arguments, as for tsubst.
6066
6067    Returns an appropriate tsubst'd friend declaration.  */
6068
6069 static tree
6070 tsubst_friend_function (tree decl, tree args)
6071 {
6072   tree new_friend;
6073
6074   if (TREE_CODE (decl) == FUNCTION_DECL
6075       && DECL_TEMPLATE_INSTANTIATION (decl)
6076       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
6077     /* This was a friend declared with an explicit template
6078        argument list, e.g.:
6079
6080        friend void f<>(T);
6081
6082        to indicate that f was a template instantiation, not a new
6083        function declaration.  Now, we have to figure out what
6084        instantiation of what template.  */
6085     {
6086       tree template_id, arglist, fns;
6087       tree new_args;
6088       tree tmpl;
6089       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
6090
6091       /* Friend functions are looked up in the containing namespace scope.
6092          We must enter that scope, to avoid finding member functions of the
6093          current cless with same name.  */
6094       push_nested_namespace (ns);
6095       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
6096                          tf_warning_or_error, NULL_TREE,
6097                          /*integral_constant_expression_p=*/false);
6098       pop_nested_namespace (ns);
6099       arglist = tsubst (DECL_TI_ARGS (decl), args,
6100                         tf_warning_or_error, NULL_TREE);
6101       template_id = lookup_template_function (fns, arglist);
6102
6103       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6104       tmpl = determine_specialization (template_id, new_friend,
6105                                        &new_args,
6106                                        /*need_member_template=*/0,
6107                                        TREE_VEC_LENGTH (args),
6108                                        tsk_none);
6109       return instantiate_template (tmpl, new_args, tf_error);
6110     }
6111
6112   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6113
6114   /* The NEW_FRIEND will look like an instantiation, to the
6115      compiler, but is not an instantiation from the point of view of
6116      the language.  For example, we might have had:
6117
6118      template <class T> struct S {
6119        template <class U> friend void f(T, U);
6120      };
6121
6122      Then, in S<int>, template <class U> void f(int, U) is not an
6123      instantiation of anything.  */
6124   if (new_friend == error_mark_node)
6125     return error_mark_node;
6126
6127   DECL_USE_TEMPLATE (new_friend) = 0;
6128   if (TREE_CODE (decl) == TEMPLATE_DECL)
6129     {
6130       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
6131       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
6132         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
6133     }
6134
6135   /* The mangled name for the NEW_FRIEND is incorrect.  The function
6136      is not a template instantiation and should not be mangled like
6137      one.  Therefore, we forget the mangling here; we'll recompute it
6138      later if we need it.  */
6139   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
6140     {
6141       SET_DECL_RTL (new_friend, NULL_RTX);
6142       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
6143     }
6144
6145   if (DECL_NAMESPACE_SCOPE_P (new_friend))
6146     {
6147       tree old_decl;
6148       tree new_friend_template_info;
6149       tree new_friend_result_template_info;
6150       tree ns;
6151       int  new_friend_is_defn;
6152
6153       /* We must save some information from NEW_FRIEND before calling
6154          duplicate decls since that function will free NEW_FRIEND if
6155          possible.  */
6156       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
6157       new_friend_is_defn =
6158             (DECL_INITIAL (DECL_TEMPLATE_RESULT
6159                            (template_for_substitution (new_friend)))
6160              != NULL_TREE);
6161       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
6162         {
6163           /* This declaration is a `primary' template.  */
6164           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
6165
6166           new_friend_result_template_info
6167             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
6168         }
6169       else
6170         new_friend_result_template_info = NULL_TREE;
6171
6172       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
6173       if (new_friend_is_defn)
6174         DECL_INITIAL (new_friend) = error_mark_node;
6175
6176       /* Inside pushdecl_namespace_level, we will push into the
6177          current namespace. However, the friend function should go
6178          into the namespace of the template.  */
6179       ns = decl_namespace_context (new_friend);
6180       push_nested_namespace (ns);
6181       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
6182       pop_nested_namespace (ns);
6183
6184       if (old_decl == error_mark_node)
6185         return error_mark_node;
6186
6187       if (old_decl != new_friend)
6188         {
6189           /* This new friend declaration matched an existing
6190              declaration.  For example, given:
6191
6192                template <class T> void f(T);
6193                template <class U> class C {
6194                  template <class T> friend void f(T) {}
6195                };
6196
6197              the friend declaration actually provides the definition
6198              of `f', once C has been instantiated for some type.  So,
6199              old_decl will be the out-of-class template declaration,
6200              while new_friend is the in-class definition.
6201
6202              But, if `f' was called before this point, the
6203              instantiation of `f' will have DECL_TI_ARGS corresponding
6204              to `T' but not to `U', references to which might appear
6205              in the definition of `f'.  Previously, the most general
6206              template for an instantiation of `f' was the out-of-class
6207              version; now it is the in-class version.  Therefore, we
6208              run through all specialization of `f', adding to their
6209              DECL_TI_ARGS appropriately.  In particular, they need a
6210              new set of outer arguments, corresponding to the
6211              arguments for this class instantiation.
6212
6213              The same situation can arise with something like this:
6214
6215                friend void f(int);
6216                template <class T> class C {
6217                  friend void f(T) {}
6218                };
6219
6220              when `C<int>' is instantiated.  Now, `f(int)' is defined
6221              in the class.  */
6222
6223           if (!new_friend_is_defn)
6224             /* On the other hand, if the in-class declaration does
6225                *not* provide a definition, then we don't want to alter
6226                existing definitions.  We can just leave everything
6227                alone.  */
6228             ;
6229           else
6230             {
6231               /* Overwrite whatever template info was there before, if
6232                  any, with the new template information pertaining to
6233                  the declaration.  */
6234               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
6235
6236               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
6237                 reregister_specialization (new_friend,
6238                                            most_general_template (old_decl),
6239                                            old_decl);
6240               else
6241                 {
6242                   tree t;
6243                   tree new_friend_args;
6244
6245                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
6246                     = new_friend_result_template_info;
6247
6248                   new_friend_args = TI_ARGS (new_friend_template_info);
6249                   for (t = DECL_TEMPLATE_SPECIALIZATIONS (old_decl);
6250                        t != NULL_TREE;
6251                        t = TREE_CHAIN (t))
6252                     {
6253                       tree spec = TREE_VALUE (t);
6254
6255                       DECL_TI_ARGS (spec)
6256                         = add_outermost_template_args (new_friend_args,
6257                                                        DECL_TI_ARGS (spec));
6258                     }
6259
6260                   /* Now, since specializations are always supposed to
6261                      hang off of the most general template, we must move
6262                      them.  */
6263                   t = most_general_template (old_decl);
6264                   if (t != old_decl)
6265                     {
6266                       DECL_TEMPLATE_SPECIALIZATIONS (t)
6267                         = chainon (DECL_TEMPLATE_SPECIALIZATIONS (t),
6268                                    DECL_TEMPLATE_SPECIALIZATIONS (old_decl));
6269                       DECL_TEMPLATE_SPECIALIZATIONS (old_decl) = NULL_TREE;
6270                     }
6271                 }
6272             }
6273
6274           /* The information from NEW_FRIEND has been merged into OLD_DECL
6275              by duplicate_decls.  */
6276           new_friend = old_decl;
6277         }
6278     }
6279   else
6280     {
6281       tree context = DECL_CONTEXT (new_friend);
6282       bool dependent_p;
6283
6284       /* In the code
6285            template <class T> class C {
6286              template <class U> friend void C1<U>::f (); // case 1
6287              friend void C2<T>::f ();                    // case 2
6288            };
6289          we only need to make sure CONTEXT is a complete type for
6290          case 2.  To distinguish between the two cases, we note that
6291          CONTEXT of case 1 remains dependent type after tsubst while
6292          this isn't true for case 2.  */
6293       ++processing_template_decl;
6294       dependent_p = dependent_type_p (context);
6295       --processing_template_decl;
6296
6297       if (!dependent_p
6298           && !complete_type_or_else (context, NULL_TREE))
6299         return error_mark_node;
6300
6301       if (COMPLETE_TYPE_P (context))
6302         {
6303           /* Check to see that the declaration is really present, and,
6304              possibly obtain an improved declaration.  */
6305           tree fn = check_classfn (context,
6306                                    new_friend, NULL_TREE);
6307
6308           if (fn)
6309             new_friend = fn;
6310         }
6311     }
6312
6313   return new_friend;
6314 }
6315
6316 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
6317    template arguments, as for tsubst.
6318
6319    Returns an appropriate tsubst'd friend type or error_mark_node on
6320    failure.  */
6321
6322 static tree
6323 tsubst_friend_class (tree friend_tmpl, tree args)
6324 {
6325   tree friend_type;
6326   tree tmpl;
6327   tree context;
6328
6329   context = DECL_CONTEXT (friend_tmpl);
6330
6331   if (context)
6332     {
6333       if (TREE_CODE (context) == NAMESPACE_DECL)
6334         push_nested_namespace (context);
6335       else
6336         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
6337     }
6338
6339   /* Look for a class template declaration.  We look for hidden names
6340      because two friend declarations of the same template are the
6341      same.  For example, in:
6342
6343        struct A { 
6344          template <typename> friend class F;
6345        };
6346        template <typename> struct B { 
6347          template <typename> friend class F;
6348        };
6349
6350      both F templates are the same.  */
6351   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
6352                            /*block_p=*/true, 0, 
6353                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
6354
6355   /* But, if we don't find one, it might be because we're in a
6356      situation like this:
6357
6358        template <class T>
6359        struct S {
6360          template <class U>
6361          friend struct S;
6362        };
6363
6364      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
6365      for `S<int>', not the TEMPLATE_DECL.  */
6366   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
6367     {
6368       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
6369       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
6370     }
6371
6372   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
6373     {
6374       /* The friend template has already been declared.  Just
6375          check to see that the declarations match, and install any new
6376          default parameters.  We must tsubst the default parameters,
6377          of course.  We only need the innermost template parameters
6378          because that is all that redeclare_class_template will look
6379          at.  */
6380       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
6381           > TMPL_ARGS_DEPTH (args))
6382         {
6383           tree parms;
6384           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
6385                                          args, tf_warning_or_error);
6386           redeclare_class_template (TREE_TYPE (tmpl), parms);
6387         }
6388
6389       friend_type = TREE_TYPE (tmpl);
6390     }
6391   else
6392     {
6393       /* The friend template has not already been declared.  In this
6394          case, the instantiation of the template class will cause the
6395          injection of this template into the global scope.  */
6396       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
6397       if (tmpl == error_mark_node)
6398         return error_mark_node;
6399
6400       /* The new TMPL is not an instantiation of anything, so we
6401          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
6402          the new type because that is supposed to be the corresponding
6403          template decl, i.e., TMPL.  */
6404       DECL_USE_TEMPLATE (tmpl) = 0;
6405       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
6406       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
6407       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
6408         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
6409
6410       /* Inject this template into the global scope.  */
6411       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
6412     }
6413
6414   if (context)
6415     {
6416       if (TREE_CODE (context) == NAMESPACE_DECL)
6417         pop_nested_namespace (context);
6418       else
6419         pop_nested_class ();
6420     }
6421
6422   return friend_type;
6423 }
6424
6425 /* Returns zero if TYPE cannot be completed later due to circularity.
6426    Otherwise returns one.  */
6427
6428 static int
6429 can_complete_type_without_circularity (tree type)
6430 {
6431   if (type == NULL_TREE || type == error_mark_node)
6432     return 0;
6433   else if (COMPLETE_TYPE_P (type))
6434     return 1;
6435   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
6436     return can_complete_type_without_circularity (TREE_TYPE (type));
6437   else if (CLASS_TYPE_P (type)
6438            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
6439     return 0;
6440   else
6441     return 1;
6442 }
6443
6444 tree
6445 instantiate_class_template (tree type)
6446 {
6447   tree template, args, pattern, t, member;
6448   tree typedecl;
6449   tree pbinfo;
6450   tree base_list;
6451
6452   if (type == error_mark_node)
6453     return error_mark_node;
6454
6455   if (TYPE_BEING_DEFINED (type)
6456       || COMPLETE_TYPE_P (type)
6457       || dependent_type_p (type))
6458     return type;
6459
6460   /* Figure out which template is being instantiated.  */
6461   template = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
6462   gcc_assert (TREE_CODE (template) == TEMPLATE_DECL);
6463
6464   /* Determine what specialization of the original template to
6465      instantiate.  */
6466   t = most_specialized_class (type, template);
6467   if (t == error_mark_node)
6468     {
6469       TYPE_BEING_DEFINED (type) = 1;
6470       return error_mark_node;
6471     }
6472   else if (t)
6473     {
6474       /* This TYPE is actually an instantiation of a partial
6475          specialization.  We replace the innermost set of ARGS with
6476          the arguments appropriate for substitution.  For example,
6477          given:
6478
6479            template <class T> struct S {};
6480            template <class T> struct S<T*> {};
6481
6482          and supposing that we are instantiating S<int*>, ARGS will
6483          presently be {int*} -- but we need {int}.  */
6484       pattern = TREE_TYPE (t);
6485       args = TREE_PURPOSE (t);
6486     }
6487   else
6488     {
6489       pattern = TREE_TYPE (template);
6490       args = CLASSTYPE_TI_ARGS (type);
6491     }
6492
6493   /* If the template we're instantiating is incomplete, then clearly
6494      there's nothing we can do.  */
6495   if (!COMPLETE_TYPE_P (pattern))
6496     return type;
6497
6498   /* If we've recursively instantiated too many templates, stop.  */
6499   if (! push_tinst_level (type))
6500     return type;
6501
6502   /* Now we're really doing the instantiation.  Mark the type as in
6503      the process of being defined.  */
6504   TYPE_BEING_DEFINED (type) = 1;
6505
6506   /* We may be in the middle of deferred access check.  Disable
6507      it now.  */
6508   push_deferring_access_checks (dk_no_deferred);
6509
6510   push_to_top_level ();
6511
6512   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
6513
6514   /* Set the input location to the template definition. This is needed
6515      if tsubsting causes an error.  */
6516   typedecl = TYPE_MAIN_DECL (type);
6517   input_location = DECL_SOURCE_LOCATION (typedecl);
6518   in_system_header = DECL_IN_SYSTEM_HEADER (typedecl);
6519
6520   TYPE_HAS_CONSTRUCTOR (type) = TYPE_HAS_CONSTRUCTOR (pattern);
6521   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
6522   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
6523   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
6524   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
6525   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
6526   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
6527   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
6528   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
6529   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
6530   TYPE_PACKED (type) = TYPE_PACKED (pattern);
6531   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
6532   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
6533   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
6534   if (ANON_AGGR_TYPE_P (pattern))
6535     SET_ANON_AGGR_TYPE_P (type);
6536   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
6537     {
6538       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
6539       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
6540     }
6541
6542   pbinfo = TYPE_BINFO (pattern);
6543
6544   /* We should never instantiate a nested class before its enclosing
6545      class; we need to look up the nested class by name before we can
6546      instantiate it, and that lookup should instantiate the enclosing
6547      class.  */
6548   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
6549               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
6550               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
6551
6552   base_list = NULL_TREE;
6553   if (BINFO_N_BASE_BINFOS (pbinfo))
6554     {
6555       tree pbase_binfo;
6556       tree context = TYPE_CONTEXT (type);
6557       tree pushed_scope;
6558       int i;
6559
6560       /* We must enter the scope containing the type, as that is where
6561          the accessibility of types named in dependent bases are
6562          looked up from.  */
6563       pushed_scope = push_scope (context ? context : global_namespace);
6564
6565       /* Substitute into each of the bases to determine the actual
6566          basetypes.  */
6567       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
6568         {
6569           tree base;
6570           tree access = BINFO_BASE_ACCESS (pbinfo, i);
6571           tree expanded_bases = NULL_TREE;
6572           int idx, len = 1;
6573
6574           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
6575             {
6576               expanded_bases = 
6577                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
6578                                        args, tf_error, NULL_TREE);
6579               if (expanded_bases == error_mark_node)
6580                 continue;
6581
6582               len = TREE_VEC_LENGTH (expanded_bases);
6583             }
6584
6585           for (idx = 0; idx < len; idx++)
6586             {
6587               if (expanded_bases)
6588                 /* Extract the already-expanded base class.  */
6589                 base = TREE_VEC_ELT (expanded_bases, idx);
6590               else
6591                 /* Substitute to figure out the base class.  */
6592                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
6593                                NULL_TREE);
6594
6595               if (base == error_mark_node)
6596                 continue;
6597
6598               base_list = tree_cons (access, base, base_list);
6599               if (BINFO_VIRTUAL_P (pbase_binfo))
6600                 TREE_TYPE (base_list) = integer_type_node;
6601             }
6602         }
6603
6604       /* The list is now in reverse order; correct that.  */
6605       base_list = nreverse (base_list);
6606
6607       if (pushed_scope)
6608         pop_scope (pushed_scope);
6609     }
6610   /* Now call xref_basetypes to set up all the base-class
6611      information.  */
6612   xref_basetypes (type, base_list);
6613
6614
6615   /* Now that our base classes are set up, enter the scope of the
6616      class, so that name lookups into base classes, etc. will work
6617      correctly.  This is precisely analogous to what we do in
6618      begin_class_definition when defining an ordinary non-template
6619      class.  */
6620   pushclass (type);
6621
6622   /* Now members are processed in the order of declaration.  */
6623   for (member = CLASSTYPE_DECL_LIST (pattern);
6624        member; member = TREE_CHAIN (member))
6625     {
6626       tree t = TREE_VALUE (member);
6627
6628       if (TREE_PURPOSE (member))
6629         {
6630           if (TYPE_P (t))
6631             {
6632               /* Build new CLASSTYPE_NESTED_UTDS.  */
6633
6634               tree newtag;
6635               bool class_template_p;
6636
6637               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
6638                                   && TYPE_LANG_SPECIFIC (t)
6639                                   && CLASSTYPE_IS_TEMPLATE (t));
6640               /* If the member is a class template, then -- even after
6641                  substitution -- there may be dependent types in the
6642                  template argument list for the class.  We increment
6643                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
6644                  that function will assume that no types are dependent
6645                  when outside of a template.  */
6646               if (class_template_p)
6647                 ++processing_template_decl;
6648               newtag = tsubst (t, args, tf_error, NULL_TREE);
6649               if (class_template_p)
6650                 --processing_template_decl;
6651               if (newtag == error_mark_node)
6652                 continue;
6653
6654               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
6655                 {
6656                   tree name = TYPE_IDENTIFIER (t);
6657
6658                   if (class_template_p)
6659                     /* Unfortunately, lookup_template_class sets
6660                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
6661                        instantiation (i.e., for the type of a member
6662                        template class nested within a template class.)
6663                        This behavior is required for
6664                        maybe_process_partial_specialization to work
6665                        correctly, but is not accurate in this case;
6666                        the TAG is not an instantiation of anything.
6667                        (The corresponding TEMPLATE_DECL is an
6668                        instantiation, but the TYPE is not.) */
6669                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
6670
6671                   /* Now, we call pushtag to put this NEWTAG into the scope of
6672                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
6673                      pushtag calling push_template_decl.  We don't have to do
6674                      this for enums because it will already have been done in
6675                      tsubst_enum.  */
6676                   if (name)
6677                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
6678                   pushtag (name, newtag, /*tag_scope=*/ts_current);
6679                 }
6680             }
6681           else if (TREE_CODE (t) == FUNCTION_DECL
6682                    || DECL_FUNCTION_TEMPLATE_P (t))
6683             {
6684               /* Build new TYPE_METHODS.  */
6685               tree r;
6686
6687               if (TREE_CODE (t) == TEMPLATE_DECL)
6688                 ++processing_template_decl;
6689               r = tsubst (t, args, tf_error, NULL_TREE);
6690               if (TREE_CODE (t) == TEMPLATE_DECL)
6691                 --processing_template_decl;
6692               set_current_access_from_decl (r);
6693               finish_member_declaration (r);
6694             }
6695           else
6696             {
6697               /* Build new TYPE_FIELDS.  */
6698               if (TREE_CODE (t) == STATIC_ASSERT)
6699                 {
6700                   tree condition = 
6701                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
6702                                  tf_warning_or_error, NULL_TREE,
6703                                  /*integral_constant_expression_p=*/true);
6704                   finish_static_assert (condition,
6705                                         STATIC_ASSERT_MESSAGE (t), 
6706                                         STATIC_ASSERT_SOURCE_LOCATION (t),
6707                                         /*member_p=*/true);
6708                 }
6709               else if (TREE_CODE (t) != CONST_DECL)
6710                 {
6711                   tree r;
6712
6713                   /* The the file and line for this declaration, to
6714                      assist in error message reporting.  Since we
6715                      called push_tinst_level above, we don't need to
6716                      restore these.  */
6717                   input_location = DECL_SOURCE_LOCATION (t);
6718
6719                   if (TREE_CODE (t) == TEMPLATE_DECL)
6720                     ++processing_template_decl;
6721                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
6722                   if (TREE_CODE (t) == TEMPLATE_DECL)
6723                     --processing_template_decl;
6724                   if (TREE_CODE (r) == VAR_DECL)
6725                     {
6726                       /* In [temp.inst]:
6727
6728                            [t]he initialization (and any associated
6729                            side-effects) of a static data member does
6730                            not occur unless the static data member is
6731                            itself used in a way that requires the
6732                            definition of the static data member to
6733                            exist.
6734
6735                          Therefore, we do not substitute into the
6736                          initialized for the static data member here.  */
6737                       finish_static_data_member_decl
6738                         (r,
6739                          /*init=*/NULL_TREE,
6740                          /*init_const_expr_p=*/false,
6741                          /*asmspec_tree=*/NULL_TREE,
6742                          /*flags=*/0);
6743                       if (DECL_INITIALIZED_IN_CLASS_P (r))
6744                         check_static_variable_definition (r, TREE_TYPE (r));
6745                     }
6746                   else if (TREE_CODE (r) == FIELD_DECL)
6747                     {
6748                       /* Determine whether R has a valid type and can be
6749                          completed later.  If R is invalid, then it is
6750                          replaced by error_mark_node so that it will not be
6751                          added to TYPE_FIELDS.  */
6752                       tree rtype = TREE_TYPE (r);
6753                       if (can_complete_type_without_circularity (rtype))
6754                         complete_type (rtype);
6755
6756                       if (!COMPLETE_TYPE_P (rtype))
6757                         {
6758                           cxx_incomplete_type_error (r, rtype);
6759                           r = error_mark_node;
6760                         }
6761                     }
6762
6763                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
6764                      such a thing will already have been added to the field
6765                      list by tsubst_enum in finish_member_declaration in the
6766                      CLASSTYPE_NESTED_UTDS case above.  */
6767                   if (!(TREE_CODE (r) == TYPE_DECL
6768                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
6769                         && DECL_ARTIFICIAL (r)))
6770                     {
6771                       set_current_access_from_decl (r);
6772                       finish_member_declaration (r);
6773                     }
6774                 }
6775             }
6776         }
6777       else
6778         {
6779           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
6780             {
6781               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
6782
6783               tree friend_type = t;
6784               bool adjust_processing_template_decl = false;
6785
6786               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
6787                 {
6788                   /* template <class T> friend class C;  */
6789                   friend_type = tsubst_friend_class (friend_type, args);
6790                   adjust_processing_template_decl = true;
6791                 }
6792               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
6793                 {
6794                   /* template <class T> friend class C::D;  */
6795                   friend_type = tsubst (friend_type, args,
6796                                         tf_warning_or_error, NULL_TREE);
6797                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
6798                     friend_type = TREE_TYPE (friend_type);
6799                   adjust_processing_template_decl = true;
6800                 }
6801               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
6802                 {
6803                   /* This could be either
6804
6805                        friend class T::C;
6806
6807                      when dependent_type_p is false or
6808
6809                        template <class U> friend class T::C;
6810
6811                      otherwise.  */
6812                   friend_type = tsubst (friend_type, args,
6813                                         tf_warning_or_error, NULL_TREE);
6814                   /* Bump processing_template_decl for correct
6815                      dependent_type_p calculation.  */
6816                   ++processing_template_decl;
6817                   if (dependent_type_p (friend_type))
6818                     adjust_processing_template_decl = true;
6819                   --processing_template_decl;
6820                 }
6821               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
6822                        && hidden_name_p (TYPE_NAME (friend_type)))
6823                 {
6824                   /* friend class C;
6825
6826                      where C hasn't been declared yet.  Let's lookup name
6827                      from namespace scope directly, bypassing any name that
6828                      come from dependent base class.  */
6829                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
6830
6831                   /* The call to xref_tag_from_type does injection for friend
6832                      classes.  */
6833                   push_nested_namespace (ns);
6834                   friend_type =
6835                     xref_tag_from_type (friend_type, NULL_TREE,
6836                                         /*tag_scope=*/ts_current);
6837                   pop_nested_namespace (ns);
6838                 }
6839               else if (uses_template_parms (friend_type))
6840                 /* friend class C<T>;  */
6841                 friend_type = tsubst (friend_type, args,
6842                                       tf_warning_or_error, NULL_TREE);
6843               /* Otherwise it's
6844
6845                    friend class C;
6846
6847                  where C is already declared or
6848
6849                    friend class C<int>;
6850
6851                  We don't have to do anything in these cases.  */
6852
6853               if (adjust_processing_template_decl)
6854                 /* Trick make_friend_class into realizing that the friend
6855                    we're adding is a template, not an ordinary class.  It's
6856                    important that we use make_friend_class since it will
6857                    perform some error-checking and output cross-reference
6858                    information.  */
6859                 ++processing_template_decl;
6860
6861               if (friend_type != error_mark_node)
6862                 make_friend_class (type, friend_type, /*complain=*/false);
6863
6864               if (adjust_processing_template_decl)
6865                 --processing_template_decl;
6866             }
6867           else
6868             {
6869               /* Build new DECL_FRIENDLIST.  */
6870               tree r;
6871
6872               /* The the file and line for this declaration, to
6873                  assist in error message reporting.  Since we
6874                  called push_tinst_level above, we don't need to
6875                  restore these.  */
6876               input_location = DECL_SOURCE_LOCATION (t);
6877
6878               if (TREE_CODE (t) == TEMPLATE_DECL)
6879                 {
6880                   ++processing_template_decl;
6881                   push_deferring_access_checks (dk_no_check);
6882                 }
6883
6884               r = tsubst_friend_function (t, args);
6885               add_friend (type, r, /*complain=*/false);
6886               if (TREE_CODE (t) == TEMPLATE_DECL)
6887                 {
6888                   pop_deferring_access_checks ();
6889                   --processing_template_decl;
6890                 }
6891             }
6892         }
6893     }
6894
6895   /* Set the file and line number information to whatever is given for
6896      the class itself.  This puts error messages involving generated
6897      implicit functions at a predictable point, and the same point
6898      that would be used for non-template classes.  */
6899   input_location = DECL_SOURCE_LOCATION (typedecl);
6900
6901   unreverse_member_declarations (type);
6902   finish_struct_1 (type);
6903   TYPE_BEING_DEFINED (type) = 0;
6904
6905   /* Now that the class is complete, instantiate default arguments for
6906      any member functions.  We don't do this earlier because the
6907      default arguments may reference members of the class.  */
6908   if (!PRIMARY_TEMPLATE_P (template))
6909     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
6910       if (TREE_CODE (t) == FUNCTION_DECL
6911           /* Implicitly generated member functions will not have template
6912              information; they are not instantiations, but instead are
6913              created "fresh" for each instantiation.  */
6914           && DECL_TEMPLATE_INFO (t))
6915         tsubst_default_arguments (t);
6916
6917   popclass ();
6918   pop_from_top_level ();
6919   pop_deferring_access_checks ();
6920   pop_tinst_level ();
6921
6922   /* The vtable for a template class can be emitted in any translation
6923      unit in which the class is instantiated.  When there is no key
6924      method, however, finish_struct_1 will already have added TYPE to
6925      the keyed_classes list.  */
6926   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
6927     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
6928
6929   return type;
6930 }
6931
6932 static tree
6933 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
6934 {
6935   tree r;
6936
6937   if (!t)
6938     r = t;
6939   else if (TYPE_P (t))
6940     r = tsubst (t, args, complain, in_decl);
6941   else
6942     {
6943       r = tsubst_expr (t, args, complain, in_decl,
6944                        /*integral_constant_expression_p=*/true);
6945       r = fold_non_dependent_expr (r);
6946     }
6947   return r;
6948 }
6949
6950 /* Substitute ARGS into T, which is an pack expansion
6951    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
6952    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
6953    (if only a partial substitution could be performed) or
6954    ERROR_MARK_NODE if there was an error.  */
6955 tree
6956 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
6957                        tree in_decl)
6958 {
6959   tree pattern;
6960   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
6961   tree first_arg_pack; int i, len = -1;
6962   tree result;
6963   int incomplete = 0;
6964
6965   gcc_assert (PACK_EXPANSION_P (t));
6966   pattern = PACK_EXPANSION_PATTERN (t);
6967
6968   /* Determine the argument packs that will instantiate the parameter
6969      packs used in the expansion expression. While we're at it,
6970      compute the number of arguments to be expanded and make sure it
6971      is consistent.  */
6972   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
6973        pack = TREE_CHAIN (pack))
6974     {
6975       tree parm_pack = TREE_VALUE (pack);
6976       tree arg_pack = NULL_TREE;
6977       tree orig_arg = NULL_TREE;
6978
6979       if (TREE_CODE (parm_pack) == PARM_DECL)
6980         {
6981           if (local_specializations)
6982             arg_pack = retrieve_local_specialization (parm_pack);
6983         }
6984       else
6985         {
6986           int level, idx, levels;
6987           template_parm_level_and_index (parm_pack, &level, &idx);
6988
6989           levels = TMPL_ARGS_DEPTH (args);
6990           if (level <= levels)
6991             arg_pack = TMPL_ARG (args, level, idx);
6992         }
6993
6994       orig_arg = arg_pack;
6995       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
6996         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
6997       
6998       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
6999         /* This can only happen if we forget to expand an argument
7000            pack somewhere else. Just return an error, silently.  */
7001         {
7002           result = make_tree_vec (1);
7003           TREE_VEC_ELT (result, 0) = error_mark_node;
7004           return result;
7005         }
7006
7007       if (arg_pack)
7008         {
7009           int my_len = 
7010             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
7011
7012           /* It's all-or-nothing with incomplete argument packs.  */
7013           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7014             return error_mark_node;
7015           
7016           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7017             incomplete = 1;
7018
7019           if (len < 0)
7020             {
7021               len = my_len;
7022               first_arg_pack = arg_pack;
7023             }
7024           else if (len != my_len)
7025             {
7026               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
7027                 error ("mismatched argument pack lengths while expanding "
7028                        "%<%T%>",
7029                        pattern);
7030               else
7031                 error ("mismatched argument pack lengths while expanding "
7032                        "%<%E%>",
7033                        pattern);
7034               return error_mark_node;
7035             }
7036
7037           /* Keep track of the parameter packs and their corresponding
7038              argument packs.  */
7039           packs = tree_cons (parm_pack, arg_pack, packs);
7040           TREE_TYPE (packs) = orig_arg;
7041         }
7042       else
7043         /* We can't substitute for this parameter pack.  */
7044         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
7045                                          TREE_VALUE (pack),
7046                                          unsubstituted_packs);
7047     }
7048
7049   /* We cannot expand this expansion expression, because we don't have
7050      all of the argument packs we need. Substitute into the pattern
7051      and return a PACK_EXPANSION_*. The caller will need to deal with
7052      that.  */
7053   if (unsubstituted_packs)
7054     return make_pack_expansion (tsubst (pattern, args, complain, 
7055                                         in_decl));
7056
7057   /* We could not find any argument packs that work.  */
7058   if (len < 0)
7059     return error_mark_node;
7060
7061   /* For each argument in each argument pack, substitute into the
7062      pattern.  */
7063   result = make_tree_vec (len + incomplete);
7064   for (i = 0; i < len + incomplete; ++i)
7065     {
7066       /* For parameter pack, change the substitution of the parameter
7067          pack to the ith argument in its argument pack, then expand
7068          the pattern.  */
7069       for (pack = packs; pack; pack = TREE_CHAIN (pack))
7070         {
7071           tree parm = TREE_PURPOSE (pack);
7072
7073           if (TREE_CODE (parm) == PARM_DECL)
7074             {
7075               /* Select the Ith argument from the pack.  */
7076               tree arg = make_node (ARGUMENT_PACK_SELECT);
7077               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
7078               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
7079               mark_used (parm);
7080               register_local_specialization (arg, parm);
7081             }
7082           else
7083             {
7084               tree value = parm;
7085               int idx, level;
7086               template_parm_level_and_index (parm, &level, &idx);
7087               
7088               if (i < len) 
7089                 {
7090                   /* Select the Ith argument from the pack. */
7091                   value = make_node (ARGUMENT_PACK_SELECT);
7092                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
7093                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
7094                 }
7095
7096               /* Update the corresponding argument.  */
7097               TMPL_ARG (args, level, idx) = value;
7098             }
7099         }
7100
7101       /* Substitute into the PATTERN with the altered arguments.  */
7102       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
7103         TREE_VEC_ELT (result, i) = 
7104           tsubst_expr (pattern, args, complain, in_decl,
7105                        /*integral_constant_expression_p=*/false);
7106       else
7107         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
7108
7109       if (i == len)
7110         /* When we have incomplete argument packs, the last "expanded"
7111            result is itself a pack expansion, which allows us
7112            to deduce more arguments.  */
7113         TREE_VEC_ELT (result, i) = 
7114           make_pack_expansion (TREE_VEC_ELT (result, i));
7115
7116       if (TREE_VEC_ELT (result, i) == error_mark_node)
7117         {
7118           result = error_mark_node;
7119           break;
7120         }
7121     }
7122   
7123   /* Update ARGS to restore the substitution from parameter packs to
7124      their argument packs.  */
7125   for (pack = packs; pack; pack = TREE_CHAIN (pack))
7126     {
7127       tree parm = TREE_PURPOSE (pack);
7128
7129       if (TREE_CODE (parm) == PARM_DECL)
7130         register_local_specialization (TREE_TYPE (pack), parm);
7131       else
7132         {
7133           int idx, level;
7134           template_parm_level_and_index (parm, &level, &idx);
7135           
7136           /* Update the corresponding argument.  */
7137           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
7138             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
7139               TREE_TYPE (pack);
7140           else
7141             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
7142         }
7143     }
7144
7145   return result;
7146 }
7147
7148 /* Substitute ARGS into the vector or list of template arguments T.  */
7149
7150 static tree
7151 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7152 {
7153   tree orig_t = t;
7154   int len = TREE_VEC_LENGTH (t);
7155   int need_new = 0, i, expanded_len_adjust = 0, out;
7156   tree *elts = (tree *) alloca (len * sizeof (tree));
7157
7158   for (i = 0; i < len; i++)
7159     {
7160       tree orig_arg = TREE_VEC_ELT (t, i);
7161       tree new_arg;
7162
7163       if (TREE_CODE (orig_arg) == TREE_VEC)
7164         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
7165       else if (PACK_EXPANSION_P (orig_arg))
7166         {
7167           /* Substitute into an expansion expression.  */
7168           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
7169
7170           if (TREE_CODE (new_arg) == TREE_VEC)
7171             /* Add to the expanded length adjustment the number of
7172                expanded arguments. We subtract one from this
7173                measurement, because the argument pack expression
7174                itself is already counted as 1 in
7175                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
7176                the argument pack is empty.  */
7177             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
7178         }
7179       else if (ARGUMENT_PACK_P (orig_arg))
7180         {
7181           /* Substitute into each of the arguments.  */
7182           new_arg = make_node (TREE_CODE (orig_arg));
7183           
7184           SET_ARGUMENT_PACK_ARGS (
7185             new_arg,
7186             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
7187                                   args, complain, in_decl));
7188
7189           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
7190             new_arg = error_mark_node;
7191
7192           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
7193             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
7194                                           complain, in_decl);
7195             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
7196
7197             if (TREE_TYPE (new_arg) == error_mark_node)
7198               new_arg = error_mark_node;
7199           }
7200         }
7201       else
7202         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
7203
7204       if (new_arg == error_mark_node)
7205         return error_mark_node;
7206
7207       elts[i] = new_arg;
7208       if (new_arg != orig_arg)
7209         need_new = 1;
7210     }
7211
7212   if (!need_new)
7213     return t;
7214
7215   /* Make space for the expanded arguments coming from template
7216      argument packs.  */
7217   t = make_tree_vec (len + expanded_len_adjust);
7218   for (i = 0, out = 0; i < len; i++)
7219     {
7220       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
7221            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
7222           && TREE_CODE (elts[i]) == TREE_VEC)
7223         {
7224           int idx;
7225
7226           /* Now expand the template argument pack "in place".  */
7227           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
7228             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
7229         }
7230       else
7231         {
7232           TREE_VEC_ELT (t, out) = elts[i];
7233           out++;
7234         }
7235     }
7236
7237   return t;
7238 }
7239
7240 /* Return the result of substituting ARGS into the template parameters
7241    given by PARMS.  If there are m levels of ARGS and m + n levels of
7242    PARMS, then the result will contain n levels of PARMS.  For
7243    example, if PARMS is `template <class T> template <class U>
7244    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
7245    result will be `template <int*, double, class V>'.  */
7246
7247 static tree
7248 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
7249 {
7250   tree r = NULL_TREE;
7251   tree* new_parms;
7252
7253   /* When substituting into a template, we must set
7254      PROCESSING_TEMPLATE_DECL as the template parameters may be
7255      dependent if they are based on one-another, and the dependency
7256      predicates are short-circuit outside of templates.  */
7257   ++processing_template_decl;
7258
7259   for (new_parms = &r;
7260        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
7261        new_parms = &(TREE_CHAIN (*new_parms)),
7262          parms = TREE_CHAIN (parms))
7263     {
7264       tree new_vec =
7265         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
7266       int i;
7267
7268       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
7269         {
7270           tree tuple;
7271           tree default_value;
7272           tree parm_decl;
7273
7274           if (parms == error_mark_node)
7275             continue;
7276
7277           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
7278
7279           if (tuple == error_mark_node)
7280             continue;
7281
7282           default_value = TREE_PURPOSE (tuple);
7283           parm_decl = TREE_VALUE (tuple);
7284
7285           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
7286           if (TREE_CODE (parm_decl) == PARM_DECL
7287               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
7288             parm_decl = error_mark_node;
7289           default_value = tsubst_template_arg (default_value, args,
7290                                                complain, NULL_TREE);
7291
7292           tuple = build_tree_list (default_value, parm_decl);
7293           TREE_VEC_ELT (new_vec, i) = tuple;
7294         }
7295
7296       *new_parms =
7297         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
7298                              - TMPL_ARGS_DEPTH (args)),
7299                    new_vec, NULL_TREE);
7300     }
7301
7302   --processing_template_decl;
7303
7304   return r;
7305 }
7306
7307 /* Substitute the ARGS into the indicated aggregate (or enumeration)
7308    type T.  If T is not an aggregate or enumeration type, it is
7309    handled as if by tsubst.  IN_DECL is as for tsubst.  If
7310    ENTERING_SCOPE is nonzero, T is the context for a template which
7311    we are presently tsubst'ing.  Return the substituted value.  */
7312
7313 static tree
7314 tsubst_aggr_type (tree t,
7315                   tree args,
7316                   tsubst_flags_t complain,
7317                   tree in_decl,
7318                   int entering_scope)
7319 {
7320   if (t == NULL_TREE)
7321     return NULL_TREE;
7322
7323   switch (TREE_CODE (t))
7324     {
7325     case RECORD_TYPE:
7326       if (TYPE_PTRMEMFUNC_P (t))
7327         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
7328
7329       /* Else fall through.  */
7330     case ENUMERAL_TYPE:
7331     case UNION_TYPE:
7332       if (TYPE_TEMPLATE_INFO (t))
7333         {
7334           tree argvec;
7335           tree context;
7336           tree r;
7337           bool saved_skip_evaluation;
7338
7339           /* In "sizeof(X<I>)" we need to evaluate "I".  */
7340           saved_skip_evaluation = skip_evaluation;
7341           skip_evaluation = false;
7342
7343           /* First, determine the context for the type we are looking
7344              up.  */
7345           context = TYPE_CONTEXT (t);
7346           if (context)
7347             context = tsubst_aggr_type (context, args, complain,
7348                                         in_decl, /*entering_scope=*/1);
7349
7350           /* Then, figure out what arguments are appropriate for the
7351              type we are trying to find.  For example, given:
7352
7353                template <class T> struct S;
7354                template <class T, class U> void f(T, U) { S<U> su; }
7355
7356              and supposing that we are instantiating f<int, double>,
7357              then our ARGS will be {int, double}, but, when looking up
7358              S we only want {double}.  */
7359           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
7360                                          complain, in_decl);
7361           if (argvec == error_mark_node)
7362             r = error_mark_node;
7363           else
7364             {
7365               r = lookup_template_class (t, argvec, in_decl, context,
7366                                          entering_scope, complain);
7367               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
7368             }
7369
7370           skip_evaluation = saved_skip_evaluation;
7371
7372           return r;
7373         }
7374       else
7375         /* This is not a template type, so there's nothing to do.  */
7376         return t;
7377
7378     default:
7379       return tsubst (t, args, complain, in_decl);
7380     }
7381 }
7382
7383 /* Substitute into the default argument ARG (a default argument for
7384    FN), which has the indicated TYPE.  */
7385
7386 tree
7387 tsubst_default_argument (tree fn, tree type, tree arg)
7388 {
7389   tree saved_class_ptr = NULL_TREE;
7390   tree saved_class_ref = NULL_TREE;
7391
7392   /* This default argument came from a template.  Instantiate the
7393      default argument here, not in tsubst.  In the case of
7394      something like:
7395
7396        template <class T>
7397        struct S {
7398          static T t();
7399          void f(T = t());
7400        };
7401
7402      we must be careful to do name lookup in the scope of S<T>,
7403      rather than in the current class.  */
7404   push_access_scope (fn);
7405   /* The "this" pointer is not valid in a default argument.  */
7406   if (cfun)
7407     {
7408       saved_class_ptr = current_class_ptr;
7409       cp_function_chain->x_current_class_ptr = NULL_TREE;
7410       saved_class_ref = current_class_ref;
7411       cp_function_chain->x_current_class_ref = NULL_TREE;
7412     }
7413
7414   push_deferring_access_checks(dk_no_deferred);
7415   /* The default argument expression may cause implicitly defined
7416      member functions to be synthesized, which will result in garbage
7417      collection.  We must treat this situation as if we were within
7418      the body of function so as to avoid collecting live data on the
7419      stack.  */
7420   ++function_depth;
7421   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
7422                      tf_warning_or_error, NULL_TREE,
7423                      /*integral_constant_expression_p=*/false);
7424   --function_depth;
7425   pop_deferring_access_checks();
7426
7427   /* Restore the "this" pointer.  */
7428   if (cfun)
7429     {
7430       cp_function_chain->x_current_class_ptr = saved_class_ptr;
7431       cp_function_chain->x_current_class_ref = saved_class_ref;
7432     }
7433
7434   pop_access_scope (fn);
7435
7436   /* Make sure the default argument is reasonable.  */
7437   arg = check_default_argument (type, arg);
7438
7439   return arg;
7440 }
7441
7442 /* Substitute into all the default arguments for FN.  */
7443
7444 static void
7445 tsubst_default_arguments (tree fn)
7446 {
7447   tree arg;
7448   tree tmpl_args;
7449
7450   tmpl_args = DECL_TI_ARGS (fn);
7451
7452   /* If this function is not yet instantiated, we certainly don't need
7453      its default arguments.  */
7454   if (uses_template_parms (tmpl_args))
7455     return;
7456
7457   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
7458        arg;
7459        arg = TREE_CHAIN (arg))
7460     if (TREE_PURPOSE (arg))
7461       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
7462                                                     TREE_VALUE (arg),
7463                                                     TREE_PURPOSE (arg));
7464 }
7465
7466 /* Substitute the ARGS into the T, which is a _DECL.  Return the
7467    result of the substitution.  Issue error and warning messages under
7468    control of COMPLAIN.  */
7469
7470 static tree
7471 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
7472 {
7473   location_t saved_loc;
7474   tree r = NULL_TREE;
7475   tree in_decl = t;
7476
7477   /* Set the filename and linenumber to improve error-reporting.  */
7478   saved_loc = input_location;
7479   input_location = DECL_SOURCE_LOCATION (t);
7480
7481   switch (TREE_CODE (t))
7482     {
7483     case TEMPLATE_DECL:
7484       {
7485         /* We can get here when processing a member function template,
7486            member class template, and template template parameter of
7487            a template class.  */
7488         tree decl = DECL_TEMPLATE_RESULT (t);
7489         tree spec;
7490         tree tmpl_args;
7491         tree full_args;
7492
7493         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
7494           {
7495             /* Template template parameter is treated here.  */
7496             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
7497             if (new_type == error_mark_node)
7498               return error_mark_node;
7499
7500             r = copy_decl (t);
7501             TREE_CHAIN (r) = NULL_TREE;
7502             TREE_TYPE (r) = new_type;
7503             DECL_TEMPLATE_RESULT (r)
7504               = build_decl (TYPE_DECL, DECL_NAME (decl), new_type);
7505             DECL_TEMPLATE_PARMS (r)
7506               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
7507                                        complain);
7508             TYPE_NAME (new_type) = r;
7509             break;
7510           }
7511
7512         /* We might already have an instance of this template.
7513            The ARGS are for the surrounding class type, so the
7514            full args contain the tsubst'd args for the context,
7515            plus the innermost args from the template decl.  */
7516         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
7517           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
7518           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
7519         /* Because this is a template, the arguments will still be
7520            dependent, even after substitution.  If
7521            PROCESSING_TEMPLATE_DECL is not set, the dependency
7522            predicates will short-circuit.  */
7523         ++processing_template_decl;
7524         full_args = tsubst_template_args (tmpl_args, args,
7525                                           complain, in_decl);
7526         --processing_template_decl;
7527         if (full_args == error_mark_node)
7528           return error_mark_node;
7529
7530         /* tsubst_template_args doesn't copy the vector if
7531            nothing changed.  But, *something* should have
7532            changed.  */
7533         gcc_assert (full_args != tmpl_args);
7534
7535         spec = retrieve_specialization (t, full_args,
7536                                         /*class_specializations_p=*/true);
7537         if (spec != NULL_TREE)
7538           {
7539             r = spec;
7540             break;
7541           }
7542
7543         /* Make a new template decl.  It will be similar to the
7544            original, but will record the current template arguments.
7545            We also create a new function declaration, which is just
7546            like the old one, but points to this new template, rather
7547            than the old one.  */
7548         r = copy_decl (t);
7549         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
7550         TREE_CHAIN (r) = NULL_TREE;
7551
7552         DECL_TEMPLATE_INFO (r) = build_tree_list (t, args);
7553
7554         if (TREE_CODE (decl) == TYPE_DECL)
7555           {
7556             tree new_type;
7557             ++processing_template_decl;
7558             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
7559             --processing_template_decl;
7560             if (new_type == error_mark_node)
7561               return error_mark_node;
7562
7563             TREE_TYPE (r) = new_type;
7564             CLASSTYPE_TI_TEMPLATE (new_type) = r;
7565             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
7566             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
7567             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
7568           }
7569         else
7570           {
7571             tree new_decl;
7572             ++processing_template_decl;
7573             new_decl = tsubst (decl, args, complain, in_decl);
7574             --processing_template_decl;
7575             if (new_decl == error_mark_node)
7576               return error_mark_node;
7577
7578             DECL_TEMPLATE_RESULT (r) = new_decl;
7579             DECL_TI_TEMPLATE (new_decl) = r;
7580             TREE_TYPE (r) = TREE_TYPE (new_decl);
7581             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
7582             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
7583           }
7584
7585         SET_DECL_IMPLICIT_INSTANTIATION (r);
7586         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
7587         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
7588
7589         /* The template parameters for this new template are all the
7590            template parameters for the old template, except the
7591            outermost level of parameters.  */
7592         DECL_TEMPLATE_PARMS (r)
7593           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
7594                                    complain);
7595
7596         if (PRIMARY_TEMPLATE_P (t))
7597           DECL_PRIMARY_TEMPLATE (r) = r;
7598
7599         if (TREE_CODE (decl) != TYPE_DECL)
7600           /* Record this non-type partial instantiation.  */
7601           register_specialization (r, t,
7602                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
7603                                    false);
7604       }
7605       break;
7606
7607     case FUNCTION_DECL:
7608       {
7609         tree ctx;
7610         tree argvec = NULL_TREE;
7611         tree *friends;
7612         tree gen_tmpl;
7613         tree type;
7614         int member;
7615         int args_depth;
7616         int parms_depth;
7617
7618         /* Nobody should be tsubst'ing into non-template functions.  */
7619         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
7620
7621         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
7622           {
7623             tree spec;
7624             bool dependent_p;
7625
7626             /* If T is not dependent, just return it.  We have to
7627                increment PROCESSING_TEMPLATE_DECL because
7628                value_dependent_expression_p assumes that nothing is
7629                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
7630             ++processing_template_decl;
7631             dependent_p = value_dependent_expression_p (t);
7632             --processing_template_decl;
7633             if (!dependent_p)
7634               return t;
7635
7636             /* Calculate the most general template of which R is a
7637                specialization, and the complete set of arguments used to
7638                specialize R.  */
7639             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
7640             argvec = tsubst_template_args (DECL_TI_ARGS
7641                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
7642                                            args, complain, in_decl);
7643
7644             /* Check to see if we already have this specialization.  */
7645             spec = retrieve_specialization (gen_tmpl, argvec,
7646                                             /*class_specializations_p=*/false);
7647
7648             if (spec)
7649               {
7650                 r = spec;
7651                 break;
7652               }
7653
7654             /* We can see more levels of arguments than parameters if
7655                there was a specialization of a member template, like
7656                this:
7657
7658                  template <class T> struct S { template <class U> void f(); }
7659                  template <> template <class U> void S<int>::f(U);
7660
7661                Here, we'll be substituting into the specialization,
7662                because that's where we can find the code we actually
7663                want to generate, but we'll have enough arguments for
7664                the most general template.
7665
7666                We also deal with the peculiar case:
7667
7668                  template <class T> struct S {
7669                    template <class U> friend void f();
7670                  };
7671                  template <class U> void f() {}
7672                  template S<int>;
7673                  template void f<double>();
7674
7675                Here, the ARGS for the instantiation of will be {int,
7676                double}.  But, we only need as many ARGS as there are
7677                levels of template parameters in CODE_PATTERN.  We are
7678                careful not to get fooled into reducing the ARGS in
7679                situations like:
7680
7681                  template <class T> struct S { template <class U> void f(U); }
7682                  template <class T> template <> void S<T>::f(int) {}
7683
7684                which we can spot because the pattern will be a
7685                specialization in this case.  */
7686             args_depth = TMPL_ARGS_DEPTH (args);
7687             parms_depth =
7688               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
7689             if (args_depth > parms_depth
7690                 && !DECL_TEMPLATE_SPECIALIZATION (t))
7691               args = get_innermost_template_args (args, parms_depth);
7692           }
7693         else
7694           {
7695             /* This special case arises when we have something like this:
7696
7697                  template <class T> struct S {
7698                    friend void f<int>(int, double);
7699                  };
7700
7701                Here, the DECL_TI_TEMPLATE for the friend declaration
7702                will be an IDENTIFIER_NODE.  We are being called from
7703                tsubst_friend_function, and we want only to create a
7704                new decl (R) with appropriate types so that we can call
7705                determine_specialization.  */
7706             gen_tmpl = NULL_TREE;
7707           }
7708
7709         if (DECL_CLASS_SCOPE_P (t))
7710           {
7711             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
7712               member = 2;
7713             else
7714               member = 1;
7715             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
7716                                     complain, t, /*entering_scope=*/1);
7717           }
7718         else
7719           {
7720             member = 0;
7721             ctx = DECL_CONTEXT (t);
7722           }
7723         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
7724         if (type == error_mark_node)
7725           return error_mark_node;
7726
7727         /* We do NOT check for matching decls pushed separately at this
7728            point, as they may not represent instantiations of this
7729            template, and in any case are considered separate under the
7730            discrete model.  */
7731         r = copy_decl (t);
7732         DECL_USE_TEMPLATE (r) = 0;
7733         TREE_TYPE (r) = type;
7734         /* Clear out the mangled name and RTL for the instantiation.  */
7735         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
7736         SET_DECL_RTL (r, NULL_RTX);
7737         DECL_INITIAL (r) = NULL_TREE;
7738         DECL_CONTEXT (r) = ctx;
7739
7740         if (member && DECL_CONV_FN_P (r))
7741           /* Type-conversion operator.  Reconstruct the name, in
7742              case it's the name of one of the template's parameters.  */
7743           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
7744
7745         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
7746                                      complain, t);
7747         DECL_RESULT (r) = NULL_TREE;
7748
7749         TREE_STATIC (r) = 0;
7750         TREE_PUBLIC (r) = TREE_PUBLIC (t);
7751         DECL_EXTERNAL (r) = 1;
7752         /* If this is an instantiation of a function with internal
7753            linkage, we already know what object file linkage will be
7754            assigned to the instantiation.  */
7755         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
7756         DECL_DEFER_OUTPUT (r) = 0;
7757         TREE_CHAIN (r) = NULL_TREE;
7758         DECL_PENDING_INLINE_INFO (r) = 0;
7759         DECL_PENDING_INLINE_P (r) = 0;
7760         DECL_SAVED_TREE (r) = NULL_TREE;
7761         TREE_USED (r) = 0;
7762         if (DECL_CLONED_FUNCTION (r))
7763           {
7764             DECL_CLONED_FUNCTION (r) = tsubst (DECL_CLONED_FUNCTION (t),
7765                                                args, complain, t);
7766             TREE_CHAIN (r) = TREE_CHAIN (DECL_CLONED_FUNCTION (r));
7767             TREE_CHAIN (DECL_CLONED_FUNCTION (r)) = r;
7768           }
7769
7770         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
7771            this in the special friend case mentioned above where
7772            GEN_TMPL is NULL.  */
7773         if (gen_tmpl)
7774           {
7775             DECL_TEMPLATE_INFO (r)
7776               = tree_cons (gen_tmpl, argvec, NULL_TREE);
7777             SET_DECL_IMPLICIT_INSTANTIATION (r);
7778             register_specialization (r, gen_tmpl, argvec, false);
7779
7780             /* We're not supposed to instantiate default arguments
7781                until they are called, for a template.  But, for a
7782                declaration like:
7783
7784                  template <class T> void f ()
7785                  { extern void g(int i = T()); }
7786
7787                we should do the substitution when the template is
7788                instantiated.  We handle the member function case in
7789                instantiate_class_template since the default arguments
7790                might refer to other members of the class.  */
7791             if (!member
7792                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
7793                 && !uses_template_parms (argvec))
7794               tsubst_default_arguments (r);
7795           }
7796         else
7797           DECL_TEMPLATE_INFO (r) = NULL_TREE;
7798
7799         /* Copy the list of befriending classes.  */
7800         for (friends = &DECL_BEFRIENDING_CLASSES (r);
7801              *friends;
7802              friends = &TREE_CHAIN (*friends))
7803           {
7804             *friends = copy_node (*friends);
7805             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
7806                                             args, complain,
7807                                             in_decl);
7808           }
7809
7810         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
7811           {
7812             maybe_retrofit_in_chrg (r);
7813             if (DECL_CONSTRUCTOR_P (r))
7814               grok_ctor_properties (ctx, r);
7815             /* If this is an instantiation of a member template, clone it.
7816                If it isn't, that'll be handled by
7817                clone_constructors_and_destructors.  */
7818             if (PRIMARY_TEMPLATE_P (gen_tmpl))
7819               clone_function_decl (r, /*update_method_vec_p=*/0);
7820           }
7821         else if (IDENTIFIER_OPNAME_P (DECL_NAME (r))
7822                  && !grok_op_properties (r, (complain & tf_error) != 0))
7823           return error_mark_node;
7824
7825         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
7826           SET_DECL_FRIEND_CONTEXT (r,
7827                                    tsubst (DECL_FRIEND_CONTEXT (t),
7828                                             args, complain, in_decl));
7829
7830         /* Possibly limit visibility based on template args.  */
7831         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
7832         if (DECL_VISIBILITY_SPECIFIED (t))
7833           {
7834             DECL_VISIBILITY_SPECIFIED (r) = 0;
7835             DECL_ATTRIBUTES (r)
7836               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
7837           }
7838         determine_visibility (r);
7839       }
7840       break;
7841
7842     case PARM_DECL:
7843       {
7844         tree type = NULL_TREE;
7845         int i, len = 1;
7846         tree expanded_types = NULL_TREE;
7847         tree prev_r = NULL_TREE;
7848         tree first_r = NULL_TREE;
7849
7850         if (FUNCTION_PARAMETER_PACK_P (t))
7851           {
7852             /* If there is a local specialization that isn't a
7853                parameter pack, it means that we're doing a "simple"
7854                substitution from inside tsubst_pack_expansion. Just
7855                return the local specialization (which will be a single
7856                parm).  */
7857             tree spec = NULL_TREE;
7858             if (local_specializations)
7859               spec = retrieve_local_specialization (t);
7860             if (spec 
7861                 && TREE_CODE (spec) == PARM_DECL
7862                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
7863               return spec;
7864
7865             /* Expand the TYPE_PACK_EXPANSION that provides the types for
7866                the parameters in this function parameter pack.  */
7867             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
7868                                                     complain, in_decl);
7869             if (TREE_CODE (expanded_types) == TREE_VEC)
7870               {
7871                 len = TREE_VEC_LENGTH (expanded_types);
7872
7873                 /* Zero-length parameter packs are boring. Just substitute
7874                    into the chain.  */
7875                 if (len == 0)
7876                   return tsubst (TREE_CHAIN (t), args, complain, 
7877                                  TREE_CHAIN (t));
7878               }
7879             else
7880               {
7881                 /* All we did was update the type. Make a note of that.  */
7882                 type = expanded_types;
7883                 expanded_types = NULL_TREE;
7884               }
7885           }
7886
7887         /* Loop through all of the parameter's we'll build. When T is
7888            a function parameter pack, LEN is the number of expanded
7889            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
7890         r = NULL_TREE;
7891         for (i = 0; i < len; ++i)
7892           {
7893             prev_r = r;
7894             r = copy_node (t);
7895             if (DECL_TEMPLATE_PARM_P (t))
7896               SET_DECL_TEMPLATE_PARM_P (r);
7897
7898             if (expanded_types)
7899               /* We're on the Ith parameter of the function parameter
7900                  pack.  */
7901               {
7902                 /* Get the Ith type.  */
7903                 type = TREE_VEC_ELT (expanded_types, i);
7904
7905                 if (DECL_NAME (r))
7906                   /* Rename the parameter to include the index.  */
7907                   DECL_NAME (r) =
7908                     make_ith_pack_parameter_name (DECL_NAME (r), i);
7909               }
7910             else if (!type)
7911               /* We're dealing with a normal parameter.  */
7912               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
7913
7914             type = type_decays_to (type);
7915             TREE_TYPE (r) = type;
7916             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
7917
7918             if (DECL_INITIAL (r))
7919               {
7920                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
7921                   DECL_INITIAL (r) = TREE_TYPE (r);
7922                 else
7923                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
7924                                              complain, in_decl);
7925               }
7926
7927             DECL_CONTEXT (r) = NULL_TREE;
7928
7929             if (!DECL_TEMPLATE_PARM_P (r))
7930               DECL_ARG_TYPE (r) = type_passed_as (type);
7931
7932             /* Keep track of the first new parameter we
7933                generate. That's what will be returned to the
7934                caller.  */
7935             if (!first_r)
7936               first_r = r;
7937
7938             /* Build a proper chain of parameters when substituting
7939                into a function parameter pack.  */
7940             if (prev_r)
7941               TREE_CHAIN (prev_r) = r;
7942           }
7943
7944         if (TREE_CHAIN (t))
7945           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
7946                                    complain, TREE_CHAIN (t));
7947
7948         /* FIRST_R contains the start of the chain we've built.  */
7949         r = first_r;
7950       }
7951       break;
7952
7953     case FIELD_DECL:
7954       {
7955         tree type;
7956
7957         r = copy_decl (t);
7958         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
7959         if (type == error_mark_node)
7960           return error_mark_node;
7961         TREE_TYPE (r) = type;
7962         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
7963
7964         /* DECL_INITIAL gives the number of bits in a bit-field.  */
7965         DECL_INITIAL (r)
7966           = tsubst_expr (DECL_INITIAL (t), args,
7967                          complain, in_decl,
7968                          /*integral_constant_expression_p=*/true);
7969         /* We don't have to set DECL_CONTEXT here; it is set by
7970            finish_member_declaration.  */
7971         TREE_CHAIN (r) = NULL_TREE;
7972         if (VOID_TYPE_P (type))
7973           error ("instantiation of %q+D as type %qT", r, type);
7974       }
7975       break;
7976
7977     case USING_DECL:
7978       /* We reach here only for member using decls.  */
7979       if (DECL_DEPENDENT_P (t))
7980         {
7981           r = do_class_using_decl
7982             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
7983              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
7984           if (!r)
7985             r = error_mark_node;
7986         }
7987       else
7988         {
7989           r = copy_node (t);
7990           TREE_CHAIN (r) = NULL_TREE;
7991         }
7992       break;
7993
7994     case TYPE_DECL:
7995     case VAR_DECL:
7996       {
7997         tree argvec = NULL_TREE;
7998         tree gen_tmpl = NULL_TREE;
7999         tree spec;
8000         tree tmpl = NULL_TREE;
8001         tree ctx;
8002         tree type = NULL_TREE;
8003         bool local_p;
8004
8005         if (TREE_CODE (t) == TYPE_DECL)
8006           {
8007             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8008             if (TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM
8009                 || t == TYPE_MAIN_DECL (TREE_TYPE (t)))
8010               {
8011                 /* If this is the canonical decl, we don't have to
8012                    mess with instantiations, and often we can't (for
8013                    typename, template type parms and such).  Note that
8014                    TYPE_NAME is not correct for the above test if
8015                    we've copied the type for a typedef.  */
8016                 r = TYPE_NAME (type);
8017                 break;
8018               }
8019           }
8020
8021         /* Check to see if we already have the specialization we
8022            need.  */
8023         spec = NULL_TREE;
8024         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
8025           {
8026             /* T is a static data member or namespace-scope entity.
8027                We have to substitute into namespace-scope variables
8028                (even though such entities are never templates) because
8029                of cases like:
8030                
8031                  template <class T> void f() { extern T t; }
8032
8033                where the entity referenced is not known until
8034                instantiation time.  */
8035             local_p = false;
8036             ctx = DECL_CONTEXT (t);
8037             if (DECL_CLASS_SCOPE_P (t))
8038               {
8039                 ctx = tsubst_aggr_type (ctx, args,
8040                                         complain,
8041                                         in_decl, /*entering_scope=*/1);
8042                 /* If CTX is unchanged, then T is in fact the
8043                    specialization we want.  That situation occurs when
8044                    referencing a static data member within in its own
8045                    class.  We can use pointer equality, rather than
8046                    same_type_p, because DECL_CONTEXT is always
8047                    canonical.  */
8048                 if (ctx == DECL_CONTEXT (t))
8049                   spec = t;
8050               }
8051
8052             if (!spec)
8053               {
8054                 tmpl = DECL_TI_TEMPLATE (t);
8055                 gen_tmpl = most_general_template (tmpl);
8056                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
8057                 spec = (retrieve_specialization 
8058                         (gen_tmpl, argvec,
8059                          /*class_specializations_p=*/false));
8060               }
8061           }
8062         else
8063           {
8064             /* A local variable.  */
8065             local_p = true;
8066             /* Subsequent calls to pushdecl will fill this in.  */
8067             ctx = NULL_TREE;
8068             spec = retrieve_local_specialization (t);
8069           }
8070         /* If we already have the specialization we need, there is
8071            nothing more to do.  */ 
8072         if (spec)
8073           {
8074             r = spec;
8075             break;
8076           }
8077
8078         /* Create a new node for the specialization we need.  */
8079         r = copy_decl (t);
8080         if (TREE_CODE (r) == VAR_DECL)
8081           {
8082             /* Even if the original location is out of scope, the
8083                newly substituted one is not.  */
8084             DECL_DEAD_FOR_LOCAL (r) = 0;
8085             DECL_INITIALIZED_P (r) = 0;
8086             DECL_TEMPLATE_INSTANTIATED (r) = 0;
8087             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8088             if (type == error_mark_node)
8089               return error_mark_node;
8090             if (TREE_CODE (type) == FUNCTION_TYPE)
8091               {
8092                 /* It may seem that this case cannot occur, since:
8093
8094                      typedef void f();
8095                      void g() { f x; }
8096
8097                    declares a function, not a variable.  However:
8098       
8099                      typedef void f();
8100                      template <typename T> void g() { T t; }
8101                      template void g<f>();
8102
8103                    is an attempt to declare a variable with function
8104                    type.  */
8105                 error ("variable %qD has function type",
8106                        /* R is not yet sufficiently initialized, so we
8107                           just use its name.  */
8108                        DECL_NAME (r));
8109                 return error_mark_node;
8110               }
8111             type = complete_type (type);
8112             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
8113               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
8114             type = check_var_type (DECL_NAME (r), type);
8115
8116             if (DECL_HAS_VALUE_EXPR_P (t))
8117               {
8118                 tree ve = DECL_VALUE_EXPR (t);
8119                 ve = tsubst_expr (ve, args, complain, in_decl,
8120                                   /*constant_expression_p=*/false);
8121                 SET_DECL_VALUE_EXPR (r, ve);
8122               }
8123           }
8124         else if (DECL_SELF_REFERENCE_P (t))
8125           SET_DECL_SELF_REFERENCE_P (r);
8126         TREE_TYPE (r) = type;
8127         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8128         DECL_CONTEXT (r) = ctx;
8129         /* Clear out the mangled name and RTL for the instantiation.  */
8130         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8131         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8132           SET_DECL_RTL (r, NULL_RTX);
8133         /* The initializer must not be expanded until it is required;
8134            see [temp.inst].  */
8135         DECL_INITIAL (r) = NULL_TREE;
8136         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8137           SET_DECL_RTL (r, NULL_RTX);
8138         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
8139         if (TREE_CODE (r) == VAR_DECL)
8140           {
8141             /* Possibly limit visibility based on template args.  */
8142             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8143             if (DECL_VISIBILITY_SPECIFIED (t))
8144               {
8145                 DECL_VISIBILITY_SPECIFIED (r) = 0;
8146                 DECL_ATTRIBUTES (r)
8147                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8148               }
8149             determine_visibility (r);
8150           }
8151
8152         if (!local_p)
8153           {
8154             /* A static data member declaration is always marked
8155                external when it is declared in-class, even if an
8156                initializer is present.  We mimic the non-template
8157                processing here.  */
8158             DECL_EXTERNAL (r) = 1;
8159
8160             register_specialization (r, gen_tmpl, argvec, false);
8161             DECL_TEMPLATE_INFO (r) = tree_cons (tmpl, argvec, NULL_TREE);
8162             SET_DECL_IMPLICIT_INSTANTIATION (r);
8163           }
8164         else
8165           register_local_specialization (r, t);
8166
8167         TREE_CHAIN (r) = NULL_TREE;
8168         layout_decl (r, 0);
8169       }
8170       break;
8171
8172     default:
8173       gcc_unreachable ();
8174     }
8175
8176   /* Restore the file and line information.  */
8177   input_location = saved_loc;
8178
8179   return r;
8180 }
8181
8182 /* Substitute into the ARG_TYPES of a function type.  */
8183
8184 static tree
8185 tsubst_arg_types (tree arg_types,
8186                   tree args,
8187                   tsubst_flags_t complain,
8188                   tree in_decl)
8189 {
8190   tree remaining_arg_types;
8191   tree type = NULL_TREE;
8192   int i = 1;
8193   tree expanded_args = NULL_TREE;
8194   tree default_arg;
8195
8196   if (!arg_types || arg_types == void_list_node)
8197     return arg_types;
8198
8199   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
8200                                           args, complain, in_decl);
8201   if (remaining_arg_types == error_mark_node)
8202     return error_mark_node;
8203
8204   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
8205     {
8206       /* For a pack expansion, perform substitution on the
8207          entire expression. Later on, we'll handle the arguments
8208          one-by-one.  */
8209       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
8210                                             args, complain, in_decl);
8211
8212       if (TREE_CODE (expanded_args) == TREE_VEC)
8213         /* So that we'll spin through the parameters, one by one.  */
8214         i = TREE_VEC_LENGTH (expanded_args);
8215       else
8216         {
8217           /* We only partially substituted into the parameter
8218              pack. Our type is TYPE_PACK_EXPANSION.  */
8219           type = expanded_args;
8220           expanded_args = NULL_TREE;
8221         }
8222     }
8223
8224   while (i > 0) {
8225     --i;
8226     
8227     if (expanded_args)
8228       type = TREE_VEC_ELT (expanded_args, i);
8229     else if (!type)
8230       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
8231
8232     if (type == error_mark_node)
8233       return error_mark_node;
8234     if (VOID_TYPE_P (type))
8235       {
8236         if (complain & tf_error)
8237           {
8238             error ("invalid parameter type %qT", type);
8239             if (in_decl)
8240               error ("in declaration %q+D", in_decl);
8241           }
8242         return error_mark_node;
8243     }
8244     
8245     /* Do array-to-pointer, function-to-pointer conversion, and ignore
8246        top-level qualifiers as required.  */
8247     type = TYPE_MAIN_VARIANT (type_decays_to (type));
8248
8249     /* We do not substitute into default arguments here.  The standard
8250        mandates that they be instantiated only when needed, which is
8251        done in build_over_call.  */
8252     default_arg = TREE_PURPOSE (arg_types);
8253
8254     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
8255       {
8256         /* We've instantiated a template before its default arguments
8257            have been parsed.  This can happen for a nested template
8258            class, and is not an error unless we require the default
8259            argument in a call of this function.  */
8260         remaining_arg_types = 
8261           tree_cons (default_arg, type, remaining_arg_types);
8262         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
8263                        remaining_arg_types);
8264       }
8265     else
8266       remaining_arg_types = 
8267         hash_tree_cons (default_arg, type, remaining_arg_types);
8268   }
8269         
8270   return remaining_arg_types;
8271 }
8272
8273 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
8274    *not* handle the exception-specification for FNTYPE, because the
8275    initial substitution of explicitly provided template parameters
8276    during argument deduction forbids substitution into the
8277    exception-specification:
8278
8279      [temp.deduct]
8280
8281      All references in the function type of the function template to  the
8282      corresponding template parameters are replaced by the specified tem-
8283      plate argument values.  If a substitution in a template parameter or
8284      in  the function type of the function template results in an invalid
8285      type, type deduction fails.  [Note: The equivalent  substitution  in
8286      exception specifications is done only when the function is instanti-
8287      ated, at which point a program is  ill-formed  if  the  substitution
8288      results in an invalid type.]  */
8289
8290 static tree
8291 tsubst_function_type (tree t,
8292                       tree args,
8293                       tsubst_flags_t complain,
8294                       tree in_decl)
8295 {
8296   tree return_type;
8297   tree arg_types;
8298   tree fntype;
8299
8300   /* The TYPE_CONTEXT is not used for function/method types.  */
8301   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
8302
8303   /* Substitute the return type.  */
8304   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8305   if (return_type == error_mark_node)
8306     return error_mark_node;
8307   /* The standard does not presently indicate that creation of a
8308      function type with an invalid return type is a deduction failure.
8309      However, that is clearly analogous to creating an array of "void"
8310      or a reference to a reference.  This is core issue #486.  */
8311   if (TREE_CODE (return_type) == ARRAY_TYPE
8312       || TREE_CODE (return_type) == FUNCTION_TYPE)
8313     {
8314       if (complain & tf_error)
8315         {
8316           if (TREE_CODE (return_type) == ARRAY_TYPE)
8317             error ("function returning an array");
8318           else
8319             error ("function returning a function");
8320         }
8321       return error_mark_node;
8322     }
8323
8324   /* Substitute the argument types.  */
8325   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
8326                                 complain, in_decl);
8327   if (arg_types == error_mark_node)
8328     return error_mark_node;
8329
8330   if (TYPE_QUALS (return_type) != TYPE_UNQUALIFIED
8331       && in_decl != NULL_TREE
8332       && !TREE_NO_WARNING (in_decl)
8333       && (SCALAR_TYPE_P (return_type) || VOID_TYPE_P (return_type)))
8334     warning (OPT_Wreturn_type,
8335             "type qualifiers ignored on function return type");
8336
8337   /* Construct a new type node and return it.  */
8338   if (TREE_CODE (t) == FUNCTION_TYPE)
8339     fntype = build_function_type (return_type, arg_types);
8340   else
8341     {
8342       tree r = TREE_TYPE (TREE_VALUE (arg_types));
8343       if (! IS_AGGR_TYPE (r))
8344         {
8345           /* [temp.deduct]
8346
8347              Type deduction may fail for any of the following
8348              reasons:
8349
8350              -- Attempting to create "pointer to member of T" when T
8351              is not a class type.  */
8352           if (complain & tf_error)
8353             error ("creating pointer to member function of non-class type %qT",
8354                       r);
8355           return error_mark_node;
8356         }
8357
8358       fntype = build_method_type_directly (r, return_type,
8359                                            TREE_CHAIN (arg_types));
8360     }
8361   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
8362   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
8363
8364   return fntype;
8365 }
8366
8367 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
8368    ARGS into that specification, and return the substituted
8369    specification.  If there is no specification, return NULL_TREE.  */
8370
8371 static tree
8372 tsubst_exception_specification (tree fntype,
8373                                 tree args,
8374                                 tsubst_flags_t complain,
8375                                 tree in_decl)
8376 {
8377   tree specs;
8378   tree new_specs;
8379
8380   specs = TYPE_RAISES_EXCEPTIONS (fntype);
8381   new_specs = NULL_TREE;
8382   if (specs)
8383     {
8384       if (! TREE_VALUE (specs))
8385         new_specs = specs;
8386       else
8387         while (specs)
8388           {
8389             tree spec;
8390             int i, len = 1;
8391             tree expanded_specs = NULL_TREE;
8392
8393             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
8394               {
8395                 /* Expand the pack expansion type.  */
8396                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
8397                                                        args, complain,
8398                                                        in_decl);
8399                 len = TREE_VEC_LENGTH (expanded_specs);
8400               }
8401
8402             for (i = 0; i < len; ++i)
8403               {
8404                 if (expanded_specs)
8405                   spec = TREE_VEC_ELT (expanded_specs, i);
8406                 else
8407                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
8408                 if (spec == error_mark_node)
8409                   return spec;
8410                 new_specs = add_exception_specifier (new_specs, spec, 
8411                                                      complain);
8412               }
8413
8414             specs = TREE_CHAIN (specs);
8415           }
8416     }
8417   return new_specs;
8418 }
8419
8420 /* Take the tree structure T and replace template parameters used
8421    therein with the argument vector ARGS.  IN_DECL is an associated
8422    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
8423    Issue error and warning messages under control of COMPLAIN.  Note
8424    that we must be relatively non-tolerant of extensions here, in
8425    order to preserve conformance; if we allow substitutions that
8426    should not be allowed, we may allow argument deductions that should
8427    not succeed, and therefore report ambiguous overload situations
8428    where there are none.  In theory, we could allow the substitution,
8429    but indicate that it should have failed, and allow our caller to
8430    make sure that the right thing happens, but we don't try to do this
8431    yet.
8432
8433    This function is used for dealing with types, decls and the like;
8434    for expressions, use tsubst_expr or tsubst_copy.  */
8435
8436 static tree
8437 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8438 {
8439   tree type, r;
8440
8441   if (t == NULL_TREE || t == error_mark_node
8442       || t == integer_type_node
8443       || t == void_type_node
8444       || t == char_type_node
8445       || t == unknown_type_node
8446       || TREE_CODE (t) == NAMESPACE_DECL)
8447     return t;
8448
8449   if (DECL_P (t))
8450     return tsubst_decl (t, args, complain);
8451
8452   if (TREE_CODE (t) == IDENTIFIER_NODE)
8453     type = IDENTIFIER_TYPE_VALUE (t);
8454   else
8455     type = TREE_TYPE (t);
8456
8457   gcc_assert (type != unknown_type_node);
8458
8459   if (type
8460       && TREE_CODE (t) != TYPENAME_TYPE
8461       && TREE_CODE (t) != IDENTIFIER_NODE
8462       && TREE_CODE (t) != FUNCTION_TYPE
8463       && TREE_CODE (t) != METHOD_TYPE)
8464     type = tsubst (type, args, complain, in_decl);
8465   if (type == error_mark_node)
8466     return error_mark_node;
8467
8468   switch (TREE_CODE (t))
8469     {
8470     case RECORD_TYPE:
8471     case UNION_TYPE:
8472     case ENUMERAL_TYPE:
8473       return tsubst_aggr_type (t, args, complain, in_decl,
8474                                /*entering_scope=*/0);
8475
8476     case ERROR_MARK:
8477     case IDENTIFIER_NODE:
8478     case VOID_TYPE:
8479     case REAL_TYPE:
8480     case COMPLEX_TYPE:
8481     case VECTOR_TYPE:
8482     case BOOLEAN_TYPE:
8483     case INTEGER_CST:
8484     case REAL_CST:
8485     case STRING_CST:
8486       return t;
8487
8488     case INTEGER_TYPE:
8489       if (t == integer_type_node)
8490         return t;
8491
8492       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
8493           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
8494         return t;
8495
8496       {
8497         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
8498
8499         max = tsubst_expr (omax, args, complain, in_decl,
8500                            /*integral_constant_expression_p=*/false);
8501         max = fold_decl_constant_value (max);
8502
8503         if (TREE_CODE (max) != INTEGER_CST 
8504             && TREE_CODE (max) != TEMPLATE_PARM_INDEX
8505             && !at_function_scope_p ())
8506           {
8507             if (complain & tf_error)
8508               error ("array bound is not an integer constant");
8509             return error_mark_node;
8510           }
8511
8512         /* [temp.deduct]
8513
8514            Type deduction may fail for any of the following
8515            reasons:
8516
8517              Attempting to create an array with a size that is
8518              zero or negative.  */
8519         if (integer_zerop (max) && !(complain & tf_error))
8520           /* We must fail if performing argument deduction (as
8521              indicated by the state of complain), so that
8522              another substitution can be found.  */
8523           return error_mark_node;
8524         else if (TREE_CODE (max) == INTEGER_CST
8525                  && INT_CST_LT (max, integer_zero_node))
8526           {
8527             if (complain & tf_error)
8528               error ("creating array with negative size (%qE)", max);
8529
8530             return error_mark_node;
8531           }
8532
8533         return compute_array_index_type (NULL_TREE, max);
8534       }
8535
8536     case TEMPLATE_TYPE_PARM:
8537     case TEMPLATE_TEMPLATE_PARM:
8538     case BOUND_TEMPLATE_TEMPLATE_PARM:
8539     case TEMPLATE_PARM_INDEX:
8540       {
8541         int idx;
8542         int level;
8543         int levels;
8544         tree arg = NULL_TREE;
8545
8546         r = NULL_TREE;
8547
8548         gcc_assert (TREE_VEC_LENGTH (args) > 0);
8549         if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
8550             || TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
8551             || TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
8552           {
8553             idx = TEMPLATE_TYPE_IDX (t);
8554             level = TEMPLATE_TYPE_LEVEL (t);
8555           }
8556         else
8557           {
8558             idx = TEMPLATE_PARM_IDX (t);
8559             level = TEMPLATE_PARM_LEVEL (t);
8560           }
8561
8562         levels = TMPL_ARGS_DEPTH (args);
8563         if (level <= levels)
8564           {
8565             arg = TMPL_ARG (args, level, idx);
8566
8567             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
8568               /* See through ARGUMENT_PACK_SELECT arguments. */
8569               arg = ARGUMENT_PACK_SELECT_ARG (arg);
8570           }
8571
8572         if (arg == error_mark_node)
8573           return error_mark_node;
8574         else if (arg != NULL_TREE)
8575           {
8576             if (ARGUMENT_PACK_P (arg))
8577               /* If ARG is an argument pack, we don't actually want to
8578                  perform a substitution here, because substitutions
8579                  for argument packs are only done
8580                  element-by-element. We can get to this point when
8581                  substituting the type of a non-type template
8582                  parameter pack, when that type actually contains
8583                  template parameter packs from an outer template, e.g.,
8584
8585                  template<typename... Types> struct A {
8586                    template<Types... Values> struct B { };
8587                  };  */
8588               return t;
8589
8590             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
8591               {
8592                 int quals;
8593                 gcc_assert (TYPE_P (arg));
8594
8595                 /* cv-quals from the template are discarded when
8596                    substituting in a function or reference type.  */
8597                 if (TREE_CODE (arg) == FUNCTION_TYPE
8598                     || TREE_CODE (arg) == METHOD_TYPE
8599                     || TREE_CODE (arg) == REFERENCE_TYPE)
8600                   quals = cp_type_quals (arg);
8601                 else
8602                   quals = cp_type_quals (arg) | cp_type_quals (t);
8603                   
8604                 return cp_build_qualified_type_real
8605                   (arg, quals, complain | tf_ignore_bad_quals);
8606               }
8607             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
8608               {
8609                 /* We are processing a type constructed from a
8610                    template template parameter.  */
8611                 tree argvec = tsubst (TYPE_TI_ARGS (t),
8612                                       args, complain, in_decl);
8613                 if (argvec == error_mark_node)
8614                   return error_mark_node;
8615
8616                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
8617                    are resolving nested-types in the signature of a
8618                    member function templates.  Otherwise ARG is a
8619                    TEMPLATE_DECL and is the real template to be
8620                    instantiated.  */
8621                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
8622                   arg = TYPE_NAME (arg);
8623
8624                 r = lookup_template_class (arg,
8625                                            argvec, in_decl,
8626                                            DECL_CONTEXT (arg),
8627                                             /*entering_scope=*/0,
8628                                            complain);
8629                 return cp_build_qualified_type_real
8630                   (r, TYPE_QUALS (t), complain);
8631               }
8632             else
8633               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
8634               return arg;
8635           }
8636
8637         if (level == 1)
8638           /* This can happen during the attempted tsubst'ing in
8639              unify.  This means that we don't yet have any information
8640              about the template parameter in question.  */
8641           return t;
8642
8643         /* If we get here, we must have been looking at a parm for a
8644            more deeply nested template.  Make a new version of this
8645            template parameter, but with a lower level.  */
8646         switch (TREE_CODE (t))
8647           {
8648           case TEMPLATE_TYPE_PARM:
8649           case TEMPLATE_TEMPLATE_PARM:
8650           case BOUND_TEMPLATE_TEMPLATE_PARM:
8651             if (cp_type_quals (t))
8652               {
8653                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
8654                 r = cp_build_qualified_type_real
8655                   (r, cp_type_quals (t),
8656                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
8657                                ? tf_ignore_bad_quals : 0));
8658               }
8659             else
8660               {
8661                 r = copy_type (t);
8662                 TEMPLATE_TYPE_PARM_INDEX (r)
8663                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
8664                                                 r, levels);
8665                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
8666                 TYPE_MAIN_VARIANT (r) = r;
8667                 TYPE_POINTER_TO (r) = NULL_TREE;
8668                 TYPE_REFERENCE_TO (r) = NULL_TREE;
8669
8670                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
8671                   /* We have reduced the level of the template
8672                      template parameter, but not the levels of its
8673                      template parameters, so canonical_type_parameter
8674                      will not be able to find the canonical template
8675                      template parameter for this level. Thus, we
8676                      require structural equality checking to compare
8677                      TEMPLATE_TEMPLATE_PARMs. */
8678                   SET_TYPE_STRUCTURAL_EQUALITY (r);
8679                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
8680                   SET_TYPE_STRUCTURAL_EQUALITY (r);
8681                 else
8682                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
8683
8684                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
8685                   {
8686                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
8687                                           complain, in_decl);
8688                     if (argvec == error_mark_node)
8689                       return error_mark_node;
8690
8691                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
8692                       = tree_cons (TYPE_TI_TEMPLATE (t), argvec, NULL_TREE);
8693                   }
8694               }
8695             break;
8696
8697           case TEMPLATE_PARM_INDEX:
8698             r = reduce_template_parm_level (t, type, levels);
8699             break;
8700
8701           default:
8702             gcc_unreachable ();
8703           }
8704
8705         return r;
8706       }
8707
8708     case TREE_LIST:
8709       {
8710         tree purpose, value, chain;
8711
8712         if (t == void_list_node)
8713           return t;
8714
8715         purpose = TREE_PURPOSE (t);
8716         if (purpose)
8717           {
8718             purpose = tsubst (purpose, args, complain, in_decl);
8719             if (purpose == error_mark_node)
8720               return error_mark_node;
8721           }
8722         value = TREE_VALUE (t);
8723         if (value)
8724           {
8725             value = tsubst (value, args, complain, in_decl);
8726             if (value == error_mark_node)
8727               return error_mark_node;
8728           }
8729         chain = TREE_CHAIN (t);
8730         if (chain && chain != void_type_node)
8731           {
8732             chain = tsubst (chain, args, complain, in_decl);
8733             if (chain == error_mark_node)
8734               return error_mark_node;
8735           }
8736         if (purpose == TREE_PURPOSE (t)
8737             && value == TREE_VALUE (t)
8738             && chain == TREE_CHAIN (t))
8739           return t;
8740         return hash_tree_cons (purpose, value, chain);
8741       }
8742
8743     case TREE_BINFO:
8744       /* We should never be tsubsting a binfo.  */
8745       gcc_unreachable ();
8746
8747     case TREE_VEC:
8748       /* A vector of template arguments.  */
8749       gcc_assert (!type);
8750       return tsubst_template_args (t, args, complain, in_decl);
8751
8752     case POINTER_TYPE:
8753     case REFERENCE_TYPE:
8754       {
8755         enum tree_code code;
8756
8757         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
8758           return t;
8759
8760         code = TREE_CODE (t);
8761
8762
8763         /* [temp.deduct]
8764
8765            Type deduction may fail for any of the following
8766            reasons:
8767
8768            -- Attempting to create a pointer to reference type.
8769            -- Attempting to create a reference to a reference type or
8770               a reference to void.
8771
8772           Core issue 106 says that creating a reference to a reference
8773           during instantiation is no longer a cause for failure. We
8774           only enforce this check in strict C++98 mode.  */
8775         if ((TREE_CODE (type) == REFERENCE_TYPE
8776              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
8777             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
8778           {
8779             static location_t last_loc;
8780
8781             /* We keep track of the last time we issued this error
8782                message to avoid spewing a ton of messages during a
8783                single bad template instantiation.  */
8784             if (complain & tf_error
8785 #ifdef USE_MAPPED_LOCATION
8786                 && last_loc != input_location
8787 #else
8788                 && (last_loc.line != input_line
8789                     || last_loc.file != input_filename)
8790 #endif
8791                   )
8792               {
8793                 if (TREE_CODE (type) == VOID_TYPE)
8794                   error ("forming reference to void");
8795                 else
8796                   error ("forming %s to reference type %qT",
8797                          (code == POINTER_TYPE) ? "pointer" : "reference",
8798                          type);
8799                 last_loc = input_location;
8800               }
8801
8802             return error_mark_node;
8803           }
8804         else if (code == POINTER_TYPE)
8805           {
8806             r = build_pointer_type (type);
8807             if (TREE_CODE (type) == METHOD_TYPE)
8808               r = build_ptrmemfunc_type (r);
8809           }
8810         else if (TREE_CODE (type) == REFERENCE_TYPE)
8811           /* In C++0x, during template argument substitution, when there is an
8812              attempt to create a reference to a reference type, reference
8813              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
8814
8815              "If a template-argument for a template-parameter T names a type
8816              that is a reference to a type A, an attempt to create the type
8817              'lvalue reference to cv T' creates the type 'lvalue reference to
8818              A,' while an attempt to create the type type rvalue reference to
8819              cv T' creates the type T"
8820           */
8821           r = cp_build_reference_type
8822               (TREE_TYPE (type),
8823                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
8824         else
8825           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
8826         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
8827
8828         if (r != error_mark_node)
8829           /* Will this ever be needed for TYPE_..._TO values?  */
8830           layout_type (r);
8831
8832         return r;
8833       }
8834     case OFFSET_TYPE:
8835       {
8836         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
8837         if (r == error_mark_node || !IS_AGGR_TYPE (r))
8838           {
8839             /* [temp.deduct]
8840
8841                Type deduction may fail for any of the following
8842                reasons:
8843
8844                -- Attempting to create "pointer to member of T" when T
8845                   is not a class type.  */
8846             if (complain & tf_error)
8847               error ("creating pointer to member of non-class type %qT", r);
8848             return error_mark_node;
8849           }
8850         if (TREE_CODE (type) == REFERENCE_TYPE)
8851           {
8852             if (complain & tf_error)
8853               error ("creating pointer to member reference type %qT", type);
8854             return error_mark_node;
8855           }
8856         if (TREE_CODE (type) == VOID_TYPE)
8857           {
8858             if (complain & tf_error)
8859               error ("creating pointer to member of type void");
8860             return error_mark_node;
8861           }
8862         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
8863         if (TREE_CODE (type) == FUNCTION_TYPE)
8864           {
8865             /* The type of the implicit object parameter gets its
8866                cv-qualifiers from the FUNCTION_TYPE. */
8867             tree method_type;
8868             tree this_type = cp_build_qualified_type (TYPE_MAIN_VARIANT (r),
8869                                                       cp_type_quals (type));
8870             tree memptr;
8871             method_type = build_method_type_directly (this_type,
8872                                                       TREE_TYPE (type),
8873                                                       TYPE_ARG_TYPES (type));
8874             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
8875             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
8876                                                  complain);
8877           }
8878         else
8879           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
8880                                                TYPE_QUALS (t),
8881                                                complain);
8882       }
8883     case FUNCTION_TYPE:
8884     case METHOD_TYPE:
8885       {
8886         tree fntype;
8887         tree specs;
8888         fntype = tsubst_function_type (t, args, complain, in_decl);
8889         if (fntype == error_mark_node)
8890           return error_mark_node;
8891
8892         /* Substitute the exception specification.  */
8893         specs = tsubst_exception_specification (t, args, complain,
8894                                                 in_decl);
8895         if (specs == error_mark_node)
8896           return error_mark_node;
8897         if (specs)
8898           fntype = build_exception_variant (fntype, specs);
8899         return fntype;
8900       }
8901     case ARRAY_TYPE:
8902       {
8903         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
8904         if (domain == error_mark_node)
8905           return error_mark_node;
8906
8907         /* As an optimization, we avoid regenerating the array type if
8908            it will obviously be the same as T.  */
8909         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
8910           return t;
8911
8912         /* These checks should match the ones in grokdeclarator.
8913
8914            [temp.deduct]
8915
8916            The deduction may fail for any of the following reasons:
8917
8918            -- Attempting to create an array with an element type that
8919               is void, a function type, or a reference type, or [DR337]
8920               an abstract class type.  */
8921         if (TREE_CODE (type) == VOID_TYPE
8922             || TREE_CODE (type) == FUNCTION_TYPE
8923             || TREE_CODE (type) == REFERENCE_TYPE)
8924           {
8925             if (complain & tf_error)
8926               error ("creating array of %qT", type);
8927             return error_mark_node;
8928           }
8929         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
8930           {
8931             if (complain & tf_error)
8932               error ("creating array of %qT, which is an abstract class type",
8933                      type);
8934             return error_mark_node;
8935           }
8936
8937         r = build_cplus_array_type (type, domain);
8938         return r;
8939       }
8940
8941     case PLUS_EXPR:
8942     case MINUS_EXPR:
8943       {
8944         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
8945         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
8946
8947         if (e1 == error_mark_node || e2 == error_mark_node)
8948           return error_mark_node;
8949
8950         return fold_build2 (TREE_CODE (t), TREE_TYPE (t), e1, e2);
8951       }
8952
8953     case NEGATE_EXPR:
8954     case NOP_EXPR:
8955       {
8956         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
8957         if (e == error_mark_node)
8958           return error_mark_node;
8959
8960         return fold_build1 (TREE_CODE (t), TREE_TYPE (t), e);
8961       }
8962
8963     case TYPENAME_TYPE:
8964       {
8965         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
8966                                      in_decl, /*entering_scope=*/1);
8967         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
8968                               complain, in_decl);
8969
8970         if (ctx == error_mark_node || f == error_mark_node)
8971           return error_mark_node;
8972
8973         if (!IS_AGGR_TYPE (ctx))
8974           {
8975             if (complain & tf_error)
8976               error ("%qT is not a class, struct, or union type", ctx);
8977             return error_mark_node;
8978           }
8979         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
8980           {
8981             /* Normally, make_typename_type does not require that the CTX
8982                have complete type in order to allow things like:
8983
8984                  template <class T> struct S { typename S<T>::X Y; };
8985
8986                But, such constructs have already been resolved by this
8987                point, so here CTX really should have complete type, unless
8988                it's a partial instantiation.  */
8989             ctx = complete_type (ctx);
8990             if (!COMPLETE_TYPE_P (ctx))
8991               {
8992                 if (complain & tf_error)
8993                   cxx_incomplete_type_error (NULL_TREE, ctx);
8994                 return error_mark_node;
8995               }
8996           }
8997
8998         f = make_typename_type (ctx, f, typename_type,
8999                                 (complain & tf_error) | tf_keep_type_decl);
9000         if (f == error_mark_node)
9001           return f;
9002         if (TREE_CODE (f) == TYPE_DECL)
9003           {
9004             complain |= tf_ignore_bad_quals;
9005             f = TREE_TYPE (f);
9006           }
9007
9008         if (TREE_CODE (f) != TYPENAME_TYPE)
9009           {
9010             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
9011               error ("%qT resolves to %qT, which is not an enumeration type",
9012                      t, f);
9013             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
9014               error ("%qT resolves to %qT, which is is not a class type",
9015                      t, f);
9016           }
9017
9018         return cp_build_qualified_type_real
9019           (f, cp_type_quals (f) | cp_type_quals (t), complain);
9020       }
9021
9022     case UNBOUND_CLASS_TEMPLATE:
9023       {
9024         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9025                                      in_decl, /*entering_scope=*/1);
9026         tree name = TYPE_IDENTIFIER (t);
9027         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
9028
9029         if (ctx == error_mark_node || name == error_mark_node)
9030           return error_mark_node;
9031
9032         if (parm_list)
9033           parm_list = tsubst_template_parms (parm_list, args, complain);
9034         return make_unbound_class_template (ctx, name, parm_list, complain);
9035       }
9036
9037     case INDIRECT_REF:
9038     case ADDR_EXPR:
9039     case CALL_EXPR:
9040       gcc_unreachable ();
9041
9042     case ARRAY_REF:
9043       {
9044         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9045         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
9046                                /*integral_constant_expression_p=*/false);
9047         if (e1 == error_mark_node || e2 == error_mark_node)
9048           return error_mark_node;
9049
9050         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
9051       }
9052
9053     case SCOPE_REF:
9054       {
9055         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9056         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9057         if (e1 == error_mark_node || e2 == error_mark_node)
9058           return error_mark_node;
9059
9060         return build_qualified_name (/*type=*/NULL_TREE,
9061                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
9062       }
9063
9064     case TYPEOF_TYPE:
9065       {
9066         tree type;
9067
9068         type = finish_typeof (tsubst_expr 
9069                               (TYPEOF_TYPE_EXPR (t), args,
9070                                complain, in_decl,
9071                                /*integral_constant_expression_p=*/false));
9072         return cp_build_qualified_type_real (type,
9073                                              cp_type_quals (t)
9074                                              | cp_type_quals (type),
9075                                              complain);
9076       }
9077
9078     case DECLTYPE_TYPE:
9079       {
9080         tree type;
9081
9082         type = 
9083           finish_decltype_type (tsubst_expr 
9084                                 (DECLTYPE_TYPE_EXPR (t), args,
9085                                  complain, in_decl,
9086                                  /*integral_constant_expression_p=*/false),
9087                                 DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
9088         return cp_build_qualified_type_real (type,
9089                                              cp_type_quals (t)
9090                                              | cp_type_quals (type),
9091                                              complain);
9092       }
9093
9094     case TYPE_ARGUMENT_PACK:
9095     case NONTYPE_ARGUMENT_PACK:
9096       {
9097         tree r = make_node (TREE_CODE (t));
9098         tree packed_out = 
9099           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
9100                                 args,
9101                                 complain,
9102                                 in_decl);
9103         SET_ARGUMENT_PACK_ARGS (r, packed_out);
9104
9105         /* For template nontype argument packs, also substitute into
9106            the type.  */
9107         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
9108           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
9109
9110         return r;
9111       }
9112       break;
9113
9114     default:
9115       sorry ("use of %qs in template",
9116              tree_code_name [(int) TREE_CODE (t)]);
9117       return error_mark_node;
9118     }
9119 }
9120
9121 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
9122    type of the expression on the left-hand side of the "." or "->"
9123    operator.  */
9124
9125 static tree
9126 tsubst_baselink (tree baselink, tree object_type,
9127                  tree args, tsubst_flags_t complain, tree in_decl)
9128 {
9129     tree name;
9130     tree qualifying_scope;
9131     tree fns;
9132     tree optype;
9133     tree template_args = 0;
9134     bool template_id_p = false;
9135
9136     /* A baselink indicates a function from a base class.  Both the
9137        BASELINK_ACCESS_BINFO and the base class referenced may
9138        indicate bases of the template class, rather than the
9139        instantiated class.  In addition, lookups that were not
9140        ambiguous before may be ambiguous now.  Therefore, we perform
9141        the lookup again.  */
9142     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
9143     qualifying_scope = tsubst (qualifying_scope, args,
9144                                complain, in_decl);
9145     fns = BASELINK_FUNCTIONS (baselink);
9146     optype = BASELINK_OPTYPE (baselink);
9147     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
9148       {
9149         template_id_p = true;
9150         template_args = TREE_OPERAND (fns, 1);
9151         fns = TREE_OPERAND (fns, 0);
9152         if (template_args)
9153           template_args = tsubst_template_args (template_args, args,
9154                                                 complain, in_decl);
9155       }
9156     name = DECL_NAME (get_first_fn (fns));
9157     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
9158
9159     /* If lookup found a single function, mark it as used at this
9160        point.  (If it lookup found multiple functions the one selected
9161        later by overload resolution will be marked as used at that
9162        point.)  */
9163     if (BASELINK_P (baselink))
9164       fns = BASELINK_FUNCTIONS (baselink);
9165     if (!template_id_p && !really_overloaded_fn (fns))
9166       mark_used (OVL_CURRENT (fns));
9167
9168     /* Add back the template arguments, if present.  */
9169     if (BASELINK_P (baselink) && template_id_p)
9170       BASELINK_FUNCTIONS (baselink)
9171         = build_nt (TEMPLATE_ID_EXPR,
9172                     BASELINK_FUNCTIONS (baselink),
9173                     template_args);
9174     /* Update the conversion operator type.  */
9175     BASELINK_OPTYPE (baselink) 
9176       = tsubst (optype, args, complain, in_decl);
9177
9178     if (!object_type)
9179       object_type = current_class_type;
9180     return adjust_result_of_qualified_name_lookup (baselink,
9181                                                    qualifying_scope,
9182                                                    object_type);
9183 }
9184
9185 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
9186    true if the qualified-id will be a postfix-expression in-and-of
9187    itself; false if more of the postfix-expression follows the
9188    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
9189    of "&".  */
9190
9191 static tree
9192 tsubst_qualified_id (tree qualified_id, tree args,
9193                      tsubst_flags_t complain, tree in_decl,
9194                      bool done, bool address_p)
9195 {
9196   tree expr;
9197   tree scope;
9198   tree name;
9199   bool is_template;
9200   tree template_args;
9201
9202   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
9203
9204   /* Figure out what name to look up.  */
9205   name = TREE_OPERAND (qualified_id, 1);
9206   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
9207     {
9208       is_template = true;
9209       template_args = TREE_OPERAND (name, 1);
9210       if (template_args)
9211         template_args = tsubst_template_args (template_args, args,
9212                                               complain, in_decl);
9213       name = TREE_OPERAND (name, 0);
9214     }
9215   else
9216     {
9217       is_template = false;
9218       template_args = NULL_TREE;
9219     }
9220
9221   /* Substitute into the qualifying scope.  When there are no ARGS, we
9222      are just trying to simplify a non-dependent expression.  In that
9223      case the qualifying scope may be dependent, and, in any case,
9224      substituting will not help.  */
9225   scope = TREE_OPERAND (qualified_id, 0);
9226   if (args)
9227     {
9228       scope = tsubst (scope, args, complain, in_decl);
9229       expr = tsubst_copy (name, args, complain, in_decl);
9230     }
9231   else
9232     expr = name;
9233
9234   if (dependent_type_p (scope))
9235     return build_qualified_name (/*type=*/NULL_TREE,
9236                                  scope, expr,
9237                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
9238
9239   if (!BASELINK_P (name) && !DECL_P (expr))
9240     {
9241       if (TREE_CODE (expr) == BIT_NOT_EXPR)
9242         /* If this were actually a destructor call, it would have been
9243            parsed as such by the parser.  */
9244         expr = error_mark_node;
9245       else
9246         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
9247       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
9248                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
9249         {
9250           if (complain & tf_error)
9251             {
9252               error ("dependent-name %qE is parsed as a non-type, but "
9253                      "instantiation yields a type", qualified_id);
9254               inform ("say %<typename %E%> if a type is meant", qualified_id);
9255             }
9256           return error_mark_node;
9257         }
9258     }
9259
9260   if (DECL_P (expr))
9261     {
9262       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
9263                                            scope);
9264       /* Remember that there was a reference to this entity.  */
9265       mark_used (expr);
9266     }
9267
9268   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
9269     {
9270       if (complain & tf_error)
9271         qualified_name_lookup_error (scope,
9272                                      TREE_OPERAND (qualified_id, 1),
9273                                      expr);
9274       return error_mark_node;
9275     }
9276
9277   if (is_template)
9278     expr = lookup_template_function (expr, template_args);
9279
9280   if (expr == error_mark_node && complain & tf_error)
9281     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
9282                                  expr);
9283   else if (TYPE_P (scope))
9284     {
9285       expr = (adjust_result_of_qualified_name_lookup
9286               (expr, scope, current_class_type));
9287       expr = (finish_qualified_id_expr
9288               (scope, expr, done, address_p,
9289                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
9290                /*template_arg_p=*/false));
9291     }
9292
9293   /* Expressions do not generally have reference type.  */
9294   if (TREE_CODE (expr) != SCOPE_REF
9295       /* However, if we're about to form a pointer-to-member, we just
9296          want the referenced member referenced.  */
9297       && TREE_CODE (expr) != OFFSET_REF)
9298     expr = convert_from_reference (expr);
9299
9300   return expr;
9301 }
9302
9303 /* Like tsubst, but deals with expressions.  This function just replaces
9304    template parms; to finish processing the resultant expression, use
9305    tsubst_expr.  */
9306
9307 static tree
9308 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9309 {
9310   enum tree_code code;
9311   tree r;
9312
9313   if (t == NULL_TREE || t == error_mark_node)
9314     return t;
9315
9316   code = TREE_CODE (t);
9317
9318   switch (code)
9319     {
9320     case PARM_DECL:
9321       r = retrieve_local_specialization (t);
9322       gcc_assert (r != NULL);
9323       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
9324         r = ARGUMENT_PACK_SELECT_ARG (r);
9325       mark_used (r);
9326       return r;
9327
9328     case CONST_DECL:
9329       {
9330         tree enum_type;
9331         tree v;
9332
9333         if (DECL_TEMPLATE_PARM_P (t))
9334           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
9335         /* There is no need to substitute into namespace-scope
9336            enumerators.  */
9337         if (DECL_NAMESPACE_SCOPE_P (t))
9338           return t;
9339         /* If ARGS is NULL, then T is known to be non-dependent.  */
9340         if (args == NULL_TREE)
9341           return integral_constant_value (t);
9342
9343         /* Unfortunately, we cannot just call lookup_name here.
9344            Consider:
9345
9346              template <int I> int f() {
9347              enum E { a = I };
9348              struct S { void g() { E e = a; } };
9349              };
9350
9351            When we instantiate f<7>::S::g(), say, lookup_name is not
9352            clever enough to find f<7>::a.  */
9353         enum_type
9354           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
9355                               /*entering_scope=*/0);
9356
9357         for (v = TYPE_VALUES (enum_type);
9358              v != NULL_TREE;
9359              v = TREE_CHAIN (v))
9360           if (TREE_PURPOSE (v) == DECL_NAME (t))
9361             return TREE_VALUE (v);
9362
9363           /* We didn't find the name.  That should never happen; if
9364              name-lookup found it during preliminary parsing, we
9365              should find it again here during instantiation.  */
9366         gcc_unreachable ();
9367       }
9368       return t;
9369
9370     case FIELD_DECL:
9371       if (DECL_CONTEXT (t))
9372         {
9373           tree ctx;
9374
9375           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
9376                                   /*entering_scope=*/1);
9377           if (ctx != DECL_CONTEXT (t))
9378             {
9379               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
9380               if (!r)
9381                 {
9382                   if (complain & tf_error)
9383                     error ("using invalid field %qD", t);
9384                   return error_mark_node;
9385                 }
9386               return r;
9387             }
9388         }
9389
9390       return t;
9391
9392     case VAR_DECL:
9393     case FUNCTION_DECL:
9394       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
9395           || local_variable_p (t))
9396         t = tsubst (t, args, complain, in_decl);
9397       mark_used (t);
9398       return t;
9399
9400     case BASELINK:
9401       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
9402
9403     case TEMPLATE_DECL:
9404       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9405         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
9406                        args, complain, in_decl);
9407       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
9408         return tsubst (t, args, complain, in_decl);
9409       else if (DECL_CLASS_SCOPE_P (t)
9410                && uses_template_parms (DECL_CONTEXT (t)))
9411         {
9412           /* Template template argument like the following example need
9413              special treatment:
9414
9415                template <template <class> class TT> struct C {};
9416                template <class T> struct D {
9417                  template <class U> struct E {};
9418                  C<E> c;                                // #1
9419                };
9420                D<int> d;                                // #2
9421
9422              We are processing the template argument `E' in #1 for
9423              the template instantiation #2.  Originally, `E' is a
9424              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
9425              have to substitute this with one having context `D<int>'.  */
9426
9427           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
9428           return lookup_field (context, DECL_NAME(t), 0, false);
9429         }
9430       else
9431         /* Ordinary template template argument.  */
9432         return t;
9433
9434     case CAST_EXPR:
9435     case REINTERPRET_CAST_EXPR:
9436     case CONST_CAST_EXPR:
9437     case STATIC_CAST_EXPR:
9438     case DYNAMIC_CAST_EXPR:
9439     case NOP_EXPR:
9440       return build1
9441         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
9442          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
9443
9444     case SIZEOF_EXPR:
9445       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
9446         {
9447           /* We only want to compute the number of arguments.  */
9448           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
9449                                                 complain, in_decl);
9450           return build_int_cst (size_type_node, TREE_VEC_LENGTH (expanded));
9451         }
9452       /* Fall through */
9453
9454     case INDIRECT_REF:
9455     case NEGATE_EXPR:
9456     case TRUTH_NOT_EXPR:
9457     case BIT_NOT_EXPR:
9458     case ADDR_EXPR:
9459     case UNARY_PLUS_EXPR:      /* Unary + */
9460     case ALIGNOF_EXPR:
9461     case ARROW_EXPR:
9462     case THROW_EXPR:
9463     case TYPEID_EXPR:
9464     case REALPART_EXPR:
9465     case IMAGPART_EXPR:
9466       return build1
9467         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
9468          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
9469
9470     case COMPONENT_REF:
9471       {
9472         tree object;
9473         tree name;
9474
9475         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
9476         name = TREE_OPERAND (t, 1);
9477         if (TREE_CODE (name) == BIT_NOT_EXPR)
9478           {
9479             name = tsubst_copy (TREE_OPERAND (name, 0), args,
9480                                 complain, in_decl);
9481             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
9482           }
9483         else if (TREE_CODE (name) == SCOPE_REF
9484                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
9485           {
9486             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
9487                                      complain, in_decl);
9488             name = TREE_OPERAND (name, 1);
9489             name = tsubst_copy (TREE_OPERAND (name, 0), args,
9490                                 complain, in_decl);
9491             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
9492             name = build_qualified_name (/*type=*/NULL_TREE,
9493                                          base, name,
9494                                          /*template_p=*/false);
9495           }
9496         else if (TREE_CODE (name) == BASELINK)
9497           name = tsubst_baselink (name,
9498                                   non_reference (TREE_TYPE (object)),
9499                                   args, complain,
9500                                   in_decl);
9501         else
9502           name = tsubst_copy (name, args, complain, in_decl);
9503         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
9504       }
9505
9506     case PLUS_EXPR:
9507     case MINUS_EXPR:
9508     case MULT_EXPR:
9509     case TRUNC_DIV_EXPR:
9510     case CEIL_DIV_EXPR:
9511     case FLOOR_DIV_EXPR:
9512     case ROUND_DIV_EXPR:
9513     case EXACT_DIV_EXPR:
9514     case BIT_AND_EXPR:
9515     case BIT_IOR_EXPR:
9516     case BIT_XOR_EXPR:
9517     case TRUNC_MOD_EXPR:
9518     case FLOOR_MOD_EXPR:
9519     case TRUTH_ANDIF_EXPR:
9520     case TRUTH_ORIF_EXPR:
9521     case TRUTH_AND_EXPR:
9522     case TRUTH_OR_EXPR:
9523     case RSHIFT_EXPR:
9524     case LSHIFT_EXPR:
9525     case RROTATE_EXPR:
9526     case LROTATE_EXPR:
9527     case EQ_EXPR:
9528     case NE_EXPR:
9529     case MAX_EXPR:
9530     case MIN_EXPR:
9531     case LE_EXPR:
9532     case GE_EXPR:
9533     case LT_EXPR:
9534     case GT_EXPR:
9535     case COMPOUND_EXPR:
9536     case DOTSTAR_EXPR:
9537     case MEMBER_REF:
9538     case PREDECREMENT_EXPR:
9539     case PREINCREMENT_EXPR:
9540     case POSTDECREMENT_EXPR:
9541     case POSTINCREMENT_EXPR:
9542       return build_nt
9543         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
9544          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
9545
9546     case SCOPE_REF:
9547       return build_qualified_name (/*type=*/NULL_TREE,
9548                                    tsubst_copy (TREE_OPERAND (t, 0),
9549                                                 args, complain, in_decl),
9550                                    tsubst_copy (TREE_OPERAND (t, 1),
9551                                                 args, complain, in_decl),
9552                                    QUALIFIED_NAME_IS_TEMPLATE (t));
9553
9554     case ARRAY_REF:
9555       return build_nt
9556         (ARRAY_REF,
9557          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
9558          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
9559          NULL_TREE, NULL_TREE);
9560
9561     case CALL_EXPR:
9562       {
9563         int n = VL_EXP_OPERAND_LENGTH (t);
9564         tree result = build_vl_exp (CALL_EXPR, n);
9565         int i;
9566         for (i = 0; i < n; i++)
9567           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
9568                                              complain, in_decl);
9569         return result;
9570       }
9571
9572     case COND_EXPR:
9573     case MODOP_EXPR:
9574     case PSEUDO_DTOR_EXPR:
9575       {
9576         r = build_nt
9577           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
9578            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
9579            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
9580         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
9581         return r;
9582       }
9583
9584     case NEW_EXPR:
9585       {
9586         r = build_nt
9587         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
9588          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
9589          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
9590         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
9591         return r;
9592       }
9593
9594     case DELETE_EXPR:
9595       {
9596         r = build_nt
9597         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
9598          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
9599         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
9600         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
9601         return r;
9602       }
9603
9604     case TEMPLATE_ID_EXPR:
9605       {
9606         /* Substituted template arguments */
9607         tree fn = TREE_OPERAND (t, 0);
9608         tree targs = TREE_OPERAND (t, 1);
9609
9610         fn = tsubst_copy (fn, args, complain, in_decl);
9611         if (targs)
9612           targs = tsubst_template_args (targs, args, complain, in_decl);
9613
9614         return lookup_template_function (fn, targs);
9615       }
9616
9617     case TREE_LIST:
9618       {
9619         tree purpose, value, chain;
9620
9621         if (t == void_list_node)
9622           return t;
9623
9624         purpose = TREE_PURPOSE (t);
9625         if (purpose)
9626           purpose = tsubst_copy (purpose, args, complain, in_decl);
9627         value = TREE_VALUE (t);
9628         if (value)
9629           value = tsubst_copy (value, args, complain, in_decl);
9630         chain = TREE_CHAIN (t);
9631         if (chain && chain != void_type_node)
9632           chain = tsubst_copy (chain, args, complain, in_decl);
9633         if (purpose == TREE_PURPOSE (t)
9634             && value == TREE_VALUE (t)
9635             && chain == TREE_CHAIN (t))
9636           return t;
9637         return tree_cons (purpose, value, chain);
9638       }
9639
9640     case RECORD_TYPE:
9641     case UNION_TYPE:
9642     case ENUMERAL_TYPE:
9643     case INTEGER_TYPE:
9644     case TEMPLATE_TYPE_PARM:
9645     case TEMPLATE_TEMPLATE_PARM:
9646     case BOUND_TEMPLATE_TEMPLATE_PARM:
9647     case TEMPLATE_PARM_INDEX:
9648     case POINTER_TYPE:
9649     case REFERENCE_TYPE:
9650     case OFFSET_TYPE:
9651     case FUNCTION_TYPE:
9652     case METHOD_TYPE:
9653     case ARRAY_TYPE:
9654     case TYPENAME_TYPE:
9655     case UNBOUND_CLASS_TEMPLATE:
9656     case TYPEOF_TYPE:
9657     case DECLTYPE_TYPE:
9658     case TYPE_DECL:
9659       return tsubst (t, args, complain, in_decl);
9660
9661     case IDENTIFIER_NODE:
9662       if (IDENTIFIER_TYPENAME_P (t))
9663         {
9664           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9665           return mangle_conv_op_name_for_type (new_type);
9666         }
9667       else
9668         return t;
9669
9670     case CONSTRUCTOR:
9671       /* This is handled by tsubst_copy_and_build.  */
9672       gcc_unreachable ();
9673
9674     case VA_ARG_EXPR:
9675       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
9676                                           in_decl),
9677                              tsubst (TREE_TYPE (t), args, complain, in_decl));
9678
9679     case CLEANUP_POINT_EXPR:
9680       /* We shouldn't have built any of these during initial template
9681          generation.  Instead, they should be built during instantiation
9682          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
9683       gcc_unreachable ();
9684
9685     case OFFSET_REF:
9686       mark_used (TREE_OPERAND (t, 1));
9687       return t;
9688
9689     case EXPR_PACK_EXPANSION:
9690       error ("invalid use of pack expansion expression");
9691       return error_mark_node;
9692
9693     case NONTYPE_ARGUMENT_PACK:
9694       error ("use %<...%> to expand argument pack");
9695       return error_mark_node;
9696
9697     default:
9698       return t;
9699     }
9700 }
9701
9702 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
9703
9704 static tree
9705 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
9706                     tree in_decl)
9707 {
9708   tree new_clauses = NULL, nc, oc;
9709
9710   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
9711     {
9712       nc = copy_node (oc);
9713       OMP_CLAUSE_CHAIN (nc) = new_clauses;
9714       new_clauses = nc;
9715
9716       switch (OMP_CLAUSE_CODE (nc))
9717         {
9718         case OMP_CLAUSE_PRIVATE:
9719         case OMP_CLAUSE_SHARED:
9720         case OMP_CLAUSE_FIRSTPRIVATE:
9721         case OMP_CLAUSE_LASTPRIVATE:
9722         case OMP_CLAUSE_REDUCTION:
9723         case OMP_CLAUSE_COPYIN:
9724         case OMP_CLAUSE_COPYPRIVATE:
9725         case OMP_CLAUSE_IF:
9726         case OMP_CLAUSE_NUM_THREADS:
9727         case OMP_CLAUSE_SCHEDULE:
9728           OMP_CLAUSE_OPERAND (nc, 0)
9729             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
9730                            in_decl, /*integral_constant_expression_p=*/false);
9731           break;
9732         case OMP_CLAUSE_NOWAIT:
9733         case OMP_CLAUSE_ORDERED:
9734         case OMP_CLAUSE_DEFAULT:
9735           break;
9736         default:
9737           gcc_unreachable ();
9738         }
9739     }
9740
9741   return finish_omp_clauses (nreverse (new_clauses));
9742 }
9743
9744 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
9745
9746 static tree
9747 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
9748                           tree in_decl)
9749 {
9750 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
9751
9752   tree purpose, value, chain;
9753
9754   if (t == NULL)
9755     return t;
9756
9757   if (TREE_CODE (t) != TREE_LIST)
9758     return tsubst_copy_and_build (t, args, complain, in_decl,
9759                                   /*function_p=*/false,
9760                                   /*integral_constant_expression_p=*/false);
9761
9762   if (t == void_list_node)
9763     return t;
9764
9765   purpose = TREE_PURPOSE (t);
9766   if (purpose)
9767     purpose = RECUR (purpose);
9768   value = TREE_VALUE (t);
9769   if (value)
9770     value = RECUR (value);
9771   chain = TREE_CHAIN (t);
9772   if (chain && chain != void_type_node)
9773     chain = RECUR (chain);
9774   return tree_cons (purpose, value, chain);
9775 #undef RECUR
9776 }
9777
9778 /* Like tsubst_copy for expressions, etc. but also does semantic
9779    processing.  */
9780
9781 static tree
9782 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
9783              bool integral_constant_expression_p)
9784 {
9785 #define RECUR(NODE)                             \
9786   tsubst_expr ((NODE), args, complain, in_decl, \
9787                integral_constant_expression_p)
9788
9789   tree stmt, tmp;
9790
9791   if (t == NULL_TREE || t == error_mark_node)
9792     return t;
9793
9794   if (EXPR_HAS_LOCATION (t))
9795     input_location = EXPR_LOCATION (t);
9796   if (STATEMENT_CODE_P (TREE_CODE (t)))
9797     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
9798
9799   switch (TREE_CODE (t))
9800     {
9801     case STATEMENT_LIST:
9802       {
9803         tree_stmt_iterator i;
9804         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
9805           RECUR (tsi_stmt (i));
9806         break;
9807       }
9808
9809     case CTOR_INITIALIZER:
9810       finish_mem_initializers (tsubst_initializer_list
9811                                (TREE_OPERAND (t, 0), args));
9812       break;
9813
9814     case RETURN_EXPR:
9815       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
9816       break;
9817
9818     case EXPR_STMT:
9819       tmp = RECUR (EXPR_STMT_EXPR (t));
9820       if (EXPR_STMT_STMT_EXPR_RESULT (t))
9821         finish_stmt_expr_expr (tmp, cur_stmt_expr);
9822       else
9823         finish_expr_stmt (tmp);
9824       break;
9825
9826     case USING_STMT:
9827       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
9828       break;
9829
9830     case DECL_EXPR:
9831       {
9832         tree decl;
9833         tree init;
9834
9835         decl = DECL_EXPR_DECL (t);
9836         if (TREE_CODE (decl) == LABEL_DECL)
9837           finish_label_decl (DECL_NAME (decl));
9838         else if (TREE_CODE (decl) == USING_DECL)
9839           {
9840             tree scope = USING_DECL_SCOPE (decl);
9841             tree name = DECL_NAME (decl);
9842             tree decl;
9843
9844             scope = RECUR (scope);
9845             decl = lookup_qualified_name (scope, name,
9846                                           /*is_type_p=*/false,
9847                                           /*complain=*/false);
9848             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
9849               qualified_name_lookup_error (scope, name, decl);
9850             else
9851               do_local_using_decl (decl, scope, name);
9852           }
9853         else
9854           {
9855             init = DECL_INITIAL (decl);
9856             decl = tsubst (decl, args, complain, in_decl);
9857             if (decl != error_mark_node)
9858               {
9859                 /* By marking the declaration as instantiated, we avoid
9860                    trying to instantiate it.  Since instantiate_decl can't
9861                    handle local variables, and since we've already done
9862                    all that needs to be done, that's the right thing to
9863                    do.  */
9864                 if (TREE_CODE (decl) == VAR_DECL)
9865                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
9866                 if (TREE_CODE (decl) == VAR_DECL
9867                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
9868                   /* Anonymous aggregates are a special case.  */
9869                   finish_anon_union (decl);
9870                 else
9871                   {
9872                     maybe_push_decl (decl);
9873                     if (TREE_CODE (decl) == VAR_DECL
9874                         && DECL_PRETTY_FUNCTION_P (decl))
9875                       {
9876                         /* For __PRETTY_FUNCTION__ we have to adjust the
9877                            initializer.  */
9878                         const char *const name
9879                           = cxx_printable_name (current_function_decl, 2);
9880                         init = cp_fname_init (name, &TREE_TYPE (decl));
9881                       }
9882                     else
9883                       init = RECUR (init);
9884                     finish_decl (decl, init, NULL_TREE);
9885                   }
9886               }
9887           }
9888
9889         /* A DECL_EXPR can also be used as an expression, in the condition
9890            clause of an if/for/while construct.  */
9891         return decl;
9892       }
9893
9894     case FOR_STMT:
9895       stmt = begin_for_stmt ();
9896                           RECUR (FOR_INIT_STMT (t));
9897       finish_for_init_stmt (stmt);
9898       tmp = RECUR (FOR_COND (t));
9899       finish_for_cond (tmp, stmt);
9900       tmp = RECUR (FOR_EXPR (t));
9901       finish_for_expr (tmp, stmt);
9902       RECUR (FOR_BODY (t));
9903       finish_for_stmt (stmt);
9904       break;
9905
9906     case WHILE_STMT:
9907       stmt = begin_while_stmt ();
9908       tmp = RECUR (WHILE_COND (t));
9909       finish_while_stmt_cond (tmp, stmt);
9910       RECUR (WHILE_BODY (t));
9911       finish_while_stmt (stmt);
9912       break;
9913
9914     case DO_STMT:
9915       stmt = begin_do_stmt ();
9916       RECUR (DO_BODY (t));
9917       finish_do_body (stmt);
9918       tmp = RECUR (DO_COND (t));
9919       finish_do_stmt (tmp, stmt);
9920       break;
9921
9922     case IF_STMT:
9923       stmt = begin_if_stmt ();
9924       tmp = RECUR (IF_COND (t));
9925       finish_if_stmt_cond (tmp, stmt);
9926       RECUR (THEN_CLAUSE (t));
9927       finish_then_clause (stmt);
9928
9929       if (ELSE_CLAUSE (t))
9930         {
9931           begin_else_clause (stmt);
9932           RECUR (ELSE_CLAUSE (t));
9933           finish_else_clause (stmt);
9934         }
9935
9936       finish_if_stmt (stmt);
9937       break;
9938
9939     case BIND_EXPR:
9940       if (BIND_EXPR_BODY_BLOCK (t))
9941         stmt = begin_function_body ();
9942       else
9943         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
9944                                     ? BCS_TRY_BLOCK : 0);
9945
9946       RECUR (BIND_EXPR_BODY (t));
9947
9948       if (BIND_EXPR_BODY_BLOCK (t))
9949         finish_function_body (stmt);
9950       else
9951         finish_compound_stmt (stmt);
9952       break;
9953
9954     case BREAK_STMT:
9955       finish_break_stmt ();
9956       break;
9957
9958     case CONTINUE_STMT:
9959       finish_continue_stmt ();
9960       break;
9961
9962     case SWITCH_STMT:
9963       stmt = begin_switch_stmt ();
9964       tmp = RECUR (SWITCH_STMT_COND (t));
9965       finish_switch_cond (tmp, stmt);
9966       RECUR (SWITCH_STMT_BODY (t));
9967       finish_switch_stmt (stmt);
9968       break;
9969
9970     case CASE_LABEL_EXPR:
9971       finish_case_label (RECUR (CASE_LOW (t)),
9972                          RECUR (CASE_HIGH (t)));
9973       break;
9974
9975     case LABEL_EXPR:
9976       finish_label_stmt (DECL_NAME (LABEL_EXPR_LABEL (t)));
9977       break;
9978
9979     case GOTO_EXPR:
9980       tmp = GOTO_DESTINATION (t);
9981       if (TREE_CODE (tmp) != LABEL_DECL)
9982         /* Computed goto's must be tsubst'd into.  On the other hand,
9983            non-computed gotos must not be; the identifier in question
9984            will have no binding.  */
9985         tmp = RECUR (tmp);
9986       else
9987         tmp = DECL_NAME (tmp);
9988       finish_goto_stmt (tmp);
9989       break;
9990
9991     case ASM_EXPR:
9992       tmp = finish_asm_stmt
9993         (ASM_VOLATILE_P (t),
9994          RECUR (ASM_STRING (t)),
9995          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
9996          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
9997          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl));
9998       {
9999         tree asm_expr = tmp;
10000         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
10001           asm_expr = TREE_OPERAND (asm_expr, 0);
10002         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
10003       }
10004       break;
10005
10006     case TRY_BLOCK:
10007       if (CLEANUP_P (t))
10008         {
10009           stmt = begin_try_block ();
10010           RECUR (TRY_STMTS (t));
10011           finish_cleanup_try_block (stmt);
10012           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
10013         }
10014       else
10015         {
10016           tree compound_stmt = NULL_TREE;
10017
10018           if (FN_TRY_BLOCK_P (t))
10019             stmt = begin_function_try_block (&compound_stmt);
10020           else
10021             stmt = begin_try_block ();
10022
10023           RECUR (TRY_STMTS (t));
10024
10025           if (FN_TRY_BLOCK_P (t))
10026             finish_function_try_block (stmt);
10027           else
10028             finish_try_block (stmt);
10029
10030           RECUR (TRY_HANDLERS (t));
10031           if (FN_TRY_BLOCK_P (t))
10032             finish_function_handler_sequence (stmt, compound_stmt);
10033           else
10034             finish_handler_sequence (stmt);
10035         }
10036       break;
10037
10038     case HANDLER:
10039       {
10040         tree decl = HANDLER_PARMS (t);
10041
10042         if (decl)
10043           {
10044             decl = tsubst (decl, args, complain, in_decl);
10045             /* Prevent instantiate_decl from trying to instantiate
10046                this variable.  We've already done all that needs to be
10047                done.  */
10048             if (decl != error_mark_node)
10049               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10050           }
10051         stmt = begin_handler ();
10052         finish_handler_parms (decl, stmt);
10053         RECUR (HANDLER_BODY (t));
10054         finish_handler (stmt);
10055       }
10056       break;
10057
10058     case TAG_DEFN:
10059       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
10060       break;
10061
10062     case STATIC_ASSERT:
10063       {
10064         tree condition = 
10065           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
10066                        args,
10067                        complain, in_decl,
10068                        /*integral_constant_expression_p=*/true);
10069         finish_static_assert (condition,
10070                               STATIC_ASSERT_MESSAGE (t),
10071                               STATIC_ASSERT_SOURCE_LOCATION (t),
10072                               /*member_p=*/false);
10073       }
10074       break;
10075
10076     case OMP_PARALLEL:
10077       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
10078                                 args, complain, in_decl);
10079       stmt = begin_omp_parallel ();
10080       RECUR (OMP_PARALLEL_BODY (t));
10081       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
10082         = OMP_PARALLEL_COMBINED (t);
10083       break;
10084
10085     case OMP_FOR:
10086       {
10087         tree clauses, decl, init, cond, incr, body, pre_body;
10088
10089         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
10090                                       args, complain, in_decl);
10091         init = OMP_FOR_INIT (t);
10092         gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
10093         decl = RECUR (TREE_OPERAND (init, 0));
10094         init = RECUR (TREE_OPERAND (init, 1));
10095         cond = RECUR (OMP_FOR_COND (t));
10096         incr = RECUR (OMP_FOR_INCR (t));
10097
10098         stmt = begin_omp_structured_block ();
10099
10100         pre_body = push_stmt_list ();
10101         RECUR (OMP_FOR_PRE_BODY (t));
10102         pre_body = pop_stmt_list (pre_body);
10103
10104         body = push_stmt_list ();
10105         RECUR (OMP_FOR_BODY (t));
10106         body = pop_stmt_list (body);
10107
10108         t = finish_omp_for (EXPR_LOCATION (t), decl, init, cond, incr, body,
10109                             pre_body);
10110         if (t)
10111           OMP_FOR_CLAUSES (t) = clauses;
10112
10113         add_stmt (finish_omp_structured_block (stmt));
10114       }
10115       break;
10116
10117     case OMP_SECTIONS:
10118     case OMP_SINGLE:
10119       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
10120       stmt = push_stmt_list ();
10121       RECUR (OMP_BODY (t));
10122       stmt = pop_stmt_list (stmt);
10123
10124       t = copy_node (t);
10125       OMP_BODY (t) = stmt;
10126       OMP_CLAUSES (t) = tmp;
10127       add_stmt (t);
10128       break;
10129
10130     case OMP_SECTION:
10131     case OMP_CRITICAL:
10132     case OMP_MASTER:
10133     case OMP_ORDERED:
10134       stmt = push_stmt_list ();
10135       RECUR (OMP_BODY (t));
10136       stmt = pop_stmt_list (stmt);
10137
10138       t = copy_node (t);
10139       OMP_BODY (t) = stmt;
10140       add_stmt (t);
10141       break;
10142
10143     case OMP_ATOMIC:
10144       if (OMP_ATOMIC_DEPENDENT_P (t))
10145         {
10146           tree op1 = TREE_OPERAND (t, 1);
10147           tree lhs = RECUR (TREE_OPERAND (op1, 0));
10148           tree rhs = RECUR (TREE_OPERAND (op1, 1));
10149           finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
10150         }
10151       break;
10152
10153     case EXPR_PACK_EXPANSION:
10154       error ("invalid use of pack expansion expression");
10155       return error_mark_node;
10156
10157     case NONTYPE_ARGUMENT_PACK:
10158       error ("use %<...%> to expand argument pack");
10159       return error_mark_node;
10160
10161     default:
10162       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
10163
10164       return tsubst_copy_and_build (t, args, complain, in_decl,
10165                                     /*function_p=*/false,
10166                                     integral_constant_expression_p);
10167     }
10168
10169   return NULL_TREE;
10170 #undef RECUR
10171 }
10172
10173 /* T is a postfix-expression that is not being used in a function
10174    call.  Return the substituted version of T.  */
10175
10176 static tree
10177 tsubst_non_call_postfix_expression (tree t, tree args,
10178                                     tsubst_flags_t complain,
10179                                     tree in_decl)
10180 {
10181   if (TREE_CODE (t) == SCOPE_REF)
10182     t = tsubst_qualified_id (t, args, complain, in_decl,
10183                              /*done=*/false, /*address_p=*/false);
10184   else
10185     t = tsubst_copy_and_build (t, args, complain, in_decl,
10186                                /*function_p=*/false,
10187                                /*integral_constant_expression_p=*/false);
10188
10189   return t;
10190 }
10191
10192 /* Like tsubst but deals with expressions and performs semantic
10193    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
10194
10195 tree
10196 tsubst_copy_and_build (tree t,
10197                        tree args,
10198                        tsubst_flags_t complain,
10199                        tree in_decl,
10200                        bool function_p,
10201                        bool integral_constant_expression_p)
10202 {
10203 #define RECUR(NODE)                                             \
10204   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
10205                          /*function_p=*/false,                  \
10206                          integral_constant_expression_p)
10207
10208   tree op1;
10209
10210   if (t == NULL_TREE || t == error_mark_node)
10211     return t;
10212
10213   switch (TREE_CODE (t))
10214     {
10215     case USING_DECL:
10216       t = DECL_NAME (t);
10217       /* Fall through.  */
10218     case IDENTIFIER_NODE:
10219       {
10220         tree decl;
10221         cp_id_kind idk;
10222         bool non_integral_constant_expression_p;
10223         const char *error_msg;
10224
10225         if (IDENTIFIER_TYPENAME_P (t))
10226           {
10227             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10228             t = mangle_conv_op_name_for_type (new_type);
10229           }
10230
10231         /* Look up the name.  */
10232         decl = lookup_name (t);
10233
10234         /* By convention, expressions use ERROR_MARK_NODE to indicate
10235            failure, not NULL_TREE.  */
10236         if (decl == NULL_TREE)
10237           decl = error_mark_node;
10238
10239         decl = finish_id_expression (t, decl, NULL_TREE,
10240                                      &idk,
10241                                      integral_constant_expression_p,
10242                                      /*allow_non_integral_constant_expression_p=*/false,
10243                                      &non_integral_constant_expression_p,
10244                                      /*template_p=*/false,
10245                                      /*done=*/true,
10246                                      /*address_p=*/false,
10247                                      /*template_arg_p=*/false,
10248                                      &error_msg);
10249         if (error_msg)
10250           error (error_msg);
10251         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
10252           decl = unqualified_name_lookup_error (decl);
10253         return decl;
10254       }
10255
10256     case TEMPLATE_ID_EXPR:
10257       {
10258         tree object;
10259         tree template = RECUR (TREE_OPERAND (t, 0));
10260         tree targs = TREE_OPERAND (t, 1);
10261
10262         if (targs)
10263           targs = tsubst_template_args (targs, args, complain, in_decl);
10264
10265         if (TREE_CODE (template) == COMPONENT_REF)
10266           {
10267             object = TREE_OPERAND (template, 0);
10268             template = TREE_OPERAND (template, 1);
10269           }
10270         else
10271           object = NULL_TREE;
10272         template = lookup_template_function (template, targs);
10273
10274         if (object)
10275           return build3 (COMPONENT_REF, TREE_TYPE (template),
10276                          object, template, NULL_TREE);
10277         else
10278           return baselink_for_fns (template);
10279       }
10280
10281     case INDIRECT_REF:
10282       {
10283         tree r = RECUR (TREE_OPERAND (t, 0));
10284
10285         if (REFERENCE_REF_P (t))
10286           {
10287             /* A type conversion to reference type will be enclosed in
10288                such an indirect ref, but the substitution of the cast
10289                will have also added such an indirect ref.  */
10290             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
10291               r = convert_from_reference (r);
10292           }
10293         else
10294           r = build_x_indirect_ref (r, "unary *");
10295         return r;
10296       }
10297
10298     case NOP_EXPR:
10299       return build_nop
10300         (tsubst (TREE_TYPE (t), args, complain, in_decl),
10301          RECUR (TREE_OPERAND (t, 0)));
10302
10303     case CAST_EXPR:
10304     case REINTERPRET_CAST_EXPR:
10305     case CONST_CAST_EXPR:
10306     case DYNAMIC_CAST_EXPR:
10307     case STATIC_CAST_EXPR:
10308       {
10309         tree type;
10310         tree op;
10311
10312         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10313         if (integral_constant_expression_p
10314             && !cast_valid_in_integral_constant_expression_p (type))
10315           {
10316             error ("a cast to a type other than an integral or "
10317                    "enumeration type cannot appear in a constant-expression");
10318             return error_mark_node; 
10319           }
10320
10321         op = RECUR (TREE_OPERAND (t, 0));
10322
10323         switch (TREE_CODE (t))
10324           {
10325           case CAST_EXPR:
10326             return build_functional_cast (type, op);
10327           case REINTERPRET_CAST_EXPR:
10328             return build_reinterpret_cast (type, op);
10329           case CONST_CAST_EXPR:
10330             return build_const_cast (type, op);
10331           case DYNAMIC_CAST_EXPR:
10332             return build_dynamic_cast (type, op);
10333           case STATIC_CAST_EXPR:
10334             return build_static_cast (type, op);
10335           default:
10336             gcc_unreachable ();
10337           }
10338       }
10339
10340     case POSTDECREMENT_EXPR:
10341     case POSTINCREMENT_EXPR:
10342       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
10343                                                 args, complain, in_decl);
10344       return build_x_unary_op (TREE_CODE (t), op1);
10345
10346     case PREDECREMENT_EXPR:
10347     case PREINCREMENT_EXPR:
10348     case NEGATE_EXPR:
10349     case BIT_NOT_EXPR:
10350     case ABS_EXPR:
10351     case TRUTH_NOT_EXPR:
10352     case UNARY_PLUS_EXPR:  /* Unary + */
10353     case REALPART_EXPR:
10354     case IMAGPART_EXPR:
10355       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)));
10356
10357     case ADDR_EXPR:
10358       op1 = TREE_OPERAND (t, 0);
10359       if (TREE_CODE (op1) == SCOPE_REF)
10360         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
10361                                    /*done=*/true, /*address_p=*/true);
10362       else
10363         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
10364                                                   in_decl);
10365       if (TREE_CODE (op1) == LABEL_DECL)
10366         return finish_label_address_expr (DECL_NAME (op1));
10367       return build_x_unary_op (ADDR_EXPR, op1);
10368
10369     case PLUS_EXPR:
10370     case MINUS_EXPR:
10371     case MULT_EXPR:
10372     case TRUNC_DIV_EXPR:
10373     case CEIL_DIV_EXPR:
10374     case FLOOR_DIV_EXPR:
10375     case ROUND_DIV_EXPR:
10376     case EXACT_DIV_EXPR:
10377     case BIT_AND_EXPR:
10378     case BIT_IOR_EXPR:
10379     case BIT_XOR_EXPR:
10380     case TRUNC_MOD_EXPR:
10381     case FLOOR_MOD_EXPR:
10382     case TRUTH_ANDIF_EXPR:
10383     case TRUTH_ORIF_EXPR:
10384     case TRUTH_AND_EXPR:
10385     case TRUTH_OR_EXPR:
10386     case RSHIFT_EXPR:
10387     case LSHIFT_EXPR:
10388     case RROTATE_EXPR:
10389     case LROTATE_EXPR:
10390     case EQ_EXPR:
10391     case NE_EXPR:
10392     case MAX_EXPR:
10393     case MIN_EXPR:
10394     case LE_EXPR:
10395     case GE_EXPR:
10396     case LT_EXPR:
10397     case GT_EXPR:
10398     case MEMBER_REF:
10399     case DOTSTAR_EXPR:
10400       return build_x_binary_op
10401         (TREE_CODE (t),
10402          RECUR (TREE_OPERAND (t, 0)),
10403          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
10404           ? ERROR_MARK
10405           : TREE_CODE (TREE_OPERAND (t, 0))),
10406          RECUR (TREE_OPERAND (t, 1)),
10407          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
10408           ? ERROR_MARK
10409           : TREE_CODE (TREE_OPERAND (t, 1))),
10410          /*overloaded_p=*/NULL);
10411
10412     case SCOPE_REF:
10413       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
10414                                   /*address_p=*/false);
10415     case ARRAY_REF:
10416       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
10417                                                 args, complain, in_decl);
10418       return build_x_binary_op (ARRAY_REF, op1,
10419                                 (TREE_NO_WARNING (TREE_OPERAND (t, 0))
10420                                  ? ERROR_MARK
10421                                  : TREE_CODE (TREE_OPERAND (t, 0))),
10422                                 RECUR (TREE_OPERAND (t, 1)),
10423                                 (TREE_NO_WARNING (TREE_OPERAND (t, 1))
10424                                  ? ERROR_MARK
10425                                  : TREE_CODE (TREE_OPERAND (t, 1))),
10426                                 /*overloaded_p=*/NULL);
10427
10428     case SIZEOF_EXPR:
10429       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10430         {
10431           /* We only want to compute the number of arguments.  */
10432           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
10433                                                 complain, in_decl);
10434           return build_int_cst (size_type_node, TREE_VEC_LENGTH (expanded));
10435         }
10436       /* Fall through */
10437       
10438     case ALIGNOF_EXPR:
10439       op1 = TREE_OPERAND (t, 0);
10440       if (!args)
10441         {
10442           /* When there are no ARGS, we are trying to evaluate a
10443              non-dependent expression from the parser.  Trying to do
10444              the substitutions may not work.  */
10445           if (!TYPE_P (op1))
10446             op1 = TREE_TYPE (op1);
10447         }
10448       else
10449         {
10450           ++skip_evaluation;
10451           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
10452                                        /*function_p=*/false,
10453                                        /*integral_constant_expression_p=*/false);
10454           --skip_evaluation;
10455         }
10456       if (TYPE_P (op1))
10457         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), true);
10458       else
10459         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t));
10460
10461     case MODOP_EXPR:
10462       {
10463         tree r = build_x_modify_expr
10464           (RECUR (TREE_OPERAND (t, 0)),
10465            TREE_CODE (TREE_OPERAND (t, 1)),
10466            RECUR (TREE_OPERAND (t, 2)));
10467         /* TREE_NO_WARNING must be set if either the expression was
10468            parenthesized or it uses an operator such as >>= rather
10469            than plain assignment.  In the former case, it was already
10470            set and must be copied.  In the latter case,
10471            build_x_modify_expr sets it and it must not be reset
10472            here.  */
10473         if (TREE_NO_WARNING (t))
10474           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
10475         return r;
10476       }
10477
10478     case ARROW_EXPR:
10479       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
10480                                                 args, complain, in_decl);
10481       /* Remember that there was a reference to this entity.  */
10482       if (DECL_P (op1))
10483         mark_used (op1);
10484       return build_x_arrow (op1);
10485
10486     case NEW_EXPR:
10487       return build_new
10488         (RECUR (TREE_OPERAND (t, 0)),
10489          RECUR (TREE_OPERAND (t, 1)),
10490          RECUR (TREE_OPERAND (t, 2)),
10491          RECUR (TREE_OPERAND (t, 3)),
10492          NEW_EXPR_USE_GLOBAL (t));
10493
10494     case DELETE_EXPR:
10495      return delete_sanity
10496        (RECUR (TREE_OPERAND (t, 0)),
10497         RECUR (TREE_OPERAND (t, 1)),
10498         DELETE_EXPR_USE_VEC (t),
10499         DELETE_EXPR_USE_GLOBAL (t));
10500
10501     case COMPOUND_EXPR:
10502       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
10503                                     RECUR (TREE_OPERAND (t, 1)));
10504
10505     case CALL_EXPR:
10506       {
10507         tree function;
10508         tree call_args;
10509         bool qualified_p;
10510         bool koenig_p;
10511
10512         function = CALL_EXPR_FN (t);
10513         /* When we parsed the expression,  we determined whether or
10514            not Koenig lookup should be performed.  */
10515         koenig_p = KOENIG_LOOKUP_P (t);
10516         if (TREE_CODE (function) == SCOPE_REF)
10517           {
10518             qualified_p = true;
10519             function = tsubst_qualified_id (function, args, complain, in_decl,
10520                                             /*done=*/false,
10521                                             /*address_p=*/false);
10522           }
10523         else
10524           {
10525             if (TREE_CODE (function) == COMPONENT_REF)
10526               {
10527                 tree op = TREE_OPERAND (function, 1);
10528
10529                 qualified_p = (TREE_CODE (op) == SCOPE_REF
10530                                || (BASELINK_P (op)
10531                                    && BASELINK_QUALIFIED_P (op)));
10532               }
10533             else
10534               qualified_p = false;
10535
10536             function = tsubst_copy_and_build (function, args, complain,
10537                                               in_decl,
10538                                               !qualified_p,
10539                                               integral_constant_expression_p);
10540
10541             if (BASELINK_P (function))
10542               qualified_p = true;
10543           }
10544
10545         /* FIXME:  Rewrite this so as not to construct an arglist.  */
10546         call_args = RECUR (CALL_EXPR_ARGS (t));
10547
10548         /* We do not perform argument-dependent lookup if normal
10549            lookup finds a non-function, in accordance with the
10550            expected resolution of DR 218.  */
10551         if (koenig_p
10552             && ((is_overloaded_fn (function)
10553                  /* If lookup found a member function, the Koenig lookup is
10554                     not appropriate, even if an unqualified-name was used
10555                     to denote the function.  */
10556                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
10557                 || TREE_CODE (function) == IDENTIFIER_NODE))
10558           function = perform_koenig_lookup (function, call_args);
10559
10560         if (TREE_CODE (function) == IDENTIFIER_NODE)
10561           {
10562             unqualified_name_lookup_error (function);
10563             return error_mark_node;
10564           }
10565
10566         /* Remember that there was a reference to this entity.  */
10567         if (DECL_P (function))
10568           mark_used (function);
10569
10570         if (TREE_CODE (function) == OFFSET_REF)
10571           return build_offset_ref_call_from_tree (function, call_args);
10572         if (TREE_CODE (function) == COMPONENT_REF)
10573           {
10574             if (!BASELINK_P (TREE_OPERAND (function, 1)))
10575               return finish_call_expr (function, call_args,
10576                                        /*disallow_virtual=*/false,
10577                                        /*koenig_p=*/false);
10578             else
10579               return (build_new_method_call
10580                       (TREE_OPERAND (function, 0),
10581                        TREE_OPERAND (function, 1),
10582                        call_args, NULL_TREE,
10583                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
10584                        /*fn_p=*/NULL));
10585           }
10586         return finish_call_expr (function, call_args,
10587                                  /*disallow_virtual=*/qualified_p,
10588                                  koenig_p);
10589       }
10590
10591     case COND_EXPR:
10592       return build_x_conditional_expr
10593         (RECUR (TREE_OPERAND (t, 0)),
10594          RECUR (TREE_OPERAND (t, 1)),
10595          RECUR (TREE_OPERAND (t, 2)));
10596
10597     case PSEUDO_DTOR_EXPR:
10598       return finish_pseudo_destructor_expr
10599         (RECUR (TREE_OPERAND (t, 0)),
10600          RECUR (TREE_OPERAND (t, 1)),
10601          RECUR (TREE_OPERAND (t, 2)));
10602
10603     case TREE_LIST:
10604       {
10605         tree purpose, value, chain;
10606
10607         if (t == void_list_node)
10608           return t;
10609
10610         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
10611             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
10612           {
10613             /* We have pack expansions, so expand those and
10614                create a new list out of it.  */
10615             tree purposevec = NULL_TREE;
10616             tree valuevec = NULL_TREE;
10617             tree chain;
10618             int i, len = -1;
10619
10620             /* Expand the argument expressions.  */
10621             if (TREE_PURPOSE (t))
10622               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
10623                                                  complain, in_decl);
10624             if (TREE_VALUE (t))
10625               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
10626                                                complain, in_decl);
10627
10628             /* Build the rest of the list.  */
10629             chain = TREE_CHAIN (t);
10630             if (chain && chain != void_type_node)
10631               chain = RECUR (chain);
10632
10633             /* Determine the number of arguments.  */
10634             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
10635               {
10636                 len = TREE_VEC_LENGTH (purposevec);
10637                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
10638               }
10639             else if (TREE_CODE (valuevec) == TREE_VEC)
10640               len = TREE_VEC_LENGTH (valuevec);
10641             else
10642               {
10643                 /* Since we only performed a partial substitution into
10644                    the argument pack, we only return a single list
10645                    node.  */
10646                 if (purposevec == TREE_PURPOSE (t)
10647                     && valuevec == TREE_VALUE (t)
10648                     && chain == TREE_CHAIN (t))
10649                   return t;
10650
10651                 return tree_cons (purposevec, valuevec, chain);
10652               }
10653             
10654             /* Convert the argument vectors into a TREE_LIST */
10655             i = len;
10656             while (i > 0)
10657               {
10658                 /* Grab the Ith values.  */
10659                 i--;
10660                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
10661                                      : NULL_TREE;
10662                 value 
10663                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
10664                              : NULL_TREE;
10665
10666                 /* Build the list (backwards).  */
10667                 chain = tree_cons (purpose, value, chain);
10668               }
10669
10670             return chain;
10671           }
10672
10673         purpose = TREE_PURPOSE (t);
10674         if (purpose)
10675           purpose = RECUR (purpose);
10676         value = TREE_VALUE (t);
10677         if (value)
10678           value = RECUR (value);
10679         chain = TREE_CHAIN (t);
10680         if (chain && chain != void_type_node)
10681           chain = RECUR (chain);
10682         if (purpose == TREE_PURPOSE (t)
10683             && value == TREE_VALUE (t)
10684             && chain == TREE_CHAIN (t))
10685           return t;
10686         return tree_cons (purpose, value, chain);
10687       }
10688
10689     case COMPONENT_REF:
10690       {
10691         tree object;
10692         tree object_type;
10693         tree member;
10694
10695         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
10696                                                      args, complain, in_decl);
10697         /* Remember that there was a reference to this entity.  */
10698         if (DECL_P (object))
10699           mark_used (object);
10700         object_type = TREE_TYPE (object);
10701
10702         member = TREE_OPERAND (t, 1);
10703         if (BASELINK_P (member))
10704           member = tsubst_baselink (member,
10705                                     non_reference (TREE_TYPE (object)),
10706                                     args, complain, in_decl);
10707         else
10708           member = tsubst_copy (member, args, complain, in_decl);
10709         if (member == error_mark_node)
10710           return error_mark_node;
10711
10712         if (object_type && !CLASS_TYPE_P (object_type))
10713           {
10714             if (TREE_CODE (member) == BIT_NOT_EXPR)
10715               return finish_pseudo_destructor_expr (object,
10716                                                     NULL_TREE,
10717                                                     object_type);
10718             else if (TREE_CODE (member) == SCOPE_REF
10719                      && (TREE_CODE (TREE_OPERAND (member, 1)) == BIT_NOT_EXPR))
10720               return finish_pseudo_destructor_expr (object,
10721                                                     object,
10722                                                     object_type);
10723           }
10724         else if (TREE_CODE (member) == SCOPE_REF
10725                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
10726           {
10727             tree tmpl;
10728             tree args;
10729
10730             /* Lookup the template functions now that we know what the
10731                scope is.  */
10732             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
10733             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
10734             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
10735                                             /*is_type_p=*/false,
10736                                             /*complain=*/false);
10737             if (BASELINK_P (member))
10738               {
10739                 BASELINK_FUNCTIONS (member)
10740                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
10741                               args);
10742                 member = (adjust_result_of_qualified_name_lookup
10743                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
10744                            object_type));
10745               }
10746             else
10747               {
10748                 qualified_name_lookup_error (object_type, tmpl, member);
10749                 return error_mark_node;
10750               }
10751           }
10752         else if (TREE_CODE (member) == SCOPE_REF
10753                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
10754                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
10755           {
10756             if (complain & tf_error)
10757               {
10758                 if (TYPE_P (TREE_OPERAND (member, 0)))
10759                   error ("%qT is not a class or namespace",
10760                          TREE_OPERAND (member, 0));
10761                 else
10762                   error ("%qD is not a class or namespace",
10763                          TREE_OPERAND (member, 0));
10764               }
10765             return error_mark_node;
10766           }
10767         else if (TREE_CODE (member) == FIELD_DECL)
10768           return finish_non_static_data_member (member, object, NULL_TREE);
10769
10770         return finish_class_member_access_expr (object, member,
10771                                                 /*template_p=*/false);
10772       }
10773
10774     case THROW_EXPR:
10775       return build_throw
10776         (RECUR (TREE_OPERAND (t, 0)));
10777
10778     case CONSTRUCTOR:
10779       {
10780         VEC(constructor_elt,gc) *n;
10781         constructor_elt *ce;
10782         unsigned HOST_WIDE_INT idx;
10783         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10784         bool process_index_p;
10785         int newlen;
10786         bool need_copy_p = false;
10787
10788         if (type == error_mark_node)
10789           return error_mark_node;
10790
10791         /* digest_init will do the wrong thing if we let it.  */
10792         if (type && TYPE_PTRMEMFUNC_P (type))
10793           return t;
10794
10795         /* We do not want to process the index of aggregate
10796            initializers as they are identifier nodes which will be
10797            looked up by digest_init.  */
10798         process_index_p = !(type && IS_AGGR_TYPE (type));
10799
10800         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
10801         newlen = VEC_length (constructor_elt, n);
10802         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
10803           {
10804             if (ce->index && process_index_p)
10805               ce->index = RECUR (ce->index);
10806
10807             if (PACK_EXPANSION_P (ce->value))
10808               {
10809                 /* Substitute into the pack expansion.  */
10810                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
10811                                                   in_decl);
10812
10813                 if (TREE_VEC_LENGTH (ce->value) == 1)
10814                   /* Just move the argument into place.  */
10815                   ce->value = TREE_VEC_ELT (ce->value, 0);
10816                 else
10817                   {
10818                     /* Update the length of the final CONSTRUCTOR
10819                        arguments vector, and note that we will need to
10820                        copy.*/
10821                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
10822                     need_copy_p = true;
10823                   }
10824               }
10825             else
10826               ce->value = RECUR (ce->value);
10827           }
10828
10829         if (need_copy_p)
10830           {
10831             VEC(constructor_elt,gc) *old_n = n;
10832
10833             n = VEC_alloc (constructor_elt, gc, newlen);
10834             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
10835                  idx++)
10836               {
10837                 if (TREE_CODE (ce->value) == TREE_VEC)
10838                   {
10839                     int i, len = TREE_VEC_LENGTH (ce->value);
10840                     for (i = 0; i < len; ++i)
10841                       CONSTRUCTOR_APPEND_ELT (n, 0,
10842                                               TREE_VEC_ELT (ce->value, i));
10843                   }
10844                 else
10845                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
10846               }
10847           }
10848
10849         if (TREE_HAS_CONSTRUCTOR (t))
10850           return finish_compound_literal (type, n);
10851
10852         return build_constructor (NULL_TREE, n);
10853       }
10854
10855     case TYPEID_EXPR:
10856       {
10857         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
10858         if (TYPE_P (operand_0))
10859           return get_typeid (operand_0);
10860         return build_typeid (operand_0);
10861       }
10862
10863     case VAR_DECL:
10864       if (!args)
10865         return t;
10866       /* Fall through */
10867
10868     case PARM_DECL:
10869       {
10870         tree r = tsubst_copy (t, args, complain, in_decl);
10871
10872         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
10873           /* If the original type was a reference, we'll be wrapped in
10874              the appropriate INDIRECT_REF.  */
10875           r = convert_from_reference (r);
10876         return r;
10877       }
10878
10879     case VA_ARG_EXPR:
10880       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
10881                              tsubst_copy (TREE_TYPE (t), args, complain,
10882                                           in_decl));
10883
10884     case OFFSETOF_EXPR:
10885       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
10886
10887     case TRAIT_EXPR:
10888       {
10889         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
10890                                   complain, in_decl);
10891
10892         tree type2 = TRAIT_EXPR_TYPE2 (t);
10893         if (type2)
10894           type2 = tsubst_copy (type2, args, complain, in_decl);
10895         
10896         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
10897       }
10898
10899     case STMT_EXPR:
10900       {
10901         tree old_stmt_expr = cur_stmt_expr;
10902         tree stmt_expr = begin_stmt_expr ();
10903
10904         cur_stmt_expr = stmt_expr;
10905         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
10906                      integral_constant_expression_p);
10907         stmt_expr = finish_stmt_expr (stmt_expr, false);
10908         cur_stmt_expr = old_stmt_expr;
10909
10910         return stmt_expr;
10911       }
10912
10913     case CONST_DECL:
10914       t = tsubst_copy (t, args, complain, in_decl);
10915       /* As in finish_id_expression, we resolve enumeration constants
10916          to their underlying values.  */
10917       if (TREE_CODE (t) == CONST_DECL)
10918         {
10919           used_types_insert (TREE_TYPE (t));
10920           return DECL_INITIAL (t);
10921         }
10922       return t;
10923
10924     default:
10925       /* Handle Objective-C++ constructs, if appropriate.  */
10926       {
10927         tree subst
10928           = objcp_tsubst_copy_and_build (t, args, complain,
10929                                          in_decl, /*function_p=*/false);
10930         if (subst)
10931           return subst;
10932       }
10933       return tsubst_copy (t, args, complain, in_decl);
10934     }
10935
10936 #undef RECUR
10937 }
10938
10939 /* Verify that the instantiated ARGS are valid. For type arguments,
10940    make sure that the type's linkage is ok. For non-type arguments,
10941    make sure they are constants if they are integral or enumerations.
10942    Emit an error under control of COMPLAIN, and return TRUE on error.  */
10943
10944 static bool
10945 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
10946 {
10947   int ix, len = DECL_NTPARMS (tmpl);
10948   bool result = false;
10949
10950   for (ix = 0; ix != len; ix++)
10951     {
10952       tree t = TREE_VEC_ELT (args, ix);
10953
10954       if (TYPE_P (t))
10955         {
10956           /* [basic.link]: A name with no linkage (notably, the name
10957              of a class or enumeration declared in a local scope)
10958              shall not be used to declare an entity with linkage.
10959              This implies that names with no linkage cannot be used as
10960              template arguments.  */
10961           tree nt = no_linkage_check (t, /*relaxed_p=*/false);
10962
10963           if (nt)
10964             {
10965               /* DR 488 makes use of a type with no linkage cause
10966                  type deduction to fail.  */
10967               if (complain & tf_error)
10968                 {
10969                   if (TYPE_ANONYMOUS_P (nt))
10970                     error ("%qT is/uses anonymous type", t);
10971                   else
10972                     error ("template argument for %qD uses local type %qT",
10973                            tmpl, t);
10974                 }
10975               result = true;
10976             }
10977           /* In order to avoid all sorts of complications, we do not
10978              allow variably-modified types as template arguments.  */
10979           else if (variably_modified_type_p (t, NULL_TREE))
10980             {
10981               if (complain & tf_error)
10982                 error ("%qT is a variably modified type", t);
10983               result = true;
10984             }
10985         }
10986       /* A non-type argument of integral or enumerated type must be a
10987          constant.  */
10988       else if (TREE_TYPE (t)
10989                && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
10990                && !TREE_CONSTANT (t))
10991         {
10992           if (complain & tf_error)
10993             error ("integral expression %qE is not constant", t);
10994           result = true;
10995         }
10996     }
10997   if (result && (complain & tf_error))
10998     error ("  trying to instantiate %qD", tmpl);
10999   return result;
11000 }
11001
11002 /* Instantiate the indicated variable or function template TMPL with
11003    the template arguments in TARG_PTR.  */
11004
11005 tree
11006 instantiate_template (tree tmpl, tree targ_ptr, tsubst_flags_t complain)
11007 {
11008   tree fndecl;
11009   tree gen_tmpl;
11010   tree spec;
11011   HOST_WIDE_INT saved_processing_template_decl;
11012
11013   if (tmpl == error_mark_node)
11014     return error_mark_node;
11015
11016   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
11017
11018   /* If this function is a clone, handle it specially.  */
11019   if (DECL_CLONED_FUNCTION_P (tmpl))
11020     {
11021       tree spec;
11022       tree clone;
11023
11024       spec = instantiate_template (DECL_CLONED_FUNCTION (tmpl), targ_ptr,
11025                                    complain);
11026       if (spec == error_mark_node)
11027         return error_mark_node;
11028
11029       /* Look for the clone.  */
11030       FOR_EACH_CLONE (clone, spec)
11031         if (DECL_NAME (clone) == DECL_NAME (tmpl))
11032           return clone;
11033       /* We should always have found the clone by now.  */
11034       gcc_unreachable ();
11035       return NULL_TREE;
11036     }
11037
11038   /* Check to see if we already have this specialization.  */
11039   spec = retrieve_specialization (tmpl, targ_ptr,
11040                                   /*class_specializations_p=*/false);
11041   if (spec != NULL_TREE)
11042     return spec;
11043
11044   gen_tmpl = most_general_template (tmpl);
11045   if (tmpl != gen_tmpl)
11046     {
11047       /* The TMPL is a partial instantiation.  To get a full set of
11048          arguments we must add the arguments used to perform the
11049          partial instantiation.  */
11050       targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
11051                                               targ_ptr);
11052
11053       /* Check to see if we already have this specialization.  */
11054       spec = retrieve_specialization (gen_tmpl, targ_ptr,
11055                                       /*class_specializations_p=*/false);
11056       if (spec != NULL_TREE)
11057         return spec;
11058     }
11059
11060   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
11061                                complain))
11062     return error_mark_node;
11063
11064   /* We are building a FUNCTION_DECL, during which the access of its
11065      parameters and return types have to be checked.  However this
11066      FUNCTION_DECL which is the desired context for access checking
11067      is not built yet.  We solve this chicken-and-egg problem by
11068      deferring all checks until we have the FUNCTION_DECL.  */
11069   push_deferring_access_checks (dk_deferred);
11070
11071   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
11072      (because, for example, we have encountered a non-dependent
11073      function call in the body of a template function and must now
11074      determine which of several overloaded functions will be called),
11075      within the instantiation itself we are not processing a
11076      template.  */  
11077   saved_processing_template_decl = processing_template_decl;
11078   processing_template_decl = 0;
11079   /* Substitute template parameters to obtain the specialization.  */
11080   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
11081                    targ_ptr, complain, gen_tmpl);
11082   processing_template_decl = saved_processing_template_decl;
11083   if (fndecl == error_mark_node)
11084     return error_mark_node;
11085
11086   /* Now we know the specialization, compute access previously
11087      deferred.  */
11088   push_access_scope (fndecl);
11089   perform_deferred_access_checks ();
11090   pop_access_scope (fndecl);
11091   pop_deferring_access_checks ();
11092
11093   /* The DECL_TI_TEMPLATE should always be the immediate parent
11094      template, not the most general template.  */
11095   DECL_TI_TEMPLATE (fndecl) = tmpl;
11096
11097   /* If we've just instantiated the main entry point for a function,
11098      instantiate all the alternate entry points as well.  We do this
11099      by cloning the instantiation of the main entry point, not by
11100      instantiating the template clones.  */
11101   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
11102     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
11103
11104   return fndecl;
11105 }
11106
11107 /* The FN is a TEMPLATE_DECL for a function.  The ARGS are the
11108    arguments that are being used when calling it.  TARGS is a vector
11109    into which the deduced template arguments are placed.
11110
11111    Return zero for success, 2 for an incomplete match that doesn't resolve
11112    all the types, and 1 for complete failure.  An error message will be
11113    printed only for an incomplete match.
11114
11115    If FN is a conversion operator, or we are trying to produce a specific
11116    specialization, RETURN_TYPE is the return type desired.
11117
11118    The EXPLICIT_TARGS are explicit template arguments provided via a
11119    template-id.
11120
11121    The parameter STRICT is one of:
11122
11123    DEDUCE_CALL:
11124      We are deducing arguments for a function call, as in
11125      [temp.deduct.call].
11126
11127    DEDUCE_CONV:
11128      We are deducing arguments for a conversion function, as in
11129      [temp.deduct.conv].
11130
11131    DEDUCE_EXACT:
11132      We are deducing arguments when doing an explicit instantiation
11133      as in [temp.explicit], when determining an explicit specialization
11134      as in [temp.expl.spec], or when taking the address of a function
11135      template, as in [temp.deduct.funcaddr].  */
11136
11137 int
11138 fn_type_unification (tree fn,
11139                      tree explicit_targs,
11140                      tree targs,
11141                      tree args,
11142                      tree return_type,
11143                      unification_kind_t strict,
11144                      int flags)
11145 {
11146   tree parms;
11147   tree fntype;
11148   int result;
11149   bool incomplete_argument_packs_p = false;
11150
11151   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
11152
11153   fntype = TREE_TYPE (fn);
11154   if (explicit_targs)
11155     {
11156       /* [temp.deduct]
11157
11158          The specified template arguments must match the template
11159          parameters in kind (i.e., type, nontype, template), and there
11160          must not be more arguments than there are parameters;
11161          otherwise type deduction fails.
11162
11163          Nontype arguments must match the types of the corresponding
11164          nontype template parameters, or must be convertible to the
11165          types of the corresponding nontype parameters as specified in
11166          _temp.arg.nontype_, otherwise type deduction fails.
11167
11168          All references in the function type of the function template
11169          to the corresponding template parameters are replaced by the
11170          specified template argument values.  If a substitution in a
11171          template parameter or in the function type of the function
11172          template results in an invalid type, type deduction fails.  */
11173       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
11174       int i, len = TREE_VEC_LENGTH (tparms);
11175       tree converted_args;
11176       bool incomplete = false;
11177
11178       if (explicit_targs == error_mark_node)
11179         return 1;
11180
11181       converted_args
11182         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
11183                                   /*require_all_args=*/false,
11184                                   /*use_default_args=*/false));
11185       if (converted_args == error_mark_node)
11186         return 1;
11187
11188       /* Substitute the explicit args into the function type.  This is
11189          necessary so that, for instance, explicitly declared function
11190          arguments can match null pointed constants.  If we were given
11191          an incomplete set of explicit args, we must not do semantic
11192          processing during substitution as we could create partial
11193          instantiations.  */
11194       for (i = 0; i < len; i++)
11195         {
11196           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
11197           bool parameter_pack = false;
11198
11199           /* Dig out the actual parm.  */
11200           if (TREE_CODE (parm) == TYPE_DECL
11201               || TREE_CODE (parm) == TEMPLATE_DECL)
11202             {
11203               parm = TREE_TYPE (parm);
11204               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
11205             }
11206           else if (TREE_CODE (parm) == PARM_DECL)
11207             {
11208               parm = DECL_INITIAL (parm);
11209               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
11210             }
11211
11212           if (parameter_pack)
11213             {
11214               int level, idx;
11215               tree targ;
11216               template_parm_level_and_index (parm, &level, &idx);
11217
11218               /* Mark the argument pack as "incomplete". We could
11219                  still deduce more arguments during unification.  */
11220               targ = TMPL_ARG (converted_args, level, idx);
11221               if (targ)
11222                 {
11223                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
11224                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
11225                     = ARGUMENT_PACK_ARGS (targ);
11226                 }
11227
11228               /* We have some incomplete argument packs.  */
11229               incomplete_argument_packs_p = true;
11230             }
11231         }
11232
11233       if (incomplete_argument_packs_p)
11234         /* Any substitution is guaranteed to be incomplete if there
11235            are incomplete argument packs, because we can still deduce
11236            more arguments.  */
11237         incomplete = 1;
11238       else
11239         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
11240
11241       processing_template_decl += incomplete;
11242       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
11243       processing_template_decl -= incomplete;
11244
11245       if (fntype == error_mark_node)
11246         return 1;
11247
11248       /* Place the explicitly specified arguments in TARGS.  */
11249       for (i = NUM_TMPL_ARGS (converted_args); i--;)
11250         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
11251     }
11252
11253   /* Never do unification on the 'this' parameter.  */
11254   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
11255
11256   if (return_type)
11257     {
11258       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
11259       args = tree_cons (NULL_TREE, return_type, args);
11260     }
11261
11262   /* We allow incomplete unification without an error message here
11263      because the standard doesn't seem to explicitly prohibit it.  Our
11264      callers must be ready to deal with unification failures in any
11265      event.  */
11266   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
11267                                   targs, parms, args, /*subr=*/0,
11268                                   strict, flags);
11269
11270   if (result == 0 && incomplete_argument_packs_p)
11271     {
11272       int i, len = NUM_TMPL_ARGS (targs);
11273
11274       /* Clear the "incomplete" flags on all argument packs.  */
11275       for (i = 0; i < len; i++)
11276         {
11277           tree arg = TREE_VEC_ELT (targs, i);
11278           if (ARGUMENT_PACK_P (arg))
11279             {
11280               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
11281               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
11282             }
11283         }
11284     }
11285
11286   if (result == 0)
11287     /* All is well so far.  Now, check:
11288
11289        [temp.deduct]
11290
11291        When all template arguments have been deduced, all uses of
11292        template parameters in nondeduced contexts are replaced with
11293        the corresponding deduced argument values.  If the
11294        substitution results in an invalid type, as described above,
11295        type deduction fails.  */
11296     if (tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE)
11297         == error_mark_node)
11298       return 1;
11299
11300   return result;
11301 }
11302
11303 /* Adjust types before performing type deduction, as described in
11304    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
11305    sections are symmetric.  PARM is the type of a function parameter
11306    or the return type of the conversion function.  ARG is the type of
11307    the argument passed to the call, or the type of the value
11308    initialized with the result of the conversion function.
11309    ARG_EXPR is the original argument expression, which may be null.  */
11310
11311 static int
11312 maybe_adjust_types_for_deduction (unification_kind_t strict,
11313                                   tree* parm,
11314                                   tree* arg,
11315                                   tree arg_expr)
11316 {
11317   int result = 0;
11318
11319   switch (strict)
11320     {
11321     case DEDUCE_CALL:
11322       break;
11323
11324     case DEDUCE_CONV:
11325       {
11326         /* Swap PARM and ARG throughout the remainder of this
11327            function; the handling is precisely symmetric since PARM
11328            will initialize ARG rather than vice versa.  */
11329         tree* temp = parm;
11330         parm = arg;
11331         arg = temp;
11332         break;
11333       }
11334
11335     case DEDUCE_EXACT:
11336       /* There is nothing to do in this case.  */
11337       return 0;
11338
11339     default:
11340       gcc_unreachable ();
11341     }
11342
11343   if (TREE_CODE (*parm) != REFERENCE_TYPE)
11344     {
11345       /* [temp.deduct.call]
11346
11347          If P is not a reference type:
11348
11349          --If A is an array type, the pointer type produced by the
11350          array-to-pointer standard conversion (_conv.array_) is
11351          used in place of A for type deduction; otherwise,
11352
11353          --If A is a function type, the pointer type produced by
11354          the function-to-pointer standard conversion
11355          (_conv.func_) is used in place of A for type deduction;
11356          otherwise,
11357
11358          --If A is a cv-qualified type, the top level
11359          cv-qualifiers of A's type are ignored for type
11360          deduction.  */
11361       if (TREE_CODE (*arg) == ARRAY_TYPE)
11362         *arg = build_pointer_type (TREE_TYPE (*arg));
11363       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
11364         *arg = build_pointer_type (*arg);
11365       else
11366         *arg = TYPE_MAIN_VARIANT (*arg);
11367     }
11368
11369   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
11370      of the form T&&, where T is a template parameter, and the argument
11371      is an lvalue, T is deduced as A& */
11372   if (TREE_CODE (*parm) == REFERENCE_TYPE
11373       && TYPE_REF_IS_RVALUE (*parm)
11374       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
11375       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
11376       && arg_expr && real_lvalue_p (arg_expr))
11377     *arg = build_reference_type (*arg);
11378
11379   /* [temp.deduct.call]
11380
11381      If P is a cv-qualified type, the top level cv-qualifiers
11382      of P's type are ignored for type deduction.  If P is a
11383      reference type, the type referred to by P is used for
11384      type deduction.  */
11385   *parm = TYPE_MAIN_VARIANT (*parm);
11386   if (TREE_CODE (*parm) == REFERENCE_TYPE)
11387     {
11388       *parm = TREE_TYPE (*parm);
11389       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
11390     }
11391
11392   /* DR 322. For conversion deduction, remove a reference type on parm
11393      too (which has been swapped into ARG).  */
11394   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
11395     *arg = TREE_TYPE (*arg);
11396
11397   return result;
11398 }
11399
11400 /* Most parms like fn_type_unification.
11401
11402    If SUBR is 1, we're being called recursively (to unify the
11403    arguments of a function or method parameter of a function
11404    template). */
11405
11406 static int
11407 type_unification_real (tree tparms,
11408                        tree targs,
11409                        tree xparms,
11410                        tree xargs,
11411                        int subr,
11412                        unification_kind_t strict,
11413                        int flags)
11414 {
11415   tree parm, arg, arg_expr;
11416   int i;
11417   int ntparms = TREE_VEC_LENGTH (tparms);
11418   int sub_strict;
11419   int saw_undeduced = 0;
11420   tree parms, args;
11421
11422   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
11423   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
11424   gcc_assert (!xargs || TREE_CODE (xargs) == TREE_LIST);
11425   gcc_assert (ntparms > 0);
11426
11427   switch (strict)
11428     {
11429     case DEDUCE_CALL:
11430       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
11431                     | UNIFY_ALLOW_DERIVED);
11432       break;
11433
11434     case DEDUCE_CONV:
11435       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
11436       break;
11437
11438     case DEDUCE_EXACT:
11439       sub_strict = UNIFY_ALLOW_NONE;
11440       break;
11441
11442     default:
11443       gcc_unreachable ();
11444     }
11445
11446  again:
11447   parms = xparms;
11448   args = xargs;
11449
11450   while (parms && parms != void_list_node
11451          && args && args != void_list_node)
11452     {
11453       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
11454         break;
11455
11456       parm = TREE_VALUE (parms);
11457       parms = TREE_CHAIN (parms);
11458       arg = TREE_VALUE (args);
11459       args = TREE_CHAIN (args);
11460       arg_expr = NULL;
11461
11462       if (arg == error_mark_node)
11463         return 1;
11464       if (arg == unknown_type_node)
11465         /* We can't deduce anything from this, but we might get all the
11466            template args from other function args.  */
11467         continue;
11468
11469       /* Conversions will be performed on a function argument that
11470          corresponds with a function parameter that contains only
11471          non-deducible template parameters and explicitly specified
11472          template parameters.  */
11473       if (!uses_template_parms (parm))
11474         {
11475           tree type;
11476
11477           if (!TYPE_P (arg))
11478             type = TREE_TYPE (arg);
11479           else
11480             type = arg;
11481
11482           if (same_type_p (parm, type))
11483             continue;
11484           if (strict != DEDUCE_EXACT
11485               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
11486                                   flags))
11487             continue;
11488
11489           return 1;
11490         }
11491
11492       if (!TYPE_P (arg))
11493         {
11494           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
11495           if (type_unknown_p (arg))
11496             {
11497               /* [temp.deduct.type] 
11498
11499                  A template-argument can be deduced from a pointer to
11500                  function or pointer to member function argument if
11501                  the set of overloaded functions does not contain
11502                  function templates and at most one of a set of
11503                  overloaded functions provides a unique match.  */
11504               if (resolve_overloaded_unification
11505                   (tparms, targs, parm, arg, strict, sub_strict))
11506                 continue;
11507
11508               return 1;
11509             }
11510           arg_expr = arg;
11511           arg = unlowered_expr_type (arg);
11512           if (arg == error_mark_node)
11513             return 1;
11514         }
11515
11516       {
11517         int arg_strict = sub_strict;
11518
11519         if (!subr)
11520           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
11521                                                           arg_expr);
11522
11523         if (unify (tparms, targs, parm, arg, arg_strict))
11524           return 1;
11525       }
11526     }
11527
11528
11529   if (parms 
11530       && parms != void_list_node
11531       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
11532     {
11533       /* Unify the remaining arguments with the pack expansion type.  */
11534       tree argvec;
11535       tree parmvec = make_tree_vec (1);
11536       int len = 0;
11537       tree t;
11538
11539       /* Count the number of arguments that remain.  */
11540       for (t = args; t && t != void_list_node; t = TREE_CHAIN (t))
11541         len++;
11542         
11543       /* Allocate a TREE_VEC and copy in all of the arguments */ 
11544       argvec = make_tree_vec (len);
11545       for (i = 0; args && args != void_list_node; args = TREE_CHAIN (args))
11546         {
11547           TREE_VEC_ELT (argvec, i) = TREE_VALUE (args);
11548           ++i;
11549         }
11550
11551       /* Copy the parameter into parmvec.  */
11552       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
11553       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
11554                                 /*call_args_p=*/true, /*subr=*/subr))
11555         return 1;
11556
11557       /* Advance to the end of the list of parameters.  */
11558       parms = TREE_CHAIN (parms);
11559     }
11560
11561   /* Fail if we've reached the end of the parm list, and more args
11562      are present, and the parm list isn't variadic.  */
11563   if (args && args != void_list_node && parms == void_list_node)
11564     return 1;
11565   /* Fail if parms are left and they don't have default values.  */
11566   if (parms && parms != void_list_node
11567       && TREE_PURPOSE (parms) == NULL_TREE)
11568     return 1;
11569
11570   if (!subr)
11571     for (i = 0; i < ntparms; i++)
11572       if (!TREE_VEC_ELT (targs, i))
11573         {
11574           tree tparm;
11575
11576           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
11577             continue;
11578
11579           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
11580
11581           /* If this is an undeduced nontype parameter that depends on
11582              a type parameter, try another pass; its type may have been
11583              deduced from a later argument than the one from which
11584              this parameter can be deduced.  */
11585           if (TREE_CODE (tparm) == PARM_DECL
11586               && uses_template_parms (TREE_TYPE (tparm))
11587               && !saw_undeduced++)
11588             goto again;
11589
11590           /* Core issue #226 (C++0x) [temp.deduct]:
11591
11592                If a template argument has not been deduced, its
11593                default template argument, if any, is used. 
11594
11595              When we are in C++98 mode, TREE_PURPOSE will either
11596              be NULL_TREE or ERROR_MARK_NODE, so we do not need
11597              to explicitly check cxx_dialect here.  */
11598           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
11599             {
11600               tree arg = tsubst (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)), 
11601                                  targs, tf_none, NULL_TREE);
11602               if (arg == error_mark_node)
11603                 return 1;
11604               else
11605                 {
11606                   TREE_VEC_ELT (targs, i) = arg;
11607                   continue;
11608                 }
11609             }
11610
11611           /* If the type parameter is a parameter pack, then it will
11612              be deduced to an empty parameter pack.  */
11613           if (template_parameter_pack_p (tparm))
11614             {
11615               tree arg;
11616
11617               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
11618                 {
11619                   arg = make_node (NONTYPE_ARGUMENT_PACK);
11620                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
11621                   TREE_CONSTANT (arg) = 1;
11622                 }
11623               else
11624                 arg = make_node (TYPE_ARGUMENT_PACK);
11625
11626               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
11627
11628               TREE_VEC_ELT (targs, i) = arg;
11629               continue;
11630             }
11631
11632           return 2;
11633         }
11634
11635   return 0;
11636 }
11637
11638 /* Subroutine of type_unification_real.  Args are like the variables
11639    at the call site.  ARG is an overloaded function (or template-id);
11640    we try deducing template args from each of the overloads, and if
11641    only one succeeds, we go with that.  Modifies TARGS and returns
11642    true on success.  */
11643
11644 static bool
11645 resolve_overloaded_unification (tree tparms,
11646                                 tree targs,
11647                                 tree parm,
11648                                 tree arg,
11649                                 unification_kind_t strict,
11650                                 int sub_strict)
11651 {
11652   tree tempargs = copy_node (targs);
11653   int good = 0;
11654   bool addr_p;
11655
11656   if (TREE_CODE (arg) == ADDR_EXPR)
11657     {
11658       arg = TREE_OPERAND (arg, 0);
11659       addr_p = true;
11660     }
11661   else
11662     addr_p = false;
11663
11664   if (TREE_CODE (arg) == COMPONENT_REF)
11665     /* Handle `&x' where `x' is some static or non-static member
11666        function name.  */
11667     arg = TREE_OPERAND (arg, 1);
11668
11669   if (TREE_CODE (arg) == OFFSET_REF)
11670     arg = TREE_OPERAND (arg, 1);
11671
11672   /* Strip baselink information.  */
11673   if (BASELINK_P (arg))
11674     arg = BASELINK_FUNCTIONS (arg);
11675
11676   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
11677     {
11678       /* If we got some explicit template args, we need to plug them into
11679          the affected templates before we try to unify, in case the
11680          explicit args will completely resolve the templates in question.  */
11681
11682       tree expl_subargs = TREE_OPERAND (arg, 1);
11683       arg = TREE_OPERAND (arg, 0);
11684
11685       for (; arg; arg = OVL_NEXT (arg))
11686         {
11687           tree fn = OVL_CURRENT (arg);
11688           tree subargs, elem;
11689
11690           if (TREE_CODE (fn) != TEMPLATE_DECL)
11691             continue;
11692
11693           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
11694                                   expl_subargs, /*check_ret=*/false);
11695           if (subargs)
11696             {
11697               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
11698               good += try_one_overload (tparms, targs, tempargs, parm,
11699                                         elem, strict, sub_strict, addr_p);
11700             }
11701         }
11702     }
11703   else if (TREE_CODE (arg) != OVERLOAD
11704            && TREE_CODE (arg) != FUNCTION_DECL)
11705     /* If ARG is, for example, "(0, &f)" then its type will be unknown
11706        -- but the deduction does not succeed because the expression is
11707        not just the function on its own.  */
11708     return false;
11709   else
11710     for (; arg; arg = OVL_NEXT (arg))
11711       good += try_one_overload (tparms, targs, tempargs, parm,
11712                                 TREE_TYPE (OVL_CURRENT (arg)),
11713                                 strict, sub_strict, addr_p);
11714
11715   /* [temp.deduct.type] A template-argument can be deduced from a pointer
11716      to function or pointer to member function argument if the set of
11717      overloaded functions does not contain function templates and at most
11718      one of a set of overloaded functions provides a unique match.
11719
11720      So if we found multiple possibilities, we return success but don't
11721      deduce anything.  */
11722
11723   if (good == 1)
11724     {
11725       int i = TREE_VEC_LENGTH (targs);
11726       for (; i--; )
11727         if (TREE_VEC_ELT (tempargs, i))
11728           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
11729     }
11730   if (good)
11731     return true;
11732
11733   return false;
11734 }
11735
11736 /* Subroutine of resolve_overloaded_unification; does deduction for a single
11737    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
11738    different overloads deduce different arguments for a given parm.
11739    ADDR_P is true if the expression for which deduction is being
11740    performed was of the form "& fn" rather than simply "fn".
11741
11742    Returns 1 on success.  */
11743
11744 static int
11745 try_one_overload (tree tparms,
11746                   tree orig_targs,
11747                   tree targs,
11748                   tree parm,
11749                   tree arg,
11750                   unification_kind_t strict,
11751                   int sub_strict,
11752                   bool addr_p)
11753 {
11754   int nargs;
11755   tree tempargs;
11756   int i;
11757
11758   /* [temp.deduct.type] A template-argument can be deduced from a pointer
11759      to function or pointer to member function argument if the set of
11760      overloaded functions does not contain function templates and at most
11761      one of a set of overloaded functions provides a unique match.
11762
11763      So if this is a template, just return success.  */
11764
11765   if (uses_template_parms (arg))
11766     return 1;
11767
11768   if (TREE_CODE (arg) == METHOD_TYPE)
11769     arg = build_ptrmemfunc_type (build_pointer_type (arg));
11770   else if (addr_p)
11771     arg = build_pointer_type (arg);
11772
11773   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
11774
11775   /* We don't copy orig_targs for this because if we have already deduced
11776      some template args from previous args, unify would complain when we
11777      try to deduce a template parameter for the same argument, even though
11778      there isn't really a conflict.  */
11779   nargs = TREE_VEC_LENGTH (targs);
11780   tempargs = make_tree_vec (nargs);
11781
11782   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
11783     return 0;
11784
11785   /* First make sure we didn't deduce anything that conflicts with
11786      explicitly specified args.  */
11787   for (i = nargs; i--; )
11788     {
11789       tree elt = TREE_VEC_ELT (tempargs, i);
11790       tree oldelt = TREE_VEC_ELT (orig_targs, i);
11791
11792       if (!elt)
11793         /*NOP*/;
11794       else if (uses_template_parms (elt))
11795         /* Since we're unifying against ourselves, we will fill in
11796            template args used in the function parm list with our own
11797            template parms.  Discard them.  */
11798         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
11799       else if (oldelt && !template_args_equal (oldelt, elt))
11800         return 0;
11801     }
11802
11803   for (i = nargs; i--; )
11804     {
11805       tree elt = TREE_VEC_ELT (tempargs, i);
11806
11807       if (elt)
11808         TREE_VEC_ELT (targs, i) = elt;
11809     }
11810
11811   return 1;
11812 }
11813
11814 /* PARM is a template class (perhaps with unbound template
11815    parameters).  ARG is a fully instantiated type.  If ARG can be
11816    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
11817    TARGS are as for unify.  */
11818
11819 static tree
11820 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
11821 {
11822   tree copy_of_targs;
11823
11824   if (!CLASSTYPE_TEMPLATE_INFO (arg)
11825       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
11826           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
11827     return NULL_TREE;
11828
11829   /* We need to make a new template argument vector for the call to
11830      unify.  If we used TARGS, we'd clutter it up with the result of
11831      the attempted unification, even if this class didn't work out.
11832      We also don't want to commit ourselves to all the unifications
11833      we've already done, since unification is supposed to be done on
11834      an argument-by-argument basis.  In other words, consider the
11835      following pathological case:
11836
11837        template <int I, int J, int K>
11838        struct S {};
11839
11840        template <int I, int J>
11841        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
11842
11843        template <int I, int J, int K>
11844        void f(S<I, J, K>, S<I, I, I>);
11845
11846        void g() {
11847          S<0, 0, 0> s0;
11848          S<0, 1, 2> s2;
11849
11850          f(s0, s2);
11851        }
11852
11853      Now, by the time we consider the unification involving `s2', we
11854      already know that we must have `f<0, 0, 0>'.  But, even though
11855      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
11856      because there are two ways to unify base classes of S<0, 1, 2>
11857      with S<I, I, I>.  If we kept the already deduced knowledge, we
11858      would reject the possibility I=1.  */
11859   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
11860
11861   /* If unification failed, we're done.  */
11862   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
11863              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
11864     return NULL_TREE;
11865
11866   return arg;
11867 }
11868
11869 /* Given a template type PARM and a class type ARG, find the unique
11870    base type in ARG that is an instance of PARM.  We do not examine
11871    ARG itself; only its base-classes.  If there is not exactly one
11872    appropriate base class, return NULL_TREE.  PARM may be the type of
11873    a partial specialization, as well as a plain template type.  Used
11874    by unify.  */
11875
11876 static tree
11877 get_template_base (tree tparms, tree targs, tree parm, tree arg)
11878 {
11879   tree rval = NULL_TREE;
11880   tree binfo;
11881
11882   gcc_assert (IS_AGGR_TYPE_CODE (TREE_CODE (arg)));
11883
11884   binfo = TYPE_BINFO (complete_type (arg));
11885   if (!binfo)
11886     /* The type could not be completed.  */
11887     return NULL_TREE;
11888
11889   /* Walk in inheritance graph order.  The search order is not
11890      important, and this avoids multiple walks of virtual bases.  */
11891   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
11892     {
11893       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
11894
11895       if (r)
11896         {
11897           /* If there is more than one satisfactory baseclass, then:
11898
11899                [temp.deduct.call]
11900
11901               If they yield more than one possible deduced A, the type
11902               deduction fails.
11903
11904              applies.  */
11905           if (rval && !same_type_p (r, rval))
11906             return NULL_TREE;
11907
11908           rval = r;
11909         }
11910     }
11911
11912   return rval;
11913 }
11914
11915 /* Returns the level of DECL, which declares a template parameter.  */
11916
11917 static int
11918 template_decl_level (tree decl)
11919 {
11920   switch (TREE_CODE (decl))
11921     {
11922     case TYPE_DECL:
11923     case TEMPLATE_DECL:
11924       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
11925
11926     case PARM_DECL:
11927       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
11928
11929     default:
11930       gcc_unreachable ();
11931     }
11932   return 0;
11933 }
11934
11935 /* Decide whether ARG can be unified with PARM, considering only the
11936    cv-qualifiers of each type, given STRICT as documented for unify.
11937    Returns nonzero iff the unification is OK on that basis.  */
11938
11939 static int
11940 check_cv_quals_for_unify (int strict, tree arg, tree parm)
11941 {
11942   int arg_quals = cp_type_quals (arg);
11943   int parm_quals = cp_type_quals (parm);
11944
11945   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
11946       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
11947     {
11948       /*  Although a CVR qualifier is ignored when being applied to a
11949           substituted template parameter ([8.3.2]/1 for example), that
11950           does not apply during deduction [14.8.2.4]/1, (even though
11951           that is not explicitly mentioned, [14.8.2.4]/9 indicates
11952           this).  Except when we're allowing additional CV qualifiers
11953           at the outer level [14.8.2.1]/3,1st bullet.  */
11954       if ((TREE_CODE (arg) == REFERENCE_TYPE
11955            || TREE_CODE (arg) == FUNCTION_TYPE
11956            || TREE_CODE (arg) == METHOD_TYPE)
11957           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
11958         return 0;
11959
11960       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
11961           && (parm_quals & TYPE_QUAL_RESTRICT))
11962         return 0;
11963     }
11964
11965   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
11966       && (arg_quals & parm_quals) != parm_quals)
11967     return 0;
11968
11969   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
11970       && (parm_quals & arg_quals) != arg_quals)
11971     return 0;
11972
11973   return 1;
11974 }
11975
11976 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
11977 void 
11978 template_parm_level_and_index (tree parm, int* level, int* index)
11979 {
11980   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
11981       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
11982       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
11983     {
11984       *index = TEMPLATE_TYPE_IDX (parm);
11985       *level = TEMPLATE_TYPE_LEVEL (parm);
11986     }
11987   else
11988     {
11989       *index = TEMPLATE_PARM_IDX (parm);
11990       *level = TEMPLATE_PARM_LEVEL (parm);
11991     }
11992 }
11993
11994 /* Unifies the remaining arguments in PACKED_ARGS with the pack
11995    expansion at the end of PACKED_PARMS. Returns 0 if the type
11996    deduction succeeds, 1 otherwise. STRICT is the same as in
11997    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
11998    call argument list. We'll need to adjust the arguments to make them
11999    types. SUBR tells us if this is from a recursive call to
12000    type_unification_real.  */
12001 int
12002 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
12003                       tree packed_args, int strict, bool call_args_p,
12004                       bool subr)
12005 {
12006   tree parm 
12007     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
12008   tree pattern = PACK_EXPANSION_PATTERN (parm);
12009   tree pack, packs = NULL_TREE;
12010   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
12011   int len = TREE_VEC_LENGTH (packed_args);
12012
12013   /* Determine the parameter packs we will be deducing from the
12014      pattern, and record their current deductions.  */
12015   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
12016        pack; pack = TREE_CHAIN (pack))
12017     {
12018       tree parm_pack = TREE_VALUE (pack);
12019       int idx, level;
12020
12021       /* Determine the index and level of this parameter pack.  */
12022       template_parm_level_and_index (parm_pack, &level, &idx);
12023
12024       /* Keep track of the parameter packs and their corresponding
12025          argument packs.  */
12026       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
12027       TREE_TYPE (packs) = make_tree_vec (len - start);
12028     }
12029   
12030   /* Loop through all of the arguments that have not yet been
12031      unified and unify each with the pattern.  */
12032   for (i = start; i < len; i++)
12033     {
12034       tree parm = pattern;
12035
12036       /* For each parameter pack, clear out the deduced value so that
12037          we can deduce it again.  */
12038       for (pack = packs; pack; pack = TREE_CHAIN (pack))
12039         {
12040           int idx, level;
12041           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12042
12043           TMPL_ARG (targs, level, idx) = NULL_TREE;
12044         }
12045
12046       /* Unify the pattern with the current argument.  */
12047       {
12048         tree arg = TREE_VEC_ELT (packed_args, i);
12049         int arg_strict = strict;
12050         bool skip_arg_p = false;
12051
12052         if (call_args_p)
12053           {
12054             int sub_strict;
12055
12056             /* This mirrors what we do in type_unification_real.  */
12057             switch (strict)
12058               {
12059               case DEDUCE_CALL:
12060                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
12061                               | UNIFY_ALLOW_MORE_CV_QUAL
12062                               | UNIFY_ALLOW_DERIVED);
12063                 break;
12064                 
12065               case DEDUCE_CONV:
12066                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
12067                 break;
12068                 
12069               case DEDUCE_EXACT:
12070                 sub_strict = UNIFY_ALLOW_NONE;
12071                 break;
12072                 
12073               default:
12074                 gcc_unreachable ();
12075               }
12076
12077             if (!TYPE_P (arg))
12078               {
12079                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
12080                 if (type_unknown_p (arg))
12081                   {
12082                     /* [temp.deduct.type] A template-argument can be
12083                        deduced from a pointer to function or pointer
12084                        to member function argument if the set of
12085                        overloaded functions does not contain function
12086                        templates and at most one of a set of
12087                        overloaded functions provides a unique
12088                        match.  */
12089
12090                     if (resolve_overloaded_unification
12091                         (tparms, targs, parm, arg, strict, sub_strict)
12092                         != 0)
12093                       return 1;
12094                     skip_arg_p = true;
12095                   }
12096
12097                 if (!skip_arg_p)
12098                   {
12099                     arg = TREE_TYPE (arg);
12100                     if (arg == error_mark_node)
12101                       return 1;
12102                   }
12103               }
12104       
12105             arg_strict = sub_strict;
12106
12107             if (!subr)
12108               arg_strict |= 
12109                 maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
12110           }
12111
12112         if (!skip_arg_p)
12113           {
12114             if (unify (tparms, targs, parm, arg, arg_strict))
12115               return 1;
12116           }
12117       }
12118
12119       /* For each parameter pack, collect the deduced value.  */
12120       for (pack = packs; pack; pack = TREE_CHAIN (pack))
12121         {
12122           int idx, level;
12123           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12124
12125           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
12126             TMPL_ARG (targs, level, idx);
12127         }
12128     }
12129
12130   /* Verify that the results of unification with the parameter packs
12131      produce results consistent with what we've seen before, and make
12132      the deduced argument packs available.  */
12133   for (pack = packs; pack; pack = TREE_CHAIN (pack))
12134     {
12135       tree old_pack = TREE_VALUE (pack);
12136       tree new_args = TREE_TYPE (pack);
12137
12138       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
12139         {
12140           /* Prepend the explicit arguments onto NEW_ARGS.  */
12141           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
12142           tree old_args = new_args;
12143           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
12144           int len = explicit_len + TREE_VEC_LENGTH (old_args);
12145
12146           /* Copy the explicit arguments.  */
12147           new_args = make_tree_vec (len);
12148           for (i = 0; i < explicit_len; i++)
12149             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
12150
12151           /* Copy the deduced arguments.  */
12152           for (; i < len; i++)
12153             TREE_VEC_ELT (new_args, i) =
12154               TREE_VEC_ELT (old_args, i - explicit_len);
12155         }
12156
12157       if (!old_pack)
12158         {
12159           tree result;
12160           int idx, level;
12161           
12162           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12163
12164           /* Build the deduced *_ARGUMENT_PACK.  */
12165           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
12166             {
12167               result = make_node (NONTYPE_ARGUMENT_PACK);
12168               TREE_TYPE (result) = 
12169                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
12170               TREE_CONSTANT (result) = 1;
12171             }
12172           else
12173             result = make_node (TYPE_ARGUMENT_PACK);
12174
12175           SET_ARGUMENT_PACK_ARGS (result, new_args);
12176
12177           /* Note the deduced argument packs for this parameter
12178              pack.  */
12179           TMPL_ARG (targs, level, idx) = result;
12180         }
12181       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
12182                && (ARGUMENT_PACK_ARGS (old_pack) 
12183                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
12184         {
12185           /* We only had the explicitly-provided arguments before, but
12186              now we have a complete set of arguments.  */
12187           int idx, level;
12188           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
12189           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12190
12191           /* Keep the original deduced argument pack.  */
12192           TMPL_ARG (targs, level, idx) = old_pack;
12193
12194           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
12195           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
12196           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
12197         }
12198       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
12199                                     new_args))
12200         /* Inconsistent unification of this parameter pack.  */
12201         return 1;
12202       else
12203         {
12204           int idx, level;
12205           
12206           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12207
12208           /* Keep the original deduced argument pack.  */
12209           TMPL_ARG (targs, level, idx) = old_pack;
12210         }
12211     }
12212
12213   return 0;
12214 }
12215
12216 /* Deduce the value of template parameters.  TPARMS is the (innermost)
12217    set of template parameters to a template.  TARGS is the bindings
12218    for those template parameters, as determined thus far; TARGS may
12219    include template arguments for outer levels of template parameters
12220    as well.  PARM is a parameter to a template function, or a
12221    subcomponent of that parameter; ARG is the corresponding argument.
12222    This function attempts to match PARM with ARG in a manner
12223    consistent with the existing assignments in TARGS.  If more values
12224    are deduced, then TARGS is updated.
12225
12226    Returns 0 if the type deduction succeeds, 1 otherwise.  The
12227    parameter STRICT is a bitwise or of the following flags:
12228
12229      UNIFY_ALLOW_NONE:
12230        Require an exact match between PARM and ARG.
12231      UNIFY_ALLOW_MORE_CV_QUAL:
12232        Allow the deduced ARG to be more cv-qualified (by qualification
12233        conversion) than ARG.
12234      UNIFY_ALLOW_LESS_CV_QUAL:
12235        Allow the deduced ARG to be less cv-qualified than ARG.
12236      UNIFY_ALLOW_DERIVED:
12237        Allow the deduced ARG to be a template base class of ARG,
12238        or a pointer to a template base class of the type pointed to by
12239        ARG.
12240      UNIFY_ALLOW_INTEGER:
12241        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
12242        case for more information.
12243      UNIFY_ALLOW_OUTER_LEVEL:
12244        This is the outermost level of a deduction. Used to determine validity
12245        of qualification conversions. A valid qualification conversion must
12246        have const qualified pointers leading up to the inner type which
12247        requires additional CV quals, except at the outer level, where const
12248        is not required [conv.qual]. It would be normal to set this flag in
12249        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
12250      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
12251        This is the outermost level of a deduction, and PARM can be more CV
12252        qualified at this point.
12253      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
12254        This is the outermost level of a deduction, and PARM can be less CV
12255        qualified at this point.  */
12256
12257 static int
12258 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
12259 {
12260   int idx;
12261   tree targ;
12262   tree tparm;
12263   int strict_in = strict;
12264
12265   /* I don't think this will do the right thing with respect to types.
12266      But the only case I've seen it in so far has been array bounds, where
12267      signedness is the only information lost, and I think that will be
12268      okay.  */
12269   while (TREE_CODE (parm) == NOP_EXPR)
12270     parm = TREE_OPERAND (parm, 0);
12271
12272   if (arg == error_mark_node)
12273     return 1;
12274   if (arg == unknown_type_node)
12275     /* We can't deduce anything from this, but we might get all the
12276        template args from other function args.  */
12277     return 0;
12278
12279   /* If PARM uses template parameters, then we can't bail out here,
12280      even if ARG == PARM, since we won't record unifications for the
12281      template parameters.  We might need them if we're trying to
12282      figure out which of two things is more specialized.  */
12283   if (arg == parm && !uses_template_parms (parm))
12284     return 0;
12285
12286   /* Immediately reject some pairs that won't unify because of
12287      cv-qualification mismatches.  */
12288   if (TREE_CODE (arg) == TREE_CODE (parm)
12289       && TYPE_P (arg)
12290       /* It is the elements of the array which hold the cv quals of an array
12291          type, and the elements might be template type parms. We'll check
12292          when we recurse.  */
12293       && TREE_CODE (arg) != ARRAY_TYPE
12294       /* We check the cv-qualifiers when unifying with template type
12295          parameters below.  We want to allow ARG `const T' to unify with
12296          PARM `T' for example, when computing which of two templates
12297          is more specialized, for example.  */
12298       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
12299       && !check_cv_quals_for_unify (strict_in, arg, parm))
12300     return 1;
12301
12302   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
12303       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
12304     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
12305   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
12306   strict &= ~UNIFY_ALLOW_DERIVED;
12307   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
12308   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
12309
12310   switch (TREE_CODE (parm))
12311     {
12312     case TYPENAME_TYPE:
12313     case SCOPE_REF:
12314     case UNBOUND_CLASS_TEMPLATE:
12315       /* In a type which contains a nested-name-specifier, template
12316          argument values cannot be deduced for template parameters used
12317          within the nested-name-specifier.  */
12318       return 0;
12319
12320     case TEMPLATE_TYPE_PARM:
12321     case TEMPLATE_TEMPLATE_PARM:
12322     case BOUND_TEMPLATE_TEMPLATE_PARM:
12323       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
12324       if (tparm == error_mark_node)
12325         return 1;
12326
12327       if (TEMPLATE_TYPE_LEVEL (parm)
12328           != template_decl_level (tparm))
12329         /* The PARM is not one we're trying to unify.  Just check
12330            to see if it matches ARG.  */
12331         return (TREE_CODE (arg) == TREE_CODE (parm)
12332                 && same_type_p (parm, arg)) ? 0 : 1;
12333       idx = TEMPLATE_TYPE_IDX (parm);
12334       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
12335       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
12336
12337       /* Check for mixed types and values.  */
12338       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
12339            && TREE_CODE (tparm) != TYPE_DECL)
12340           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
12341               && TREE_CODE (tparm) != TEMPLATE_DECL))
12342         return 1;
12343
12344       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
12345         {
12346           /* ARG must be constructed from a template class or a template
12347              template parameter.  */
12348           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
12349               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
12350             return 1;
12351
12352           {
12353             tree parmvec = TYPE_TI_ARGS (parm);
12354             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
12355             tree argtmplvec
12356               = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_TI_TEMPLATE (arg));
12357             int i;
12358
12359             /* The resolution to DR150 makes clear that default
12360                arguments for an N-argument may not be used to bind T
12361                to a template template parameter with fewer than N
12362                parameters.  It is not safe to permit the binding of
12363                default arguments as an extension, as that may change
12364                the meaning of a conforming program.  Consider:
12365
12366                   struct Dense { static const unsigned int dim = 1; };
12367
12368                   template <template <typename> class View,
12369                             typename Block>
12370                   void operator+(float, View<Block> const&);
12371
12372                   template <typename Block,
12373                             unsigned int Dim = Block::dim>
12374                   struct Lvalue_proxy { operator float() const; };
12375
12376                   void
12377                   test_1d (void) {
12378                     Lvalue_proxy<Dense> p;
12379                     float b;
12380                     b + p;
12381                   }
12382
12383               Here, if Lvalue_proxy is permitted to bind to View, then
12384               the global operator+ will be used; if they are not, the
12385               Lvalue_proxy will be converted to float.  */
12386             if (coerce_template_parms (argtmplvec, parmvec,
12387                                        TYPE_TI_TEMPLATE (parm),
12388                                        tf_none,
12389                                        /*require_all_args=*/true,
12390                                        /*use_default_args=*/false)
12391                 == error_mark_node)
12392               return 1;
12393
12394             /* Deduce arguments T, i from TT<T> or TT<i>.
12395                We check each element of PARMVEC and ARGVEC individually
12396                rather than the whole TREE_VEC since they can have
12397                different number of elements.  */
12398
12399             for (i = 0; i < TREE_VEC_LENGTH (parmvec); ++i)
12400               {
12401                 if (unify (tparms, targs,
12402                            TREE_VEC_ELT (parmvec, i),
12403                            TREE_VEC_ELT (argvec, i),
12404                            UNIFY_ALLOW_NONE))
12405                   return 1;
12406               }
12407           }
12408           arg = TYPE_TI_TEMPLATE (arg);
12409
12410           /* Fall through to deduce template name.  */
12411         }
12412
12413       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
12414           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
12415         {
12416           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
12417
12418           /* Simple cases: Value already set, does match or doesn't.  */
12419           if (targ != NULL_TREE && template_args_equal (targ, arg))
12420             return 0;
12421           else if (targ)
12422             return 1;
12423         }
12424       else
12425         {
12426           /* If PARM is `const T' and ARG is only `int', we don't have
12427              a match unless we are allowing additional qualification.
12428              If ARG is `const int' and PARM is just `T' that's OK;
12429              that binds `const int' to `T'.  */
12430           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
12431                                          arg, parm))
12432             return 1;
12433
12434           /* Consider the case where ARG is `const volatile int' and
12435              PARM is `const T'.  Then, T should be `volatile int'.  */
12436           arg = cp_build_qualified_type_real
12437             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
12438           if (arg == error_mark_node)
12439             return 1;
12440
12441           /* Simple cases: Value already set, does match or doesn't.  */
12442           if (targ != NULL_TREE && same_type_p (targ, arg))
12443             return 0;
12444           else if (targ)
12445             return 1;
12446
12447           /* Make sure that ARG is not a variable-sized array.  (Note
12448              that were talking about variable-sized arrays (like
12449              `int[n]'), rather than arrays of unknown size (like
12450              `int[]').)  We'll get very confused by such a type since
12451              the bound of the array will not be computable in an
12452              instantiation.  Besides, such types are not allowed in
12453              ISO C++, so we can do as we please here.  */
12454           if (variably_modified_type_p (arg, NULL_TREE))
12455             return 1;
12456         }
12457
12458       /* If ARG is a parameter pack or an expansion, we cannot unify
12459          against it unless PARM is also a parameter pack.  */
12460       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
12461           && !template_parameter_pack_p (parm))
12462         return 1;
12463
12464       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
12465       return 0;
12466
12467     case TEMPLATE_PARM_INDEX:
12468       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
12469       if (tparm == error_mark_node)
12470         return 1;
12471
12472       if (TEMPLATE_PARM_LEVEL (parm)
12473           != template_decl_level (tparm))
12474         /* The PARM is not one we're trying to unify.  Just check
12475            to see if it matches ARG.  */
12476         return !(TREE_CODE (arg) == TREE_CODE (parm)
12477                  && cp_tree_equal (parm, arg));
12478
12479       idx = TEMPLATE_PARM_IDX (parm);
12480       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
12481
12482       if (targ)
12483         return !cp_tree_equal (targ, arg);
12484
12485       /* [temp.deduct.type] If, in the declaration of a function template
12486          with a non-type template-parameter, the non-type
12487          template-parameter is used in an expression in the function
12488          parameter-list and, if the corresponding template-argument is
12489          deduced, the template-argument type shall match the type of the
12490          template-parameter exactly, except that a template-argument
12491          deduced from an array bound may be of any integral type.
12492          The non-type parameter might use already deduced type parameters.  */
12493       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
12494       if (!TREE_TYPE (arg))
12495         /* Template-parameter dependent expression.  Just accept it for now.
12496            It will later be processed in convert_template_argument.  */
12497         ;
12498       else if (same_type_p (TREE_TYPE (arg), tparm))
12499         /* OK */;
12500       else if ((strict & UNIFY_ALLOW_INTEGER)
12501                && (TREE_CODE (tparm) == INTEGER_TYPE
12502                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
12503         /* Convert the ARG to the type of PARM; the deduced non-type
12504            template argument must exactly match the types of the
12505            corresponding parameter.  */
12506         arg = fold (build_nop (TREE_TYPE (parm), arg));
12507       else if (uses_template_parms (tparm))
12508         /* We haven't deduced the type of this parameter yet.  Try again
12509            later.  */
12510         return 0;
12511       else
12512         return 1;
12513
12514       /* If ARG is a parameter pack or an expansion, we cannot unify
12515          against it unless PARM is also a parameter pack.  */
12516       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
12517           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
12518         return 1;
12519
12520       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
12521       return 0;
12522
12523     case PTRMEM_CST:
12524      {
12525         /* A pointer-to-member constant can be unified only with
12526          another constant.  */
12527       if (TREE_CODE (arg) != PTRMEM_CST)
12528         return 1;
12529
12530       /* Just unify the class member. It would be useless (and possibly
12531          wrong, depending on the strict flags) to unify also
12532          PTRMEM_CST_CLASS, because we want to be sure that both parm and
12533          arg refer to the same variable, even if through different
12534          classes. For instance:
12535
12536          struct A { int x; };
12537          struct B : A { };
12538
12539          Unification of &A::x and &B::x must succeed.  */
12540       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
12541                     PTRMEM_CST_MEMBER (arg), strict);
12542      }
12543
12544     case POINTER_TYPE:
12545       {
12546         if (TREE_CODE (arg) != POINTER_TYPE)
12547           return 1;
12548
12549         /* [temp.deduct.call]
12550
12551            A can be another pointer or pointer to member type that can
12552            be converted to the deduced A via a qualification
12553            conversion (_conv.qual_).
12554
12555            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
12556            This will allow for additional cv-qualification of the
12557            pointed-to types if appropriate.  */
12558
12559         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
12560           /* The derived-to-base conversion only persists through one
12561              level of pointers.  */
12562           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
12563
12564         return unify (tparms, targs, TREE_TYPE (parm),
12565                       TREE_TYPE (arg), strict);
12566       }
12567
12568     case REFERENCE_TYPE:
12569       if (TREE_CODE (arg) != REFERENCE_TYPE)
12570         return 1;
12571       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
12572                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
12573
12574     case ARRAY_TYPE:
12575       if (TREE_CODE (arg) != ARRAY_TYPE)
12576         return 1;
12577       if ((TYPE_DOMAIN (parm) == NULL_TREE)
12578           != (TYPE_DOMAIN (arg) == NULL_TREE))
12579         return 1;
12580       if (TYPE_DOMAIN (parm) != NULL_TREE)
12581         {
12582           tree parm_max;
12583           tree arg_max;
12584           bool parm_cst;
12585           bool arg_cst;
12586
12587           /* Our representation of array types uses "N - 1" as the
12588              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
12589              not an integer constant.  We cannot unify arbitrarily
12590              complex expressions, so we eliminate the MINUS_EXPRs
12591              here.  */
12592           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
12593           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
12594           if (!parm_cst)
12595             {
12596               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
12597               parm_max = TREE_OPERAND (parm_max, 0);
12598             }
12599           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
12600           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
12601           if (!arg_cst)
12602             {
12603               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
12604                  trying to unify the type of a variable with the type
12605                  of a template parameter.  For example:
12606
12607                    template <unsigned int N>
12608                    void f (char (&) [N]);
12609                    int g(); 
12610                    void h(int i) {
12611                      char a[g(i)];
12612                      f(a); 
12613                    }
12614
12615                 Here, the type of the ARG will be "int [g(i)]", and
12616                 may be a SAVE_EXPR, etc.  */
12617               if (TREE_CODE (arg_max) != MINUS_EXPR)
12618                 return 1;
12619               arg_max = TREE_OPERAND (arg_max, 0);
12620             }
12621
12622           /* If only one of the bounds used a MINUS_EXPR, compensate
12623              by adding one to the other bound.  */
12624           if (parm_cst && !arg_cst)
12625             parm_max = fold_build2 (PLUS_EXPR,
12626                                     integer_type_node,
12627                                     parm_max,
12628                                     integer_one_node);
12629           else if (arg_cst && !parm_cst)
12630             arg_max = fold_build2 (PLUS_EXPR,
12631                                    integer_type_node,
12632                                    arg_max,
12633                                    integer_one_node);
12634
12635           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
12636             return 1;
12637         }
12638       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
12639                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
12640
12641     case REAL_TYPE:
12642     case COMPLEX_TYPE:
12643     case VECTOR_TYPE:
12644     case INTEGER_TYPE:
12645     case BOOLEAN_TYPE:
12646     case ENUMERAL_TYPE:
12647     case VOID_TYPE:
12648       if (TREE_CODE (arg) != TREE_CODE (parm))
12649         return 1;
12650
12651       /* We have already checked cv-qualification at the top of the
12652          function.  */
12653       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
12654         return 1;
12655
12656       /* As far as unification is concerned, this wins.  Later checks
12657          will invalidate it if necessary.  */
12658       return 0;
12659
12660       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
12661       /* Type INTEGER_CST can come from ordinary constant template args.  */
12662     case INTEGER_CST:
12663       while (TREE_CODE (arg) == NOP_EXPR)
12664         arg = TREE_OPERAND (arg, 0);
12665
12666       if (TREE_CODE (arg) != INTEGER_CST)
12667         return 1;
12668       return !tree_int_cst_equal (parm, arg);
12669
12670     case TREE_VEC:
12671       {
12672         int i;
12673         if (TREE_CODE (arg) != TREE_VEC)
12674           return 1;
12675         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
12676           return 1;
12677         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
12678           if (unify (tparms, targs,
12679                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
12680                      UNIFY_ALLOW_NONE))
12681             return 1;
12682         return 0;
12683       }
12684
12685     case RECORD_TYPE:
12686     case UNION_TYPE:
12687       if (TREE_CODE (arg) != TREE_CODE (parm))
12688         return 1;
12689
12690       if (TYPE_PTRMEMFUNC_P (parm))
12691         {
12692           if (!TYPE_PTRMEMFUNC_P (arg))
12693             return 1;
12694
12695           return unify (tparms, targs,
12696                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
12697                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
12698                         strict);
12699         }
12700
12701       if (CLASSTYPE_TEMPLATE_INFO (parm))
12702         {
12703           tree t = NULL_TREE;
12704
12705           if (strict_in & UNIFY_ALLOW_DERIVED)
12706             {
12707               /* First, we try to unify the PARM and ARG directly.  */
12708               t = try_class_unification (tparms, targs,
12709                                          parm, arg);
12710
12711               if (!t)
12712                 {
12713                   /* Fallback to the special case allowed in
12714                      [temp.deduct.call]:
12715
12716                        If P is a class, and P has the form
12717                        template-id, then A can be a derived class of
12718                        the deduced A.  Likewise, if P is a pointer to
12719                        a class of the form template-id, A can be a
12720                        pointer to a derived class pointed to by the
12721                        deduced A.  */
12722                   t = get_template_base (tparms, targs, parm, arg);
12723
12724                   if (!t)
12725                     return 1;
12726                 }
12727             }
12728           else if (CLASSTYPE_TEMPLATE_INFO (arg)
12729                    && (CLASSTYPE_TI_TEMPLATE (parm)
12730                        == CLASSTYPE_TI_TEMPLATE (arg)))
12731             /* Perhaps PARM is something like S<U> and ARG is S<int>.
12732                Then, we should unify `int' and `U'.  */
12733             t = arg;
12734           else
12735             /* There's no chance of unification succeeding.  */
12736             return 1;
12737
12738           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
12739                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
12740         }
12741       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
12742         return 1;
12743       return 0;
12744
12745     case METHOD_TYPE:
12746     case FUNCTION_TYPE:
12747       if (TREE_CODE (arg) != TREE_CODE (parm))
12748         return 1;
12749
12750       /* CV qualifications for methods can never be deduced, they must
12751          match exactly.  We need to check them explicitly here,
12752          because type_unification_real treats them as any other
12753          cvqualified parameter.  */
12754       if (TREE_CODE (parm) == METHOD_TYPE
12755           && (!check_cv_quals_for_unify
12756               (UNIFY_ALLOW_NONE,
12757                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
12758                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
12759         return 1;
12760
12761       if (unify (tparms, targs, TREE_TYPE (parm),
12762                  TREE_TYPE (arg), UNIFY_ALLOW_NONE))
12763         return 1;
12764       return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
12765                                     TYPE_ARG_TYPES (arg), 1, DEDUCE_EXACT,
12766                                     LOOKUP_NORMAL);
12767
12768     case OFFSET_TYPE:
12769       /* Unify a pointer to member with a pointer to member function, which
12770          deduces the type of the member as a function type. */
12771       if (TYPE_PTRMEMFUNC_P (arg))
12772         {
12773           tree method_type;
12774           tree fntype;
12775           cp_cv_quals cv_quals;
12776
12777           /* Check top-level cv qualifiers */
12778           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
12779             return 1;
12780
12781           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
12782                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
12783             return 1;
12784
12785           /* Determine the type of the function we are unifying against. */
12786           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
12787           fntype =
12788             build_function_type (TREE_TYPE (method_type),
12789                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
12790
12791           /* Extract the cv-qualifiers of the member function from the
12792              implicit object parameter and place them on the function
12793              type to be restored later. */
12794           cv_quals =
12795             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
12796           fntype = build_qualified_type (fntype, cv_quals);
12797           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
12798         }
12799
12800       if (TREE_CODE (arg) != OFFSET_TYPE)
12801         return 1;
12802       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
12803                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
12804         return 1;
12805       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
12806                     strict);
12807
12808     case CONST_DECL:
12809       if (DECL_TEMPLATE_PARM_P (parm))
12810         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
12811       if (arg != integral_constant_value (parm))
12812         return 1;
12813       return 0;
12814
12815     case FIELD_DECL:
12816     case TEMPLATE_DECL:
12817       /* Matched cases are handled by the ARG == PARM test above.  */
12818       return 1;
12819
12820     case TYPE_ARGUMENT_PACK:
12821     case NONTYPE_ARGUMENT_PACK:
12822       {
12823         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
12824         tree packed_args = ARGUMENT_PACK_ARGS (arg);
12825         int i, len = TREE_VEC_LENGTH (packed_parms);
12826         int argslen = TREE_VEC_LENGTH (packed_args);
12827         int parm_variadic_p = 0;
12828
12829         /* Check if the parameters end in a pack, making them variadic.  */
12830         if (len > 0 
12831             && PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, len - 1)))
12832           parm_variadic_p = 1;
12833
12834         /* If we don't have enough arguments to satisfy the parameters
12835            (not counting the pack expression at the end), or we have
12836            too many arguments for a parameter list that doesn't end in
12837            a pack expression, we can't unify.  */
12838         if (argslen < (len - parm_variadic_p)
12839             || (argslen > len && !parm_variadic_p))
12840           return 1;
12841
12842         /* Unify all of the parameters that precede the (optional)
12843            pack expression.  */
12844         for (i = 0; i < len - parm_variadic_p; ++i)
12845           {
12846             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
12847                        TREE_VEC_ELT (packed_args, i), strict))
12848               return 1;
12849           }
12850
12851         if (parm_variadic_p)
12852           return unify_pack_expansion (tparms, targs, 
12853                                        packed_parms, packed_args,
12854                                        strict, /*call_args_p=*/false,
12855                                        /*subr=*/false);
12856         return 0;
12857       }
12858
12859       break;
12860
12861     case TYPEOF_TYPE:
12862     case DECLTYPE_TYPE:
12863       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
12864          nodes.  */
12865       return 0;
12866
12867     default:
12868       gcc_assert (EXPR_P (parm));
12869
12870       /* We must be looking at an expression.  This can happen with
12871          something like:
12872
12873            template <int I>
12874            void foo(S<I>, S<I + 2>);
12875
12876          This is a "nondeduced context":
12877
12878            [deduct.type]
12879
12880            The nondeduced contexts are:
12881
12882            --A type that is a template-id in which one or more of
12883              the template-arguments is an expression that references
12884              a template-parameter.
12885
12886          In these cases, we assume deduction succeeded, but don't
12887          actually infer any unifications.  */
12888
12889       if (!uses_template_parms (parm)
12890           && !template_args_equal (parm, arg))
12891         return 1;
12892       else
12893         return 0;
12894     }
12895 }
12896 \f
12897 /* Note that DECL can be defined in this translation unit, if
12898    required.  */
12899
12900 static void
12901 mark_definable (tree decl)
12902 {
12903   tree clone;
12904   DECL_NOT_REALLY_EXTERN (decl) = 1;
12905   FOR_EACH_CLONE (clone, decl)
12906     DECL_NOT_REALLY_EXTERN (clone) = 1;
12907 }
12908
12909 /* Called if RESULT is explicitly instantiated, or is a member of an
12910    explicitly instantiated class.  */
12911
12912 void
12913 mark_decl_instantiated (tree result, int extern_p)
12914 {
12915   SET_DECL_EXPLICIT_INSTANTIATION (result);
12916
12917   /* If this entity has already been written out, it's too late to
12918      make any modifications.  */
12919   if (TREE_ASM_WRITTEN (result))
12920     return;
12921
12922   if (TREE_CODE (result) != FUNCTION_DECL)
12923     /* The TREE_PUBLIC flag for function declarations will have been
12924        set correctly by tsubst.  */
12925     TREE_PUBLIC (result) = 1;
12926
12927   /* This might have been set by an earlier implicit instantiation.  */
12928   DECL_COMDAT (result) = 0;
12929
12930   if (extern_p)
12931     DECL_NOT_REALLY_EXTERN (result) = 0;
12932   else
12933     {
12934       mark_definable (result);
12935       /* Always make artificials weak.  */
12936       if (DECL_ARTIFICIAL (result) && flag_weak)
12937         comdat_linkage (result);
12938       /* For WIN32 we also want to put explicit instantiations in
12939          linkonce sections.  */
12940       else if (TREE_PUBLIC (result))
12941         maybe_make_one_only (result);
12942     }
12943
12944   /* If EXTERN_P, then this function will not be emitted -- unless
12945      followed by an explicit instantiation, at which point its linkage
12946      will be adjusted.  If !EXTERN_P, then this function will be
12947      emitted here.  In neither circumstance do we want
12948      import_export_decl to adjust the linkage.  */
12949   DECL_INTERFACE_KNOWN (result) = 1;
12950 }
12951
12952 /* Given two function templates PAT1 and PAT2, return:
12953
12954    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
12955    -1 if PAT2 is more specialized than PAT1.
12956    0 if neither is more specialized.
12957
12958    LEN indicates the number of parameters we should consider
12959    (defaulted parameters should not be considered).
12960
12961    The 1998 std underspecified function template partial ordering, and
12962    DR214 addresses the issue.  We take pairs of arguments, one from
12963    each of the templates, and deduce them against each other.  One of
12964    the templates will be more specialized if all the *other*
12965    template's arguments deduce against its arguments and at least one
12966    of its arguments *does* *not* deduce against the other template's
12967    corresponding argument.  Deduction is done as for class templates.
12968    The arguments used in deduction have reference and top level cv
12969    qualifiers removed.  Iff both arguments were originally reference
12970    types *and* deduction succeeds in both directions, the template
12971    with the more cv-qualified argument wins for that pairing (if
12972    neither is more cv-qualified, they both are equal).  Unlike regular
12973    deduction, after all the arguments have been deduced in this way,
12974    we do *not* verify the deduced template argument values can be
12975    substituted into non-deduced contexts, nor do we have to verify
12976    that all template arguments have been deduced.  */
12977
12978 int
12979 more_specialized_fn (tree pat1, tree pat2, int len)
12980 {
12981   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
12982   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
12983   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
12984   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
12985   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
12986   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
12987   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
12988   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
12989   int better1 = 0;
12990   int better2 = 0;
12991
12992   /* Remove the this parameter from non-static member functions.  If
12993      one is a non-static member function and the other is not a static
12994      member function, remove the first parameter from that function
12995      also.  This situation occurs for operator functions where we
12996      locate both a member function (with this pointer) and non-member
12997      operator (with explicit first operand).  */
12998   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
12999     {
13000       len--; /* LEN is the number of significant arguments for DECL1 */
13001       args1 = TREE_CHAIN (args1);
13002       if (!DECL_STATIC_FUNCTION_P (decl2))
13003         args2 = TREE_CHAIN (args2);
13004     }
13005   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
13006     {
13007       args2 = TREE_CHAIN (args2);
13008       if (!DECL_STATIC_FUNCTION_P (decl1))
13009         {
13010           len--;
13011           args1 = TREE_CHAIN (args1);
13012         }
13013     }
13014
13015   /* If only one is a conversion operator, they are unordered.  */
13016   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
13017     return 0;
13018
13019   /* Consider the return type for a conversion function */
13020   if (DECL_CONV_FN_P (decl1))
13021     {
13022       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
13023       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
13024       len++;
13025     }
13026
13027   processing_template_decl++;
13028
13029   while (len--)
13030     {
13031       tree arg1 = TREE_VALUE (args1);
13032       tree arg2 = TREE_VALUE (args2);
13033       int deduce1, deduce2;
13034       int quals1 = -1;
13035       int quals2 = -1;
13036
13037       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
13038           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
13039         {
13040           /* When both arguments are pack expansions, we need only
13041              unify the patterns themselves.  */
13042           arg1 = PACK_EXPANSION_PATTERN (arg1);
13043           arg2 = PACK_EXPANSION_PATTERN (arg2);
13044
13045           /* This is the last comparison we need to do.  */
13046           len = 0;
13047         }
13048
13049       if (TREE_CODE (arg1) == REFERENCE_TYPE)
13050         {
13051           arg1 = TREE_TYPE (arg1);
13052           quals1 = cp_type_quals (arg1);
13053         }
13054
13055       if (TREE_CODE (arg2) == REFERENCE_TYPE)
13056         {
13057           arg2 = TREE_TYPE (arg2);
13058           quals2 = cp_type_quals (arg2);
13059         }
13060
13061       if ((quals1 < 0) != (quals2 < 0))
13062         {
13063           /* Only of the args is a reference, see if we should apply
13064              array/function pointer decay to it.  This is not part of
13065              DR214, but is, IMHO, consistent with the deduction rules
13066              for the function call itself, and with our earlier
13067              implementation of the underspecified partial ordering
13068              rules.  (nathan).  */
13069           if (quals1 >= 0)
13070             {
13071               switch (TREE_CODE (arg1))
13072                 {
13073                 case ARRAY_TYPE:
13074                   arg1 = TREE_TYPE (arg1);
13075                   /* FALLTHROUGH. */
13076                 case FUNCTION_TYPE:
13077                   arg1 = build_pointer_type (arg1);
13078                   break;
13079
13080                 default:
13081                   break;
13082                 }
13083             }
13084           else
13085             {
13086               switch (TREE_CODE (arg2))
13087                 {
13088                 case ARRAY_TYPE:
13089                   arg2 = TREE_TYPE (arg2);
13090                   /* FALLTHROUGH. */
13091                 case FUNCTION_TYPE:
13092                   arg2 = build_pointer_type (arg2);
13093                   break;
13094
13095                 default:
13096                   break;
13097                 }
13098             }
13099         }
13100
13101       arg1 = TYPE_MAIN_VARIANT (arg1);
13102       arg2 = TYPE_MAIN_VARIANT (arg2);
13103
13104       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
13105         {
13106           int i, len2 = list_length (args2);
13107           tree parmvec = make_tree_vec (1);
13108           tree argvec = make_tree_vec (len2);
13109           tree ta = args2;
13110
13111           /* Setup the parameter vector, which contains only ARG1.  */
13112           TREE_VEC_ELT (parmvec, 0) = arg1;
13113
13114           /* Setup the argument vector, which contains the remaining
13115              arguments.  */
13116           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
13117             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
13118
13119           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
13120                                            argvec, UNIFY_ALLOW_NONE, 
13121                                            /*call_args_p=*/false, 
13122                                            /*subr=*/0);
13123
13124           /* We cannot deduce in the other direction, because ARG1 is
13125              a pack expansion but ARG2 is not.  */
13126           deduce2 = 0;
13127         }
13128       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
13129         {
13130           int i, len1 = list_length (args1);
13131           tree parmvec = make_tree_vec (1);
13132           tree argvec = make_tree_vec (len1);
13133           tree ta = args1;
13134
13135           /* Setup the parameter vector, which contains only ARG1.  */
13136           TREE_VEC_ELT (parmvec, 0) = arg2;
13137
13138           /* Setup the argument vector, which contains the remaining
13139              arguments.  */
13140           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
13141             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
13142
13143           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
13144                                            argvec, UNIFY_ALLOW_NONE, 
13145                                            /*call_args_p=*/false, 
13146                                            /*subr=*/0);
13147
13148           /* We cannot deduce in the other direction, because ARG2 is
13149              a pack expansion but ARG1 is not.*/
13150           deduce1 = 0;
13151         }
13152
13153       else
13154         {
13155           /* The normal case, where neither argument is a pack
13156              expansion.  */
13157           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
13158           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
13159         }
13160
13161       if (!deduce1)
13162         better2 = -1;
13163       if (!deduce2)
13164         better1 = -1;
13165       if (better1 < 0 && better2 < 0)
13166         /* We've failed to deduce something in either direction.
13167            These must be unordered.  */
13168         break;
13169
13170       if (deduce1 && deduce2 && quals1 >= 0 && quals2 >= 0)
13171         {
13172           /* Deduces in both directions, see if quals can
13173              disambiguate.  Pretend the worse one failed to deduce. */
13174           if ((quals1 & quals2) == quals2)
13175             deduce1 = 0;
13176           if ((quals1 & quals2) == quals1)
13177             deduce2 = 0;
13178         }
13179       if (deduce1 && !deduce2 && !better2)
13180         better2 = 1;
13181       if (deduce2 && !deduce1 && !better1)
13182         better1 = 1;
13183
13184       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
13185           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
13186         /* We have already processed all of the arguments in our
13187            handing of the pack expansion type.  */
13188         len = 0;
13189
13190       args1 = TREE_CHAIN (args1);
13191       args2 = TREE_CHAIN (args2);
13192     }
13193
13194   processing_template_decl--;
13195
13196   /* All things being equal, if the next argument is a pack expansion
13197      for one function but not for the other, prefer the
13198      non-variadic function.  */
13199   if ((better1 > 0) - (better2 > 0) == 0
13200       && args1 && TREE_VALUE (args1)
13201       && args2 && TREE_VALUE (args2))
13202     {
13203       if (TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION)
13204         return TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION ? 0 : -1;
13205       else if (TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION)
13206         return 1;
13207     }
13208
13209   return (better1 > 0) - (better2 > 0);
13210 }
13211
13212 /* Determine which of two partial specializations is more specialized.
13213
13214    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
13215    to the first partial specialization.  The TREE_VALUE is the
13216    innermost set of template parameters for the partial
13217    specialization.  PAT2 is similar, but for the second template.
13218
13219    Return 1 if the first partial specialization is more specialized;
13220    -1 if the second is more specialized; 0 if neither is more
13221    specialized.
13222
13223    See [temp.class.order] for information about determining which of
13224    two templates is more specialized.  */
13225
13226 static int
13227 more_specialized_class (tree pat1, tree pat2)
13228 {
13229   tree targs;
13230   tree tmpl1, tmpl2;
13231   int winner = 0;
13232   bool any_deductions = false;
13233
13234   tmpl1 = TREE_TYPE (pat1);
13235   tmpl2 = TREE_TYPE (pat2);
13236
13237   /* Just like what happens for functions, if we are ordering between
13238      different class template specializations, we may encounter dependent
13239      types in the arguments, and we need our dependency check functions
13240      to behave correctly.  */
13241   ++processing_template_decl;
13242   targs = get_class_bindings (TREE_VALUE (pat1),
13243                               CLASSTYPE_TI_ARGS (tmpl1),
13244                               CLASSTYPE_TI_ARGS (tmpl2));
13245   if (targs)
13246     {
13247       --winner;
13248       any_deductions = true;
13249     }
13250
13251   targs = get_class_bindings (TREE_VALUE (pat2),
13252                               CLASSTYPE_TI_ARGS (tmpl2),
13253                               CLASSTYPE_TI_ARGS (tmpl1));
13254   if (targs)
13255     {
13256       ++winner;
13257       any_deductions = true;
13258     }
13259   --processing_template_decl;
13260
13261   /* In the case of a tie where at least one of the class templates
13262      has a parameter pack at the end, the template with the most
13263      non-packed parameters wins.  */
13264   if (winner == 0
13265       && any_deductions
13266       && (template_args_variadic_p (TREE_PURPOSE (pat1))
13267           || template_args_variadic_p (TREE_PURPOSE (pat2))))
13268     {
13269       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
13270       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
13271       int len1 = TREE_VEC_LENGTH (args1);
13272       int len2 = TREE_VEC_LENGTH (args2);
13273
13274       /* We don't count the pack expansion at the end.  */
13275       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
13276         --len1;
13277       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
13278         --len2;
13279
13280       if (len1 > len2)
13281         return 1;
13282       else if (len1 < len2)
13283         return -1;
13284     }
13285
13286   return winner;
13287 }
13288
13289 /* Return the template arguments that will produce the function signature
13290    DECL from the function template FN, with the explicit template
13291    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
13292    also match.  Return NULL_TREE if no satisfactory arguments could be
13293    found.  */
13294
13295 static tree
13296 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
13297 {
13298   int ntparms = DECL_NTPARMS (fn);
13299   tree targs = make_tree_vec (ntparms);
13300   tree decl_type;
13301   tree decl_arg_types;
13302
13303   /* Substitute the explicit template arguments into the type of DECL.
13304      The call to fn_type_unification will handle substitution into the
13305      FN.  */
13306   decl_type = TREE_TYPE (decl);
13307   if (explicit_args && uses_template_parms (decl_type))
13308     {
13309       tree tmpl;
13310       tree converted_args;
13311
13312       if (DECL_TEMPLATE_INFO (decl))
13313         tmpl = DECL_TI_TEMPLATE (decl);
13314       else
13315         /* We can get here for some invalid specializations.  */
13316         return NULL_TREE;
13317
13318       converted_args
13319         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
13320                                  explicit_args, NULL_TREE,
13321                                  tf_none,
13322                                  /*require_all_args=*/false,
13323                                  /*use_default_args=*/false);
13324       if (converted_args == error_mark_node)
13325         return NULL_TREE;
13326
13327       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
13328       if (decl_type == error_mark_node)
13329         return NULL_TREE;
13330     }
13331
13332   /* Never do unification on the 'this' parameter.  */
13333   decl_arg_types = skip_artificial_parms_for (decl, 
13334                                               TYPE_ARG_TYPES (decl_type));
13335
13336   if (fn_type_unification (fn, explicit_args, targs,
13337                            decl_arg_types,
13338                            (check_rettype || DECL_CONV_FN_P (fn)
13339                             ? TREE_TYPE (decl_type) : NULL_TREE),
13340                            DEDUCE_EXACT, LOOKUP_NORMAL))
13341     return NULL_TREE;
13342
13343   return targs;
13344 }
13345
13346 /* Return the innermost template arguments that, when applied to a
13347    template specialization whose innermost template parameters are
13348    TPARMS, and whose specialization arguments are PARMS, yield the
13349    ARGS.
13350
13351    For example, suppose we have:
13352
13353      template <class T, class U> struct S {};
13354      template <class T> struct S<T*, int> {};
13355
13356    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
13357    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
13358    int}.  The resulting vector will be {double}, indicating that `T'
13359    is bound to `double'.  */
13360
13361 static tree
13362 get_class_bindings (tree tparms, tree spec_args, tree args)
13363 {
13364   int i, ntparms = TREE_VEC_LENGTH (tparms);
13365   tree deduced_args;
13366   tree innermost_deduced_args;
13367
13368   innermost_deduced_args = make_tree_vec (ntparms);
13369   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
13370     {
13371       deduced_args = copy_node (args);
13372       SET_TMPL_ARGS_LEVEL (deduced_args,
13373                            TMPL_ARGS_DEPTH (deduced_args),
13374                            innermost_deduced_args);
13375     }
13376   else
13377     deduced_args = innermost_deduced_args;
13378
13379   if (unify (tparms, deduced_args,
13380              INNERMOST_TEMPLATE_ARGS (spec_args),
13381              INNERMOST_TEMPLATE_ARGS (args),
13382              UNIFY_ALLOW_NONE))
13383     return NULL_TREE;
13384
13385   for (i =  0; i < ntparms; ++i)
13386     if (! TREE_VEC_ELT (innermost_deduced_args, i))
13387       return NULL_TREE;
13388
13389   /* Verify that nondeduced template arguments agree with the type
13390      obtained from argument deduction.
13391
13392      For example:
13393
13394        struct A { typedef int X; };
13395        template <class T, class U> struct C {};
13396        template <class T> struct C<T, typename T::X> {};
13397
13398      Then with the instantiation `C<A, int>', we can deduce that
13399      `T' is `A' but unify () does not check whether `typename T::X'
13400      is `int'.  */
13401   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
13402   if (spec_args == error_mark_node
13403       /* We only need to check the innermost arguments; the other
13404          arguments will always agree.  */
13405       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
13406                               INNERMOST_TEMPLATE_ARGS (args)))
13407     return NULL_TREE;
13408
13409   return deduced_args;
13410 }
13411
13412 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
13413    Return the TREE_LIST node with the most specialized template, if
13414    any.  If there is no most specialized template, the error_mark_node
13415    is returned.
13416
13417    Note that this function does not look at, or modify, the
13418    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
13419    returned is one of the elements of INSTANTIATIONS, callers may
13420    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
13421    and retrieve it from the value returned.  */
13422
13423 tree
13424 most_specialized_instantiation (tree templates)
13425 {
13426   tree fn, champ;
13427
13428   ++processing_template_decl;
13429
13430   champ = templates;
13431   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
13432     {
13433       int fate = 0;
13434
13435       if (get_bindings (TREE_VALUE (champ),
13436                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
13437                         NULL_TREE, /*check_ret=*/false))
13438         fate--;
13439
13440       if (get_bindings (TREE_VALUE (fn),
13441                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
13442                         NULL_TREE, /*check_ret=*/false))
13443         fate++;
13444
13445       if (fate == -1)
13446         champ = fn;
13447       else if (!fate)
13448         {
13449           /* Equally specialized, move to next function.  If there
13450              is no next function, nothing's most specialized.  */
13451           fn = TREE_CHAIN (fn);
13452           champ = fn;
13453           if (!fn)
13454             break;
13455         }
13456     }
13457
13458   if (champ)
13459     /* Now verify that champ is better than everything earlier in the
13460        instantiation list.  */
13461     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
13462       if (get_bindings (TREE_VALUE (champ),
13463                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
13464                         NULL_TREE, /*check_ret=*/false)
13465           || !get_bindings (TREE_VALUE (fn),
13466                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
13467                             NULL_TREE, /*check_ret=*/false))
13468         {
13469           champ = NULL_TREE;
13470           break;
13471         }
13472
13473   processing_template_decl--;
13474
13475   if (!champ)
13476     return error_mark_node;
13477
13478   return champ;
13479 }
13480
13481 /* If DECL is a specialization of some template, return the most
13482    general such template.  Otherwise, returns NULL_TREE.
13483
13484    For example, given:
13485
13486      template <class T> struct S { template <class U> void f(U); };
13487
13488    if TMPL is `template <class U> void S<int>::f(U)' this will return
13489    the full template.  This function will not trace past partial
13490    specializations, however.  For example, given in addition:
13491
13492      template <class T> struct S<T*> { template <class U> void f(U); };
13493
13494    if TMPL is `template <class U> void S<int*>::f(U)' this will return
13495    `template <class T> template <class U> S<T*>::f(U)'.  */
13496
13497 tree
13498 most_general_template (tree decl)
13499 {
13500   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
13501      an immediate specialization.  */
13502   if (TREE_CODE (decl) == FUNCTION_DECL)
13503     {
13504       if (DECL_TEMPLATE_INFO (decl)) {
13505         decl = DECL_TI_TEMPLATE (decl);
13506
13507         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
13508            template friend.  */
13509         if (TREE_CODE (decl) != TEMPLATE_DECL)
13510           return NULL_TREE;
13511       } else
13512         return NULL_TREE;
13513     }
13514
13515   /* Look for more and more general templates.  */
13516   while (DECL_TEMPLATE_INFO (decl))
13517     {
13518       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
13519          (See cp-tree.h for details.)  */
13520       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
13521         break;
13522
13523       if (CLASS_TYPE_P (TREE_TYPE (decl))
13524           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
13525         break;
13526
13527       /* Stop if we run into an explicitly specialized class template.  */
13528       if (!DECL_NAMESPACE_SCOPE_P (decl)
13529           && DECL_CONTEXT (decl)
13530           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
13531         break;
13532
13533       decl = DECL_TI_TEMPLATE (decl);
13534     }
13535
13536   return decl;
13537 }
13538
13539 /* Return the most specialized of the class template partial
13540    specializations of TMPL which can produce TYPE, a specialization of
13541    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
13542    a _TYPE node corresponding to the partial specialization, while the
13543    TREE_PURPOSE is the set of template arguments that must be
13544    substituted into the TREE_TYPE in order to generate TYPE.
13545
13546    If the choice of partial specialization is ambiguous, a diagnostic
13547    is issued, and the error_mark_node is returned.  If there are no
13548    partial specializations of TMPL matching TYPE, then NULL_TREE is
13549    returned.  */
13550
13551 static tree
13552 most_specialized_class (tree type, tree tmpl)
13553 {
13554   tree list = NULL_TREE;
13555   tree t;
13556   tree champ;
13557   int fate;
13558   bool ambiguous_p;
13559   tree args;
13560
13561   tmpl = most_general_template (tmpl);
13562   args = CLASSTYPE_TI_ARGS (type);
13563   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
13564     {
13565       tree partial_spec_args;
13566       tree spec_args;
13567
13568       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
13569       spec_args = get_class_bindings (TREE_VALUE (t),
13570                                       partial_spec_args,
13571                                       args);
13572       if (spec_args)
13573         {
13574           list = tree_cons (spec_args, TREE_VALUE (t), list);
13575           TREE_TYPE (list) = TREE_TYPE (t);
13576         }
13577     }
13578
13579   if (! list)
13580     return NULL_TREE;
13581
13582   ambiguous_p = false;
13583   t = list;
13584   champ = t;
13585   t = TREE_CHAIN (t);
13586   for (; t; t = TREE_CHAIN (t))
13587     {
13588       fate = more_specialized_class (champ, t);
13589       if (fate == 1)
13590         ;
13591       else
13592         {
13593           if (fate == 0)
13594             {
13595               t = TREE_CHAIN (t);
13596               if (! t)
13597                 {
13598                   ambiguous_p = true;
13599                   break;
13600                 }
13601             }
13602           champ = t;
13603         }
13604     }
13605
13606   if (!ambiguous_p)
13607     for (t = list; t && t != champ; t = TREE_CHAIN (t))
13608       {
13609         fate = more_specialized_class (champ, t);
13610         if (fate != 1)
13611           {
13612             ambiguous_p = true;
13613             break;
13614           }
13615       }
13616
13617   if (ambiguous_p)
13618     {
13619       const char *str = "candidates are:";
13620       error ("ambiguous class template instantiation for %q#T", type);
13621       for (t = list; t; t = TREE_CHAIN (t))
13622         {
13623           error ("%s %+#T", str, TREE_TYPE (t));
13624           str = "               ";
13625         }
13626       return error_mark_node;
13627     }
13628
13629   return champ;
13630 }
13631
13632 /* Explicitly instantiate DECL.  */
13633
13634 void
13635 do_decl_instantiation (tree decl, tree storage)
13636 {
13637   tree result = NULL_TREE;
13638   int extern_p = 0;
13639
13640   if (!decl || decl == error_mark_node)
13641     /* An error occurred, for which grokdeclarator has already issued
13642        an appropriate message.  */
13643     return;
13644   else if (! DECL_LANG_SPECIFIC (decl))
13645     {
13646       error ("explicit instantiation of non-template %q#D", decl);
13647       return;
13648     }
13649   else if (TREE_CODE (decl) == VAR_DECL)
13650     {
13651       /* There is an asymmetry here in the way VAR_DECLs and
13652          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
13653          the latter, the DECL we get back will be marked as a
13654          template instantiation, and the appropriate
13655          DECL_TEMPLATE_INFO will be set up.  This does not happen for
13656          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
13657          should handle VAR_DECLs as it currently handles
13658          FUNCTION_DECLs.  */
13659       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
13660       if (!result || TREE_CODE (result) != VAR_DECL)
13661         {
13662           error ("no matching template for %qD found", decl);
13663           return;
13664         }
13665       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
13666         {
13667           error ("type %qT for explicit instantiation %qD does not match "
13668                  "declared type %qT", TREE_TYPE (result), decl,
13669                  TREE_TYPE (decl));
13670           return;
13671         }
13672     }
13673   else if (TREE_CODE (decl) != FUNCTION_DECL)
13674     {
13675       error ("explicit instantiation of %q#D", decl);
13676       return;
13677     }
13678   else
13679     result = decl;
13680
13681   /* Check for various error cases.  Note that if the explicit
13682      instantiation is valid the RESULT will currently be marked as an
13683      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
13684      until we get here.  */
13685
13686   if (DECL_TEMPLATE_SPECIALIZATION (result))
13687     {
13688       /* DR 259 [temp.spec].
13689
13690          Both an explicit instantiation and a declaration of an explicit
13691          specialization shall not appear in a program unless the explicit
13692          instantiation follows a declaration of the explicit specialization.
13693
13694          For a given set of template parameters, if an explicit
13695          instantiation of a template appears after a declaration of an
13696          explicit specialization for that template, the explicit
13697          instantiation has no effect.  */
13698       return;
13699     }
13700   else if (DECL_EXPLICIT_INSTANTIATION (result))
13701     {
13702       /* [temp.spec]
13703
13704          No program shall explicitly instantiate any template more
13705          than once.
13706
13707          We check DECL_NOT_REALLY_EXTERN so as not to complain when
13708          the first instantiation was `extern' and the second is not,
13709          and EXTERN_P for the opposite case.  */
13710       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
13711         pedwarn ("duplicate explicit instantiation of %q#D", result);
13712       /* If an "extern" explicit instantiation follows an ordinary
13713          explicit instantiation, the template is instantiated.  */
13714       if (extern_p)
13715         return;
13716     }
13717   else if (!DECL_IMPLICIT_INSTANTIATION (result))
13718     {
13719       error ("no matching template for %qD found", result);
13720       return;
13721     }
13722   else if (!DECL_TEMPLATE_INFO (result))
13723     {
13724       pedwarn ("explicit instantiation of non-template %q#D", result);
13725       return;
13726     }
13727
13728   if (storage == NULL_TREE)
13729     ;
13730   else if (storage == ridpointers[(int) RID_EXTERN])
13731     {
13732       if (pedantic && !in_system_header)
13733         pedwarn ("ISO C++ forbids the use of %<extern%> on explicit "
13734                  "instantiations");
13735       extern_p = 1;
13736     }
13737   else
13738     error ("storage class %qD applied to template instantiation", storage);
13739
13740   check_explicit_instantiation_namespace (result);
13741   mark_decl_instantiated (result, extern_p);
13742   if (! extern_p)
13743     instantiate_decl (result, /*defer_ok=*/1,
13744                       /*expl_inst_class_mem_p=*/false);
13745 }
13746
13747 static void
13748 mark_class_instantiated (tree t, int extern_p)
13749 {
13750   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
13751   SET_CLASSTYPE_INTERFACE_KNOWN (t);
13752   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
13753   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
13754   if (! extern_p)
13755     {
13756       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
13757       rest_of_type_compilation (t, 1);
13758     }
13759 }
13760
13761 /* Called from do_type_instantiation through binding_table_foreach to
13762    do recursive instantiation for the type bound in ENTRY.  */
13763 static void
13764 bt_instantiate_type_proc (binding_entry entry, void *data)
13765 {
13766   tree storage = *(tree *) data;
13767
13768   if (IS_AGGR_TYPE (entry->type)
13769       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
13770     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
13771 }
13772
13773 /* Called from do_type_instantiation to instantiate a member
13774    (a member function or a static member variable) of an
13775    explicitly instantiated class template.  */
13776 static void
13777 instantiate_class_member (tree decl, int extern_p)
13778 {
13779   mark_decl_instantiated (decl, extern_p);
13780   if (! extern_p)
13781     instantiate_decl (decl, /*defer_ok=*/1,
13782                       /*expl_inst_class_mem_p=*/true);
13783 }
13784
13785 /* Perform an explicit instantiation of template class T.  STORAGE, if
13786    non-null, is the RID for extern, inline or static.  COMPLAIN is
13787    nonzero if this is called from the parser, zero if called recursively,
13788    since the standard is unclear (as detailed below).  */
13789
13790 void
13791 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
13792 {
13793   int extern_p = 0;
13794   int nomem_p = 0;
13795   int static_p = 0;
13796   int previous_instantiation_extern_p = 0;
13797
13798   if (TREE_CODE (t) == TYPE_DECL)
13799     t = TREE_TYPE (t);
13800
13801   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
13802     {
13803       error ("explicit instantiation of non-template type %qT", t);
13804       return;
13805     }
13806
13807   complete_type (t);
13808
13809   if (!COMPLETE_TYPE_P (t))
13810     {
13811       if (complain & tf_error)
13812         error ("explicit instantiation of %q#T before definition of template",
13813                t);
13814       return;
13815     }
13816
13817   if (storage != NULL_TREE)
13818     {
13819       if (pedantic && !in_system_header)
13820         pedwarn("ISO C++ forbids the use of %qE on explicit instantiations",
13821                 storage);
13822
13823       if (storage == ridpointers[(int) RID_INLINE])
13824         nomem_p = 1;
13825       else if (storage == ridpointers[(int) RID_EXTERN])
13826         extern_p = 1;
13827       else if (storage == ridpointers[(int) RID_STATIC])
13828         static_p = 1;
13829       else
13830         {
13831           error ("storage class %qD applied to template instantiation",
13832                  storage);
13833           extern_p = 0;
13834         }
13835     }
13836
13837   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
13838     {
13839       /* DR 259 [temp.spec].
13840
13841          Both an explicit instantiation and a declaration of an explicit
13842          specialization shall not appear in a program unless the explicit
13843          instantiation follows a declaration of the explicit specialization.
13844
13845          For a given set of template parameters, if an explicit
13846          instantiation of a template appears after a declaration of an
13847          explicit specialization for that template, the explicit
13848          instantiation has no effect.  */
13849       return;
13850     }
13851   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
13852     {
13853       /* [temp.spec]
13854
13855          No program shall explicitly instantiate any template more
13856          than once.
13857
13858          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
13859          instantiation was `extern'.  If EXTERN_P then the second is.
13860          These cases are OK.  */
13861       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
13862
13863       if (!previous_instantiation_extern_p && !extern_p
13864           && (complain & tf_error))
13865         pedwarn ("duplicate explicit instantiation of %q#T", t);
13866
13867       /* If we've already instantiated the template, just return now.  */
13868       if (!CLASSTYPE_INTERFACE_ONLY (t))
13869         return;
13870     }
13871
13872   check_explicit_instantiation_namespace (TYPE_NAME (t));
13873   mark_class_instantiated (t, extern_p);
13874
13875   if (nomem_p)
13876     return;
13877
13878   {
13879     tree tmp;
13880
13881     /* In contrast to implicit instantiation, where only the
13882        declarations, and not the definitions, of members are
13883        instantiated, we have here:
13884
13885          [temp.explicit]
13886
13887          The explicit instantiation of a class template specialization
13888          implies the instantiation of all of its members not
13889          previously explicitly specialized in the translation unit
13890          containing the explicit instantiation.
13891
13892        Of course, we can't instantiate member template classes, since
13893        we don't have any arguments for them.  Note that the standard
13894        is unclear on whether the instantiation of the members are
13895        *explicit* instantiations or not.  However, the most natural
13896        interpretation is that it should be an explicit instantiation.  */
13897
13898     if (! static_p)
13899       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
13900         if (TREE_CODE (tmp) == FUNCTION_DECL
13901             && DECL_TEMPLATE_INSTANTIATION (tmp))
13902           instantiate_class_member (tmp, extern_p);
13903
13904     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
13905       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
13906         instantiate_class_member (tmp, extern_p);
13907
13908     if (CLASSTYPE_NESTED_UTDS (t))
13909       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
13910                              bt_instantiate_type_proc, &storage);
13911   }
13912 }
13913
13914 /* Given a function DECL, which is a specialization of TMPL, modify
13915    DECL to be a re-instantiation of TMPL with the same template
13916    arguments.  TMPL should be the template into which tsubst'ing
13917    should occur for DECL, not the most general template.
13918
13919    One reason for doing this is a scenario like this:
13920
13921      template <class T>
13922      void f(const T&, int i);
13923
13924      void g() { f(3, 7); }
13925
13926      template <class T>
13927      void f(const T& t, const int i) { }
13928
13929    Note that when the template is first instantiated, with
13930    instantiate_template, the resulting DECL will have no name for the
13931    first parameter, and the wrong type for the second.  So, when we go
13932    to instantiate the DECL, we regenerate it.  */
13933
13934 static void
13935 regenerate_decl_from_template (tree decl, tree tmpl)
13936 {
13937   /* The arguments used to instantiate DECL, from the most general
13938      template.  */
13939   tree args;
13940   tree code_pattern;
13941
13942   args = DECL_TI_ARGS (decl);
13943   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
13944
13945   /* Make sure that we can see identifiers, and compute access
13946      correctly.  */
13947   push_access_scope (decl);
13948
13949   if (TREE_CODE (decl) == FUNCTION_DECL)
13950     {
13951       tree decl_parm;
13952       tree pattern_parm;
13953       tree specs;
13954       int args_depth;
13955       int parms_depth;
13956
13957       args_depth = TMPL_ARGS_DEPTH (args);
13958       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
13959       if (args_depth > parms_depth)
13960         args = get_innermost_template_args (args, parms_depth);
13961
13962       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
13963                                               args, tf_error, NULL_TREE);
13964       if (specs)
13965         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
13966                                                     specs);
13967
13968       /* Merge parameter declarations.  */
13969       decl_parm = skip_artificial_parms_for (decl,
13970                                              DECL_ARGUMENTS (decl));
13971       pattern_parm
13972         = skip_artificial_parms_for (code_pattern,
13973                                      DECL_ARGUMENTS (code_pattern));
13974       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
13975         {
13976           tree parm_type;
13977           tree attributes;
13978           
13979           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
13980             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
13981           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
13982                               NULL_TREE);
13983           parm_type = type_decays_to (parm_type);
13984           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
13985             TREE_TYPE (decl_parm) = parm_type;
13986           attributes = DECL_ATTRIBUTES (pattern_parm);
13987           if (DECL_ATTRIBUTES (decl_parm) != attributes)
13988             {
13989               DECL_ATTRIBUTES (decl_parm) = attributes;
13990               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
13991             }
13992           decl_parm = TREE_CHAIN (decl_parm);
13993           pattern_parm = TREE_CHAIN (pattern_parm);
13994         }
13995       /* Merge any parameters that match with the function parameter
13996          pack.  */
13997       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
13998         {
13999           int i, len;
14000           tree expanded_types;
14001           /* Expand the TYPE_PACK_EXPANSION that provides the types for
14002              the parameters in this function parameter pack.  */
14003           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
14004                                                  args, tf_error, NULL_TREE);
14005           len = TREE_VEC_LENGTH (expanded_types);
14006           for (i = 0; i < len; i++)
14007             {
14008               tree parm_type;
14009               tree attributes;
14010           
14011               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
14012                 /* Rename the parameter to include the index.  */
14013                 DECL_NAME (decl_parm) = 
14014                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
14015               parm_type = TREE_VEC_ELT (expanded_types, i);
14016               parm_type = type_decays_to (parm_type);
14017               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
14018                 TREE_TYPE (decl_parm) = parm_type;
14019               attributes = DECL_ATTRIBUTES (pattern_parm);
14020               if (DECL_ATTRIBUTES (decl_parm) != attributes)
14021                 {
14022                   DECL_ATTRIBUTES (decl_parm) = attributes;
14023                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
14024                 }
14025               decl_parm = TREE_CHAIN (decl_parm);
14026             }
14027         }
14028       /* Merge additional specifiers from the CODE_PATTERN.  */
14029       if (DECL_DECLARED_INLINE_P (code_pattern)
14030           && !DECL_DECLARED_INLINE_P (decl))
14031         DECL_DECLARED_INLINE_P (decl) = 1;
14032       if (DECL_INLINE (code_pattern) && !DECL_INLINE (decl))
14033         DECL_INLINE (decl) = 1;
14034     }
14035   else if (TREE_CODE (decl) == VAR_DECL)
14036     DECL_INITIAL (decl) =
14037       tsubst_expr (DECL_INITIAL (code_pattern), args,
14038                    tf_error, DECL_TI_TEMPLATE (decl),
14039                    /*integral_constant_expression_p=*/false);
14040   else
14041     gcc_unreachable ();
14042
14043   pop_access_scope (decl);
14044 }
14045
14046 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
14047    substituted to get DECL.  */
14048
14049 tree
14050 template_for_substitution (tree decl)
14051 {
14052   tree tmpl = DECL_TI_TEMPLATE (decl);
14053
14054   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
14055      for the instantiation.  This is not always the most general
14056      template.  Consider, for example:
14057
14058         template <class T>
14059         struct S { template <class U> void f();
14060                    template <> void f<int>(); };
14061
14062      and an instantiation of S<double>::f<int>.  We want TD to be the
14063      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
14064   while (/* An instantiation cannot have a definition, so we need a
14065             more general template.  */
14066          DECL_TEMPLATE_INSTANTIATION (tmpl)
14067            /* We must also deal with friend templates.  Given:
14068
14069                 template <class T> struct S {
14070                   template <class U> friend void f() {};
14071                 };
14072
14073               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
14074               so far as the language is concerned, but that's still
14075               where we get the pattern for the instantiation from.  On
14076               other hand, if the definition comes outside the class, say:
14077
14078                 template <class T> struct S {
14079                   template <class U> friend void f();
14080                 };
14081                 template <class U> friend void f() {}
14082
14083               we don't need to look any further.  That's what the check for
14084               DECL_INITIAL is for.  */
14085           || (TREE_CODE (decl) == FUNCTION_DECL
14086               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
14087               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
14088     {
14089       /* The present template, TD, should not be a definition.  If it
14090          were a definition, we should be using it!  Note that we
14091          cannot restructure the loop to just keep going until we find
14092          a template with a definition, since that might go too far if
14093          a specialization was declared, but not defined.  */
14094       gcc_assert (TREE_CODE (decl) != VAR_DECL
14095                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
14096
14097       /* Fetch the more general template.  */
14098       tmpl = DECL_TI_TEMPLATE (tmpl);
14099     }
14100
14101   return tmpl;
14102 }
14103
14104 /* Produce the definition of D, a _DECL generated from a template.  If
14105    DEFER_OK is nonzero, then we don't have to actually do the
14106    instantiation now; we just have to do it sometime.  Normally it is
14107    an error if this is an explicit instantiation but D is undefined.
14108    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
14109    explicitly instantiated class template.  */
14110
14111 tree
14112 instantiate_decl (tree d, int defer_ok,
14113                   bool expl_inst_class_mem_p)
14114 {
14115   tree tmpl = DECL_TI_TEMPLATE (d);
14116   tree gen_args;
14117   tree args;
14118   tree td;
14119   tree code_pattern;
14120   tree spec;
14121   tree gen_tmpl;
14122   bool pattern_defined;
14123   int need_push;
14124   location_t saved_loc = input_location;
14125   int saved_in_system_header = in_system_header;
14126   bool external_p;
14127
14128   /* This function should only be used to instantiate templates for
14129      functions and static member variables.  */
14130   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
14131               || TREE_CODE (d) == VAR_DECL);
14132
14133   /* Variables are never deferred; if instantiation is required, they
14134      are instantiated right away.  That allows for better code in the
14135      case that an expression refers to the value of the variable --
14136      if the variable has a constant value the referring expression can
14137      take advantage of that fact.  */
14138   if (TREE_CODE (d) == VAR_DECL)
14139     defer_ok = 0;
14140
14141   /* Don't instantiate cloned functions.  Instead, instantiate the
14142      functions they cloned.  */
14143   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
14144     d = DECL_CLONED_FUNCTION (d);
14145
14146   if (DECL_TEMPLATE_INSTANTIATED (d))
14147     /* D has already been instantiated.  It might seem reasonable to
14148        check whether or not D is an explicit instantiation, and, if so,
14149        stop here.  But when an explicit instantiation is deferred
14150        until the end of the compilation, DECL_EXPLICIT_INSTANTIATION
14151        is set, even though we still need to do the instantiation.  */
14152     return d;
14153
14154   /* If we already have a specialization of this declaration, then
14155      there's no reason to instantiate it.  Note that
14156      retrieve_specialization gives us both instantiations and
14157      specializations, so we must explicitly check
14158      DECL_TEMPLATE_SPECIALIZATION.  */
14159   gen_tmpl = most_general_template (tmpl);
14160   gen_args = DECL_TI_ARGS (d);
14161   spec = retrieve_specialization (gen_tmpl, gen_args,
14162                                   /*class_specializations_p=*/false);
14163   if (spec != NULL_TREE && DECL_TEMPLATE_SPECIALIZATION (spec))
14164     return spec;
14165
14166   /* This needs to happen before any tsubsting.  */
14167   if (! push_tinst_level (d))
14168     return d;
14169
14170   timevar_push (TV_PARSE);
14171
14172   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
14173      for the instantiation.  */
14174   td = template_for_substitution (d);
14175   code_pattern = DECL_TEMPLATE_RESULT (td);
14176
14177   /* We should never be trying to instantiate a member of a class
14178      template or partial specialization.  */
14179   gcc_assert (d != code_pattern);
14180
14181   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
14182       || DECL_TEMPLATE_SPECIALIZATION (td))
14183     /* In the case of a friend template whose definition is provided
14184        outside the class, we may have too many arguments.  Drop the
14185        ones we don't need.  The same is true for specializations.  */
14186     args = get_innermost_template_args
14187       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
14188   else
14189     args = gen_args;
14190
14191   if (TREE_CODE (d) == FUNCTION_DECL)
14192     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
14193   else
14194     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
14195
14196   /* We may be in the middle of deferred access check.  Disable it now.  */
14197   push_deferring_access_checks (dk_no_deferred);
14198
14199   /* Unless an explicit instantiation directive has already determined
14200      the linkage of D, remember that a definition is available for
14201      this entity.  */
14202   if (pattern_defined
14203       && !DECL_INTERFACE_KNOWN (d)
14204       && !DECL_NOT_REALLY_EXTERN (d))
14205     mark_definable (d);
14206
14207   input_location = DECL_SOURCE_LOCATION (d);
14208   in_system_header = DECL_IN_SYSTEM_HEADER (d);
14209
14210   /* If D is a member of an explicitly instantiated class template,
14211      and no definition is available, treat it like an implicit
14212      instantiation.  */
14213   if (!pattern_defined && expl_inst_class_mem_p
14214       && DECL_EXPLICIT_INSTANTIATION (d))
14215     {
14216       DECL_NOT_REALLY_EXTERN (d) = 0;
14217       DECL_INTERFACE_KNOWN (d) = 0;
14218       SET_DECL_IMPLICIT_INSTANTIATION (d);
14219     }
14220
14221   if (!defer_ok)
14222     {
14223       /* Recheck the substitutions to obtain any warning messages
14224          about ignoring cv qualifiers.  */
14225       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
14226       tree type = TREE_TYPE (gen);
14227
14228       /* Make sure that we can see identifiers, and compute access
14229          correctly.  D is already the target FUNCTION_DECL with the
14230          right context.  */
14231       push_access_scope (d);
14232
14233       if (TREE_CODE (gen) == FUNCTION_DECL)
14234         {
14235           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
14236           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
14237                                           d);
14238           /* Don't simply tsubst the function type, as that will give
14239              duplicate warnings about poor parameter qualifications.
14240              The function arguments are the same as the decl_arguments
14241              without the top level cv qualifiers.  */
14242           type = TREE_TYPE (type);
14243         }
14244       tsubst (type, gen_args, tf_warning_or_error, d);
14245
14246       pop_access_scope (d);
14247     }
14248
14249   /* Check to see whether we know that this template will be
14250      instantiated in some other file, as with "extern template"
14251      extension.  */
14252   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
14253   /* In general, we do not instantiate such templates...  */
14254   if (external_p
14255       /* ... but we instantiate inline functions so that we can inline
14256          them and ... */
14257       && ! (TREE_CODE (d) == FUNCTION_DECL && DECL_INLINE (d))
14258       /* ... we instantiate static data members whose values are
14259          needed in integral constant expressions.  */
14260       && ! (TREE_CODE (d) == VAR_DECL
14261             && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (d)))
14262     goto out;
14263   /* Defer all other templates, unless we have been explicitly
14264      forbidden from doing so.  */
14265   if (/* If there is no definition, we cannot instantiate the
14266          template.  */
14267       ! pattern_defined
14268       /* If it's OK to postpone instantiation, do so.  */
14269       || defer_ok
14270       /* If this is a static data member that will be defined
14271          elsewhere, we don't want to instantiate the entire data
14272          member, but we do want to instantiate the initializer so that
14273          we can substitute that elsewhere.  */
14274       || (external_p && TREE_CODE (d) == VAR_DECL))
14275     {
14276       /* The definition of the static data member is now required so
14277          we must substitute the initializer.  */
14278       if (TREE_CODE (d) == VAR_DECL
14279           && !DECL_INITIAL (d)
14280           && DECL_INITIAL (code_pattern))
14281         {
14282           tree ns;
14283           tree init;
14284
14285           ns = decl_namespace_context (d);
14286           push_nested_namespace (ns);
14287           push_nested_class (DECL_CONTEXT (d));
14288           init = tsubst_expr (DECL_INITIAL (code_pattern),
14289                               args,
14290                               tf_warning_or_error, NULL_TREE,
14291                               /*integral_constant_expression_p=*/false);
14292           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
14293                           /*asmspec_tree=*/NULL_TREE,
14294                           LOOKUP_ONLYCONVERTING);
14295           pop_nested_class ();
14296           pop_nested_namespace (ns);
14297         }
14298
14299       /* We restore the source position here because it's used by
14300          add_pending_template.  */
14301       input_location = saved_loc;
14302
14303       if (at_eof && !pattern_defined
14304           && DECL_EXPLICIT_INSTANTIATION (d))
14305         /* [temp.explicit]
14306
14307            The definition of a non-exported function template, a
14308            non-exported member function template, or a non-exported
14309            member function or static data member of a class template
14310            shall be present in every translation unit in which it is
14311            explicitly instantiated.  */
14312         pedwarn
14313           ("explicit instantiation of %qD but no definition available", d);
14314
14315       /* ??? Historically, we have instantiated inline functions, even
14316          when marked as "extern template".  */
14317       if (!(external_p && TREE_CODE (d) == VAR_DECL))
14318         add_pending_template (d);
14319       goto out;
14320     }
14321   /* Tell the repository that D is available in this translation unit
14322      -- and see if it is supposed to be instantiated here.  */
14323   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
14324     {
14325       /* In a PCH file, despite the fact that the repository hasn't
14326          requested instantiation in the PCH it is still possible that
14327          an instantiation will be required in a file that includes the
14328          PCH.  */
14329       if (pch_file)
14330         add_pending_template (d);
14331       /* Instantiate inline functions so that the inliner can do its
14332          job, even though we'll not be emitting a copy of this
14333          function.  */
14334       if (!(TREE_CODE (d) == FUNCTION_DECL
14335             && flag_inline_trees
14336             && DECL_DECLARED_INLINE_P (d)))
14337         goto out;
14338     }
14339
14340   need_push = !cfun || !global_bindings_p ();
14341   if (need_push)
14342     push_to_top_level ();
14343
14344   /* Mark D as instantiated so that recursive calls to
14345      instantiate_decl do not try to instantiate it again.  */
14346   DECL_TEMPLATE_INSTANTIATED (d) = 1;
14347
14348   /* Regenerate the declaration in case the template has been modified
14349      by a subsequent redeclaration.  */
14350   regenerate_decl_from_template (d, td);
14351
14352   /* We already set the file and line above.  Reset them now in case
14353      they changed as a result of calling regenerate_decl_from_template.  */
14354   input_location = DECL_SOURCE_LOCATION (d);
14355
14356   if (TREE_CODE (d) == VAR_DECL)
14357     {
14358       tree init;
14359
14360       /* Clear out DECL_RTL; whatever was there before may not be right
14361          since we've reset the type of the declaration.  */
14362       SET_DECL_RTL (d, NULL_RTX);
14363       DECL_IN_AGGR_P (d) = 0;
14364
14365       /* The initializer is placed in DECL_INITIAL by
14366          regenerate_decl_from_template.  Pull it out so that
14367          finish_decl can process it.  */
14368       init = DECL_INITIAL (d);
14369       DECL_INITIAL (d) = NULL_TREE;
14370       DECL_INITIALIZED_P (d) = 0;
14371
14372       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
14373          initializer.  That function will defer actual emission until
14374          we have a chance to determine linkage.  */
14375       DECL_EXTERNAL (d) = 0;
14376
14377       /* Enter the scope of D so that access-checking works correctly.  */
14378       push_nested_class (DECL_CONTEXT (d));
14379       finish_decl (d, init, NULL_TREE);
14380       pop_nested_class ();
14381     }
14382   else if (TREE_CODE (d) == FUNCTION_DECL)
14383     {
14384       htab_t saved_local_specializations;
14385       tree subst_decl;
14386       tree tmpl_parm;
14387       tree spec_parm;
14388
14389       /* Save away the current list, in case we are instantiating one
14390          template from within the body of another.  */
14391       saved_local_specializations = local_specializations;
14392
14393       /* Set up the list of local specializations.  */
14394       local_specializations = htab_create (37,
14395                                            hash_local_specialization,
14396                                            eq_local_specializations,
14397                                            NULL);
14398
14399       /* Set up context.  */
14400       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
14401
14402       /* Create substitution entries for the parameters.  */
14403       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
14404       tmpl_parm = DECL_ARGUMENTS (subst_decl);
14405       spec_parm = DECL_ARGUMENTS (d);
14406       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
14407         {
14408           register_local_specialization (spec_parm, tmpl_parm);
14409           spec_parm = skip_artificial_parms_for (d, spec_parm);
14410           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
14411         }
14412       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
14413         {
14414           register_local_specialization (spec_parm, tmpl_parm);
14415           tmpl_parm = TREE_CHAIN (tmpl_parm);
14416           spec_parm = TREE_CHAIN (spec_parm);
14417         }
14418       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
14419         {
14420           /* Collect all of the extra "packed" parameters into an
14421              argument pack.  */
14422           tree parmvec;
14423           tree parmtypevec;
14424           tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
14425           tree argtypepack = make_node (TYPE_ARGUMENT_PACK);
14426           int i, len = 0;
14427           tree t;
14428           
14429           /* Count how many parameters remain.  */
14430           for (t = spec_parm; t; t = TREE_CHAIN (t))
14431             len++;
14432
14433           /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
14434           parmvec = make_tree_vec (len);
14435           parmtypevec = make_tree_vec (len);
14436           for(i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
14437             {
14438               TREE_VEC_ELT (parmvec, i) = spec_parm;
14439               TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
14440             }
14441
14442           /* Build the argument packs.  */
14443           SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
14444           SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
14445           TREE_TYPE (argpack) = argtypepack;
14446           
14447           /* Register the (value) argument pack as a specialization of
14448              TMPL_PARM, then move on.  */
14449           register_local_specialization (argpack, tmpl_parm);
14450           tmpl_parm = TREE_CHAIN (tmpl_parm);
14451         }
14452       gcc_assert (!spec_parm);
14453
14454       /* Substitute into the body of the function.  */
14455       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
14456                    tf_warning_or_error, tmpl,
14457                    /*integral_constant_expression_p=*/false);
14458
14459       /* Set the current input_location to the end of the function
14460          so that finish_function knows where we are.  */
14461       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
14462
14463       /* We don't need the local specializations any more.  */
14464       htab_delete (local_specializations);
14465       local_specializations = saved_local_specializations;
14466
14467       /* Finish the function.  */
14468       d = finish_function (0);
14469       expand_or_defer_fn (d);
14470     }
14471
14472   /* We're not deferring instantiation any more.  */
14473   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
14474
14475   if (need_push)
14476     pop_from_top_level ();
14477
14478 out:
14479   input_location = saved_loc;
14480   in_system_header = saved_in_system_header;
14481   pop_deferring_access_checks ();
14482   pop_tinst_level ();
14483
14484   timevar_pop (TV_PARSE);
14485
14486   return d;
14487 }
14488
14489 /* Run through the list of templates that we wish we could
14490    instantiate, and instantiate any we can.  RETRIES is the
14491    number of times we retry pending template instantiation.  */
14492
14493 void
14494 instantiate_pending_templates (int retries)
14495 {
14496   int reconsider;
14497   location_t saved_loc = input_location;
14498   int saved_in_system_header = in_system_header;
14499
14500   /* Instantiating templates may trigger vtable generation.  This in turn
14501      may require further template instantiations.  We place a limit here
14502      to avoid infinite loop.  */
14503   if (pending_templates && retries >= max_tinst_depth)
14504     {
14505       tree decl = pending_templates->tinst->decl;
14506
14507       error ("template instantiation depth exceeds maximum of %d"
14508              " instantiating %q+D, possibly from virtual table generation"
14509              " (use -ftemplate-depth-NN to increase the maximum)",
14510              max_tinst_depth, decl);
14511       if (TREE_CODE (decl) == FUNCTION_DECL)
14512         /* Pretend that we defined it.  */
14513         DECL_INITIAL (decl) = error_mark_node;
14514       return;
14515     }
14516
14517   do
14518     {
14519       struct pending_template **t = &pending_templates;
14520       struct pending_template *last = NULL;
14521       reconsider = 0;
14522       while (*t)
14523         {
14524           tree instantiation = reopen_tinst_level ((*t)->tinst);
14525           bool complete = false;
14526
14527           if (TYPE_P (instantiation))
14528             {
14529               tree fn;
14530
14531               if (!COMPLETE_TYPE_P (instantiation))
14532                 {
14533                   instantiate_class_template (instantiation);
14534                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
14535                     for (fn = TYPE_METHODS (instantiation);
14536                          fn;
14537                          fn = TREE_CHAIN (fn))
14538                       if (! DECL_ARTIFICIAL (fn))
14539                         instantiate_decl (fn,
14540                                           /*defer_ok=*/0,
14541                                           /*expl_inst_class_mem_p=*/false);
14542                   if (COMPLETE_TYPE_P (instantiation))
14543                     reconsider = 1;
14544                 }
14545
14546               complete = COMPLETE_TYPE_P (instantiation);
14547             }
14548           else
14549             {
14550               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
14551                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
14552                 {
14553                   instantiation
14554                     = instantiate_decl (instantiation,
14555                                         /*defer_ok=*/0,
14556                                         /*expl_inst_class_mem_p=*/false);
14557                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
14558                     reconsider = 1;
14559                 }
14560
14561               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
14562                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
14563             }
14564
14565           if (complete)
14566             /* If INSTANTIATION has been instantiated, then we don't
14567                need to consider it again in the future.  */
14568             *t = (*t)->next;
14569           else
14570             {
14571               last = *t;
14572               t = &(*t)->next;
14573             }
14574           tinst_depth = 0;
14575           current_tinst_level = NULL;
14576         }
14577       last_pending_template = last;
14578     }
14579   while (reconsider);
14580
14581   input_location = saved_loc;
14582   in_system_header = saved_in_system_header;
14583 }
14584
14585 /* Substitute ARGVEC into T, which is a list of initializers for
14586    either base class or a non-static data member.  The TREE_PURPOSEs
14587    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
14588    instantiate_decl.  */
14589
14590 static tree
14591 tsubst_initializer_list (tree t, tree argvec)
14592 {
14593   tree inits = NULL_TREE;
14594
14595   for (; t; t = TREE_CHAIN (t))
14596     {
14597       tree decl;
14598       tree init;
14599       tree expanded_bases = NULL_TREE;
14600       tree expanded_arguments = NULL_TREE;
14601       int i, len = 1;
14602
14603       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
14604         {
14605           tree expr;
14606           tree arg;
14607
14608           /* Expand the base class expansion type into separate base
14609              classes.  */
14610           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
14611                                                  tf_warning_or_error,
14612                                                  NULL_TREE);
14613           if (expanded_bases == error_mark_node)
14614             continue;
14615           
14616           /* We'll be building separate TREE_LISTs of arguments for
14617              each base.  */
14618           len = TREE_VEC_LENGTH (expanded_bases);
14619           expanded_arguments = make_tree_vec (len);
14620           for (i = 0; i < len; i++)
14621             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
14622
14623           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
14624              expand each argument in the TREE_VALUE of t.  */
14625           expr = make_node (EXPR_PACK_EXPANSION);
14626           PACK_EXPANSION_PARAMETER_PACKS (expr) =
14627             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
14628
14629           /* Substitute parameter packs into each argument in the
14630              TREE_LIST.  */
14631           in_base_initializer = 1;
14632           for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
14633             {
14634               tree expanded_exprs;
14635
14636               /* Expand the argument.  */
14637               SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
14638               expanded_exprs = tsubst_pack_expansion (expr, argvec,
14639                                                       tf_warning_or_error,
14640                                                       NULL_TREE);
14641
14642               /* Prepend each of the expanded expressions to the
14643                  corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
14644               for (i = 0; i < len; i++)
14645                 {
14646                   TREE_VEC_ELT (expanded_arguments, i) = 
14647                     tree_cons (NULL_TREE, TREE_VEC_ELT (expanded_exprs, i),
14648                                TREE_VEC_ELT (expanded_arguments, i));
14649                 }
14650             }
14651           in_base_initializer = 0;
14652
14653           /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
14654              since we built them backwards.  */
14655           for (i = 0; i < len; i++)
14656             {
14657               TREE_VEC_ELT (expanded_arguments, i) = 
14658                 nreverse (TREE_VEC_ELT (expanded_arguments, i));
14659             }
14660         }
14661
14662       for (i = 0; i < len; ++i)
14663         {
14664           if (expanded_bases)
14665             {
14666               decl = TREE_VEC_ELT (expanded_bases, i);
14667               decl = expand_member_init (decl);
14668               init = TREE_VEC_ELT (expanded_arguments, i);
14669             }
14670           else
14671             {
14672               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
14673                                   tf_warning_or_error, NULL_TREE);
14674
14675               decl = expand_member_init (decl);
14676               if (decl && !DECL_P (decl))
14677                 in_base_initializer = 1;
14678
14679               init = tsubst_expr (TREE_VALUE (t), argvec, 
14680                                   tf_warning_or_error, NULL_TREE,
14681                                   /*integral_constant_expression_p=*/false);
14682               in_base_initializer = 0;
14683             }
14684
14685           if (decl)
14686             {
14687               init = build_tree_list (decl, init);
14688               TREE_CHAIN (init) = inits;
14689               inits = init;
14690             }
14691         }
14692     }
14693   return inits;
14694 }
14695
14696 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
14697
14698 static void
14699 set_current_access_from_decl (tree decl)
14700 {
14701   if (TREE_PRIVATE (decl))
14702     current_access_specifier = access_private_node;
14703   else if (TREE_PROTECTED (decl))
14704     current_access_specifier = access_protected_node;
14705   else
14706     current_access_specifier = access_public_node;
14707 }
14708
14709 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
14710    is the instantiation (which should have been created with
14711    start_enum) and ARGS are the template arguments to use.  */
14712
14713 static void
14714 tsubst_enum (tree tag, tree newtag, tree args)
14715 {
14716   tree e;
14717
14718   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
14719     {
14720       tree value;
14721       tree decl;
14722
14723       decl = TREE_VALUE (e);
14724       /* Note that in a template enum, the TREE_VALUE is the
14725          CONST_DECL, not the corresponding INTEGER_CST.  */
14726       value = tsubst_expr (DECL_INITIAL (decl),
14727                            args, tf_warning_or_error, NULL_TREE,
14728                            /*integral_constant_expression_p=*/true);
14729
14730       /* Give this enumeration constant the correct access.  */
14731       set_current_access_from_decl (decl);
14732
14733       /* Actually build the enumerator itself.  */
14734       build_enumerator (DECL_NAME (decl), value, newtag);
14735     }
14736
14737   finish_enum (newtag);
14738   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
14739     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
14740 }
14741
14742 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
14743    its type -- but without substituting the innermost set of template
14744    arguments.  So, innermost set of template parameters will appear in
14745    the type.  */
14746
14747 tree
14748 get_mostly_instantiated_function_type (tree decl)
14749 {
14750   tree fn_type;
14751   tree tmpl;
14752   tree targs;
14753   tree tparms;
14754   int parm_depth;
14755
14756   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
14757   targs = DECL_TI_ARGS (decl);
14758   tparms = DECL_TEMPLATE_PARMS (tmpl);
14759   parm_depth = TMPL_PARMS_DEPTH (tparms);
14760
14761   /* There should be as many levels of arguments as there are levels
14762      of parameters.  */
14763   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
14764
14765   fn_type = TREE_TYPE (tmpl);
14766
14767   if (parm_depth == 1)
14768     /* No substitution is necessary.  */
14769     ;
14770   else
14771     {
14772       int i, save_access_control;
14773       tree partial_args;
14774
14775       /* Replace the innermost level of the TARGS with NULL_TREEs to
14776          let tsubst know not to substitute for those parameters.  */
14777       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
14778       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
14779         SET_TMPL_ARGS_LEVEL (partial_args, i,
14780                              TMPL_ARGS_LEVEL (targs, i));
14781       SET_TMPL_ARGS_LEVEL (partial_args,
14782                            TMPL_ARGS_DEPTH (targs),
14783                            make_tree_vec (DECL_NTPARMS (tmpl)));
14784
14785       /* Disable access control as this function is used only during
14786          name-mangling.  */
14787       save_access_control = flag_access_control;
14788       flag_access_control = 0;
14789
14790       ++processing_template_decl;
14791       /* Now, do the (partial) substitution to figure out the
14792          appropriate function type.  */
14793       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
14794       --processing_template_decl;
14795
14796       /* Substitute into the template parameters to obtain the real
14797          innermost set of parameters.  This step is important if the
14798          innermost set of template parameters contains value
14799          parameters whose types depend on outer template parameters.  */
14800       TREE_VEC_LENGTH (partial_args)--;
14801       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
14802
14803       flag_access_control = save_access_control;
14804     }
14805
14806   return fn_type;
14807 }
14808
14809 /* Return truthvalue if we're processing a template different from
14810    the last one involved in diagnostics.  */
14811 int
14812 problematic_instantiation_changed (void)
14813 {
14814   return last_template_error_tick != tinst_level_tick;
14815 }
14816
14817 /* Remember current template involved in diagnostics.  */
14818 void
14819 record_last_problematic_instantiation (void)
14820 {
14821   last_template_error_tick = tinst_level_tick;
14822 }
14823
14824 struct tinst_level *
14825 current_instantiation (void)
14826 {
14827   return current_tinst_level;
14828 }
14829
14830 /* [temp.param] Check that template non-type parm TYPE is of an allowable
14831    type. Return zero for ok, nonzero for disallowed. Issue error and
14832    warning messages under control of COMPLAIN.  */
14833
14834 static int
14835 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
14836 {
14837   if (INTEGRAL_TYPE_P (type))
14838     return 0;
14839   else if (POINTER_TYPE_P (type))
14840     return 0;
14841   else if (TYPE_PTR_TO_MEMBER_P (type))
14842     return 0;
14843   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
14844     return 0;
14845   else if (TREE_CODE (type) == TYPENAME_TYPE)
14846     return 0;
14847
14848   if (complain & tf_error)
14849     error ("%q#T is not a valid type for a template constant parameter", type);
14850   return 1;
14851 }
14852
14853 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
14854    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
14855
14856 static bool
14857 dependent_type_p_r (tree type)
14858 {
14859   tree scope;
14860
14861   /* [temp.dep.type]
14862
14863      A type is dependent if it is:
14864
14865      -- a template parameter. Template template parameters are types
14866         for us (since TYPE_P holds true for them) so we handle
14867         them here.  */
14868   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
14869       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
14870     return true;
14871   /* -- a qualified-id with a nested-name-specifier which contains a
14872         class-name that names a dependent type or whose unqualified-id
14873         names a dependent type.  */
14874   if (TREE_CODE (type) == TYPENAME_TYPE)
14875     return true;
14876   /* -- a cv-qualified type where the cv-unqualified type is
14877         dependent.  */
14878   type = TYPE_MAIN_VARIANT (type);
14879   /* -- a compound type constructed from any dependent type.  */
14880   if (TYPE_PTR_TO_MEMBER_P (type))
14881     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
14882             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
14883                                            (type)));
14884   else if (TREE_CODE (type) == POINTER_TYPE
14885            || TREE_CODE (type) == REFERENCE_TYPE)
14886     return dependent_type_p (TREE_TYPE (type));
14887   else if (TREE_CODE (type) == FUNCTION_TYPE
14888            || TREE_CODE (type) == METHOD_TYPE)
14889     {
14890       tree arg_type;
14891
14892       if (dependent_type_p (TREE_TYPE (type)))
14893         return true;
14894       for (arg_type = TYPE_ARG_TYPES (type);
14895            arg_type;
14896            arg_type = TREE_CHAIN (arg_type))
14897         if (dependent_type_p (TREE_VALUE (arg_type)))
14898           return true;
14899       return false;
14900     }
14901   /* -- an array type constructed from any dependent type or whose
14902         size is specified by a constant expression that is
14903         value-dependent.  */
14904   if (TREE_CODE (type) == ARRAY_TYPE)
14905     {
14906       if (TYPE_DOMAIN (type)
14907           && ((value_dependent_expression_p
14908                (TYPE_MAX_VALUE (TYPE_DOMAIN (type))))
14909               || (type_dependent_expression_p
14910                   (TYPE_MAX_VALUE (TYPE_DOMAIN (type))))))
14911         return true;
14912       return dependent_type_p (TREE_TYPE (type));
14913     }
14914
14915   /* -- a template-id in which either the template name is a template
14916      parameter ...  */
14917   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
14918     return true;
14919   /* ... or any of the template arguments is a dependent type or
14920         an expression that is type-dependent or value-dependent.  */
14921   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
14922            && (any_dependent_template_arguments_p
14923                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
14924     return true;
14925
14926   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
14927      argument of the `typeof' expression is not type-dependent, then
14928      it should already been have resolved.  */
14929   if (TREE_CODE (type) == TYPEOF_TYPE
14930       || TREE_CODE (type) == DECLTYPE_TYPE)
14931     return true;
14932
14933   /* A template argument pack is dependent if any of its packed
14934      arguments are.  */
14935   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
14936     {
14937       tree args = ARGUMENT_PACK_ARGS (type);
14938       int i, len = TREE_VEC_LENGTH (args);
14939       for (i = 0; i < len; ++i)
14940         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
14941           return true;
14942     }
14943
14944   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
14945      be template parameters.  */
14946   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
14947     return true;
14948
14949   /* The standard does not specifically mention types that are local
14950      to template functions or local classes, but they should be
14951      considered dependent too.  For example:
14952
14953        template <int I> void f() {
14954          enum E { a = I };
14955          S<sizeof (E)> s;
14956        }
14957
14958      The size of `E' cannot be known until the value of `I' has been
14959      determined.  Therefore, `E' must be considered dependent.  */
14960   scope = TYPE_CONTEXT (type);
14961   if (scope && TYPE_P (scope))
14962     return dependent_type_p (scope);
14963   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
14964     return type_dependent_expression_p (scope);
14965
14966   /* Other types are non-dependent.  */
14967   return false;
14968 }
14969
14970 /* Returns TRUE if TYPE is dependent, in the sense of
14971    [temp.dep.type].  */
14972
14973 bool
14974 dependent_type_p (tree type)
14975 {
14976   /* If there are no template parameters in scope, then there can't be
14977      any dependent types.  */
14978   if (!processing_template_decl)
14979     {
14980       /* If we are not processing a template, then nobody should be
14981          providing us with a dependent type.  */
14982       gcc_assert (type);
14983       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM);
14984       return false;
14985     }
14986
14987   /* If the type is NULL, we have not computed a type for the entity
14988      in question; in that case, the type is dependent.  */
14989   if (!type)
14990     return true;
14991
14992   /* Erroneous types can be considered non-dependent.  */
14993   if (type == error_mark_node)
14994     return false;
14995
14996   /* If we have not already computed the appropriate value for TYPE,
14997      do so now.  */
14998   if (!TYPE_DEPENDENT_P_VALID (type))
14999     {
15000       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
15001       TYPE_DEPENDENT_P_VALID (type) = 1;
15002     }
15003
15004   return TYPE_DEPENDENT_P (type);
15005 }
15006
15007 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
15008
15009 static bool
15010 dependent_scope_ref_p (tree expression, bool criterion (tree))
15011 {
15012   tree scope;
15013   tree name;
15014
15015   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
15016
15017   if (!TYPE_P (TREE_OPERAND (expression, 0)))
15018     return true;
15019
15020   scope = TREE_OPERAND (expression, 0);
15021   name = TREE_OPERAND (expression, 1);
15022
15023   /* [temp.dep.expr]
15024
15025      An id-expression is type-dependent if it contains a
15026      nested-name-specifier that contains a class-name that names a
15027      dependent type.  */
15028   /* The suggested resolution to Core Issue 2 implies that if the
15029      qualifying type is the current class, then we must peek
15030      inside it.  */
15031   if (DECL_P (name)
15032       && currently_open_class (scope)
15033       && !criterion (name))
15034     return false;
15035   if (dependent_type_p (scope))
15036     return true;
15037
15038   return false;
15039 }
15040
15041 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
15042    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
15043    expression.  */
15044
15045 bool
15046 value_dependent_expression_p (tree expression)
15047 {
15048   if (!processing_template_decl)
15049     return false;
15050
15051   /* A name declared with a dependent type.  */
15052   if (DECL_P (expression) && type_dependent_expression_p (expression))
15053     return true;
15054
15055   switch (TREE_CODE (expression))
15056     {
15057     case IDENTIFIER_NODE:
15058       /* A name that has not been looked up -- must be dependent.  */
15059       return true;
15060
15061     case TEMPLATE_PARM_INDEX:
15062       /* A non-type template parm.  */
15063       return true;
15064
15065     case CONST_DECL:
15066       /* A non-type template parm.  */
15067       if (DECL_TEMPLATE_PARM_P (expression))
15068         return true;
15069       return false;
15070
15071     case VAR_DECL:
15072        /* A constant with integral or enumeration type and is initialized
15073           with an expression that is value-dependent.  */
15074       if (DECL_INITIAL (expression)
15075           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
15076           && value_dependent_expression_p (DECL_INITIAL (expression)))
15077         return true;
15078       return false;
15079
15080     case DYNAMIC_CAST_EXPR:
15081     case STATIC_CAST_EXPR:
15082     case CONST_CAST_EXPR:
15083     case REINTERPRET_CAST_EXPR:
15084     case CAST_EXPR:
15085       /* These expressions are value-dependent if the type to which
15086          the cast occurs is dependent or the expression being casted
15087          is value-dependent.  */
15088       {
15089         tree type = TREE_TYPE (expression);
15090
15091         if (dependent_type_p (type))
15092           return true;
15093
15094         /* A functional cast has a list of operands.  */
15095         expression = TREE_OPERAND (expression, 0);
15096         if (!expression)
15097           {
15098             /* If there are no operands, it must be an expression such
15099                as "int()". This should not happen for aggregate types
15100                because it would form non-constant expressions.  */
15101             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
15102
15103             return false;
15104           }
15105
15106         if (TREE_CODE (expression) == TREE_LIST)
15107           return any_value_dependent_elements_p (expression);
15108
15109         return value_dependent_expression_p (expression);
15110       }
15111
15112     case SIZEOF_EXPR:
15113     case ALIGNOF_EXPR:
15114       /* A `sizeof' expression is value-dependent if the operand is
15115          type-dependent or is a pack expansion.  */
15116       expression = TREE_OPERAND (expression, 0);
15117       if (PACK_EXPANSION_P (expression))
15118         return true;
15119       else if (TYPE_P (expression))
15120         return dependent_type_p (expression);
15121       return type_dependent_expression_p (expression);
15122
15123     case SCOPE_REF:
15124       return dependent_scope_ref_p (expression, value_dependent_expression_p);
15125
15126     case COMPONENT_REF:
15127       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
15128               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
15129
15130     case CALL_EXPR:
15131       /* A CALL_EXPR may appear in a constant expression if it is a
15132          call to a builtin function, e.g., __builtin_constant_p.  All
15133          such calls are value-dependent.  */
15134       return true;
15135
15136     case NONTYPE_ARGUMENT_PACK:
15137       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
15138          is value-dependent.  */
15139       {
15140         tree values = ARGUMENT_PACK_ARGS (expression);
15141         int i, len = TREE_VEC_LENGTH (values);
15142         
15143         for (i = 0; i < len; ++i)
15144           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
15145             return true;
15146         
15147         return false;
15148       }
15149
15150     case TRAIT_EXPR:
15151       {
15152         tree type2 = TRAIT_EXPR_TYPE2 (expression);
15153         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
15154                 || (type2 ? dependent_type_p (type2) : false));
15155       }
15156
15157     case MODOP_EXPR:
15158       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
15159               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
15160
15161     default:
15162       /* A constant expression is value-dependent if any subexpression is
15163          value-dependent.  */
15164       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
15165         {
15166         case tcc_reference:
15167         case tcc_unary:
15168           return (value_dependent_expression_p
15169                   (TREE_OPERAND (expression, 0)));
15170
15171         case tcc_comparison:
15172         case tcc_binary:
15173           return ((value_dependent_expression_p
15174                    (TREE_OPERAND (expression, 0)))
15175                   || (value_dependent_expression_p
15176                       (TREE_OPERAND (expression, 1))));
15177
15178         case tcc_expression:
15179         case tcc_vl_exp:
15180           {
15181             int i;
15182             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
15183               /* In some cases, some of the operands may be missing.
15184                  (For example, in the case of PREDECREMENT_EXPR, the
15185                  amount to increment by may be missing.)  That doesn't
15186                  make the expression dependent.  */
15187               if (TREE_OPERAND (expression, i)
15188                   && (value_dependent_expression_p
15189                       (TREE_OPERAND (expression, i))))
15190                 return true;
15191             return false;
15192           }
15193
15194         default:
15195           break;
15196         }
15197     }
15198
15199   /* The expression is not value-dependent.  */
15200   return false;
15201 }
15202
15203 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
15204    [temp.dep.expr].  */
15205
15206 bool
15207 type_dependent_expression_p (tree expression)
15208 {
15209   if (!processing_template_decl)
15210     return false;
15211
15212   if (expression == error_mark_node)
15213     return false;
15214
15215   /* An unresolved name is always dependent.  */
15216   if (TREE_CODE (expression) == IDENTIFIER_NODE
15217       || TREE_CODE (expression) == USING_DECL)
15218     return true;
15219
15220   /* Some expression forms are never type-dependent.  */
15221   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
15222       || TREE_CODE (expression) == SIZEOF_EXPR
15223       || TREE_CODE (expression) == ALIGNOF_EXPR
15224       || TREE_CODE (expression) == TRAIT_EXPR
15225       || TREE_CODE (expression) == TYPEID_EXPR
15226       || TREE_CODE (expression) == DELETE_EXPR
15227       || TREE_CODE (expression) == VEC_DELETE_EXPR
15228       || TREE_CODE (expression) == THROW_EXPR)
15229     return false;
15230
15231   /* The types of these expressions depends only on the type to which
15232      the cast occurs.  */
15233   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
15234       || TREE_CODE (expression) == STATIC_CAST_EXPR
15235       || TREE_CODE (expression) == CONST_CAST_EXPR
15236       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
15237       || TREE_CODE (expression) == CAST_EXPR)
15238     return dependent_type_p (TREE_TYPE (expression));
15239
15240   /* The types of these expressions depends only on the type created
15241      by the expression.  */
15242   if (TREE_CODE (expression) == NEW_EXPR
15243       || TREE_CODE (expression) == VEC_NEW_EXPR)
15244     {
15245       /* For NEW_EXPR tree nodes created inside a template, either
15246          the object type itself or a TREE_LIST may appear as the
15247          operand 1.  */
15248       tree type = TREE_OPERAND (expression, 1);
15249       if (TREE_CODE (type) == TREE_LIST)
15250         /* This is an array type.  We need to check array dimensions
15251            as well.  */
15252         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
15253                || value_dependent_expression_p
15254                     (TREE_OPERAND (TREE_VALUE (type), 1));
15255       else
15256         return dependent_type_p (type);
15257     }
15258
15259   if (TREE_CODE (expression) == SCOPE_REF
15260       && dependent_scope_ref_p (expression,
15261                                 type_dependent_expression_p))
15262     return true;
15263
15264   if (TREE_CODE (expression) == FUNCTION_DECL
15265       && DECL_LANG_SPECIFIC (expression)
15266       && DECL_TEMPLATE_INFO (expression)
15267       && (any_dependent_template_arguments_p
15268           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
15269     return true;
15270
15271   if (TREE_CODE (expression) == TEMPLATE_DECL
15272       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
15273     return false;
15274
15275   if (TREE_TYPE (expression) == unknown_type_node)
15276     {
15277       if (TREE_CODE (expression) == ADDR_EXPR)
15278         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
15279       if (TREE_CODE (expression) == COMPONENT_REF
15280           || TREE_CODE (expression) == OFFSET_REF)
15281         {
15282           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
15283             return true;
15284           expression = TREE_OPERAND (expression, 1);
15285           if (TREE_CODE (expression) == IDENTIFIER_NODE)
15286             return false;
15287         }
15288       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
15289       if (TREE_CODE (expression) == SCOPE_REF)
15290         return false;
15291
15292       if (TREE_CODE (expression) == BASELINK)
15293         expression = BASELINK_FUNCTIONS (expression);
15294
15295       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
15296         {
15297           if (any_dependent_template_arguments_p
15298               (TREE_OPERAND (expression, 1)))
15299             return true;
15300           expression = TREE_OPERAND (expression, 0);
15301         }
15302       gcc_assert (TREE_CODE (expression) == OVERLOAD
15303                   || TREE_CODE (expression) == FUNCTION_DECL);
15304
15305       while (expression)
15306         {
15307           if (type_dependent_expression_p (OVL_CURRENT (expression)))
15308             return true;
15309           expression = OVL_NEXT (expression);
15310         }
15311       return false;
15312     }
15313
15314   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
15315
15316   return (dependent_type_p (TREE_TYPE (expression)));
15317 }
15318
15319 /* Returns TRUE if ARGS (a TREE_LIST of arguments to a function call)
15320    contains a type-dependent expression.  */
15321
15322 bool
15323 any_type_dependent_arguments_p (const_tree args)
15324 {
15325   while (args)
15326     {
15327       tree arg = TREE_VALUE (args);
15328
15329       if (type_dependent_expression_p (arg))
15330         return true;
15331       args = TREE_CHAIN (args);
15332     }
15333   return false;
15334 }
15335
15336 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
15337    expressions) contains any value-dependent expressions.  */
15338
15339 bool
15340 any_value_dependent_elements_p (const_tree list)
15341 {
15342   for (; list; list = TREE_CHAIN (list))
15343     if (value_dependent_expression_p (TREE_VALUE (list)))
15344       return true;
15345
15346   return false;
15347 }
15348
15349 /* Returns TRUE if the ARG (a template argument) is dependent.  */
15350
15351 bool
15352 dependent_template_arg_p (tree arg)
15353 {
15354   if (!processing_template_decl)
15355     return false;
15356
15357   if (TREE_CODE (arg) == TEMPLATE_DECL
15358       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
15359     return dependent_template_p (arg);
15360   else if (ARGUMENT_PACK_P (arg))
15361     {
15362       tree args = ARGUMENT_PACK_ARGS (arg);
15363       int i, len = TREE_VEC_LENGTH (args);
15364       for (i = 0; i < len; ++i)
15365         {
15366           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
15367             return true;
15368         }
15369
15370       return false;
15371     }
15372   else if (TYPE_P (arg))
15373     return dependent_type_p (arg);
15374   else
15375     return (type_dependent_expression_p (arg)
15376             || value_dependent_expression_p (arg));
15377 }
15378
15379 /* Returns true if ARGS (a collection of template arguments) contains
15380    any types that require structural equality testing.  */
15381
15382 bool
15383 any_template_arguments_need_structural_equality_p (tree args)
15384 {
15385   int i;
15386   int j;
15387
15388   if (!args)
15389     return false;
15390   if (args == error_mark_node)
15391     return true;
15392
15393   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
15394     {
15395       tree level = TMPL_ARGS_LEVEL (args, i + 1);
15396       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
15397         {
15398           tree arg = TREE_VEC_ELT (level, j);
15399           tree packed_args = NULL_TREE;
15400           int k, len = 1;
15401
15402           if (ARGUMENT_PACK_P (arg))
15403             {
15404               /* Look inside the argument pack.  */
15405               packed_args = ARGUMENT_PACK_ARGS (arg);
15406               len = TREE_VEC_LENGTH (packed_args);
15407             }
15408
15409           for (k = 0; k < len; ++k)
15410             {
15411               if (packed_args)
15412                 arg = TREE_VEC_ELT (packed_args, k);
15413
15414               if (error_operand_p (arg))
15415                 return true;
15416               else if (TREE_CODE (arg) == TEMPLATE_DECL
15417                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
15418                 continue;
15419               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
15420                 return true;
15421               else if (!TYPE_P (arg) && TREE_TYPE (arg)
15422                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
15423                 return true;
15424             }
15425         }
15426     }
15427
15428   return false;
15429 }
15430
15431 /* Returns true if ARGS (a collection of template arguments) contains
15432    any dependent arguments.  */
15433
15434 bool
15435 any_dependent_template_arguments_p (const_tree args)
15436 {
15437   int i;
15438   int j;
15439
15440   if (!args)
15441     return false;
15442   if (args == error_mark_node)
15443     return true;
15444
15445   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
15446     {
15447       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
15448       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
15449         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
15450           return true;
15451     }
15452
15453   return false;
15454 }
15455
15456 /* Returns TRUE if the template TMPL is dependent.  */
15457
15458 bool
15459 dependent_template_p (tree tmpl)
15460 {
15461   if (TREE_CODE (tmpl) == OVERLOAD)
15462     {
15463       while (tmpl)
15464         {
15465           if (dependent_template_p (OVL_FUNCTION (tmpl)))
15466             return true;
15467           tmpl = OVL_CHAIN (tmpl);
15468         }
15469       return false;
15470     }
15471
15472   /* Template template parameters are dependent.  */
15473   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
15474       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
15475     return true;
15476   /* So are names that have not been looked up.  */
15477   if (TREE_CODE (tmpl) == SCOPE_REF
15478       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
15479     return true;
15480   /* So are member templates of dependent classes.  */
15481   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
15482     return dependent_type_p (DECL_CONTEXT (tmpl));
15483   return false;
15484 }
15485
15486 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
15487
15488 bool
15489 dependent_template_id_p (tree tmpl, tree args)
15490 {
15491   return (dependent_template_p (tmpl)
15492           || any_dependent_template_arguments_p (args));
15493 }
15494
15495 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
15496    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
15497    no such TYPE can be found.  Note that this function peers inside
15498    uninstantiated templates and therefore should be used only in
15499    extremely limited situations.  ONLY_CURRENT_P restricts this
15500    peering to the currently open classes hierarchy (which is required
15501    when comparing types).  */
15502
15503 tree
15504 resolve_typename_type (tree type, bool only_current_p)
15505 {
15506   tree scope;
15507   tree name;
15508   tree decl;
15509   int quals;
15510   tree pushed_scope;
15511   tree result;
15512
15513   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
15514
15515   scope = TYPE_CONTEXT (type);
15516   name = TYPE_IDENTIFIER (type);
15517
15518   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
15519      it first before we can figure out what NAME refers to.  */
15520   if (TREE_CODE (scope) == TYPENAME_TYPE)
15521     scope = resolve_typename_type (scope, only_current_p);
15522   /* If we don't know what SCOPE refers to, then we cannot resolve the
15523      TYPENAME_TYPE.  */
15524   if (TREE_CODE (scope) == TYPENAME_TYPE)
15525     return type;
15526   /* If the SCOPE is a template type parameter, we have no way of
15527      resolving the name.  */
15528   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
15529     return type;
15530   /* If the SCOPE is not the current instantiation, there's no reason
15531      to look inside it.  */
15532   if (only_current_p && !currently_open_class (scope))
15533     return type;
15534   /* If SCOPE is a partial instantiation, it will not have a valid
15535      TYPE_FIELDS list, so use the original template.  */
15536   scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
15537   /* Enter the SCOPE so that name lookup will be resolved as if we
15538      were in the class definition.  In particular, SCOPE will no
15539      longer be considered a dependent type.  */
15540   pushed_scope = push_scope (scope);
15541   /* Look up the declaration.  */
15542   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
15543
15544   result = NULL_TREE;
15545   
15546   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
15547      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
15548   if (!decl)
15549     /*nop*/;
15550   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
15551            && TREE_CODE (decl) == TYPE_DECL)
15552     {
15553       result = TREE_TYPE (decl);
15554       if (result == error_mark_node)
15555         result = NULL_TREE;
15556     }
15557   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
15558            && DECL_CLASS_TEMPLATE_P (decl))
15559     {
15560       tree tmpl;
15561       tree args;
15562       /* Obtain the template and the arguments.  */
15563       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
15564       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
15565       /* Instantiate the template.  */
15566       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
15567                                       /*entering_scope=*/0,
15568                                       tf_error | tf_user);
15569       if (result == error_mark_node)
15570         result = NULL_TREE;
15571     }
15572   
15573   /* Leave the SCOPE.  */
15574   if (pushed_scope)
15575     pop_scope (pushed_scope);
15576
15577   /* If we failed to resolve it, return the original typename.  */
15578   if (!result)
15579     return type;
15580   
15581   /* If lookup found a typename type, resolve that too.  */
15582   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
15583     {
15584       /* Ill-formed programs can cause infinite recursion here, so we
15585          must catch that.  */
15586       TYPENAME_IS_RESOLVING_P (type) = 1;
15587       result = resolve_typename_type (result, only_current_p);
15588       TYPENAME_IS_RESOLVING_P (type) = 0;
15589     }
15590   
15591   /* Qualify the resulting type.  */
15592   quals = cp_type_quals (type);
15593   if (quals)
15594     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
15595
15596   return result;
15597 }
15598
15599 /* EXPR is an expression which is not type-dependent.  Return a proxy
15600    for EXPR that can be used to compute the types of larger
15601    expressions containing EXPR.  */
15602
15603 tree
15604 build_non_dependent_expr (tree expr)
15605 {
15606   tree inner_expr;
15607
15608   /* Preserve null pointer constants so that the type of things like
15609      "p == 0" where "p" is a pointer can be determined.  */
15610   if (null_ptr_cst_p (expr))
15611     return expr;
15612   /* Preserve OVERLOADs; the functions must be available to resolve
15613      types.  */
15614   inner_expr = expr;
15615   if (TREE_CODE (inner_expr) == ADDR_EXPR)
15616     inner_expr = TREE_OPERAND (inner_expr, 0);
15617   if (TREE_CODE (inner_expr) == COMPONENT_REF)
15618     inner_expr = TREE_OPERAND (inner_expr, 1);
15619   if (is_overloaded_fn (inner_expr)
15620       || TREE_CODE (inner_expr) == OFFSET_REF)
15621     return expr;
15622   /* There is no need to return a proxy for a variable.  */
15623   if (TREE_CODE (expr) == VAR_DECL)
15624     return expr;
15625   /* Preserve string constants; conversions from string constants to
15626      "char *" are allowed, even though normally a "const char *"
15627      cannot be used to initialize a "char *".  */
15628   if (TREE_CODE (expr) == STRING_CST)
15629     return expr;
15630   /* Preserve arithmetic constants, as an optimization -- there is no
15631      reason to create a new node.  */
15632   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
15633     return expr;
15634   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
15635      There is at least one place where we want to know that a
15636      particular expression is a throw-expression: when checking a ?:
15637      expression, there are special rules if the second or third
15638      argument is a throw-expression.  */
15639   if (TREE_CODE (expr) == THROW_EXPR)
15640     return expr;
15641
15642   if (TREE_CODE (expr) == COND_EXPR)
15643     return build3 (COND_EXPR,
15644                    TREE_TYPE (expr),
15645                    TREE_OPERAND (expr, 0),
15646                    (TREE_OPERAND (expr, 1)
15647                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
15648                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
15649                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
15650   if (TREE_CODE (expr) == COMPOUND_EXPR
15651       && !COMPOUND_EXPR_OVERLOADED (expr))
15652     return build2 (COMPOUND_EXPR,
15653                    TREE_TYPE (expr),
15654                    TREE_OPERAND (expr, 0),
15655                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
15656
15657   /* If the type is unknown, it can't really be non-dependent */
15658   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
15659
15660   /* Otherwise, build a NON_DEPENDENT_EXPR.
15661
15662      REFERENCE_TYPEs are not stripped for expressions in templates
15663      because doing so would play havoc with mangling.  Consider, for
15664      example:
15665
15666        template <typename T> void f<T& g>() { g(); }
15667
15668      In the body of "f", the expression for "g" will have
15669      REFERENCE_TYPE, even though the standard says that it should
15670      not.  The reason is that we must preserve the syntactic form of
15671      the expression so that mangling (say) "f<g>" inside the body of
15672      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
15673      stripped here.  */
15674   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
15675 }
15676
15677 /* ARGS is a TREE_LIST of expressions as arguments to a function call.
15678    Return a new TREE_LIST with the various arguments replaced with
15679    equivalent non-dependent expressions.  */
15680
15681 tree
15682 build_non_dependent_args (tree args)
15683 {
15684   tree a;
15685   tree new_args;
15686
15687   new_args = NULL_TREE;
15688   for (a = args; a; a = TREE_CHAIN (a))
15689     new_args = tree_cons (NULL_TREE,
15690                           build_non_dependent_expr (TREE_VALUE (a)),
15691                           new_args);
15692   return nreverse (new_args);
15693 }
15694
15695 #include "gt-cp-pt.h"