OSDN Git Service

d918d86a2f39e59ce163cbef4c095528921b0aa3
[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 /* The inverse of get_innermost_template_args: Return all but the innermost
523    EXTRA_LEVELS levels of template arguments from the ARGS.  */
524
525 static tree
526 strip_innermost_template_args (tree args, int extra_levels)
527 {
528   tree new_args;
529   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
530   int i;
531
532   gcc_assert (n >= 0);
533
534   /* If N is 1, just return the outermost set of template arguments.  */
535   if (n == 1)
536     return TMPL_ARGS_LEVEL (args, 1);
537
538   /* If we're not removing anything, just return the arguments we were
539      given.  */
540   gcc_assert (extra_levels >= 0);
541   if (extra_levels == 0)
542     return args;
543
544   /* Make a new set of arguments, not containing the inner arguments.  */
545   new_args = make_tree_vec (n);
546   for (i = 1; i <= n; ++i)
547     SET_TMPL_ARGS_LEVEL (new_args, i,
548                          TMPL_ARGS_LEVEL (args, i));
549
550   return new_args;
551 }
552
553 /* We've got a template header coming up; push to a new level for storing
554    the parms.  */
555
556 void
557 begin_template_parm_list (void)
558 {
559   /* We use a non-tag-transparent scope here, which causes pushtag to
560      put tags in this scope, rather than in the enclosing class or
561      namespace scope.  This is the right thing, since we want
562      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
563      global template class, push_template_decl handles putting the
564      TEMPLATE_DECL into top-level scope.  For a nested template class,
565      e.g.:
566
567        template <class T> struct S1 {
568          template <class T> struct S2 {};
569        };
570
571      pushtag contains special code to call pushdecl_with_scope on the
572      TEMPLATE_DECL for S2.  */
573   begin_scope (sk_template_parms, NULL);
574   ++processing_template_decl;
575   ++processing_template_parmlist;
576   note_template_header (0);
577 }
578
579 /* This routine is called when a specialization is declared.  If it is
580    invalid to declare a specialization here, an error is reported and
581    false is returned, otherwise this routine will return true.  */
582
583 static bool
584 check_specialization_scope (void)
585 {
586   tree scope = current_scope ();
587
588   /* [temp.expl.spec]
589
590      An explicit specialization shall be declared in the namespace of
591      which the template is a member, or, for member templates, in the
592      namespace of which the enclosing class or enclosing class
593      template is a member.  An explicit specialization of a member
594      function, member class or static data member of a class template
595      shall be declared in the namespace of which the class template
596      is a member.  */
597   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
598     {
599       error ("explicit specialization in non-namespace scope %qD", scope);
600       return false;
601     }
602
603   /* [temp.expl.spec]
604
605      In an explicit specialization declaration for a member of a class
606      template or a member template that appears in namespace scope,
607      the member template and some of its enclosing class templates may
608      remain unspecialized, except that the declaration shall not
609      explicitly specialize a class member template if its enclosing
610      class templates are not explicitly specialized as well.  */
611   if (current_template_parms)
612     {
613       error ("enclosing class templates are not explicitly specialized");
614       return false;
615     }
616
617   return true;
618 }
619
620 /* We've just seen template <>.  */
621
622 bool
623 begin_specialization (void)
624 {
625   begin_scope (sk_template_spec, NULL);
626   note_template_header (1);
627   return check_specialization_scope ();
628 }
629
630 /* Called at then end of processing a declaration preceded by
631    template<>.  */
632
633 void
634 end_specialization (void)
635 {
636   finish_scope ();
637   reset_specialization ();
638 }
639
640 /* Any template <>'s that we have seen thus far are not referring to a
641    function specialization.  */
642
643 void
644 reset_specialization (void)
645 {
646   processing_specialization = 0;
647   template_header_count = 0;
648 }
649
650 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
651    it was of the form template <>.  */
652
653 static void
654 note_template_header (int specialization)
655 {
656   processing_specialization = specialization;
657   template_header_count++;
658 }
659
660 /* We're beginning an explicit instantiation.  */
661
662 void
663 begin_explicit_instantiation (void)
664 {
665   gcc_assert (!processing_explicit_instantiation);
666   processing_explicit_instantiation = true;
667 }
668
669
670 void
671 end_explicit_instantiation (void)
672 {
673   gcc_assert (processing_explicit_instantiation);
674   processing_explicit_instantiation = false;
675 }
676
677 /* An explicit specialization or partial specialization TMPL is being
678    declared.  Check that the namespace in which the specialization is
679    occurring is permissible.  Returns false iff it is invalid to
680    specialize TMPL in the current namespace.  */
681
682 static bool
683 check_specialization_namespace (tree tmpl)
684 {
685   tree tpl_ns = decl_namespace_context (tmpl);
686
687   /* [tmpl.expl.spec]
688
689      An explicit specialization shall be declared in the namespace of
690      which the template is a member, or, for member templates, in the
691      namespace of which the enclosing class or enclosing class
692      template is a member.  An explicit specialization of a member
693      function, member class or static data member of a class template
694      shall be declared in the namespace of which the class template is
695      a member.  */
696   if (is_associated_namespace (current_namespace, tpl_ns))
697     /* Same or super-using namespace.  */
698     return true;
699   else
700     {
701       pedwarn ("specialization of %qD in different namespace", tmpl);
702       pedwarn ("  from definition of %q+#D", tmpl);
703       return false;
704     }
705 }
706
707 /* SPEC is an explicit instantiation.  Check that it is valid to
708    perform this explicit instantiation in the current namespace.  */
709
710 static void
711 check_explicit_instantiation_namespace (tree spec)
712 {
713   tree ns;
714
715   /* DR 275: An explicit instantiation shall appear in an enclosing
716      namespace of its template.  */
717   ns = decl_namespace_context (spec);
718   if (!is_ancestor (current_namespace, ns))
719     pedwarn ("explicit instantiation of %qD in namespace %qD "
720              "(which does not enclose namespace %qD)",
721              spec, current_namespace, ns);
722 }
723
724 /* The TYPE is being declared.  If it is a template type, that means it
725    is a partial specialization.  Do appropriate error-checking.  */
726
727 tree
728 maybe_process_partial_specialization (tree type)
729 {
730   tree context;
731
732   if (type == error_mark_node)
733     return error_mark_node;
734
735   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
736     {
737       error ("name of class shadows template template parameter %qD",
738              TYPE_NAME (type));
739       return error_mark_node;
740     }
741
742   context = TYPE_CONTEXT (type);
743
744   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
745     {
746       /* This is for ordinary explicit specialization and partial
747          specialization of a template class such as:
748
749            template <> class C<int>;
750
751          or:
752
753            template <class T> class C<T*>;
754
755          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
756
757       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
758           && !COMPLETE_TYPE_P (type))
759         {
760           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
761           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
762           if (processing_template_decl)
763             push_template_decl (TYPE_MAIN_DECL (type));
764         }
765       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
766         error ("specialization of %qT after instantiation", type);
767     }
768   else if (CLASS_TYPE_P (type)
769            && !CLASSTYPE_USE_TEMPLATE (type)
770            && CLASSTYPE_TEMPLATE_INFO (type)
771            && context && CLASS_TYPE_P (context)
772            && CLASSTYPE_TEMPLATE_INFO (context))
773     {
774       /* This is for an explicit specialization of member class
775          template according to [temp.expl.spec/18]:
776
777            template <> template <class U> class C<int>::D;
778
779          The context `C<int>' must be an implicit instantiation.
780          Otherwise this is just a member class template declared
781          earlier like:
782
783            template <> class C<int> { template <class U> class D; };
784            template <> template <class U> class C<int>::D;
785
786          In the first case, `C<int>::D' is a specialization of `C<T>::D'
787          while in the second case, `C<int>::D' is a primary template
788          and `C<T>::D' may not exist.  */
789
790       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
791           && !COMPLETE_TYPE_P (type))
792         {
793           tree t;
794
795           if (current_namespace
796               != decl_namespace_context (CLASSTYPE_TI_TEMPLATE (type)))
797             {
798               pedwarn ("specializing %q#T in different namespace", type);
799               pedwarn ("  from definition of %q+#D",
800                        CLASSTYPE_TI_TEMPLATE (type));
801             }
802
803           /* Check for invalid specialization after instantiation:
804
805                template <> template <> class C<int>::D<int>;
806                template <> template <class U> class C<int>::D;  */
807
808           for (t = DECL_TEMPLATE_INSTANTIATIONS
809                  (most_general_template (CLASSTYPE_TI_TEMPLATE (type)));
810                t; t = TREE_CHAIN (t))
811             if (TREE_VALUE (t) != type
812                 && TYPE_CONTEXT (TREE_VALUE (t)) == context)
813               error ("specialization %qT after instantiation %qT",
814                      type, TREE_VALUE (t));
815
816           /* Mark TYPE as a specialization.  And as a result, we only
817              have one level of template argument for the innermost
818              class template.  */
819           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
820           CLASSTYPE_TI_ARGS (type)
821             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
822         }
823     }
824   else if (processing_specialization)
825     {
826       error ("explicit specialization of non-template %qT", type);
827       return error_mark_node;
828     }
829
830   return type;
831 }
832
833 /* Returns nonzero if we can optimize the retrieval of specializations
834    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
835    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
836
837 static inline bool
838 optimize_specialization_lookup_p (tree tmpl)
839 {
840   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
841           && DECL_CLASS_SCOPE_P (tmpl)
842           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
843              parameter.  */
844           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
845           /* The optimized lookup depends on the fact that the
846              template arguments for the member function template apply
847              purely to the containing class, which is not true if the
848              containing class is an explicit or partial
849              specialization.  */
850           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
851           && !DECL_MEMBER_TEMPLATE_P (tmpl)
852           && !DECL_CONV_FN_P (tmpl)
853           /* It is possible to have a template that is not a member
854              template and is not a member of a template class:
855
856              template <typename T>
857              struct S { friend A::f(); };
858
859              Here, the friend function is a template, but the context does
860              not have template information.  The optimized lookup relies
861              on having ARGS be the template arguments for both the class
862              and the function template.  */
863           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
864 }
865
866 /* Retrieve the specialization (in the sense of [temp.spec] - a
867    specialization is either an instantiation or an explicit
868    specialization) of TMPL for the given template ARGS.  If there is
869    no such specialization, return NULL_TREE.  The ARGS are a vector of
870    arguments, or a vector of vectors of arguments, in the case of
871    templates with more than one level of parameters.
872
873    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
874    then we search for a partial specialization matching ARGS.  This
875    parameter is ignored if TMPL is not a class template.  */
876
877 static tree
878 retrieve_specialization (tree tmpl, tree args,
879                          bool class_specializations_p)
880 {
881   if (args == error_mark_node)
882     return NULL_TREE;
883
884   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
885
886   /* There should be as many levels of arguments as there are
887      levels of parameters.  */
888   gcc_assert (TMPL_ARGS_DEPTH (args)
889               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
890
891   if (optimize_specialization_lookup_p (tmpl))
892     {
893       tree class_template;
894       tree class_specialization;
895       VEC(tree,gc) *methods;
896       tree fns;
897       int idx;
898
899       /* The template arguments actually apply to the containing
900          class.  Find the class specialization with those
901          arguments.  */
902       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
903       class_specialization
904         = retrieve_specialization (class_template, args,
905                                    /*class_specializations_p=*/false);
906       if (!class_specialization)
907         return NULL_TREE;
908       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
909          for the specialization.  */
910       idx = class_method_index_for_fn (class_specialization, tmpl);
911       if (idx == -1)
912         return NULL_TREE;
913       /* Iterate through the methods with the indicated name, looking
914          for the one that has an instance of TMPL.  */
915       methods = CLASSTYPE_METHOD_VEC (class_specialization);
916       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
917         {
918           tree fn = OVL_CURRENT (fns);
919           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl)
920             return fn;
921         }
922       return NULL_TREE;
923     }
924   else
925     {
926       tree *sp;
927       tree *head;
928
929       /* Class templates store their instantiations on the
930          DECL_TEMPLATE_INSTANTIATIONS list; other templates use the
931          DECL_TEMPLATE_SPECIALIZATIONS list.  */
932       if (!class_specializations_p
933           && TREE_CODE (DECL_TEMPLATE_RESULT (tmpl)) == TYPE_DECL)
934         sp = &DECL_TEMPLATE_INSTANTIATIONS (tmpl);
935       else
936         sp = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
937       head = sp;
938       /* Iterate through the list until we find a matching template.  */
939       while (*sp != NULL_TREE)
940         {
941           tree spec = *sp;
942
943           if (comp_template_args (TREE_PURPOSE (spec), args))
944             {
945               /* Use the move-to-front heuristic to speed up future
946                  searches.  */
947               if (spec != *head)
948                 {
949                   *sp = TREE_CHAIN (*sp);
950                   TREE_CHAIN (spec) = *head;
951                   *head = spec;
952                 }
953               return TREE_VALUE (spec);
954             }
955           sp = &TREE_CHAIN (spec);
956         }
957     }
958
959   return NULL_TREE;
960 }
961
962 /* Like retrieve_specialization, but for local declarations.  */
963
964 static tree
965 retrieve_local_specialization (tree tmpl)
966 {
967   tree spec = (tree) htab_find_with_hash (local_specializations, tmpl,
968                                           htab_hash_pointer (tmpl));
969   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
970 }
971
972 /* Returns nonzero iff DECL is a specialization of TMPL.  */
973
974 int
975 is_specialization_of (tree decl, tree tmpl)
976 {
977   tree t;
978
979   if (TREE_CODE (decl) == FUNCTION_DECL)
980     {
981       for (t = decl;
982            t != NULL_TREE;
983            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
984         if (t == tmpl)
985           return 1;
986     }
987   else
988     {
989       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
990
991       for (t = TREE_TYPE (decl);
992            t != NULL_TREE;
993            t = CLASSTYPE_USE_TEMPLATE (t)
994              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
995         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
996           return 1;
997     }
998
999   return 0;
1000 }
1001
1002 /* Returns nonzero iff DECL is a specialization of friend declaration
1003    FRIEND according to [temp.friend].  */
1004
1005 bool
1006 is_specialization_of_friend (tree decl, tree friend)
1007 {
1008   bool need_template = true;
1009   int template_depth;
1010
1011   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1012               || TREE_CODE (decl) == TYPE_DECL);
1013
1014   /* For [temp.friend/6] when FRIEND is an ordinary member function
1015      of a template class, we want to check if DECL is a specialization
1016      if this.  */
1017   if (TREE_CODE (friend) == FUNCTION_DECL
1018       && DECL_TEMPLATE_INFO (friend)
1019       && !DECL_USE_TEMPLATE (friend))
1020     {
1021       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1022       friend = DECL_TI_TEMPLATE (friend);
1023       need_template = false;
1024     }
1025   else if (TREE_CODE (friend) == TEMPLATE_DECL
1026            && !PRIMARY_TEMPLATE_P (friend))
1027     need_template = false;
1028
1029   /* There is nothing to do if this is not a template friend.  */
1030   if (TREE_CODE (friend) != TEMPLATE_DECL)
1031     return false;
1032
1033   if (is_specialization_of (decl, friend))
1034     return true;
1035
1036   /* [temp.friend/6]
1037      A member of a class template may be declared to be a friend of a
1038      non-template class.  In this case, the corresponding member of
1039      every specialization of the class template is a friend of the
1040      class granting friendship.
1041
1042      For example, given a template friend declaration
1043
1044        template <class T> friend void A<T>::f();
1045
1046      the member function below is considered a friend
1047
1048        template <> struct A<int> {
1049          void f();
1050        };
1051
1052      For this type of template friend, TEMPLATE_DEPTH below will be
1053      nonzero.  To determine if DECL is a friend of FRIEND, we first
1054      check if the enclosing class is a specialization of another.  */
1055
1056   template_depth = template_class_depth (DECL_CONTEXT (friend));
1057   if (template_depth
1058       && DECL_CLASS_SCOPE_P (decl)
1059       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1060                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend))))
1061     {
1062       /* Next, we check the members themselves.  In order to handle
1063          a few tricky cases, such as when FRIEND's are
1064
1065            template <class T> friend void A<T>::g(T t);
1066            template <class T> template <T t> friend void A<T>::h();
1067
1068          and DECL's are
1069
1070            void A<int>::g(int);
1071            template <int> void A<int>::h();
1072
1073          we need to figure out ARGS, the template arguments from
1074          the context of DECL.  This is required for template substitution
1075          of `T' in the function parameter of `g' and template parameter
1076          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1077
1078       tree context = DECL_CONTEXT (decl);
1079       tree args = NULL_TREE;
1080       int current_depth = 0;
1081
1082       while (current_depth < template_depth)
1083         {
1084           if (CLASSTYPE_TEMPLATE_INFO (context))
1085             {
1086               if (current_depth == 0)
1087                 args = TYPE_TI_ARGS (context);
1088               else
1089                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1090               current_depth++;
1091             }
1092           context = TYPE_CONTEXT (context);
1093         }
1094
1095       if (TREE_CODE (decl) == FUNCTION_DECL)
1096         {
1097           bool is_template;
1098           tree friend_type;
1099           tree decl_type;
1100           tree friend_args_type;
1101           tree decl_args_type;
1102
1103           /* Make sure that both DECL and FRIEND are templates or
1104              non-templates.  */
1105           is_template = DECL_TEMPLATE_INFO (decl)
1106                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1107           if (need_template ^ is_template)
1108             return false;
1109           else if (is_template)
1110             {
1111               /* If both are templates, check template parameter list.  */
1112               tree friend_parms
1113                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend),
1114                                          args, tf_none);
1115               if (!comp_template_parms
1116                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1117                       friend_parms))
1118                 return false;
1119
1120               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1121             }
1122           else
1123             decl_type = TREE_TYPE (decl);
1124
1125           friend_type = tsubst_function_type (TREE_TYPE (friend), args,
1126                                               tf_none, NULL_TREE);
1127           if (friend_type == error_mark_node)
1128             return false;
1129
1130           /* Check if return types match.  */
1131           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1132             return false;
1133
1134           /* Check if function parameter types match, ignoring the
1135              `this' parameter.  */
1136           friend_args_type = TYPE_ARG_TYPES (friend_type);
1137           decl_args_type = TYPE_ARG_TYPES (decl_type);
1138           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend))
1139             friend_args_type = TREE_CHAIN (friend_args_type);
1140           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1141             decl_args_type = TREE_CHAIN (decl_args_type);
1142
1143           return compparms (decl_args_type, friend_args_type);
1144         }
1145       else
1146         {
1147           /* DECL is a TYPE_DECL */
1148           bool is_template;
1149           tree decl_type = TREE_TYPE (decl);
1150
1151           /* Make sure that both DECL and FRIEND are templates or
1152              non-templates.  */
1153           is_template
1154             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1155               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1156
1157           if (need_template ^ is_template)
1158             return false;
1159           else if (is_template)
1160             {
1161               tree friend_parms;
1162               /* If both are templates, check the name of the two
1163                  TEMPLATE_DECL's first because is_friend didn't.  */
1164               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1165                   != DECL_NAME (friend))
1166                 return false;
1167
1168               /* Now check template parameter list.  */
1169               friend_parms
1170                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend),
1171                                          args, tf_none);
1172               return comp_template_parms
1173                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1174                  friend_parms);
1175             }
1176           else
1177             return (DECL_NAME (decl)
1178                     == DECL_NAME (friend));
1179         }
1180     }
1181   return false;
1182 }
1183
1184 /* Register the specialization SPEC as a specialization of TMPL with
1185    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1186    is actually just a friend declaration.  Returns SPEC, or an
1187    equivalent prior declaration, if available.  */
1188
1189 static tree
1190 register_specialization (tree spec, tree tmpl, tree args, bool is_friend)
1191 {
1192   tree fn;
1193
1194   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
1195
1196   if (TREE_CODE (spec) == FUNCTION_DECL
1197       && uses_template_parms (DECL_TI_ARGS (spec)))
1198     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1199        register it; we want the corresponding TEMPLATE_DECL instead.
1200        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1201        the more obvious `uses_template_parms (spec)' to avoid problems
1202        with default function arguments.  In particular, given
1203        something like this:
1204
1205           template <class T> void f(T t1, T t = T())
1206
1207        the default argument expression is not substituted for in an
1208        instantiation unless and until it is actually needed.  */
1209     return spec;
1210
1211   fn = retrieve_specialization (tmpl, args,
1212                                 /*class_specializations_p=*/false);
1213   /* We can sometimes try to re-register a specialization that we've
1214      already got.  In particular, regenerate_decl_from_template calls
1215      duplicate_decls which will update the specialization list.  But,
1216      we'll still get called again here anyhow.  It's more convenient
1217      to simply allow this than to try to prevent it.  */
1218   if (fn == spec)
1219     return spec;
1220   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1221     {
1222       if (DECL_TEMPLATE_INSTANTIATION (fn))
1223         {
1224           if (TREE_USED (fn)
1225               || DECL_EXPLICIT_INSTANTIATION (fn))
1226             {
1227               error ("specialization of %qD after instantiation",
1228                      fn);
1229               return error_mark_node;
1230             }
1231           else
1232             {
1233               tree clone;
1234               /* This situation should occur only if the first
1235                  specialization is an implicit instantiation, the
1236                  second is an explicit specialization, and the
1237                  implicit instantiation has not yet been used.  That
1238                  situation can occur if we have implicitly
1239                  instantiated a member function and then specialized
1240                  it later.
1241
1242                  We can also wind up here if a friend declaration that
1243                  looked like an instantiation turns out to be a
1244                  specialization:
1245
1246                    template <class T> void foo(T);
1247                    class S { friend void foo<>(int) };
1248                    template <> void foo(int);
1249
1250                  We transform the existing DECL in place so that any
1251                  pointers to it become pointers to the updated
1252                  declaration.
1253
1254                  If there was a definition for the template, but not
1255                  for the specialization, we want this to look as if
1256                  there were no definition, and vice versa.  */
1257               DECL_INITIAL (fn) = NULL_TREE;
1258               duplicate_decls (spec, fn, is_friend);
1259               /* The call to duplicate_decls will have applied
1260                  [temp.expl.spec]:
1261
1262                    An explicit specialization of a function template
1263                    is inline only if it is explicitly declared to be,
1264                    and independently of whether its function template
1265                    is.
1266
1267                 to the primary function; now copy the inline bits to
1268                 the various clones.  */
1269               FOR_EACH_CLONE (clone, fn)
1270                 {
1271                   DECL_DECLARED_INLINE_P (clone)
1272                     = DECL_DECLARED_INLINE_P (fn);
1273                   DECL_INLINE (clone)
1274                     = DECL_INLINE (fn);
1275                 }
1276               check_specialization_namespace (fn);
1277
1278               return fn;
1279             }
1280         }
1281       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1282         {
1283           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1284             /* Dup decl failed, but this is a new definition. Set the
1285                line number so any errors match this new
1286                definition.  */
1287             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1288
1289           return fn;
1290         }
1291     }
1292
1293   /* A specialization must be declared in the same namespace as the
1294      template it is specializing.  */
1295   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1296       && !check_specialization_namespace (tmpl))
1297     DECL_CONTEXT (spec) = FROB_CONTEXT (decl_namespace_context (tmpl));
1298
1299   if (!optimize_specialization_lookup_p (tmpl))
1300     DECL_TEMPLATE_SPECIALIZATIONS (tmpl)
1301       = tree_cons (args, spec, DECL_TEMPLATE_SPECIALIZATIONS (tmpl));
1302
1303   return spec;
1304 }
1305
1306 /* Unregister the specialization SPEC as a specialization of TMPL.
1307    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1308    if the SPEC was listed as a specialization of TMPL.  */
1309
1310 bool
1311 reregister_specialization (tree spec, tree tmpl, tree new_spec)
1312 {
1313   tree* s;
1314
1315   for (s = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
1316        *s != NULL_TREE;
1317        s = &TREE_CHAIN (*s))
1318     if (TREE_VALUE (*s) == spec)
1319       {
1320         if (!new_spec)
1321           *s = TREE_CHAIN (*s);
1322         else
1323           TREE_VALUE (*s) = new_spec;
1324         return 1;
1325       }
1326
1327   return 0;
1328 }
1329
1330 /* Compare an entry in the local specializations hash table P1 (which
1331    is really a pointer to a TREE_LIST) with P2 (which is really a
1332    DECL).  */
1333
1334 static int
1335 eq_local_specializations (const void *p1, const void *p2)
1336 {
1337   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1338 }
1339
1340 /* Hash P1, an entry in the local specializations table.  */
1341
1342 static hashval_t
1343 hash_local_specialization (const void* p1)
1344 {
1345   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1346 }
1347
1348 /* Like register_specialization, but for local declarations.  We are
1349    registering SPEC, an instantiation of TMPL.  */
1350
1351 static void
1352 register_local_specialization (tree spec, tree tmpl)
1353 {
1354   void **slot;
1355
1356   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1357                                    htab_hash_pointer (tmpl), INSERT);
1358   *slot = build_tree_list (spec, tmpl);
1359 }
1360
1361 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1362    specialized class.  */
1363
1364 bool
1365 explicit_class_specialization_p (tree type)
1366 {
1367   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1368     return false;
1369   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1370 }
1371
1372 /* Print the list of candidate FNS in an error message.  */
1373
1374 void
1375 print_candidates (tree fns)
1376 {
1377   tree fn;
1378
1379   const char *str = "candidates are:";
1380
1381   for (fn = fns; fn != NULL_TREE; fn = TREE_CHAIN (fn))
1382     {
1383       tree f;
1384
1385       for (f = TREE_VALUE (fn); f; f = OVL_NEXT (f))
1386         error ("%s %+#D", str, OVL_CURRENT (f));
1387       str = "               ";
1388     }
1389 }
1390
1391 /* Returns the template (one of the functions given by TEMPLATE_ID)
1392    which can be specialized to match the indicated DECL with the
1393    explicit template args given in TEMPLATE_ID.  The DECL may be
1394    NULL_TREE if none is available.  In that case, the functions in
1395    TEMPLATE_ID are non-members.
1396
1397    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1398    specialization of a member template.
1399
1400    The TEMPLATE_COUNT is the number of references to qualifying
1401    template classes that appeared in the name of the function. See
1402    check_explicit_specialization for a more accurate description.
1403
1404    TSK indicates what kind of template declaration (if any) is being
1405    declared.  TSK_TEMPLATE indicates that the declaration given by
1406    DECL, though a FUNCTION_DECL, has template parameters, and is
1407    therefore a template function.
1408
1409    The template args (those explicitly specified and those deduced)
1410    are output in a newly created vector *TARGS_OUT.
1411
1412    If it is impossible to determine the result, an error message is
1413    issued.  The error_mark_node is returned to indicate failure.  */
1414
1415 static tree
1416 determine_specialization (tree template_id,
1417                           tree decl,
1418                           tree* targs_out,
1419                           int need_member_template,
1420                           int template_count,
1421                           tmpl_spec_kind tsk)
1422 {
1423   tree fns;
1424   tree targs;
1425   tree explicit_targs;
1426   tree candidates = NULL_TREE;
1427   /* A TREE_LIST of templates of which DECL may be a specialization.
1428      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1429      corresponding TREE_PURPOSE is the set of template arguments that,
1430      when used to instantiate the template, would produce a function
1431      with the signature of DECL.  */
1432   tree templates = NULL_TREE;
1433   int header_count;
1434   struct cp_binding_level *b;
1435
1436   *targs_out = NULL_TREE;
1437
1438   if (template_id == error_mark_node || decl == error_mark_node)
1439     return error_mark_node;
1440
1441   fns = TREE_OPERAND (template_id, 0);
1442   explicit_targs = TREE_OPERAND (template_id, 1);
1443
1444   if (fns == error_mark_node)
1445     return error_mark_node;
1446
1447   /* Check for baselinks.  */
1448   if (BASELINK_P (fns))
1449     fns = BASELINK_FUNCTIONS (fns);
1450
1451   if (!is_overloaded_fn (fns))
1452     {
1453       error ("%qD is not a function template", fns);
1454       return error_mark_node;
1455     }
1456
1457   /* Count the number of template headers specified for this
1458      specialization.  */
1459   header_count = 0;
1460   for (b = current_binding_level;
1461        b->kind == sk_template_parms;
1462        b = b->level_chain)
1463     ++header_count;
1464
1465   for (; fns; fns = OVL_NEXT (fns))
1466     {
1467       tree fn = OVL_CURRENT (fns);
1468
1469       if (TREE_CODE (fn) == TEMPLATE_DECL)
1470         {
1471           tree decl_arg_types;
1472           tree fn_arg_types;
1473
1474           /* In case of explicit specialization, we need to check if
1475              the number of template headers appearing in the specialization
1476              is correct. This is usually done in check_explicit_specialization,
1477              but the check done there cannot be exhaustive when specializing
1478              member functions. Consider the following code:
1479
1480              template <> void A<int>::f(int);
1481              template <> template <> void A<int>::f(int);
1482
1483              Assuming that A<int> is not itself an explicit specialization
1484              already, the first line specializes "f" which is a non-template
1485              member function, whilst the second line specializes "f" which
1486              is a template member function. So both lines are syntactically
1487              correct, and check_explicit_specialization does not reject
1488              them.
1489
1490              Here, we can do better, as we are matching the specialization
1491              against the declarations. We count the number of template
1492              headers, and we check if they match TEMPLATE_COUNT + 1
1493              (TEMPLATE_COUNT is the number of qualifying template classes,
1494              plus there must be another header for the member template
1495              itself).
1496
1497              Notice that if header_count is zero, this is not a
1498              specialization but rather a template instantiation, so there
1499              is no check we can perform here.  */
1500           if (header_count && header_count != template_count + 1)
1501             continue;
1502
1503           /* Check that the number of template arguments at the
1504              innermost level for DECL is the same as for FN.  */
1505           if (current_binding_level->kind == sk_template_parms
1506               && !current_binding_level->explicit_spec_p
1507               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1508                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1509                                       (current_template_parms))))
1510             continue;
1511
1512           /* DECL might be a specialization of FN.  */
1513           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1514           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1515
1516           /* For a non-static member function, we need to make sure
1517              that the const qualification is the same.  Since
1518              get_bindings does not try to merge the "this" parameter,
1519              we must do the comparison explicitly.  */
1520           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1521               && !same_type_p (TREE_VALUE (fn_arg_types),
1522                                TREE_VALUE (decl_arg_types)))
1523             continue;
1524
1525           /* Skip the "this" parameter and, for constructors of
1526              classes with virtual bases, the VTT parameter.  A
1527              full specialization of a constructor will have a VTT
1528              parameter, but a template never will.  */ 
1529           decl_arg_types 
1530             = skip_artificial_parms_for (decl, decl_arg_types);
1531           fn_arg_types 
1532             = skip_artificial_parms_for (fn, fn_arg_types);
1533
1534           /* Check that the number of function parameters matches.
1535              For example,
1536                template <class T> void f(int i = 0);
1537                template <> void f<int>();
1538              The specialization f<int> is invalid but is not caught
1539              by get_bindings below.  */
1540           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1541             continue;
1542
1543           /* Function templates cannot be specializations; there are
1544              no partial specializations of functions.  Therefore, if
1545              the type of DECL does not match FN, there is no
1546              match.  */
1547           if (tsk == tsk_template)
1548             {
1549               if (compparms (fn_arg_types, decl_arg_types))
1550                 candidates = tree_cons (NULL_TREE, fn, candidates);
1551               continue;
1552             }
1553
1554           /* See whether this function might be a specialization of this
1555              template.  */
1556           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1557
1558           if (!targs)
1559             /* We cannot deduce template arguments that when used to
1560                specialize TMPL will produce DECL.  */
1561             continue;
1562
1563           /* Save this template, and the arguments deduced.  */
1564           templates = tree_cons (targs, fn, templates);
1565         }
1566       else if (need_member_template)
1567         /* FN is an ordinary member function, and we need a
1568            specialization of a member template.  */
1569         ;
1570       else if (TREE_CODE (fn) != FUNCTION_DECL)
1571         /* We can get IDENTIFIER_NODEs here in certain erroneous
1572            cases.  */
1573         ;
1574       else if (!DECL_FUNCTION_MEMBER_P (fn))
1575         /* This is just an ordinary non-member function.  Nothing can
1576            be a specialization of that.  */
1577         ;
1578       else if (DECL_ARTIFICIAL (fn))
1579         /* Cannot specialize functions that are created implicitly.  */
1580         ;
1581       else
1582         {
1583           tree decl_arg_types;
1584
1585           /* This is an ordinary member function.  However, since
1586              we're here, we can assume it's enclosing class is a
1587              template class.  For example,
1588
1589                template <typename T> struct S { void f(); };
1590                template <> void S<int>::f() {}
1591
1592              Here, S<int>::f is a non-template, but S<int> is a
1593              template class.  If FN has the same type as DECL, we
1594              might be in business.  */
1595
1596           if (!DECL_TEMPLATE_INFO (fn))
1597             /* Its enclosing class is an explicit specialization
1598                of a template class.  This is not a candidate.  */
1599             continue;
1600
1601           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1602                             TREE_TYPE (TREE_TYPE (fn))))
1603             /* The return types differ.  */
1604             continue;
1605
1606           /* Adjust the type of DECL in case FN is a static member.  */
1607           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1608           if (DECL_STATIC_FUNCTION_P (fn)
1609               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1610             decl_arg_types = TREE_CHAIN (decl_arg_types);
1611
1612           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1613                          decl_arg_types))
1614             /* They match!  */
1615             candidates = tree_cons (NULL_TREE, fn, candidates);
1616         }
1617     }
1618
1619   if (templates && TREE_CHAIN (templates))
1620     {
1621       /* We have:
1622
1623            [temp.expl.spec]
1624
1625            It is possible for a specialization with a given function
1626            signature to be instantiated from more than one function
1627            template.  In such cases, explicit specification of the
1628            template arguments must be used to uniquely identify the
1629            function template specialization being specialized.
1630
1631          Note that here, there's no suggestion that we're supposed to
1632          determine which of the candidate templates is most
1633          specialized.  However, we, also have:
1634
1635            [temp.func.order]
1636
1637            Partial ordering of overloaded function template
1638            declarations is used in the following contexts to select
1639            the function template to which a function template
1640            specialization refers:
1641
1642            -- when an explicit specialization refers to a function
1643               template.
1644
1645          So, we do use the partial ordering rules, at least for now.
1646          This extension can only serve to make invalid programs valid,
1647          so it's safe.  And, there is strong anecdotal evidence that
1648          the committee intended the partial ordering rules to apply;
1649          the EDG front end has that behavior, and John Spicer claims
1650          that the committee simply forgot to delete the wording in
1651          [temp.expl.spec].  */
1652       tree tmpl = most_specialized_instantiation (templates);
1653       if (tmpl != error_mark_node)
1654         {
1655           templates = tmpl;
1656           TREE_CHAIN (templates) = NULL_TREE;
1657         }
1658     }
1659
1660   if (templates == NULL_TREE && candidates == NULL_TREE)
1661     {
1662       error ("template-id %qD for %q+D does not match any template "
1663              "declaration", template_id, decl);
1664       return error_mark_node;
1665     }
1666   else if ((templates && TREE_CHAIN (templates))
1667            || (candidates && TREE_CHAIN (candidates))
1668            || (templates && candidates))
1669     {
1670       error ("ambiguous template specialization %qD for %q+D",
1671              template_id, decl);
1672       chainon (candidates, templates);
1673       print_candidates (candidates);
1674       return error_mark_node;
1675     }
1676
1677   /* We have one, and exactly one, match.  */
1678   if (candidates)
1679     {
1680       tree fn = TREE_VALUE (candidates);
1681       /* DECL is a re-declaration of a template function.  */
1682       if (TREE_CODE (fn) == TEMPLATE_DECL)
1683         return fn;
1684       /* It was a specialization of an ordinary member function in a
1685          template class.  */
1686       *targs_out = copy_node (DECL_TI_ARGS (fn));
1687       return DECL_TI_TEMPLATE (fn);
1688     }
1689
1690   /* It was a specialization of a template.  */
1691   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
1692   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
1693     {
1694       *targs_out = copy_node (targs);
1695       SET_TMPL_ARGS_LEVEL (*targs_out,
1696                            TMPL_ARGS_DEPTH (*targs_out),
1697                            TREE_PURPOSE (templates));
1698     }
1699   else
1700     *targs_out = TREE_PURPOSE (templates);
1701   return TREE_VALUE (templates);
1702 }
1703
1704 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
1705    but with the default argument values filled in from those in the
1706    TMPL_TYPES.  */
1707
1708 static tree
1709 copy_default_args_to_explicit_spec_1 (tree spec_types,
1710                                       tree tmpl_types)
1711 {
1712   tree new_spec_types;
1713
1714   if (!spec_types)
1715     return NULL_TREE;
1716
1717   if (spec_types == void_list_node)
1718     return void_list_node;
1719
1720   /* Substitute into the rest of the list.  */
1721   new_spec_types =
1722     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
1723                                           TREE_CHAIN (tmpl_types));
1724
1725   /* Add the default argument for this parameter.  */
1726   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
1727                          TREE_VALUE (spec_types),
1728                          new_spec_types);
1729 }
1730
1731 /* DECL is an explicit specialization.  Replicate default arguments
1732    from the template it specializes.  (That way, code like:
1733
1734      template <class T> void f(T = 3);
1735      template <> void f(double);
1736      void g () { f (); }
1737
1738    works, as required.)  An alternative approach would be to look up
1739    the correct default arguments at the call-site, but this approach
1740    is consistent with how implicit instantiations are handled.  */
1741
1742 static void
1743 copy_default_args_to_explicit_spec (tree decl)
1744 {
1745   tree tmpl;
1746   tree spec_types;
1747   tree tmpl_types;
1748   tree new_spec_types;
1749   tree old_type;
1750   tree new_type;
1751   tree t;
1752   tree object_type = NULL_TREE;
1753   tree in_charge = NULL_TREE;
1754   tree vtt = NULL_TREE;
1755
1756   /* See if there's anything we need to do.  */
1757   tmpl = DECL_TI_TEMPLATE (decl);
1758   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
1759   for (t = tmpl_types; t; t = TREE_CHAIN (t))
1760     if (TREE_PURPOSE (t))
1761       break;
1762   if (!t)
1763     return;
1764
1765   old_type = TREE_TYPE (decl);
1766   spec_types = TYPE_ARG_TYPES (old_type);
1767
1768   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1769     {
1770       /* Remove the this pointer, but remember the object's type for
1771          CV quals.  */
1772       object_type = TREE_TYPE (TREE_VALUE (spec_types));
1773       spec_types = TREE_CHAIN (spec_types);
1774       tmpl_types = TREE_CHAIN (tmpl_types);
1775
1776       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
1777         {
1778           /* DECL may contain more parameters than TMPL due to the extra
1779              in-charge parameter in constructors and destructors.  */
1780           in_charge = spec_types;
1781           spec_types = TREE_CHAIN (spec_types);
1782         }
1783       if (DECL_HAS_VTT_PARM_P (decl))
1784         {
1785           vtt = spec_types;
1786           spec_types = TREE_CHAIN (spec_types);
1787         }
1788     }
1789
1790   /* Compute the merged default arguments.  */
1791   new_spec_types =
1792     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
1793
1794   /* Compute the new FUNCTION_TYPE.  */
1795   if (object_type)
1796     {
1797       if (vtt)
1798         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
1799                                          TREE_VALUE (vtt),
1800                                          new_spec_types);
1801
1802       if (in_charge)
1803         /* Put the in-charge parameter back.  */
1804         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
1805                                          TREE_VALUE (in_charge),
1806                                          new_spec_types);
1807
1808       new_type = build_method_type_directly (object_type,
1809                                              TREE_TYPE (old_type),
1810                                              new_spec_types);
1811     }
1812   else
1813     new_type = build_function_type (TREE_TYPE (old_type),
1814                                     new_spec_types);
1815   new_type = cp_build_type_attribute_variant (new_type,
1816                                               TYPE_ATTRIBUTES (old_type));
1817   new_type = build_exception_variant (new_type,
1818                                       TYPE_RAISES_EXCEPTIONS (old_type));
1819   TREE_TYPE (decl) = new_type;
1820 }
1821
1822 /* Check to see if the function just declared, as indicated in
1823    DECLARATOR, and in DECL, is a specialization of a function
1824    template.  We may also discover that the declaration is an explicit
1825    instantiation at this point.
1826
1827    Returns DECL, or an equivalent declaration that should be used
1828    instead if all goes well.  Issues an error message if something is
1829    amiss.  Returns error_mark_node if the error is not easily
1830    recoverable.
1831
1832    FLAGS is a bitmask consisting of the following flags:
1833
1834    2: The function has a definition.
1835    4: The function is a friend.
1836
1837    The TEMPLATE_COUNT is the number of references to qualifying
1838    template classes that appeared in the name of the function.  For
1839    example, in
1840
1841      template <class T> struct S { void f(); };
1842      void S<int>::f();
1843
1844    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
1845    classes are not counted in the TEMPLATE_COUNT, so that in
1846
1847      template <class T> struct S {};
1848      template <> struct S<int> { void f(); }
1849      template <> void S<int>::f();
1850
1851    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
1852    invalid; there should be no template <>.)
1853
1854    If the function is a specialization, it is marked as such via
1855    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
1856    is set up correctly, and it is added to the list of specializations
1857    for that template.  */
1858
1859 tree
1860 check_explicit_specialization (tree declarator,
1861                                tree decl,
1862                                int template_count,
1863                                int flags)
1864 {
1865   int have_def = flags & 2;
1866   int is_friend = flags & 4;
1867   int specialization = 0;
1868   int explicit_instantiation = 0;
1869   int member_specialization = 0;
1870   tree ctype = DECL_CLASS_CONTEXT (decl);
1871   tree dname = DECL_NAME (decl);
1872   tmpl_spec_kind tsk;
1873
1874   if (is_friend)
1875     {
1876       if (!processing_specialization)
1877         tsk = tsk_none;
1878       else
1879         tsk = tsk_excessive_parms;
1880     }
1881   else
1882     tsk = current_tmpl_spec_kind (template_count);
1883
1884   switch (tsk)
1885     {
1886     case tsk_none:
1887       if (processing_specialization)
1888         {
1889           specialization = 1;
1890           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1891         }
1892       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1893         {
1894           if (is_friend)
1895             /* This could be something like:
1896
1897                template <class T> void f(T);
1898                class S { friend void f<>(int); }  */
1899             specialization = 1;
1900           else
1901             {
1902               /* This case handles bogus declarations like template <>
1903                  template <class T> void f<int>(); */
1904
1905               error ("template-id %qD in declaration of primary template",
1906                      declarator);
1907               return decl;
1908             }
1909         }
1910       break;
1911
1912     case tsk_invalid_member_spec:
1913       /* The error has already been reported in
1914          check_specialization_scope.  */
1915       return error_mark_node;
1916
1917     case tsk_invalid_expl_inst:
1918       error ("template parameter list used in explicit instantiation");
1919
1920       /* Fall through.  */
1921
1922     case tsk_expl_inst:
1923       if (have_def)
1924         error ("definition provided for explicit instantiation");
1925
1926       explicit_instantiation = 1;
1927       break;
1928
1929     case tsk_excessive_parms:
1930     case tsk_insufficient_parms:
1931       if (tsk == tsk_excessive_parms)
1932         error ("too many template parameter lists in declaration of %qD",
1933                decl);
1934       else if (template_header_count)
1935         error("too few template parameter lists in declaration of %qD", decl);
1936       else
1937         error("explicit specialization of %qD must be introduced by "
1938               "%<template <>%>", decl);
1939
1940       /* Fall through.  */
1941     case tsk_expl_spec:
1942       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1943       if (ctype)
1944         member_specialization = 1;
1945       else
1946         specialization = 1;
1947       break;
1948
1949     case tsk_template:
1950       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1951         {
1952           /* This case handles bogus declarations like template <>
1953              template <class T> void f<int>(); */
1954
1955           if (uses_template_parms (declarator))
1956             error ("function template partial specialization %qD "
1957                    "is not allowed", declarator);
1958           else
1959             error ("template-id %qD in declaration of primary template",
1960                    declarator);
1961           return decl;
1962         }
1963
1964       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
1965         /* This is a specialization of a member template, without
1966            specialization the containing class.  Something like:
1967
1968              template <class T> struct S {
1969                template <class U> void f (U);
1970              };
1971              template <> template <class U> void S<int>::f(U) {}
1972
1973            That's a specialization -- but of the entire template.  */
1974         specialization = 1;
1975       break;
1976
1977     default:
1978       gcc_unreachable ();
1979     }
1980
1981   if (specialization || member_specialization)
1982     {
1983       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
1984       for (; t; t = TREE_CHAIN (t))
1985         if (TREE_PURPOSE (t))
1986           {
1987             pedwarn
1988               ("default argument specified in explicit specialization");
1989             break;
1990           }
1991     }
1992
1993   if (specialization || member_specialization || explicit_instantiation)
1994     {
1995       tree tmpl = NULL_TREE;
1996       tree targs = NULL_TREE;
1997
1998       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
1999       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2000         {
2001           tree fns;
2002
2003           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2004           if (ctype)
2005             fns = dname;
2006           else
2007             {
2008               /* If there is no class context, the explicit instantiation
2009                  must be at namespace scope.  */
2010               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2011
2012               /* Find the namespace binding, using the declaration
2013                  context.  */
2014               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2015                                            false, true);
2016               if (fns == error_mark_node || !is_overloaded_fn (fns))
2017                 {
2018                   error ("%qD is not a template function", dname);
2019                   fns = error_mark_node;
2020                 }
2021               else
2022                 {
2023                   tree fn = OVL_CURRENT (fns);
2024                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2025                                                 CP_DECL_CONTEXT (fn)))
2026                     error ("%qD is not declared in %qD",
2027                            decl, current_namespace);
2028                 }
2029             }
2030
2031           declarator = lookup_template_function (fns, NULL_TREE);
2032         }
2033
2034       if (declarator == error_mark_node)
2035         return error_mark_node;
2036
2037       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2038         {
2039           if (!explicit_instantiation)
2040             /* A specialization in class scope.  This is invalid,
2041                but the error will already have been flagged by
2042                check_specialization_scope.  */
2043             return error_mark_node;
2044           else
2045             {
2046               /* It's not valid to write an explicit instantiation in
2047                  class scope, e.g.:
2048
2049                    class C { template void f(); }
2050
2051                    This case is caught by the parser.  However, on
2052                    something like:
2053
2054                    template class C { void f(); };
2055
2056                    (which is invalid) we can get here.  The error will be
2057                    issued later.  */
2058               ;
2059             }
2060
2061           return decl;
2062         }
2063       else if (ctype != NULL_TREE
2064                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2065                    IDENTIFIER_NODE))
2066         {
2067           /* Find the list of functions in ctype that have the same
2068              name as the declared function.  */
2069           tree name = TREE_OPERAND (declarator, 0);
2070           tree fns = NULL_TREE;
2071           int idx;
2072
2073           if (constructor_name_p (name, ctype))
2074             {
2075               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2076
2077               if (is_constructor ? !TYPE_HAS_CONSTRUCTOR (ctype)
2078                   : !CLASSTYPE_DESTRUCTORS (ctype))
2079                 {
2080                   /* From [temp.expl.spec]:
2081
2082                      If such an explicit specialization for the member
2083                      of a class template names an implicitly-declared
2084                      special member function (clause _special_), the
2085                      program is ill-formed.
2086
2087                      Similar language is found in [temp.explicit].  */
2088                   error ("specialization of implicitly-declared special member function");
2089                   return error_mark_node;
2090                 }
2091
2092               name = is_constructor ? ctor_identifier : dtor_identifier;
2093             }
2094
2095           if (!DECL_CONV_FN_P (decl))
2096             {
2097               idx = lookup_fnfields_1 (ctype, name);
2098               if (idx >= 0)
2099                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2100             }
2101           else
2102             {
2103               VEC(tree,gc) *methods;
2104               tree ovl;
2105
2106               /* For a type-conversion operator, we cannot do a
2107                  name-based lookup.  We might be looking for `operator
2108                  int' which will be a specialization of `operator T'.
2109                  So, we find *all* the conversion operators, and then
2110                  select from them.  */
2111               fns = NULL_TREE;
2112
2113               methods = CLASSTYPE_METHOD_VEC (ctype);
2114               if (methods)
2115                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2116                      VEC_iterate (tree, methods, idx, ovl);
2117                      ++idx)
2118                   {
2119                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2120                       /* There are no more conversion functions.  */
2121                       break;
2122
2123                     /* Glue all these conversion functions together
2124                        with those we already have.  */
2125                     for (; ovl; ovl = OVL_NEXT (ovl))
2126                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2127                   }
2128             }
2129
2130           if (fns == NULL_TREE)
2131             {
2132               error ("no member function %qD declared in %qT", name, ctype);
2133               return error_mark_node;
2134             }
2135           else
2136             TREE_OPERAND (declarator, 0) = fns;
2137         }
2138
2139       /* Figure out what exactly is being specialized at this point.
2140          Note that for an explicit instantiation, even one for a
2141          member function, we cannot tell apriori whether the
2142          instantiation is for a member template, or just a member
2143          function of a template class.  Even if a member template is
2144          being instantiated, the member template arguments may be
2145          elided if they can be deduced from the rest of the
2146          declaration.  */
2147       tmpl = determine_specialization (declarator, decl,
2148                                        &targs,
2149                                        member_specialization,
2150                                        template_count,
2151                                        tsk);
2152
2153       if (!tmpl || tmpl == error_mark_node)
2154         /* We couldn't figure out what this declaration was
2155            specializing.  */
2156         return error_mark_node;
2157       else
2158         {
2159           tree gen_tmpl = most_general_template (tmpl);
2160
2161           if (explicit_instantiation)
2162             {
2163               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2164                  is done by do_decl_instantiation later.  */
2165
2166               int arg_depth = TMPL_ARGS_DEPTH (targs);
2167               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2168
2169               if (arg_depth > parm_depth)
2170                 {
2171                   /* If TMPL is not the most general template (for
2172                      example, if TMPL is a friend template that is
2173                      injected into namespace scope), then there will
2174                      be too many levels of TARGS.  Remove some of them
2175                      here.  */
2176                   int i;
2177                   tree new_targs;
2178
2179                   new_targs = make_tree_vec (parm_depth);
2180                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2181                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2182                       = TREE_VEC_ELT (targs, i);
2183                   targs = new_targs;
2184                 }
2185
2186               return instantiate_template (tmpl, targs, tf_error);
2187             }
2188
2189           /* If we thought that the DECL was a member function, but it
2190              turns out to be specializing a static member function,
2191              make DECL a static member function as well.  */
2192           if (DECL_STATIC_FUNCTION_P (tmpl)
2193               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2194             revert_static_member_fn (decl);
2195
2196           /* If this is a specialization of a member template of a
2197              template class, we want to return the TEMPLATE_DECL, not
2198              the specialization of it.  */
2199           if (tsk == tsk_template)
2200             {
2201               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2202               DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl)) = NULL_TREE;
2203               if (have_def)
2204                 {
2205                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2206                   DECL_SOURCE_LOCATION (DECL_TEMPLATE_RESULT (tmpl))
2207                     = DECL_SOURCE_LOCATION (decl);
2208                   /* We want to use the argument list specified in the
2209                      definition, not in the original declaration.  */
2210                   DECL_ARGUMENTS (DECL_TEMPLATE_RESULT (tmpl))
2211                     = DECL_ARGUMENTS (decl);
2212                 }
2213               return tmpl;
2214             }
2215
2216           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2217           DECL_TEMPLATE_INFO (decl) = tree_cons (tmpl, targs, NULL_TREE);
2218
2219           /* Inherit default function arguments from the template
2220              DECL is specializing.  */
2221           copy_default_args_to_explicit_spec (decl);
2222
2223           /* This specialization has the same protection as the
2224              template it specializes.  */
2225           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2226           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2227
2228           /* 7.1.1-1 [dcl.stc]
2229
2230              A storage-class-specifier shall not be specified in an
2231              explicit specialization...
2232
2233              The parser rejects these, so unless action is taken here,
2234              explicit function specializations will always appear with
2235              global linkage.
2236
2237              The action recommended by the C++ CWG in response to C++
2238              defect report 605 is to make the storage class and linkage
2239              of the explicit specialization match the templated function:
2240
2241              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2242            */
2243           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2244             {
2245               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2246               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2247
2248               /* This specialization has the same linkage and visibility as
2249                  the function template it specializes.  */
2250               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2251               if (! TREE_PUBLIC (decl))
2252                 {
2253                   DECL_INTERFACE_KNOWN (decl) = 1;
2254                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2255                 }
2256               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2257               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2258                 {
2259                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2260                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2261                 }
2262             }
2263
2264           /* If DECL is a friend declaration, declared using an
2265              unqualified name, the namespace associated with DECL may
2266              have been set incorrectly.  For example, in:
2267
2268                template <typename T> void f(T);
2269                namespace N {
2270                  struct S { friend void f<int>(int); }
2271                }
2272
2273              we will have set the DECL_CONTEXT for the friend
2274              declaration to N, rather than to the global namespace.  */
2275           if (DECL_NAMESPACE_SCOPE_P (decl))
2276             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2277
2278           if (is_friend && !have_def)
2279             /* This is not really a declaration of a specialization.
2280                It's just the name of an instantiation.  But, it's not
2281                a request for an instantiation, either.  */
2282             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2283           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2284             /* This is indeed a specialization.  In case of constructors
2285                and destructors, we need in-charge and not-in-charge
2286                versions in V3 ABI.  */
2287             clone_function_decl (decl, /*update_method_vec_p=*/0);
2288
2289           /* Register this specialization so that we can find it
2290              again.  */
2291           decl = register_specialization (decl, gen_tmpl, targs, is_friend);
2292         }
2293     }
2294
2295   return decl;
2296 }
2297
2298 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2299    parameters.  These are represented in the same format used for
2300    DECL_TEMPLATE_PARMS.  */
2301
2302 int
2303 comp_template_parms (const_tree parms1, const_tree parms2)
2304 {
2305   const_tree p1;
2306   const_tree p2;
2307
2308   if (parms1 == parms2)
2309     return 1;
2310
2311   for (p1 = parms1, p2 = parms2;
2312        p1 != NULL_TREE && p2 != NULL_TREE;
2313        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2314     {
2315       tree t1 = TREE_VALUE (p1);
2316       tree t2 = TREE_VALUE (p2);
2317       int i;
2318
2319       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2320       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2321
2322       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2323         return 0;
2324
2325       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2326         {
2327           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2328           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2329
2330           /* If either of the template parameters are invalid, assume
2331              they match for the sake of error recovery. */
2332           if (parm1 == error_mark_node || parm2 == error_mark_node)
2333             return 1;
2334
2335           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2336             return 0;
2337
2338           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2339               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2340                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2341             continue;
2342           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2343             return 0;
2344         }
2345     }
2346
2347   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2348     /* One set of parameters has more parameters lists than the
2349        other.  */
2350     return 0;
2351
2352   return 1;
2353 }
2354
2355 /* Determine whether PARM is a parameter pack.  */
2356 bool 
2357 template_parameter_pack_p (const_tree parm)
2358 {
2359   /* Determine if we have a non-type template parameter pack.  */
2360   if (TREE_CODE (parm) == PARM_DECL)
2361     return (DECL_TEMPLATE_PARM_P (parm) 
2362             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2363
2364   /* If this is a list of template parameters, we could get a
2365      TYPE_DECL or a TEMPLATE_DECL.  */ 
2366   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2367     parm = TREE_TYPE (parm);
2368
2369   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2370            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2371           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2372 }
2373
2374 /* Determine whether ARGS describes a variadic template args list,
2375    i.e., one that is terminated by a template argument pack.  */
2376 static bool 
2377 template_args_variadic_p (tree args)
2378 {
2379   int nargs;
2380   tree last_parm;
2381
2382   if (args == NULL_TREE)
2383     return false;
2384
2385   args = INNERMOST_TEMPLATE_ARGS (args);
2386   nargs = TREE_VEC_LENGTH (args);
2387
2388   if (nargs == 0)
2389     return false;
2390
2391   last_parm = TREE_VEC_ELT (args, nargs - 1);
2392
2393   return ARGUMENT_PACK_P (last_parm);
2394 }
2395
2396 /* Generate a new name for the parameter pack name NAME (an
2397    IDENTIFIER_NODE) that incorporates its */
2398 static tree
2399 make_ith_pack_parameter_name (tree name, int i)
2400 {
2401   /* Munge the name to include the parameter index.  */
2402   char numbuf[128];
2403   char* newname;
2404   
2405   sprintf(numbuf, "%i", i);
2406   newname = (char*)alloca (IDENTIFIER_LENGTH (name) + strlen(numbuf) + 2);
2407   sprintf(newname, "%s#%i", IDENTIFIER_POINTER (name), i);
2408   return get_identifier (newname);
2409 }
2410
2411 /* Structure used to track the progress of find_parameter_pack_r.  */
2412 struct find_parameter_pack_data 
2413 {
2414   tree* parameter_packs;
2415   struct pointer_set_t *visited;
2416 };
2417
2418 /* Identifiers all of the argument packs that occur in a template
2419    argument and appends them to the TREE_LIST inside DATA, which is a
2420    find_parameter_pack_Data structure. This is a subroutine of
2421    make_pack_expansion and uses_parameter_packs.  */
2422 static tree
2423 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2424 {
2425   tree t = *tp;
2426   struct find_parameter_pack_data* ppd = 
2427     (struct find_parameter_pack_data*)data;
2428
2429   if (TYPE_P (t))
2430     {
2431       tree context = TYPE_CONTEXT (t);
2432       cp_walk_tree (&context, &find_parameter_packs_r, ppd, ppd->visited);
2433     }
2434
2435   /* This switch statement will return immediately if we don't find a
2436      parameter pack.  */
2437   switch (TREE_CODE (t)) 
2438     {
2439     case TEMPLATE_PARM_INDEX:
2440       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2441         break;
2442       return NULL_TREE;
2443
2444     case BOUND_TEMPLATE_TEMPLATE_PARM:
2445       /* Check the template arguments.  */
2446       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2447                     ppd->visited);
2448
2449       /* Dig out the underlying TEMPLATE_TEMPLATE_PARM.  */
2450       t = TYPE_TI_TEMPLATE (t);
2451       if (DECL_P (t) && TREE_TYPE (t))
2452         t = TREE_TYPE (t);
2453       *walk_subtrees = 0;
2454       
2455       /* Fall through.  */
2456
2457     case TEMPLATE_TYPE_PARM:
2458     case TEMPLATE_TEMPLATE_PARM:
2459       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2460         break;
2461       return NULL_TREE;
2462
2463     case PARM_DECL:
2464       if (FUNCTION_PARAMETER_PACK_P (t))
2465         {
2466           /* We don't want to walk into the type of a PARM_DECL,
2467              because we don't want to see the type parameter pack.*/
2468           *walk_subtrees = 0;
2469           break;
2470         }
2471       return NULL_TREE;
2472
2473     case RECORD_TYPE:
2474       if (TYPE_PTRMEMFUNC_P (t))
2475         return NULL_TREE;
2476       /* Fall through.  */
2477
2478     case UNION_TYPE:
2479     case ENUMERAL_TYPE:
2480       if (TYPE_TEMPLATE_INFO (t))
2481         {
2482           tree args = TREE_VALUE (TYPE_TEMPLATE_INFO (t));
2483           cp_walk_tree (&args, &find_parameter_packs_r, ppd, ppd->visited);
2484         }
2485
2486       *walk_subtrees = 0;
2487       return NULL_TREE;
2488
2489     case TEMPLATE_DECL:
2490       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
2491           && TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (t)))
2492         break;
2493       
2494       *walk_subtrees = 0;
2495       return NULL_TREE;
2496        
2497     case TYPE_PACK_EXPANSION:
2498     case EXPR_PACK_EXPANSION:
2499       *walk_subtrees = 0;
2500       return NULL_TREE;
2501
2502     case INTEGER_TYPE:
2503       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
2504                     ppd, ppd->visited);
2505       *walk_subtrees = 0;
2506       return NULL_TREE;
2507
2508     default:
2509       return NULL_TREE;
2510     }
2511   
2512   /* Add this parameter pack to the list.  */
2513   *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2514
2515   return NULL_TREE;
2516 }
2517
2518 /* Determines if the expression or type T uses any parameter packs.  */
2519 bool
2520 uses_parameter_packs (tree t)
2521 {
2522   tree parameter_packs = NULL_TREE;
2523   struct find_parameter_pack_data ppd;
2524   ppd.parameter_packs = &parameter_packs;
2525   ppd.visited = pointer_set_create ();
2526   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2527   pointer_set_destroy (ppd.visited);
2528   return parameter_packs != NULL_TREE;
2529 }
2530
2531 /* Turn ARG, which may be an expression, type, or a TREE_LIST
2532    representation a base-class initializer into a parameter pack
2533    expansion. If all goes well, the resulting node will be an
2534    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
2535    respectively.  */
2536 tree 
2537 make_pack_expansion (tree arg)
2538 {
2539   tree result;
2540   tree parameter_packs = NULL_TREE;
2541   bool for_types = false;
2542   struct find_parameter_pack_data ppd;
2543
2544   if (!arg || arg == error_mark_node)
2545     return arg;
2546
2547   if (TREE_CODE (arg) == TREE_LIST)
2548     {
2549       /* The only time we will see a TREE_LIST here is for a base
2550          class initializer.  In this case, the TREE_PURPOSE will be a
2551          _TYPE node (representing the base class expansion we're
2552          initializing) and the TREE_VALUE will be a TREE_LIST
2553          containing the initialization arguments. 
2554
2555          The resulting expansion looks somewhat different from most
2556          expansions. Rather than returning just one _EXPANSION, we
2557          return a TREE_LIST whose TREE_PURPOSE is a
2558          TYPE_PACK_EXPANSION containing the bases that will be
2559          initialized.  The TREE_VALUE will be identical to the
2560          original TREE_VALUE, which is a list of arguments that will
2561          be passed to each base.  We do not introduce any new pack
2562          expansion nodes into the TREE_VALUE (although it is possible
2563          that some already exist), because the TREE_PURPOSE and
2564          TREE_VALUE all need to be expanded together with the same
2565          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
2566          resulting TREE_PURPOSE will mention the parameter packs in
2567          both the bases and the arguments to the bases.  */
2568       tree purpose;
2569       tree value;
2570       tree parameter_packs = NULL_TREE;
2571
2572       /* Determine which parameter packs will be used by the base
2573          class expansion.  */
2574       ppd.visited = pointer_set_create ();
2575       ppd.parameter_packs = &parameter_packs;
2576       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
2577                     &ppd, ppd.visited);
2578
2579       if (parameter_packs == NULL_TREE)
2580         {
2581           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
2582           pointer_set_destroy (ppd.visited);
2583           return error_mark_node;
2584         }
2585
2586       if (TREE_VALUE (arg) != void_type_node)
2587         {
2588           /* Collect the sets of parameter packs used in each of the
2589              initialization arguments.  */
2590           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
2591             {
2592               /* Determine which parameter packs will be expanded in this
2593                  argument.  */
2594               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
2595                             &ppd, ppd.visited);
2596             }
2597         }
2598
2599       pointer_set_destroy (ppd.visited);
2600
2601       /* Create the pack expansion type for the base type.  */
2602       purpose = make_node (TYPE_PACK_EXPANSION);
2603       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
2604       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
2605
2606       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2607          they will rarely be compared to anything.  */
2608       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
2609
2610       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
2611     }
2612
2613   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
2614     for_types = true;
2615
2616   /* Build the PACK_EXPANSION_* node.  */
2617   result = make_node (for_types ? TYPE_PACK_EXPANSION : EXPR_PACK_EXPANSION);
2618   SET_PACK_EXPANSION_PATTERN (result, arg);
2619   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
2620     {
2621       /* Propagate type and const-expression information.  */
2622       TREE_TYPE (result) = TREE_TYPE (arg);
2623       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
2624     }
2625   else
2626     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2627        they will rarely be compared to anything.  */
2628     SET_TYPE_STRUCTURAL_EQUALITY (result);
2629
2630   /* Determine which parameter packs will be expanded.  */
2631   ppd.parameter_packs = &parameter_packs;
2632   ppd.visited = pointer_set_create ();
2633   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
2634   pointer_set_destroy (ppd.visited);
2635
2636   /* Make sure we found some parameter packs.  */
2637   if (parameter_packs == NULL_TREE)
2638     {
2639       if (TYPE_P (arg))
2640         error ("expansion pattern %<%T%> contains no argument packs", arg);
2641       else
2642         error ("expansion pattern %<%E%> contains no argument packs", arg);
2643       return error_mark_node;
2644     }
2645   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
2646
2647   return result;
2648 }
2649
2650 /* Checks T for any "bare" parameter packs, which have not yet been
2651    expanded, and issues an error if any are found. This operation can
2652    only be done on full expressions or types (e.g., an expression
2653    statement, "if" condition, etc.), because we could have expressions like:
2654
2655      foo(f(g(h(args)))...)
2656
2657    where "args" is a parameter pack. check_for_bare_parameter_packs
2658    should not be called for the subexpressions args, h(args),
2659    g(h(args)), or f(g(h(args))), because we would produce erroneous
2660    error messages. 
2661
2662    Returns TRUE if there were no bare parameter packs, returns FALSE
2663    (and emits an error) if there were bare parameter packs.*/
2664 bool 
2665 check_for_bare_parameter_packs (tree t)
2666 {
2667   tree parameter_packs = NULL_TREE;
2668   struct find_parameter_pack_data ppd;
2669
2670   if (!processing_template_decl || !t || t == error_mark_node)
2671     return true;
2672
2673   if (TREE_CODE (t) == TYPE_DECL)
2674     t = TREE_TYPE (t);
2675
2676   ppd.parameter_packs = &parameter_packs;
2677   ppd.visited = pointer_set_create ();
2678   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2679   pointer_set_destroy (ppd.visited);
2680
2681   if (parameter_packs) 
2682     {
2683       error ("parameter packs not expanded with `...':");
2684       while (parameter_packs)
2685         {
2686           tree pack = TREE_VALUE (parameter_packs);
2687           tree name = NULL_TREE;
2688
2689           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
2690               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
2691             name = TYPE_NAME (pack);
2692           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
2693             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
2694           else
2695             name = DECL_NAME (pack);
2696           inform ("        %qD", name);
2697
2698           parameter_packs = TREE_CHAIN (parameter_packs);
2699         }
2700
2701       return false;
2702     }
2703
2704   return true;
2705 }
2706
2707 /* Expand any parameter packs that occur in the template arguments in
2708    ARGS.  */
2709 tree
2710 expand_template_argument_pack (tree args)
2711 {
2712   tree result_args = NULL_TREE;
2713   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
2714   int num_result_args = -1;
2715
2716   /* First, determine if we need to expand anything, and the number of
2717      slots we'll need.  */
2718   for (in_arg = 0; in_arg < nargs; ++in_arg)
2719     {
2720       tree arg = TREE_VEC_ELT (args, in_arg);
2721       if (ARGUMENT_PACK_P (arg))
2722         {
2723           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
2724           if (num_result_args < 0)
2725             num_result_args = in_arg + num_packed;
2726           else
2727             num_result_args += num_packed;
2728         }
2729       else
2730         {
2731           if (num_result_args >= 0)
2732             num_result_args++;
2733         }
2734     }
2735
2736   /* If no expansion is necessary, we're done.  */
2737   if (num_result_args < 0)
2738     return args;
2739
2740   /* Expand arguments.  */
2741   result_args = make_tree_vec (num_result_args);
2742   for (in_arg = 0; in_arg < nargs; ++in_arg)
2743     {
2744       tree arg = TREE_VEC_ELT (args, in_arg);
2745       if (ARGUMENT_PACK_P (arg))
2746         {
2747           tree packed = ARGUMENT_PACK_ARGS (arg);
2748           int i, num_packed = TREE_VEC_LENGTH (packed);
2749           for (i = 0; i < num_packed; ++i, ++out_arg)
2750             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
2751         }
2752       else
2753         {
2754           TREE_VEC_ELT (result_args, out_arg) = arg;
2755           ++out_arg;
2756         }
2757     }
2758
2759   return result_args;
2760 }
2761
2762 /* Complain if DECL shadows a template parameter.
2763
2764    [temp.local]: A template-parameter shall not be redeclared within its
2765    scope (including nested scopes).  */
2766
2767 void
2768 check_template_shadow (tree decl)
2769 {
2770   tree olddecl;
2771
2772   /* If we're not in a template, we can't possibly shadow a template
2773      parameter.  */
2774   if (!current_template_parms)
2775     return;
2776
2777   /* Figure out what we're shadowing.  */
2778   if (TREE_CODE (decl) == OVERLOAD)
2779     decl = OVL_CURRENT (decl);
2780   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
2781
2782   /* If there's no previous binding for this name, we're not shadowing
2783      anything, let alone a template parameter.  */
2784   if (!olddecl)
2785     return;
2786
2787   /* If we're not shadowing a template parameter, we're done.  Note
2788      that OLDDECL might be an OVERLOAD (or perhaps even an
2789      ERROR_MARK), so we can't just blithely assume it to be a _DECL
2790      node.  */
2791   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
2792     return;
2793
2794   /* We check for decl != olddecl to avoid bogus errors for using a
2795      name inside a class.  We check TPFI to avoid duplicate errors for
2796      inline member templates.  */
2797   if (decl == olddecl
2798       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
2799     return;
2800
2801   error ("declaration of %q+#D", decl);
2802   error (" shadows template parm %q+#D", olddecl);
2803 }
2804
2805 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
2806    ORIG_LEVEL, DECL, and TYPE.  */
2807
2808 static tree
2809 build_template_parm_index (int index,
2810                            int level,
2811                            int orig_level,
2812                            tree decl,
2813                            tree type)
2814 {
2815   tree t = make_node (TEMPLATE_PARM_INDEX);
2816   TEMPLATE_PARM_IDX (t) = index;
2817   TEMPLATE_PARM_LEVEL (t) = level;
2818   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
2819   TEMPLATE_PARM_DECL (t) = decl;
2820   TREE_TYPE (t) = type;
2821   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
2822   TREE_INVARIANT (t) = TREE_INVARIANT (decl);
2823   TREE_READONLY (t) = TREE_READONLY (decl);
2824
2825   return t;
2826 }
2827
2828 /* Find the canonical type parameter for the given template type
2829    parameter.  Returns the canonical type parameter, which may be TYPE
2830    if no such parameter existed.  */
2831 static tree
2832 canonical_type_parameter (tree type)
2833 {
2834   tree list;
2835   int idx = TEMPLATE_TYPE_IDX (type);
2836   if (!canonical_template_parms)
2837     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
2838
2839   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
2840     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
2841
2842   list = VEC_index (tree, canonical_template_parms, idx);
2843   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
2844     list = TREE_CHAIN (list);
2845
2846   if (list)
2847     return TREE_VALUE (list);
2848   else
2849     {
2850       VEC_replace(tree, canonical_template_parms, idx,
2851                   tree_cons (NULL_TREE, type, 
2852                              VEC_index (tree, canonical_template_parms, idx)));
2853       return type;
2854     }
2855 }
2856
2857 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
2858    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
2859    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
2860    new one is created.  */
2861
2862 static tree
2863 reduce_template_parm_level (tree index, tree type, int levels)
2864 {
2865   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
2866       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
2867           != TEMPLATE_PARM_LEVEL (index) - levels))
2868     {
2869       tree orig_decl = TEMPLATE_PARM_DECL (index);
2870       tree decl, t;
2871
2872       decl = build_decl (TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
2873       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
2874       TREE_INVARIANT (decl) = TREE_INVARIANT (orig_decl);
2875       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
2876       DECL_ARTIFICIAL (decl) = 1;
2877       SET_DECL_TEMPLATE_PARM_P (decl);
2878
2879       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
2880                                      TEMPLATE_PARM_LEVEL (index) - levels,
2881                                      TEMPLATE_PARM_ORIG_LEVEL (index),
2882                                      decl, type);
2883       TEMPLATE_PARM_DESCENDANTS (index) = t;
2884       TEMPLATE_PARM_PARAMETER_PACK (t) 
2885         = TEMPLATE_PARM_PARAMETER_PACK (index);
2886
2887         /* Template template parameters need this.  */
2888       if (TREE_CODE (decl) != CONST_DECL)
2889         DECL_TEMPLATE_PARMS (decl)
2890           = DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index));
2891     }
2892
2893   return TEMPLATE_PARM_DESCENDANTS (index);
2894 }
2895
2896 /* Process information from new template parameter PARM and append it to the
2897    LIST being built.  This new parameter is a non-type parameter iff
2898    IS_NON_TYPE is true. This new parameter is a parameter
2899    pack iff IS_PARAMETER_PACK is true.  */
2900
2901 tree
2902 process_template_parm (tree list, tree parm, bool is_non_type, 
2903                        bool is_parameter_pack)
2904 {
2905   tree decl = 0;
2906   tree defval;
2907   tree err_parm_list;
2908   int idx = 0;
2909
2910   gcc_assert (TREE_CODE (parm) == TREE_LIST);
2911   defval = TREE_PURPOSE (parm);
2912
2913   if (list)
2914     {
2915       tree p = tree_last (list);
2916
2917       if (p && TREE_VALUE (p) != error_mark_node)
2918         {
2919           p = TREE_VALUE (p);
2920           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
2921             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
2922           else
2923             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
2924         }
2925
2926       ++idx;
2927     }
2928   else
2929     idx = 0;
2930
2931   if (is_non_type)
2932     {
2933       parm = TREE_VALUE (parm);
2934
2935       SET_DECL_TEMPLATE_PARM_P (parm);
2936
2937       if (TREE_TYPE (parm) == error_mark_node)
2938         {
2939           err_parm_list = build_tree_list (defval, parm);
2940           TREE_VALUE (err_parm_list) = error_mark_node;
2941            return chainon (list, err_parm_list);
2942         }
2943       else
2944       {
2945         /* [temp.param]
2946
2947            The top-level cv-qualifiers on the template-parameter are
2948            ignored when determining its type.  */
2949         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
2950         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
2951           {
2952             err_parm_list = build_tree_list (defval, parm);
2953             TREE_VALUE (err_parm_list) = error_mark_node;
2954              return chainon (list, err_parm_list);
2955           }
2956
2957         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
2958           {
2959             /* This template parameter is not a parameter pack, but it
2960                should be. Complain about "bare" parameter packs.  */
2961             check_for_bare_parameter_packs (TREE_TYPE (parm));
2962             
2963             /* Recover by calling this a parameter pack.  */
2964             is_parameter_pack = true;
2965           }
2966       }
2967
2968       /* A template parameter is not modifiable.  */
2969       TREE_CONSTANT (parm) = 1;
2970       TREE_INVARIANT (parm) = 1;
2971       TREE_READONLY (parm) = 1;
2972       decl = build_decl (CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
2973       TREE_CONSTANT (decl) = 1;
2974       TREE_INVARIANT (decl) = 1;
2975       TREE_READONLY (decl) = 1;
2976       DECL_INITIAL (parm) = DECL_INITIAL (decl)
2977         = build_template_parm_index (idx, processing_template_decl,
2978                                      processing_template_decl,
2979                                      decl, TREE_TYPE (parm));
2980
2981       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
2982         = is_parameter_pack;
2983     }
2984   else
2985     {
2986       tree t;
2987       parm = TREE_VALUE (TREE_VALUE (parm));
2988
2989       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
2990         {
2991           t = make_aggr_type (TEMPLATE_TEMPLATE_PARM);
2992           /* This is for distinguishing between real templates and template
2993              template parameters */
2994           TREE_TYPE (parm) = t;
2995           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
2996           decl = parm;
2997         }
2998       else
2999         {
3000           t = make_aggr_type (TEMPLATE_TYPE_PARM);
3001           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3002           decl = build_decl (TYPE_DECL, parm, t);
3003         }
3004
3005       TYPE_NAME (t) = decl;
3006       TYPE_STUB_DECL (t) = decl;
3007       parm = decl;
3008       TEMPLATE_TYPE_PARM_INDEX (t)
3009         = build_template_parm_index (idx, processing_template_decl,
3010                                      processing_template_decl,
3011                                      decl, TREE_TYPE (parm));
3012       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3013       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3014     }
3015   DECL_ARTIFICIAL (decl) = 1;
3016   SET_DECL_TEMPLATE_PARM_P (decl);
3017   pushdecl (decl);
3018   parm = build_tree_list (defval, parm);
3019   return chainon (list, parm);
3020 }
3021
3022 /* The end of a template parameter list has been reached.  Process the
3023    tree list into a parameter vector, converting each parameter into a more
3024    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3025    as PARM_DECLs.  */
3026
3027 tree
3028 end_template_parm_list (tree parms)
3029 {
3030   int nparms;
3031   tree parm, next;
3032   tree saved_parmlist = make_tree_vec (list_length (parms));
3033
3034   current_template_parms
3035     = tree_cons (size_int (processing_template_decl),
3036                  saved_parmlist, current_template_parms);
3037
3038   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3039     {
3040       next = TREE_CHAIN (parm);
3041       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3042       TREE_CHAIN (parm) = NULL_TREE;
3043     }
3044
3045   --processing_template_parmlist;
3046
3047   return saved_parmlist;
3048 }
3049
3050 /* end_template_decl is called after a template declaration is seen.  */
3051
3052 void
3053 end_template_decl (void)
3054 {
3055   reset_specialization ();
3056
3057   if (! processing_template_decl)
3058     return;
3059
3060   /* This matches the pushlevel in begin_template_parm_list.  */
3061   finish_scope ();
3062
3063   --processing_template_decl;
3064   current_template_parms = TREE_CHAIN (current_template_parms);
3065 }
3066
3067 /* Within the declaration of a template, return all levels of template
3068    parameters that apply.  The template parameters are represented as
3069    a TREE_VEC, in the form documented in cp-tree.h for template
3070    arguments.  */
3071
3072 static tree
3073 current_template_args (void)
3074 {
3075   tree header;
3076   tree args = NULL_TREE;
3077   int length = TMPL_PARMS_DEPTH (current_template_parms);
3078   int l = length;
3079
3080   /* If there is only one level of template parameters, we do not
3081      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3082      TREE_VEC containing the arguments.  */
3083   if (length > 1)
3084     args = make_tree_vec (length);
3085
3086   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3087     {
3088       tree a = copy_node (TREE_VALUE (header));
3089       int i;
3090
3091       TREE_TYPE (a) = NULL_TREE;
3092       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3093         {
3094           tree t = TREE_VEC_ELT (a, i);
3095
3096           /* T will be a list if we are called from within a
3097              begin/end_template_parm_list pair, but a vector directly
3098              if within a begin/end_member_template_processing pair.  */
3099           if (TREE_CODE (t) == TREE_LIST)
3100             {
3101               t = TREE_VALUE (t);
3102
3103               if (t != error_mark_node)
3104                 {
3105                   if (TREE_CODE (t) == TYPE_DECL
3106                       || TREE_CODE (t) == TEMPLATE_DECL)
3107                     {
3108                       t = TREE_TYPE (t);
3109                       
3110                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3111                         {
3112                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3113                              with a single element, which expands T.  */
3114                           tree vec = make_tree_vec (1);
3115                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3116                           
3117                           t = make_node (TYPE_ARGUMENT_PACK);
3118                           SET_ARGUMENT_PACK_ARGS (t, vec);
3119                         }
3120                     }
3121                   else
3122                     {
3123                       t = DECL_INITIAL (t);
3124                       
3125                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3126                         {
3127                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3128                              with a single element, which expands T.  */
3129                           tree vec = make_tree_vec (1);
3130                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3131                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3132                           
3133                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3134                           SET_ARGUMENT_PACK_ARGS (t, vec);
3135                           TREE_TYPE (t) = type;
3136                         }
3137                     }
3138                 }
3139               TREE_VEC_ELT (a, i) = t;
3140             }
3141         }
3142
3143       if (length > 1)
3144         TREE_VEC_ELT (args, --l) = a;
3145       else
3146         args = a;
3147     }
3148
3149   return args;
3150 }
3151
3152 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3153    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3154    a member template.  Used by push_template_decl below.  */
3155
3156 static tree
3157 build_template_decl (tree decl, tree parms, bool member_template_p)
3158 {
3159   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3160   DECL_TEMPLATE_PARMS (tmpl) = parms;
3161   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3162   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3163   if (DECL_LANG_SPECIFIC (decl))
3164     {
3165       DECL_STATIC_FUNCTION_P (tmpl) = DECL_STATIC_FUNCTION_P (decl);
3166       DECL_CONSTRUCTOR_P (tmpl) = DECL_CONSTRUCTOR_P (decl);
3167       DECL_DESTRUCTOR_P (tmpl) = DECL_DESTRUCTOR_P (decl);
3168       DECL_NONCONVERTING_P (tmpl) = DECL_NONCONVERTING_P (decl);
3169       DECL_ASSIGNMENT_OPERATOR_P (tmpl) = DECL_ASSIGNMENT_OPERATOR_P (decl);
3170       if (DECL_OVERLOADED_OPERATOR_P (decl))
3171         SET_OVERLOADED_OPERATOR_CODE (tmpl,
3172                                       DECL_OVERLOADED_OPERATOR_P (decl));
3173     }
3174
3175   return tmpl;
3176 }
3177
3178 struct template_parm_data
3179 {
3180   /* The level of the template parameters we are currently
3181      processing.  */
3182   int level;
3183
3184   /* The index of the specialization argument we are currently
3185      processing.  */
3186   int current_arg;
3187
3188   /* An array whose size is the number of template parameters.  The
3189      elements are nonzero if the parameter has been used in any one
3190      of the arguments processed so far.  */
3191   int* parms;
3192
3193   /* An array whose size is the number of template arguments.  The
3194      elements are nonzero if the argument makes use of template
3195      parameters of this level.  */
3196   int* arg_uses_template_parms;
3197 };
3198
3199 /* Subroutine of push_template_decl used to see if each template
3200    parameter in a partial specialization is used in the explicit
3201    argument list.  If T is of the LEVEL given in DATA (which is
3202    treated as a template_parm_data*), then DATA->PARMS is marked
3203    appropriately.  */
3204
3205 static int
3206 mark_template_parm (tree t, void* data)
3207 {
3208   int level;
3209   int idx;
3210   struct template_parm_data* tpd = (struct template_parm_data*) data;
3211
3212   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3213     {
3214       level = TEMPLATE_PARM_LEVEL (t);
3215       idx = TEMPLATE_PARM_IDX (t);
3216     }
3217   else
3218     {
3219       level = TEMPLATE_TYPE_LEVEL (t);
3220       idx = TEMPLATE_TYPE_IDX (t);
3221     }
3222
3223   if (level == tpd->level)
3224     {
3225       tpd->parms[idx] = 1;
3226       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3227     }
3228
3229   /* Return zero so that for_each_template_parm will continue the
3230      traversal of the tree; we want to mark *every* template parm.  */
3231   return 0;
3232 }
3233
3234 /* Process the partial specialization DECL.  */
3235
3236 static tree
3237 process_partial_specialization (tree decl)
3238 {
3239   tree type = TREE_TYPE (decl);
3240   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3241   tree specargs = CLASSTYPE_TI_ARGS (type);
3242   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3243   tree inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3244   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3245   int nargs = TREE_VEC_LENGTH (inner_args);
3246   int ntparms = TREE_VEC_LENGTH (inner_parms);
3247   int  i;
3248   int did_error_intro = 0;
3249   struct template_parm_data tpd;
3250   struct template_parm_data tpd2;
3251
3252   /* We check that each of the template parameters given in the
3253      partial specialization is used in the argument list to the
3254      specialization.  For example:
3255
3256        template <class T> struct S;
3257        template <class T> struct S<T*>;
3258
3259      The second declaration is OK because `T*' uses the template
3260      parameter T, whereas
3261
3262        template <class T> struct S<int>;
3263
3264      is no good.  Even trickier is:
3265
3266        template <class T>
3267        struct S1
3268        {
3269           template <class U>
3270           struct S2;
3271           template <class U>
3272           struct S2<T>;
3273        };
3274
3275      The S2<T> declaration is actually invalid; it is a
3276      full-specialization.  Of course,
3277
3278           template <class U>
3279           struct S2<T (*)(U)>;
3280
3281      or some such would have been OK.  */
3282   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3283   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3284   memset (tpd.parms, 0, sizeof (int) * ntparms);
3285
3286   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3287   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3288   for (i = 0; i < nargs; ++i)
3289     {
3290       tpd.current_arg = i;
3291       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3292                               &mark_template_parm,
3293                               &tpd,
3294                               NULL);
3295     }
3296   for (i = 0; i < ntparms; ++i)
3297     if (tpd.parms[i] == 0)
3298       {
3299         /* One of the template parms was not used in the
3300            specialization.  */
3301         if (!did_error_intro)
3302           {
3303             error ("template parameters not used in partial specialization:");
3304             did_error_intro = 1;
3305           }
3306
3307         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3308       }
3309
3310   /* [temp.class.spec]
3311
3312      The argument list of the specialization shall not be identical to
3313      the implicit argument list of the primary template.  */
3314   if (comp_template_args
3315       (inner_args,
3316        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3317                                                    (maintmpl)))))
3318     error ("partial specialization %qT does not specialize any template arguments", type);
3319
3320   /* [temp.class.spec]
3321
3322      A partially specialized non-type argument expression shall not
3323      involve template parameters of the partial specialization except
3324      when the argument expression is a simple identifier.
3325
3326      The type of a template parameter corresponding to a specialized
3327      non-type argument shall not be dependent on a parameter of the
3328      specialization. 
3329
3330      Also, we verify that pack expansions only occur at the
3331      end of the argument list.  */
3332   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3333   tpd2.parms = 0;
3334   for (i = 0; i < nargs; ++i)
3335     {
3336       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3337       tree arg = TREE_VEC_ELT (inner_args, i);
3338       tree packed_args = NULL_TREE;
3339       int j, len = 1;
3340
3341       if (ARGUMENT_PACK_P (arg))
3342         {
3343           /* Extract the arguments from the argument pack. We'll be
3344              iterating over these in the following loop.  */
3345           packed_args = ARGUMENT_PACK_ARGS (arg);
3346           len = TREE_VEC_LENGTH (packed_args);
3347         }
3348
3349       for (j = 0; j < len; j++)
3350         {
3351           if (packed_args)
3352             /* Get the Jth argument in the parameter pack.  */
3353             arg = TREE_VEC_ELT (packed_args, j);
3354
3355           if (PACK_EXPANSION_P (arg))
3356             {
3357               /* Pack expansions must come at the end of the
3358                  argument list.  */
3359               if ((packed_args && j < len - 1)
3360                   || (!packed_args && i < nargs - 1))
3361                 {
3362                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3363                     error ("parameter pack argument %qE must be at the end of the template argument list", arg);
3364                   else
3365                     error ("parameter pack argument %qT must be at the end of the template argument list", arg);                   
3366                 }
3367             }
3368
3369           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3370             /* We only care about the pattern.  */
3371             arg = PACK_EXPANSION_PATTERN (arg);
3372
3373           if (/* These first two lines are the `non-type' bit.  */
3374               !TYPE_P (arg)
3375               && TREE_CODE (arg) != TEMPLATE_DECL
3376               /* This next line is the `argument expression is not just a
3377                  simple identifier' condition and also the `specialized
3378                  non-type argument' bit.  */
3379               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3380             {
3381               if ((!packed_args && tpd.arg_uses_template_parms[i])
3382                   || (packed_args && uses_template_parms (arg)))
3383                 error ("template argument %qE involves template parameter(s)",
3384                        arg);
3385               else 
3386                 {
3387                   /* Look at the corresponding template parameter,
3388                      marking which template parameters its type depends
3389                      upon.  */
3390                   tree type = TREE_TYPE (parm);
3391
3392                   if (!tpd2.parms)
3393                     {
3394                       /* We haven't yet initialized TPD2.  Do so now.  */
3395                       tpd2.arg_uses_template_parms 
3396                         = (int *) alloca (sizeof (int) * nargs);
3397                       /* The number of parameters here is the number in the
3398                          main template, which, as checked in the assertion
3399                          above, is NARGS.  */
3400                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3401                       tpd2.level = 
3402                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3403                     }
3404
3405                   /* Mark the template parameters.  But this time, we're
3406                      looking for the template parameters of the main
3407                      template, not in the specialization.  */
3408                   tpd2.current_arg = i;
3409                   tpd2.arg_uses_template_parms[i] = 0;
3410                   memset (tpd2.parms, 0, sizeof (int) * nargs);
3411                   for_each_template_parm (type,
3412                                           &mark_template_parm,
3413                                           &tpd2,
3414                                           NULL);
3415
3416                   if (tpd2.arg_uses_template_parms [i])
3417                     {
3418                       /* The type depended on some template parameters.
3419                          If they are fully specialized in the
3420                          specialization, that's OK.  */
3421                       int j;
3422                       for (j = 0; j < nargs; ++j)
3423                         if (tpd2.parms[j] != 0
3424                             && tpd.arg_uses_template_parms [j])
3425                           {
3426                             error ("type %qT of template argument %qE depends "
3427                                    "on template parameter(s)", 
3428                                    type,
3429                                    arg);
3430                             break;
3431                           }
3432                     }
3433                 }
3434             }
3435         }
3436     }
3437
3438   if (retrieve_specialization (maintmpl, specargs,
3439                                /*class_specializations_p=*/true))
3440     /* We've already got this specialization.  */
3441     return decl;
3442
3443   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
3444     = tree_cons (specargs, inner_parms,
3445                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
3446   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
3447   return decl;
3448 }
3449
3450 /* Check that a template declaration's use of default arguments is not
3451    invalid.  Here, PARMS are the template parameters.  IS_PRIMARY is
3452    nonzero if DECL is the thing declared by a primary template.
3453    IS_PARTIAL is nonzero if DECL is a partial specialization.
3454    
3455
3456    IS_FRIEND_DECL is nonzero if DECL is a friend function template
3457    declaration (but not a definition); 1 indicates a declaration, 2
3458    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
3459    emitted for extraneous default arguments.
3460
3461    Returns TRUE if there were no errors found, FALSE otherwise. */
3462
3463 bool
3464 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
3465                          int is_partial, int is_friend_decl)
3466 {
3467   const char *msg;
3468   int last_level_to_check;
3469   tree parm_level;
3470   bool no_errors = true;
3471
3472   /* [temp.param]
3473
3474      A default template-argument shall not be specified in a
3475      function template declaration or a function template definition, nor
3476      in the template-parameter-list of the definition of a member of a
3477      class template.  */
3478
3479   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
3480     /* You can't have a function template declaration in a local
3481        scope, nor you can you define a member of a class template in a
3482        local scope.  */
3483     return true;
3484
3485   if (current_class_type
3486       && !TYPE_BEING_DEFINED (current_class_type)
3487       && DECL_LANG_SPECIFIC (decl)
3488       /* If this is either a friend defined in the scope of the class
3489          or a member function.  */
3490       && (DECL_FUNCTION_MEMBER_P (decl)
3491           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
3492           : DECL_FRIEND_CONTEXT (decl)
3493           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
3494           : false)
3495       /* And, if it was a member function, it really was defined in
3496          the scope of the class.  */
3497       && (!DECL_FUNCTION_MEMBER_P (decl)
3498           || DECL_INITIALIZED_IN_CLASS_P (decl)))
3499     /* We already checked these parameters when the template was
3500        declared, so there's no need to do it again now.  This function
3501        was defined in class scope, but we're processing it's body now
3502        that the class is complete.  */
3503     return true;
3504
3505   /* Core issue 226 (C++0x only): the following only applies to class
3506      templates.  */
3507   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
3508     {
3509       /* [temp.param]
3510
3511          If a template-parameter has a default template-argument, all
3512          subsequent template-parameters shall have a default
3513          template-argument supplied.  */
3514       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
3515         {
3516           tree inner_parms = TREE_VALUE (parm_level);
3517           int ntparms = TREE_VEC_LENGTH (inner_parms);
3518           int seen_def_arg_p = 0;
3519           int i;
3520
3521           for (i = 0; i < ntparms; ++i)
3522             {
3523               tree parm = TREE_VEC_ELT (inner_parms, i);
3524
3525               if (parm == error_mark_node)
3526                 continue;
3527
3528               if (TREE_PURPOSE (parm))
3529                 seen_def_arg_p = 1;
3530               else if (seen_def_arg_p)
3531                 {
3532                   error ("no default argument for %qD", TREE_VALUE (parm));
3533                   /* For better subsequent error-recovery, we indicate that
3534                      there should have been a default argument.  */
3535                   TREE_PURPOSE (parm) = error_mark_node;
3536                   no_errors = false;
3537                 }
3538             }
3539         }
3540     }
3541
3542   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
3543       || is_partial 
3544       || !is_primary
3545       || is_friend_decl)
3546     /* For an ordinary class template, default template arguments are
3547        allowed at the innermost level, e.g.:
3548          template <class T = int>
3549          struct S {};
3550        but, in a partial specialization, they're not allowed even
3551        there, as we have in [temp.class.spec]:
3552
3553          The template parameter list of a specialization shall not
3554          contain default template argument values.
3555
3556        So, for a partial specialization, or for a function template
3557        (in C++98/C++03), we look at all of them.  */
3558     ;
3559   else
3560     /* But, for a primary class template that is not a partial
3561        specialization we look at all template parameters except the
3562        innermost ones.  */
3563     parms = TREE_CHAIN (parms);
3564
3565   /* Figure out what error message to issue.  */
3566   if (is_friend_decl == 2)
3567     msg = "default template arguments may not be used in function template friend re-declaration";
3568   else if (is_friend_decl)
3569     msg = "default template arguments may not be used in function template friend declarations";
3570   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
3571     msg = "default template arguments may not be used in function templates";
3572   else if (is_partial)
3573     msg = "default template arguments may not be used in partial specializations";
3574   else
3575     msg = "default argument for template parameter for class enclosing %qD";
3576
3577   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
3578     /* If we're inside a class definition, there's no need to
3579        examine the parameters to the class itself.  On the one
3580        hand, they will be checked when the class is defined, and,
3581        on the other, default arguments are valid in things like:
3582          template <class T = double>
3583          struct S { template <class U> void f(U); };
3584        Here the default argument for `S' has no bearing on the
3585        declaration of `f'.  */
3586     last_level_to_check = template_class_depth (current_class_type) + 1;
3587   else
3588     /* Check everything.  */
3589     last_level_to_check = 0;
3590
3591   for (parm_level = parms;
3592        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
3593        parm_level = TREE_CHAIN (parm_level))
3594     {
3595       tree inner_parms = TREE_VALUE (parm_level);
3596       int i;
3597       int ntparms;
3598
3599       ntparms = TREE_VEC_LENGTH (inner_parms);
3600       for (i = 0; i < ntparms; ++i)
3601         {
3602           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
3603             continue;
3604
3605           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
3606             {
3607               if (msg)
3608                 {
3609                   no_errors = false;
3610                   if (is_friend_decl == 2)
3611                     return no_errors;
3612
3613                   error (msg, decl);
3614                   msg = 0;
3615                 }
3616
3617               /* Clear out the default argument so that we are not
3618                  confused later.  */
3619               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
3620             }
3621         }
3622
3623       /* At this point, if we're still interested in issuing messages,
3624          they must apply to classes surrounding the object declared.  */
3625       if (msg)
3626         msg = "default argument for template parameter for class enclosing %qD";
3627     }
3628
3629   return no_errors;
3630 }
3631
3632 /* Worker for push_template_decl_real, called via
3633    for_each_template_parm.  DATA is really an int, indicating the
3634    level of the parameters we are interested in.  If T is a template
3635    parameter of that level, return nonzero.  */
3636
3637 static int
3638 template_parm_this_level_p (tree t, void* data)
3639 {
3640   int this_level = *(int *)data;
3641   int level;
3642
3643   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3644     level = TEMPLATE_PARM_LEVEL (t);
3645   else
3646     level = TEMPLATE_TYPE_LEVEL (t);
3647   return level == this_level;
3648 }
3649
3650 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
3651    parameters given by current_template_args, or reuses a
3652    previously existing one, if appropriate.  Returns the DECL, or an
3653    equivalent one, if it is replaced via a call to duplicate_decls.
3654
3655    If IS_FRIEND is true, DECL is a friend declaration.  */
3656
3657 tree
3658 push_template_decl_real (tree decl, bool is_friend)
3659 {
3660   tree tmpl;
3661   tree args;
3662   tree info;
3663   tree ctx;
3664   int primary;
3665   int is_partial;
3666   int new_template_p = 0;
3667   /* True if the template is a member template, in the sense of
3668      [temp.mem].  */
3669   bool member_template_p = false;
3670
3671   if (decl == error_mark_node)
3672     return decl;
3673
3674   /* See if this is a partial specialization.  */
3675   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
3676                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
3677                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
3678
3679   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
3680     is_friend = true;
3681
3682   if (is_friend)
3683     /* For a friend, we want the context of the friend function, not
3684        the type of which it is a friend.  */
3685     ctx = DECL_CONTEXT (decl);
3686   else if (CP_DECL_CONTEXT (decl)
3687            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
3688     /* In the case of a virtual function, we want the class in which
3689        it is defined.  */
3690     ctx = CP_DECL_CONTEXT (decl);
3691   else
3692     /* Otherwise, if we're currently defining some class, the DECL
3693        is assumed to be a member of the class.  */
3694     ctx = current_scope ();
3695
3696   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
3697     ctx = NULL_TREE;
3698
3699   if (!DECL_CONTEXT (decl))
3700     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
3701
3702   /* See if this is a primary template.  */
3703   if (is_friend && ctx)
3704     /* A friend template that specifies a class context, i.e.
3705          template <typename T> friend void A<T>::f();
3706        is not primary.  */
3707     primary = 0;
3708   else
3709     primary = template_parm_scope_p ();
3710
3711   if (primary)
3712     {
3713       if (DECL_CLASS_SCOPE_P (decl))
3714         member_template_p = true;
3715       if (TREE_CODE (decl) == TYPE_DECL
3716           && ANON_AGGRNAME_P (DECL_NAME (decl)))
3717         error ("template class without a name");
3718       else if (TREE_CODE (decl) == FUNCTION_DECL)
3719         {
3720           if (DECL_DESTRUCTOR_P (decl))
3721             {
3722               /* [temp.mem]
3723
3724                  A destructor shall not be a member template.  */
3725               error ("destructor %qD declared as member template", decl);
3726               return error_mark_node;
3727             }
3728           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
3729               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
3730                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
3731                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
3732                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
3733                       == void_list_node)))
3734             {
3735               /* [basic.stc.dynamic.allocation]
3736
3737                  An allocation function can be a function
3738                  template. ... Template allocation functions shall
3739                  have two or more parameters.  */
3740               error ("invalid template declaration of %qD", decl);
3741               return error_mark_node;
3742             }
3743         }
3744       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3745                && CLASS_TYPE_P (TREE_TYPE (decl)))
3746         /* OK */;
3747       else
3748         {
3749           error ("template declaration of %q#D", decl);
3750           return error_mark_node;
3751         }
3752     }
3753
3754   /* Check to see that the rules regarding the use of default
3755      arguments are not being violated.  */
3756   check_default_tmpl_args (decl, current_template_parms,
3757                            primary, is_partial, /*is_friend_decl=*/0);
3758
3759   /* Ensure that there are no parameter packs in the type of this
3760      declaration that have not been expanded.  */
3761   if (TREE_CODE (decl) == FUNCTION_DECL)
3762     {
3763       /* Check each of the arguments individually to see if there are
3764          any bare parameter packs.  */
3765       tree type = TREE_TYPE (decl);
3766       tree arg = DECL_ARGUMENTS (decl);
3767       tree argtype = TYPE_ARG_TYPES (type);
3768
3769       while (arg && argtype)
3770         {
3771           if (!FUNCTION_PARAMETER_PACK_P (arg)
3772               && !check_for_bare_parameter_packs (TREE_TYPE (arg)))
3773             {
3774             /* This is a PARM_DECL that contains unexpanded parameter
3775                packs. We have already complained about this in the
3776                check_for_bare_parameter_packs call, so just replace
3777                these types with ERROR_MARK_NODE.  */
3778               TREE_TYPE (arg) = error_mark_node;
3779               TREE_VALUE (argtype) = error_mark_node;
3780             }
3781
3782           arg = TREE_CHAIN (arg);
3783           argtype = TREE_CHAIN (argtype);
3784         }
3785
3786       /* Check for bare parameter packs in the return type and the
3787          exception specifiers.  */
3788       check_for_bare_parameter_packs (TREE_TYPE (type));
3789       check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type));
3790     }
3791   else
3792     check_for_bare_parameter_packs (TREE_TYPE (decl));
3793
3794   if (is_partial)
3795     return process_partial_specialization (decl);
3796
3797   /* A primary class template can only have one parameter pack, at the
3798      end of the template parameter list.  */
3799   if (primary && TREE_CODE (decl) == TYPE_DECL)
3800     {
3801       tree inner_parms 
3802         = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3803       int i, len = TREE_VEC_LENGTH (inner_parms);
3804       for (i = 0; i < len - 1; i++)
3805         {
3806           tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
3807
3808           if (template_parameter_pack_p (parm))
3809             {
3810               if (TREE_CODE (parm) == PARM_DECL)
3811                 error ("parameter pack %qE must be at the end of the"
3812                        " template parameter list", parm);
3813               else
3814                 error ("parameter pack %qT must be at the end of the"
3815                        " template parameter list", TREE_TYPE (parm));
3816             }
3817         }
3818     }
3819
3820   args = current_template_args ();
3821
3822   if (!ctx
3823       || TREE_CODE (ctx) == FUNCTION_DECL
3824       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
3825       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
3826     {
3827       if (DECL_LANG_SPECIFIC (decl)
3828           && DECL_TEMPLATE_INFO (decl)
3829           && DECL_TI_TEMPLATE (decl))
3830         tmpl = DECL_TI_TEMPLATE (decl);
3831       /* If DECL is a TYPE_DECL for a class-template, then there won't
3832          be DECL_LANG_SPECIFIC.  The information equivalent to
3833          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
3834       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3835                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
3836                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
3837         {
3838           /* Since a template declaration already existed for this
3839              class-type, we must be redeclaring it here.  Make sure
3840              that the redeclaration is valid.  */
3841           redeclare_class_template (TREE_TYPE (decl),
3842                                     current_template_parms);
3843           /* We don't need to create a new TEMPLATE_DECL; just use the
3844              one we already had.  */
3845           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
3846         }
3847       else
3848         {
3849           tmpl = build_template_decl (decl, current_template_parms,
3850                                       member_template_p);
3851           new_template_p = 1;
3852
3853           if (DECL_LANG_SPECIFIC (decl)
3854               && DECL_TEMPLATE_SPECIALIZATION (decl))
3855             {
3856               /* A specialization of a member template of a template
3857                  class.  */
3858               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3859               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
3860               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
3861             }
3862         }
3863     }
3864   else
3865     {
3866       tree a, t, current, parms;
3867       int i;
3868
3869       if (TREE_CODE (decl) == TYPE_DECL)
3870         {
3871           if ((IS_AGGR_TYPE_CODE (TREE_CODE (TREE_TYPE (decl)))
3872                || TREE_CODE (TREE_TYPE (decl)) == ENUMERAL_TYPE)
3873               && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
3874               && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
3875             tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
3876           else
3877             {
3878               error ("%qD does not declare a template type", decl);
3879               return decl;
3880             }
3881         }
3882       else if (!DECL_LANG_SPECIFIC (decl) || !DECL_TEMPLATE_INFO (decl))
3883         {
3884           error ("template definition of non-template %q#D", decl);
3885           return decl;
3886         }
3887       else
3888         tmpl = DECL_TI_TEMPLATE (decl);
3889
3890       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3891           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
3892           && DECL_TEMPLATE_SPECIALIZATION (decl)
3893           && DECL_MEMBER_TEMPLATE_P (tmpl))
3894         {
3895           tree new_tmpl;
3896
3897           /* The declaration is a specialization of a member
3898              template, declared outside the class.  Therefore, the
3899              innermost template arguments will be NULL, so we
3900              replace them with the arguments determined by the
3901              earlier call to check_explicit_specialization.  */
3902           args = DECL_TI_ARGS (decl);
3903
3904           new_tmpl
3905             = build_template_decl (decl, current_template_parms,
3906                                    member_template_p);
3907           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
3908           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
3909           DECL_TI_TEMPLATE (decl) = new_tmpl;
3910           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
3911           DECL_TEMPLATE_INFO (new_tmpl)
3912             = tree_cons (tmpl, args, NULL_TREE);
3913
3914           register_specialization (new_tmpl,
3915                                    most_general_template (tmpl),
3916                                    args,
3917                                    is_friend);
3918           return decl;
3919         }
3920
3921       /* Make sure the template headers we got make sense.  */
3922
3923       parms = DECL_TEMPLATE_PARMS (tmpl);
3924       i = TMPL_PARMS_DEPTH (parms);
3925       if (TMPL_ARGS_DEPTH (args) != i)
3926         {
3927           error ("expected %d levels of template parms for %q#D, got %d",
3928                  i, decl, TMPL_ARGS_DEPTH (args));
3929         }
3930       else
3931         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
3932           {
3933             a = TMPL_ARGS_LEVEL (args, i);
3934             t = INNERMOST_TEMPLATE_PARMS (parms);
3935
3936             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
3937               {
3938                 if (current == decl)
3939                   error ("got %d template parameters for %q#D",
3940                          TREE_VEC_LENGTH (a), decl);
3941                 else
3942                   error ("got %d template parameters for %q#T",
3943                          TREE_VEC_LENGTH (a), current);
3944                 error ("  but %d required", TREE_VEC_LENGTH (t));
3945                 return error_mark_node;
3946               }
3947
3948             /* Perhaps we should also check that the parms are used in the
3949                appropriate qualifying scopes in the declarator?  */
3950
3951             if (current == decl)
3952               current = ctx;
3953             else
3954               current = (TYPE_P (current)
3955                          ? TYPE_CONTEXT (current)
3956                          : DECL_CONTEXT (current));
3957           }
3958     }
3959
3960   DECL_TEMPLATE_RESULT (tmpl) = decl;
3961   TREE_TYPE (tmpl) = TREE_TYPE (decl);
3962
3963   /* Push template declarations for global functions and types.  Note
3964      that we do not try to push a global template friend declared in a
3965      template class; such a thing may well depend on the template
3966      parameters of the class.  */
3967   if (new_template_p && !ctx
3968       && !(is_friend && template_class_depth (current_class_type) > 0))
3969     {
3970       tmpl = pushdecl_namespace_level (tmpl, is_friend);
3971       if (tmpl == error_mark_node)
3972         return error_mark_node;
3973
3974       /* Hide template friend classes that haven't been declared yet.  */
3975       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
3976         {
3977           DECL_ANTICIPATED (tmpl) = 1;
3978           DECL_FRIEND_P (tmpl) = 1;
3979         }
3980     }
3981
3982   if (primary)
3983     {
3984       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
3985       if (DECL_CONV_FN_P (tmpl))
3986         {
3987           int depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
3988
3989           /* It is a conversion operator. See if the type converted to
3990              depends on innermost template operands.  */
3991
3992           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
3993                                          depth))
3994             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
3995         }
3996     }
3997
3998   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
3999      back to its most general template.  If TMPL is a specialization,
4000      ARGS may only have the innermost set of arguments.  Add the missing
4001      argument levels if necessary.  */
4002   if (DECL_TEMPLATE_INFO (tmpl))
4003     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4004
4005   info = tree_cons (tmpl, args, NULL_TREE);
4006
4007   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4008     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4009   else if (DECL_LANG_SPECIFIC (decl))
4010     DECL_TEMPLATE_INFO (decl) = info;
4011
4012   return DECL_TEMPLATE_RESULT (tmpl);
4013 }
4014
4015 tree
4016 push_template_decl (tree decl)
4017 {
4018   return push_template_decl_real (decl, false);
4019 }
4020
4021 /* Called when a class template TYPE is redeclared with the indicated
4022    template PARMS, e.g.:
4023
4024      template <class T> struct S;
4025      template <class T> struct S {};  */
4026
4027 bool
4028 redeclare_class_template (tree type, tree parms)
4029 {
4030   tree tmpl;
4031   tree tmpl_parms;
4032   int i;
4033
4034   if (!TYPE_TEMPLATE_INFO (type))
4035     {
4036       error ("%qT is not a template type", type);
4037       return false;
4038     }
4039
4040   tmpl = TYPE_TI_TEMPLATE (type);
4041   if (!PRIMARY_TEMPLATE_P (tmpl))
4042     /* The type is nested in some template class.  Nothing to worry
4043        about here; there are no new template parameters for the nested
4044        type.  */
4045     return true;
4046
4047   if (!parms)
4048     {
4049       error ("template specifiers not specified in declaration of %qD",
4050              tmpl);
4051       return false;
4052     }
4053
4054   parms = INNERMOST_TEMPLATE_PARMS (parms);
4055   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4056
4057   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4058     {
4059       error ("previous declaration %q+D", tmpl);
4060       error ("used %d template parameter(s) instead of %d",
4061              TREE_VEC_LENGTH (tmpl_parms),
4062              TREE_VEC_LENGTH (parms));
4063       return false;
4064     }
4065
4066   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4067     {
4068       tree tmpl_parm;
4069       tree parm;
4070       tree tmpl_default;
4071       tree parm_default;
4072
4073       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4074           || TREE_VEC_ELT (parms, i) == error_mark_node)
4075         continue;
4076
4077       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4078       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4079       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4080       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4081
4082       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4083          TEMPLATE_DECL.  */
4084       if (tmpl_parm != error_mark_node
4085            && (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4086            || (TREE_CODE (tmpl_parm) != TYPE_DECL
4087                && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))))
4088         {
4089           error ("template parameter %q+#D", tmpl_parm);
4090           error ("redeclared here as %q#D", parm);
4091           return false;
4092         }
4093
4094       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4095         {
4096           /* We have in [temp.param]:
4097
4098              A template-parameter may not be given default arguments
4099              by two different declarations in the same scope.  */
4100           error ("redefinition of default argument for %q#D", parm);
4101           error ("%J  original definition appeared here", tmpl_parm);
4102           return false;
4103         }
4104
4105       if (parm_default != NULL_TREE)
4106         /* Update the previous template parameters (which are the ones
4107            that will really count) with the new default value.  */
4108         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4109       else if (tmpl_default != NULL_TREE)
4110         /* Update the new parameters, too; they'll be used as the
4111            parameters for any members.  */
4112         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4113     }
4114
4115     return true;
4116 }
4117
4118 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4119    (possibly simplified) expression.  */
4120
4121 tree
4122 fold_non_dependent_expr (tree expr)
4123 {
4124   if (expr == NULL_TREE)
4125     return NULL_TREE;
4126
4127   /* If we're in a template, but EXPR isn't value dependent, simplify
4128      it.  We're supposed to treat:
4129
4130        template <typename T> void f(T[1 + 1]);
4131        template <typename T> void f(T[2]);
4132
4133      as two declarations of the same function, for example.  */
4134   if (processing_template_decl
4135       && !type_dependent_expression_p (expr)
4136       && !value_dependent_expression_p (expr))
4137     {
4138       HOST_WIDE_INT saved_processing_template_decl;
4139
4140       saved_processing_template_decl = processing_template_decl;
4141       processing_template_decl = 0;
4142       expr = tsubst_copy_and_build (expr,
4143                                     /*args=*/NULL_TREE,
4144                                     tf_error,
4145                                     /*in_decl=*/NULL_TREE,
4146                                     /*function_p=*/false,
4147                                     /*integral_constant_expression_p=*/true);
4148       processing_template_decl = saved_processing_template_decl;
4149     }
4150   return expr;
4151 }
4152
4153 /* EXPR is an expression which is used in a constant-expression context.
4154    For instance, it could be a VAR_DECL with a constant initializer.
4155    Extract the innest constant expression.
4156
4157    This is basically a more powerful version of
4158    integral_constant_value, which can be used also in templates where
4159    initializers can maintain a syntactic rather than semantic form
4160    (even if they are non-dependent, for access-checking purposes).  */
4161
4162 static tree
4163 fold_decl_constant_value (tree expr)
4164 {
4165   tree const_expr = expr;
4166   do
4167     {
4168       expr = fold_non_dependent_expr (const_expr);
4169       const_expr = integral_constant_value (expr);
4170     }
4171   while (expr != const_expr);
4172
4173   return expr;
4174 }
4175
4176 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4177    must be a function or a pointer-to-function type, as specified
4178    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4179    and check that the resulting function has external linkage.  */
4180
4181 static tree
4182 convert_nontype_argument_function (tree type, tree expr)
4183 {
4184   tree fns = expr;
4185   tree fn, fn_no_ptr;
4186
4187   fn = instantiate_type (type, fns, tf_none);
4188   if (fn == error_mark_node)
4189     return error_mark_node;
4190
4191   fn_no_ptr = fn;
4192   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4193     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4194   if (TREE_CODE (fn_no_ptr) == BASELINK)
4195     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4196  
4197   /* [temp.arg.nontype]/1
4198
4199      A template-argument for a non-type, non-template template-parameter
4200      shall be one of:
4201      [...]
4202      -- the address of an object or function with external linkage.  */
4203   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4204     {
4205       error ("%qE is not a valid template argument for type %qT "
4206              "because function %qD has not external linkage",
4207              expr, type, fn_no_ptr);
4208       return NULL_TREE;
4209     }
4210
4211   return fn;
4212 }
4213
4214 /* Attempt to convert the non-type template parameter EXPR to the
4215    indicated TYPE.  If the conversion is successful, return the
4216    converted value.  If the conversion is unsuccessful, return
4217    NULL_TREE if we issued an error message, or error_mark_node if we
4218    did not.  We issue error messages for out-and-out bad template
4219    parameters, but not simply because the conversion failed, since we
4220    might be just trying to do argument deduction.  Both TYPE and EXPR
4221    must be non-dependent.
4222
4223    The conversion follows the special rules described in
4224    [temp.arg.nontype], and it is much more strict than an implicit
4225    conversion.
4226
4227    This function is called twice for each template argument (see
4228    lookup_template_class for a more accurate description of this
4229    problem). This means that we need to handle expressions which
4230    are not valid in a C++ source, but can be created from the
4231    first call (for instance, casts to perform conversions). These
4232    hacks can go away after we fix the double coercion problem.  */
4233
4234 static tree
4235 convert_nontype_argument (tree type, tree expr)
4236 {
4237   tree expr_type;
4238
4239   /* Detect immediately string literals as invalid non-type argument.
4240      This special-case is not needed for correctness (we would easily
4241      catch this later), but only to provide better diagnostic for this
4242      common user mistake. As suggested by DR 100, we do not mention
4243      linkage issues in the diagnostic as this is not the point.  */
4244   if (TREE_CODE (expr) == STRING_CST)
4245     {
4246       error ("%qE is not a valid template argument for type %qT "
4247              "because string literals can never be used in this context",
4248              expr, type);
4249       return NULL_TREE;
4250     }
4251
4252   /* If we are in a template, EXPR may be non-dependent, but still
4253      have a syntactic, rather than semantic, form.  For example, EXPR
4254      might be a SCOPE_REF, rather than the VAR_DECL to which the
4255      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4256      so that access checking can be performed when the template is
4257      instantiated -- but here we need the resolved form so that we can
4258      convert the argument.  */
4259   expr = fold_non_dependent_expr (expr);
4260   if (error_operand_p (expr))
4261     return error_mark_node;
4262   expr_type = TREE_TYPE (expr);
4263
4264   /* HACK: Due to double coercion, we can get a
4265      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4266      which is the tree that we built on the first call (see
4267      below when coercing to reference to object or to reference to
4268      function). We just strip everything and get to the arg.
4269      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4270      for examples.  */
4271   if (TREE_CODE (expr) == NOP_EXPR)
4272     {
4273       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4274         {
4275           /* ??? Maybe we could use convert_from_reference here, but we
4276              would need to relax its constraints because the NOP_EXPR
4277              could actually change the type to something more cv-qualified,
4278              and this is not folded by convert_from_reference.  */
4279           tree addr = TREE_OPERAND (expr, 0);
4280           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4281           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4282           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4283           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4284                       (TREE_TYPE (expr_type),
4285                        TREE_TYPE (TREE_TYPE (addr))));
4286
4287           expr = TREE_OPERAND (addr, 0);
4288           expr_type = TREE_TYPE (expr);
4289         }
4290
4291       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4292          parameter is a pointer to object, through decay and
4293          qualification conversion. Let's strip everything.  */
4294       else if (TYPE_PTROBV_P (type))
4295         {
4296           STRIP_NOPS (expr);
4297           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4298           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4299           /* Skip the ADDR_EXPR only if it is part of the decay for
4300              an array. Otherwise, it is part of the original argument
4301              in the source code.  */
4302           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4303             expr = TREE_OPERAND (expr, 0);
4304           expr_type = TREE_TYPE (expr);
4305         }
4306     }
4307
4308   /* [temp.arg.nontype]/5, bullet 1
4309
4310      For a non-type template-parameter of integral or enumeration type,
4311      integral promotions (_conv.prom_) and integral conversions
4312      (_conv.integral_) are applied.  */
4313   if (INTEGRAL_TYPE_P (type))
4314     {
4315       if (!INTEGRAL_TYPE_P (expr_type))
4316         return error_mark_node;
4317
4318       expr = fold_decl_constant_value (expr);
4319       /* Notice that there are constant expressions like '4 % 0' which
4320          do not fold into integer constants.  */
4321       if (TREE_CODE (expr) != INTEGER_CST)
4322         {
4323           error ("%qE is not a valid template argument for type %qT "
4324                  "because it is a non-constant expression", expr, type);
4325           return NULL_TREE;
4326         }
4327
4328       /* At this point, an implicit conversion does what we want,
4329          because we already know that the expression is of integral
4330          type.  */
4331       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4332       if (expr == error_mark_node)
4333         return error_mark_node;
4334
4335       /* Conversion was allowed: fold it to a bare integer constant.  */
4336       expr = fold (expr);
4337     }
4338   /* [temp.arg.nontype]/5, bullet 2
4339
4340      For a non-type template-parameter of type pointer to object,
4341      qualification conversions (_conv.qual_) and the array-to-pointer
4342      conversion (_conv.array_) are applied.  */
4343   else if (TYPE_PTROBV_P (type))
4344     {
4345       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
4346
4347          A template-argument for a non-type, non-template template-parameter
4348          shall be one of: [...]
4349
4350          -- the name of a non-type template-parameter;
4351          -- the address of an object or function with external linkage, [...]
4352             expressed as "& id-expression" where the & is optional if the name
4353             refers to a function or array, or if the corresponding
4354             template-parameter is a reference.
4355
4356         Here, we do not care about functions, as they are invalid anyway
4357         for a parameter of type pointer-to-object.  */
4358
4359       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
4360         /* Non-type template parameters are OK.  */
4361         ;
4362       else if (TREE_CODE (expr) != ADDR_EXPR
4363                && TREE_CODE (expr_type) != ARRAY_TYPE)
4364         {
4365           if (TREE_CODE (expr) == VAR_DECL)
4366             {
4367               error ("%qD is not a valid template argument "
4368                      "because %qD is a variable, not the address of "
4369                      "a variable",
4370                      expr, expr);
4371               return NULL_TREE;
4372             }
4373           /* Other values, like integer constants, might be valid
4374              non-type arguments of some other type.  */
4375           return error_mark_node;
4376         }
4377       else
4378         {
4379           tree decl;
4380
4381           decl = ((TREE_CODE (expr) == ADDR_EXPR)
4382                   ? TREE_OPERAND (expr, 0) : expr);
4383           if (TREE_CODE (decl) != VAR_DECL)
4384             {
4385               error ("%qE is not a valid template argument of type %qT "
4386                      "because %qE is not a variable",
4387                      expr, type, decl);
4388               return NULL_TREE;
4389             }
4390           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
4391             {
4392               error ("%qE is not a valid template argument of type %qT "
4393                      "because %qD does not have external linkage",
4394                      expr, type, decl);
4395               return NULL_TREE;
4396             }
4397         }
4398
4399       expr = decay_conversion (expr);
4400       if (expr == error_mark_node)
4401         return error_mark_node;
4402
4403       expr = perform_qualification_conversions (type, expr);
4404       if (expr == error_mark_node)
4405         return error_mark_node;
4406     }
4407   /* [temp.arg.nontype]/5, bullet 3
4408
4409      For a non-type template-parameter of type reference to object, no
4410      conversions apply. The type referred to by the reference may be more
4411      cv-qualified than the (otherwise identical) type of the
4412      template-argument. The template-parameter is bound directly to the
4413      template-argument, which must be an lvalue.  */
4414   else if (TYPE_REF_OBJ_P (type))
4415     {
4416       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
4417                                                       expr_type))
4418         return error_mark_node;
4419
4420       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
4421         {
4422           error ("%qE is not a valid template argument for type %qT "
4423                  "because of conflicts in cv-qualification", expr, type);
4424           return NULL_TREE;
4425         }
4426
4427       if (!real_lvalue_p (expr))
4428         {
4429           error ("%qE is not a valid template argument for type %qT "
4430                  "because it is not an lvalue", expr, type);
4431           return NULL_TREE;
4432         }
4433
4434       /* [temp.arg.nontype]/1
4435
4436          A template-argument for a non-type, non-template template-parameter
4437          shall be one of: [...]
4438
4439          -- the address of an object or function with external linkage.  */
4440       if (!DECL_EXTERNAL_LINKAGE_P (expr))
4441         {
4442           error ("%qE is not a valid template argument for type %qT "
4443                  "because object %qD has not external linkage",
4444                  expr, type, expr);
4445           return NULL_TREE;
4446         }
4447
4448       expr = build_nop (type, build_address (expr));
4449     }
4450   /* [temp.arg.nontype]/5, bullet 4
4451
4452      For a non-type template-parameter of type pointer to function, only
4453      the function-to-pointer conversion (_conv.func_) is applied. If the
4454      template-argument represents a set of overloaded functions (or a
4455      pointer to such), the matching function is selected from the set
4456      (_over.over_).  */
4457   else if (TYPE_PTRFN_P (type))
4458     {
4459       /* If the argument is a template-id, we might not have enough
4460          context information to decay the pointer.  */
4461       if (!type_unknown_p (expr_type))
4462         {
4463           expr = decay_conversion (expr);
4464           if (expr == error_mark_node)
4465             return error_mark_node;
4466         }
4467
4468       expr = convert_nontype_argument_function (type, expr);
4469       if (!expr || expr == error_mark_node)
4470         return expr;
4471     }
4472   /* [temp.arg.nontype]/5, bullet 5
4473
4474      For a non-type template-parameter of type reference to function, no
4475      conversions apply. If the template-argument represents a set of
4476      overloaded functions, the matching function is selected from the set
4477      (_over.over_).  */
4478   else if (TYPE_REFFN_P (type))
4479     {
4480       if (TREE_CODE (expr) == ADDR_EXPR)
4481         {
4482           error ("%qE is not a valid template argument for type %qT "
4483                  "because it is a pointer", expr, type);
4484           inform ("try using %qE instead", TREE_OPERAND (expr, 0));
4485           return NULL_TREE;
4486         }
4487
4488       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
4489       if (!expr || expr == error_mark_node)
4490         return expr;
4491
4492       expr = build_nop (type, build_address (expr));
4493     }
4494   /* [temp.arg.nontype]/5, bullet 6
4495
4496      For a non-type template-parameter of type pointer to member function,
4497      no conversions apply. If the template-argument represents a set of
4498      overloaded member functions, the matching member function is selected
4499      from the set (_over.over_).  */
4500   else if (TYPE_PTRMEMFUNC_P (type))
4501     {
4502       expr = instantiate_type (type, expr, tf_none);
4503       if (expr == error_mark_node)
4504         return error_mark_node;
4505
4506       /* There is no way to disable standard conversions in
4507          resolve_address_of_overloaded_function (called by
4508          instantiate_type). It is possible that the call succeeded by
4509          converting &B::I to &D::I (where B is a base of D), so we need
4510          to reject this conversion here.
4511
4512          Actually, even if there was a way to disable standard conversions,
4513          it would still be better to reject them here so that we can
4514          provide a superior diagnostic.  */
4515       if (!same_type_p (TREE_TYPE (expr), type))
4516         {
4517           /* Make sure we are just one standard conversion off.  */
4518           gcc_assert (can_convert (type, TREE_TYPE (expr)));
4519           error ("%qE is not a valid template argument for type %qT "
4520                  "because it is of type %qT", expr, type,
4521                  TREE_TYPE (expr));
4522           inform ("standard conversions are not allowed in this context");
4523           return NULL_TREE;
4524         }
4525     }
4526   /* [temp.arg.nontype]/5, bullet 7
4527
4528      For a non-type template-parameter of type pointer to data member,
4529      qualification conversions (_conv.qual_) are applied.  */
4530   else if (TYPE_PTRMEM_P (type))
4531     {
4532       expr = perform_qualification_conversions (type, expr);
4533       if (expr == error_mark_node)
4534         return expr;
4535     }
4536   /* A template non-type parameter must be one of the above.  */
4537   else
4538     gcc_unreachable ();
4539
4540   /* Sanity check: did we actually convert the argument to the
4541      right type?  */
4542   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
4543   return expr;
4544 }
4545
4546
4547 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
4548    template template parameters.  Both PARM_PARMS and ARG_PARMS are
4549    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
4550    or PARM_DECL.
4551
4552    Consider the example:
4553      template <class T> class A;
4554      template<template <class U> class TT> class B;
4555
4556    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
4557    the parameters to A, and OUTER_ARGS contains A.  */
4558
4559 static int
4560 coerce_template_template_parms (tree parm_parms,
4561                                 tree arg_parms,
4562                                 tsubst_flags_t complain,
4563                                 tree in_decl,
4564                                 tree outer_args)
4565 {
4566   int nparms, nargs, i;
4567   tree parm, arg;
4568
4569   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
4570   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
4571
4572   nparms = TREE_VEC_LENGTH (parm_parms);
4573   nargs = TREE_VEC_LENGTH (arg_parms);
4574
4575   if (nargs != nparms)
4576     return 0;
4577
4578   for (i = 0; i < nparms; ++i)
4579     {
4580       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
4581           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
4582         continue;
4583
4584       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
4585       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
4586
4587       if (arg == NULL_TREE || arg == error_mark_node
4588           || parm == NULL_TREE || parm == error_mark_node)
4589         return 0;
4590
4591       if (TREE_CODE (arg) != TREE_CODE (parm))
4592         return 0;
4593
4594       switch (TREE_CODE (parm))
4595         {
4596         case TEMPLATE_DECL:
4597           /* We encounter instantiations of templates like
4598                template <template <template <class> class> class TT>
4599                class C;  */
4600           {
4601             tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
4602             tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
4603
4604             if (!coerce_template_template_parms
4605                 (parmparm, argparm, complain, in_decl, outer_args))
4606               return 0;
4607           }
4608           /* Fall through.  */
4609
4610         case TYPE_DECL:
4611           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))
4612               != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg)))
4613             /* One is a parameter pack, the other is not.  */
4614             return 0;
4615           break;
4616
4617         case PARM_DECL:
4618           /* The tsubst call is used to handle cases such as
4619
4620                template <int> class C {};
4621                template <class T, template <T> class TT> class D {};
4622                D<int, C> d;
4623
4624              i.e. the parameter list of TT depends on earlier parameters.  */
4625           if (!dependent_type_p (TREE_TYPE (arg))
4626               && !same_type_p
4627                     (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
4628                              TREE_TYPE (arg)))
4629             return 0;
4630
4631           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4632               != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg)))
4633             /* One is a parameter pack, the other is not.  */
4634             return 0;
4635           break;
4636
4637         default:
4638           gcc_unreachable ();
4639         }
4640     }
4641   return 1;
4642 }
4643
4644 /* Convert the indicated template ARG as necessary to match the
4645    indicated template PARM.  Returns the converted ARG, or
4646    error_mark_node if the conversion was unsuccessful.  Error and
4647    warning messages are issued under control of COMPLAIN.  This
4648    conversion is for the Ith parameter in the parameter list.  ARGS is
4649    the full set of template arguments deduced so far.  */
4650
4651 static tree
4652 convert_template_argument (tree parm,
4653                            tree arg,
4654                            tree args,
4655                            tsubst_flags_t complain,
4656                            int i,
4657                            tree in_decl)
4658 {
4659   tree val;
4660   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
4661   tree check_arg = arg;
4662
4663   if (TREE_CODE (arg) == TREE_LIST
4664       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
4665     {
4666       /* The template argument was the name of some
4667          member function.  That's usually
4668          invalid, but static members are OK.  In any
4669          case, grab the underlying fields/functions
4670          and issue an error later if required.  */
4671       arg = TREE_VALUE (arg);
4672       TREE_TYPE (arg) = unknown_type_node;
4673     }
4674
4675   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
4676   requires_type = (TREE_CODE (parm) == TYPE_DECL
4677                    || requires_tmpl_type);
4678
4679   /* When determining whether an argument pack expansion is a template,
4680      look at the pattern.  */
4681   if (TREE_CODE (check_arg) == TYPE_PACK_EXPANSION)
4682     check_arg = PACK_EXPANSION_PATTERN (check_arg);
4683
4684   is_tmpl_type = 
4685     ((TREE_CODE (check_arg) == TEMPLATE_DECL
4686       && TREE_CODE (DECL_TEMPLATE_RESULT (check_arg)) == TYPE_DECL)
4687      || TREE_CODE (check_arg) == TEMPLATE_TEMPLATE_PARM
4688      || TREE_CODE (check_arg) == UNBOUND_CLASS_TEMPLATE);
4689
4690   if (is_tmpl_type
4691       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4692           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
4693     arg = TYPE_STUB_DECL (arg);
4694
4695   is_type = TYPE_P (arg) || is_tmpl_type;
4696
4697   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
4698       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
4699     {
4700       pedwarn ("to refer to a type member of a template parameter, "
4701                "use %<typename %E%>", arg);
4702
4703       arg = make_typename_type (TREE_OPERAND (arg, 0),
4704                                 TREE_OPERAND (arg, 1),
4705                                 typename_type,
4706                                 complain & tf_error);
4707       is_type = 1;
4708     }
4709   if (is_type != requires_type)
4710     {
4711       if (in_decl)
4712         {
4713           if (complain & tf_error)
4714             {
4715               error ("type/value mismatch at argument %d in template "
4716                      "parameter list for %qD",
4717                      i + 1, in_decl);
4718               if (is_type)
4719                 error ("  expected a constant of type %qT, got %qT",
4720                        TREE_TYPE (parm),
4721                        (is_tmpl_type ? DECL_NAME (arg) : arg));
4722               else if (requires_tmpl_type)
4723                 error ("  expected a class template, got %qE", arg);
4724               else
4725                 error ("  expected a type, got %qE", arg);
4726             }
4727         }
4728       return error_mark_node;
4729     }
4730   if (is_tmpl_type ^ requires_tmpl_type)
4731     {
4732       if (in_decl && (complain & tf_error))
4733         {
4734           error ("type/value mismatch at argument %d in template "
4735                  "parameter list for %qD",
4736                  i + 1, in_decl);
4737           if (is_tmpl_type)
4738             error ("  expected a type, got %qT", DECL_NAME (arg));
4739           else
4740             error ("  expected a class template, got %qT", arg);
4741         }
4742       return error_mark_node;
4743     }
4744
4745   if (is_type)
4746     {
4747       if (requires_tmpl_type)
4748         {
4749           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
4750             /* The number of argument required is not known yet.
4751                Just accept it for now.  */
4752             val = TREE_TYPE (arg);
4753           else
4754             {
4755               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
4756               tree argparm;
4757
4758               check_arg = arg;
4759               /* When determining whether a pack expansion is a template,
4760                  look at the pattern.  */
4761               if (TREE_CODE (check_arg) == TYPE_PACK_EXPANSION)
4762                 check_arg = PACK_EXPANSION_PATTERN (check_arg);
4763
4764               argparm = DECL_INNERMOST_TEMPLATE_PARMS (check_arg);
4765
4766               if (coerce_template_template_parms (parmparm, argparm,
4767                                                   complain, in_decl,
4768                                                   args))
4769                 {
4770                   val = arg;
4771
4772                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
4773                      TEMPLATE_DECL.  */
4774                   if (val != error_mark_node)
4775                     {
4776                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
4777                         val = TREE_TYPE (val);
4778                       else if (TREE_CODE (val) == TYPE_PACK_EXPANSION
4779                                && DECL_TEMPLATE_TEMPLATE_PARM_P (check_arg))
4780                         {
4781                           val = TREE_TYPE (check_arg);
4782                           val = make_pack_expansion (val);
4783                         }
4784                     }
4785                 }
4786               else
4787                 {
4788                   if (in_decl && (complain & tf_error))
4789                     {
4790                       error ("type/value mismatch at argument %d in "
4791                              "template parameter list for %qD",
4792                              i + 1, in_decl);
4793                       error ("  expected a template of type %qD, got %qD",
4794                              parm, arg);
4795                     }
4796
4797                   val = error_mark_node;
4798                 }
4799             }
4800         }
4801       else
4802         val = arg;
4803       /* We only form one instance of each template specialization.
4804          Therefore, if we use a non-canonical variant (i.e., a
4805          typedef), any future messages referring to the type will use
4806          the typedef, which is confusing if those future uses do not
4807          themselves also use the typedef.  */
4808       if (TYPE_P (val))
4809         val = canonical_type_variant (val);
4810     }
4811   else
4812     {
4813       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
4814
4815       if (invalid_nontype_parm_type_p (t, complain))
4816         return error_mark_node;
4817
4818       if (!uses_template_parms (arg) && !uses_template_parms (t))
4819         /* We used to call digest_init here.  However, digest_init
4820            will report errors, which we don't want when complain
4821            is zero.  More importantly, digest_init will try too
4822            hard to convert things: for example, `0' should not be
4823            converted to pointer type at this point according to
4824            the standard.  Accepting this is not merely an
4825            extension, since deciding whether or not these
4826            conversions can occur is part of determining which
4827            function template to call, or whether a given explicit
4828            argument specification is valid.  */
4829         val = convert_nontype_argument (t, arg);
4830       else
4831         val = arg;
4832
4833       if (val == NULL_TREE)
4834         val = error_mark_node;
4835       else if (val == error_mark_node && (complain & tf_error))
4836         error ("could not convert template argument %qE to %qT",  arg, t);
4837     }
4838
4839   return val;
4840 }
4841
4842 /* Coerces the remaining template arguments in INNER_ARGS (from
4843    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
4844    Returns the coerced argument pack. PARM_IDX is the position of this
4845    parameter in the template parameter list. ARGS is the original
4846    template argument list.  */
4847 static tree
4848 coerce_template_parameter_pack (tree parms,
4849                                 int parm_idx,
4850                                 tree args,
4851                                 tree inner_args,
4852                                 int arg_idx,
4853                                 tree new_args,
4854                                 int* lost,
4855                                 tree in_decl,
4856                                 tsubst_flags_t complain)
4857 {
4858   tree parm = TREE_VEC_ELT (parms, parm_idx);
4859   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
4860   tree packed_args;
4861   tree argument_pack;
4862   tree packed_types = NULL_TREE;
4863
4864   if (arg_idx > nargs)
4865     arg_idx = nargs;
4866
4867   packed_args = make_tree_vec (nargs - arg_idx);
4868
4869   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
4870       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
4871     {
4872       /* When the template parameter is a non-type template
4873          parameter pack whose type uses parameter packs, we need
4874          to look at each of the template arguments
4875          separately. Build a vector of the types for these
4876          non-type template parameters in PACKED_TYPES.  */
4877       tree expansion 
4878         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
4879       packed_types = tsubst_pack_expansion (expansion, args,
4880                                             complain, in_decl);
4881
4882       if (packed_types == error_mark_node)
4883         return error_mark_node;
4884
4885       /* Check that we have the right number of arguments.  */
4886       if (arg_idx < nargs
4887           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
4888           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
4889         {
4890           int needed_parms 
4891             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
4892           error ("wrong number of template arguments (%d, should be %d)",
4893                  nargs, needed_parms);
4894           return error_mark_node;
4895         }
4896
4897       /* If we aren't able to check the actual arguments now
4898          (because they haven't been expanded yet), we can at least
4899          verify that all of the types used for the non-type
4900          template parameter pack are, in fact, valid for non-type
4901          template parameters.  */
4902       if (arg_idx < nargs 
4903           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
4904         {
4905           int j, len = TREE_VEC_LENGTH (packed_types);
4906           for (j = 0; j < len; ++j)
4907             {
4908               tree t = TREE_VEC_ELT (packed_types, j);
4909               if (invalid_nontype_parm_type_p (t, complain))
4910                 return error_mark_node;
4911             }
4912         }
4913     }
4914
4915   /* Convert the remaining arguments, which will be a part of the
4916      parameter pack "parm".  */
4917   for (; arg_idx < nargs; ++arg_idx)
4918     {
4919       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
4920       tree actual_parm = TREE_VALUE (parm);
4921
4922       if (packed_types && !PACK_EXPANSION_P (arg))
4923         {
4924           /* When we have a vector of types (corresponding to the
4925              non-type template parameter pack that uses parameter
4926              packs in its type, as mention above), and the
4927              argument is not an expansion (which expands to a
4928              currently unknown number of arguments), clone the
4929              parm and give it the next type in PACKED_TYPES.  */
4930           actual_parm = copy_node (actual_parm);
4931           TREE_TYPE (actual_parm) = 
4932             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
4933         }
4934
4935       arg = convert_template_argument (actual_parm, 
4936                                        arg, new_args, complain, parm_idx,
4937                                        in_decl);
4938       if (arg == error_mark_node)
4939         (*lost)++;
4940       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
4941     }
4942
4943   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
4944       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
4945     argument_pack = make_node (TYPE_ARGUMENT_PACK);
4946   else
4947     {
4948       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
4949       TREE_TYPE (argument_pack) = TREE_TYPE (TREE_VALUE (parm));
4950       TREE_CONSTANT (argument_pack) = 1;
4951     }
4952
4953   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
4954   return argument_pack;
4955 }
4956
4957 /* Convert all template arguments to their appropriate types, and
4958    return a vector containing the innermost resulting template
4959    arguments.  If any error occurs, return error_mark_node. Error and
4960    warning messages are issued under control of COMPLAIN.
4961
4962    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
4963    for arguments not specified in ARGS.  Otherwise, if
4964    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
4965    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
4966    USE_DEFAULT_ARGS is false, then all arguments must be specified in
4967    ARGS.  */
4968
4969 static tree
4970 coerce_template_parms (tree parms,
4971                        tree args,
4972                        tree in_decl,
4973                        tsubst_flags_t complain,
4974                        bool require_all_args,
4975                        bool use_default_args)
4976 {
4977   int nparms, nargs, parm_idx, arg_idx, lost = 0;
4978   tree inner_args;
4979   tree new_args;
4980   tree new_inner_args;
4981   bool saved_skip_evaluation;
4982
4983   /* When used as a boolean value, indicates whether this is a
4984      variadic template parameter list. Since it's an int, we can also
4985      subtract it from nparms to get the number of non-variadic
4986      parameters.  */
4987   int variadic_p = 0;
4988
4989   inner_args 
4990     = expand_template_argument_pack (INNERMOST_TEMPLATE_ARGS (args));
4991
4992   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
4993   nparms = TREE_VEC_LENGTH (parms);
4994
4995   /* Determine if there are any parameter packs.  */
4996   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
4997     {
4998       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
4999       if (template_parameter_pack_p (tparm))
5000         {
5001           variadic_p = 1;
5002           break;
5003         }
5004     }
5005
5006   if ((nargs > nparms - variadic_p && !variadic_p)
5007       || (nargs < nparms - variadic_p
5008           && require_all_args
5009           && (!use_default_args
5010               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5011                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5012     {
5013       if (complain & tf_error)
5014         {
5015           const char *or_more = "";
5016           if (variadic_p)
5017             {
5018               or_more = " or more";
5019               --nparms;
5020             }
5021
5022           error ("wrong number of template arguments (%d, should be %d%s)",
5023                  nargs, nparms, or_more);
5024
5025           if (in_decl)
5026             error ("provided for %q+D", in_decl);
5027         }
5028
5029       return error_mark_node;
5030     }
5031
5032   /* We need to evaluate the template arguments, even though this
5033      template-id may be nested within a "sizeof".  */
5034   saved_skip_evaluation = skip_evaluation;
5035   skip_evaluation = false;
5036   new_inner_args = make_tree_vec (nparms);
5037   new_args = add_outermost_template_args (args, new_inner_args);
5038   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5039     {
5040       tree arg;
5041       tree parm;
5042
5043       /* Get the Ith template parameter.  */
5044       parm = TREE_VEC_ELT (parms, parm_idx);
5045  
5046       if (parm == error_mark_node)
5047       {
5048         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5049         continue;
5050       }
5051
5052       /* Calculate the next argument.  */
5053       if (template_parameter_pack_p (TREE_VALUE (parm)))
5054         {
5055           /* All remaining arguments will be placed in the
5056              template parameter pack PARM.  */
5057           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5058                                                 inner_args, arg_idx,
5059                                                 new_args, &lost,
5060                                                 in_decl, complain);
5061           
5062           /* Store this argument.  */
5063           if (arg == error_mark_node)
5064             lost++;
5065           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5066
5067           /* We are done with all of the arguments.  */
5068           arg_idx = nargs;
5069
5070           continue;
5071         }
5072       else if (arg_idx < nargs)
5073         {
5074           arg = TREE_VEC_ELT (inner_args, arg_idx);
5075
5076           if (arg && PACK_EXPANSION_P (arg))
5077             {
5078               /* If ARG is a pack expansion, but PARM is not a
5079                  template parameter pack (if it were, we would have
5080                  handled it above), we're trying to expand into a
5081                  fixed-length argument list.  */
5082               if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5083                 error ("cannot expand %<%E%> into a fixed-length "
5084                        "argument list", arg);
5085               else
5086                 error ("cannot expand %<%T%> into a fixed-length "
5087                        "argument list", arg);
5088             }
5089         }
5090       else if (require_all_args)
5091         /* There must be a default arg in this case.  */
5092         arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
5093                                    complain, in_decl);
5094       else
5095         break;
5096
5097       if (arg == error_mark_node)
5098         {
5099           if (complain & tf_error)
5100             error ("template argument %d is invalid", arg_idx + 1);
5101         }
5102       else if (!arg)
5103         /* This only occurs if there was an error in the template
5104            parameter list itself (which we would already have
5105            reported) that we are trying to recover from, e.g., a class
5106            template with a parameter list such as
5107            template<typename..., typename>.  */
5108         return error_mark_node;
5109       else
5110         arg = convert_template_argument (TREE_VALUE (parm),
5111                                          arg, new_args, complain, 
5112                                          parm_idx, in_decl);
5113
5114       if (arg == error_mark_node)
5115         lost++;
5116       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
5117     }
5118   skip_evaluation = saved_skip_evaluation;
5119
5120   if (lost)
5121     return error_mark_node;
5122
5123   return new_inner_args;
5124 }
5125
5126 /* Returns 1 if template args OT and NT are equivalent.  */
5127
5128 static int
5129 template_args_equal (tree ot, tree nt)
5130 {
5131   if (nt == ot)
5132     return 1;
5133
5134   if (TREE_CODE (nt) == TREE_VEC)
5135     /* For member templates */
5136     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
5137   else if (PACK_EXPANSION_P (ot))
5138     return PACK_EXPANSION_P (nt) 
5139       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
5140                               PACK_EXPANSION_PATTERN (nt));
5141   else if (TYPE_P (nt))
5142     return TYPE_P (ot) && same_type_p (ot, nt);
5143   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
5144     return 0;
5145   else
5146     return cp_tree_equal (ot, nt);
5147 }
5148
5149 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
5150    of template arguments.  Returns 0 otherwise.  */
5151
5152 int
5153 comp_template_args (tree oldargs, tree newargs)
5154 {
5155   int i;
5156
5157   oldargs = expand_template_argument_pack (oldargs);
5158   newargs = expand_template_argument_pack (newargs);
5159
5160   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
5161     return 0;
5162
5163   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
5164     {
5165       tree nt = TREE_VEC_ELT (newargs, i);
5166       tree ot = TREE_VEC_ELT (oldargs, i);
5167
5168       if (! template_args_equal (ot, nt))
5169         return 0;
5170     }
5171   return 1;
5172 }
5173
5174 static void
5175 add_pending_template (tree d)
5176 {
5177   tree ti = (TYPE_P (d)
5178              ? CLASSTYPE_TEMPLATE_INFO (d)
5179              : DECL_TEMPLATE_INFO (d));
5180   struct pending_template *pt;
5181   int level;
5182
5183   if (TI_PENDING_TEMPLATE_FLAG (ti))
5184     return;
5185
5186   /* We are called both from instantiate_decl, where we've already had a
5187      tinst_level pushed, and instantiate_template, where we haven't.
5188      Compensate.  */
5189   level = !current_tinst_level || current_tinst_level->decl != d;
5190
5191   if (level)
5192     push_tinst_level (d);
5193
5194   pt = GGC_NEW (struct pending_template);
5195   pt->next = NULL;
5196   pt->tinst = current_tinst_level;
5197   if (last_pending_template)
5198     last_pending_template->next = pt;
5199   else
5200     pending_templates = pt;
5201
5202   last_pending_template = pt;
5203
5204   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
5205
5206   if (level)
5207     pop_tinst_level ();
5208 }
5209
5210
5211 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
5212    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
5213    documentation for TEMPLATE_ID_EXPR.  */
5214
5215 tree
5216 lookup_template_function (tree fns, tree arglist)
5217 {
5218   tree type;
5219
5220   if (fns == error_mark_node || arglist == error_mark_node)
5221     return error_mark_node;
5222
5223   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
5224   gcc_assert (fns && (is_overloaded_fn (fns)
5225                       || TREE_CODE (fns) == IDENTIFIER_NODE));
5226
5227   if (BASELINK_P (fns))
5228     {
5229       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
5230                                          unknown_type_node,
5231                                          BASELINK_FUNCTIONS (fns),
5232                                          arglist);
5233       return fns;
5234     }
5235
5236   type = TREE_TYPE (fns);
5237   if (TREE_CODE (fns) == OVERLOAD || !type)
5238     type = unknown_type_node;
5239
5240   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
5241 }
5242
5243 /* Within the scope of a template class S<T>, the name S gets bound
5244    (in build_self_reference) to a TYPE_DECL for the class, not a
5245    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
5246    or one of its enclosing classes, and that type is a template,
5247    return the associated TEMPLATE_DECL.  Otherwise, the original
5248    DECL is returned.  */
5249
5250 tree
5251 maybe_get_template_decl_from_type_decl (tree decl)
5252 {
5253   return (decl != NULL_TREE
5254           && TREE_CODE (decl) == TYPE_DECL
5255           && DECL_ARTIFICIAL (decl)
5256           && CLASS_TYPE_P (TREE_TYPE (decl))
5257           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
5258     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
5259 }
5260
5261 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
5262    parameters, find the desired type.
5263
5264    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
5265
5266    IN_DECL, if non-NULL, is the template declaration we are trying to
5267    instantiate.
5268
5269    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
5270    the class we are looking up.
5271
5272    Issue error and warning messages under control of COMPLAIN.
5273
5274    If the template class is really a local class in a template
5275    function, then the FUNCTION_CONTEXT is the function in which it is
5276    being instantiated.
5277
5278    ??? Note that this function is currently called *twice* for each
5279    template-id: the first time from the parser, while creating the
5280    incomplete type (finish_template_type), and the second type during the
5281    real instantiation (instantiate_template_class). This is surely something
5282    that we want to avoid. It also causes some problems with argument
5283    coercion (see convert_nontype_argument for more information on this).  */
5284
5285 tree
5286 lookup_template_class (tree d1,
5287                        tree arglist,
5288                        tree in_decl,
5289                        tree context,
5290                        int entering_scope,
5291                        tsubst_flags_t complain)
5292 {
5293   tree template = NULL_TREE, parmlist;
5294   tree t;
5295
5296   timevar_push (TV_NAME_LOOKUP);
5297
5298   if (TREE_CODE (d1) == IDENTIFIER_NODE)
5299     {
5300       tree value = innermost_non_namespace_value (d1);
5301       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
5302         template = value;
5303       else
5304         {
5305           if (context)
5306             push_decl_namespace (context);
5307           template = lookup_name (d1);
5308           template = maybe_get_template_decl_from_type_decl (template);
5309           if (context)
5310             pop_decl_namespace ();
5311         }
5312       if (template)
5313         context = DECL_CONTEXT (template);
5314     }
5315   else if (TREE_CODE (d1) == TYPE_DECL && IS_AGGR_TYPE (TREE_TYPE (d1)))
5316     {
5317       tree type = TREE_TYPE (d1);
5318
5319       /* If we are declaring a constructor, say A<T>::A<T>, we will get
5320          an implicit typename for the second A.  Deal with it.  */
5321       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
5322         type = TREE_TYPE (type);
5323
5324       if (CLASSTYPE_TEMPLATE_INFO (type))
5325         {
5326           template = CLASSTYPE_TI_TEMPLATE (type);
5327           d1 = DECL_NAME (template);
5328         }
5329     }
5330   else if (TREE_CODE (d1) == ENUMERAL_TYPE
5331            || (TYPE_P (d1) && IS_AGGR_TYPE (d1)))
5332     {
5333       template = TYPE_TI_TEMPLATE (d1);
5334       d1 = DECL_NAME (template);
5335     }
5336   else if (TREE_CODE (d1) == TEMPLATE_DECL
5337            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
5338     {
5339       template = d1;
5340       d1 = DECL_NAME (template);
5341       context = DECL_CONTEXT (template);
5342     }
5343
5344   /* Issue an error message if we didn't find a template.  */
5345   if (! template)
5346     {
5347       if (complain & tf_error)
5348         error ("%qT is not a template", d1);
5349       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5350     }
5351
5352   if (TREE_CODE (template) != TEMPLATE_DECL
5353          /* Make sure it's a user visible template, if it was named by
5354             the user.  */
5355       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (template)
5356           && !PRIMARY_TEMPLATE_P (template)))
5357     {
5358       if (complain & tf_error)
5359         {
5360           error ("non-template type %qT used as a template", d1);
5361           if (in_decl)
5362             error ("for template declaration %q+D", in_decl);
5363         }
5364       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5365     }
5366
5367   complain &= ~tf_user;
5368
5369   if (DECL_TEMPLATE_TEMPLATE_PARM_P (template))
5370     {
5371       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
5372          template arguments */
5373
5374       tree parm;
5375       tree arglist2;
5376
5377       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (template);
5378
5379       /* Consider an example where a template template parameter declared as
5380
5381            template <class T, class U = std::allocator<T> > class TT
5382
5383          The template parameter level of T and U are one level larger than
5384          of TT.  To proper process the default argument of U, say when an
5385          instantiation `TT<int>' is seen, we need to build the full
5386          arguments containing {int} as the innermost level.  Outer levels,
5387          available when not appearing as default template argument, can be
5388          obtained from `current_template_args ()'.
5389
5390          Suppose that TT is later substituted with std::vector.  The above
5391          instantiation is `TT<int, std::allocator<T> >' with TT at
5392          level 1, and T at level 2, while the template arguments at level 1
5393          becomes {std::vector} and the inner level 2 is {int}.  */
5394
5395       if (current_template_parms)
5396         arglist = add_to_template_args (current_template_args (), arglist);
5397
5398       arglist2 = coerce_template_parms (parmlist, arglist, template,
5399                                         complain,
5400                                         /*require_all_args=*/true,
5401                                         /*use_default_args=*/true);
5402       if (arglist2 == error_mark_node
5403           || (!uses_template_parms (arglist2)
5404               && check_instantiated_args (template, arglist2, complain)))
5405         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5406
5407       parm = bind_template_template_parm (TREE_TYPE (template), arglist2);
5408       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
5409     }
5410   else
5411     {
5412       tree template_type = TREE_TYPE (template);
5413       tree gen_tmpl;
5414       tree type_decl;
5415       tree found = NULL_TREE;
5416       int arg_depth;
5417       int parm_depth;
5418       int is_partial_instantiation;
5419
5420       gen_tmpl = most_general_template (template);
5421       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
5422       parm_depth = TMPL_PARMS_DEPTH (parmlist);
5423       arg_depth = TMPL_ARGS_DEPTH (arglist);
5424
5425       if (arg_depth == 1 && parm_depth > 1)
5426         {
5427           /* We've been given an incomplete set of template arguments.
5428              For example, given:
5429
5430                template <class T> struct S1 {
5431                  template <class U> struct S2 {};
5432                  template <class U> struct S2<U*> {};
5433                 };
5434
5435              we will be called with an ARGLIST of `U*', but the
5436              TEMPLATE will be `template <class T> template
5437              <class U> struct S1<T>::S2'.  We must fill in the missing
5438              arguments.  */
5439           arglist
5440             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (template)),
5441                                            arglist);
5442           arg_depth = TMPL_ARGS_DEPTH (arglist);
5443         }
5444
5445       /* Now we should have enough arguments.  */
5446       gcc_assert (parm_depth == arg_depth);
5447
5448       /* From here on, we're only interested in the most general
5449          template.  */
5450       template = gen_tmpl;
5451
5452       /* Calculate the BOUND_ARGS.  These will be the args that are
5453          actually tsubst'd into the definition to create the
5454          instantiation.  */
5455       if (parm_depth > 1)
5456         {
5457           /* We have multiple levels of arguments to coerce, at once.  */
5458           int i;
5459           int saved_depth = TMPL_ARGS_DEPTH (arglist);
5460
5461           tree bound_args = make_tree_vec (parm_depth);
5462
5463           for (i = saved_depth,
5464                  t = DECL_TEMPLATE_PARMS (template);
5465                i > 0 && t != NULL_TREE;
5466                --i, t = TREE_CHAIN (t))
5467             {
5468               tree a = coerce_template_parms (TREE_VALUE (t),
5469                                               arglist, template,
5470                                               complain,
5471                                               /*require_all_args=*/true,
5472                                               /*use_default_args=*/true);
5473
5474               /* Don't process further if one of the levels fails.  */
5475               if (a == error_mark_node)
5476                 {
5477                   /* Restore the ARGLIST to its full size.  */
5478                   TREE_VEC_LENGTH (arglist) = saved_depth;
5479                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5480                 }
5481
5482               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
5483
5484               /* We temporarily reduce the length of the ARGLIST so
5485                  that coerce_template_parms will see only the arguments
5486                  corresponding to the template parameters it is
5487                  examining.  */
5488               TREE_VEC_LENGTH (arglist)--;
5489             }
5490
5491           /* Restore the ARGLIST to its full size.  */
5492           TREE_VEC_LENGTH (arglist) = saved_depth;
5493
5494           arglist = bound_args;
5495         }
5496       else
5497         arglist
5498           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
5499                                    INNERMOST_TEMPLATE_ARGS (arglist),
5500                                    template,
5501                                    complain,
5502                                    /*require_all_args=*/true,
5503                                    /*use_default_args=*/true);
5504
5505       if (arglist == error_mark_node)
5506         /* We were unable to bind the arguments.  */
5507         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5508
5509       /* In the scope of a template class, explicit references to the
5510          template class refer to the type of the template, not any
5511          instantiation of it.  For example, in:
5512
5513            template <class T> class C { void f(C<T>); }
5514
5515          the `C<T>' is just the same as `C'.  Outside of the
5516          class, however, such a reference is an instantiation.  */
5517       if (comp_template_args (TYPE_TI_ARGS (template_type),
5518                               arglist))
5519         {
5520           found = template_type;
5521
5522           if (!entering_scope && PRIMARY_TEMPLATE_P (template))
5523             {
5524               tree ctx;
5525
5526               for (ctx = current_class_type;
5527                    ctx && TREE_CODE (ctx) != NAMESPACE_DECL;
5528                    ctx = (TYPE_P (ctx)
5529                           ? TYPE_CONTEXT (ctx)
5530                           : DECL_CONTEXT (ctx)))
5531                 if (TYPE_P (ctx) && same_type_p (ctx, template_type))
5532                   goto found_ctx;
5533
5534               /* We're not in the scope of the class, so the
5535                  TEMPLATE_TYPE is not the type we want after all.  */
5536               found = NULL_TREE;
5537             found_ctx:;
5538             }
5539         }
5540       if (found)
5541         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5542
5543       /* If we already have this specialization, return it.  */
5544       found = retrieve_specialization (template, arglist,
5545                                        /*class_specializations_p=*/false);
5546       if (found)
5547         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5548
5549       /* This type is a "partial instantiation" if any of the template
5550          arguments still involve template parameters.  Note that we set
5551          IS_PARTIAL_INSTANTIATION for partial specializations as
5552          well.  */
5553       is_partial_instantiation = uses_template_parms (arglist);
5554
5555       /* If the deduced arguments are invalid, then the binding
5556          failed.  */
5557       if (!is_partial_instantiation
5558           && check_instantiated_args (template,
5559                                       INNERMOST_TEMPLATE_ARGS (arglist),
5560                                       complain))
5561         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5562
5563       if (!is_partial_instantiation
5564           && !PRIMARY_TEMPLATE_P (template)
5565           && TREE_CODE (CP_DECL_CONTEXT (template)) == NAMESPACE_DECL)
5566         {
5567           found = xref_tag_from_type (TREE_TYPE (template),
5568                                       DECL_NAME (template),
5569                                       /*tag_scope=*/ts_global);
5570           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5571         }
5572
5573       context = tsubst (DECL_CONTEXT (template), arglist,
5574                         complain, in_decl);
5575       if (!context)
5576         context = global_namespace;
5577
5578       /* Create the type.  */
5579       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
5580         {
5581           if (!is_partial_instantiation)
5582             {
5583               set_current_access_from_decl (TYPE_NAME (template_type));
5584               t = start_enum (TYPE_IDENTIFIER (template_type));
5585             }
5586           else
5587             /* We don't want to call start_enum for this type, since
5588                the values for the enumeration constants may involve
5589                template parameters.  And, no one should be interested
5590                in the enumeration constants for such a type.  */
5591             t = make_node (ENUMERAL_TYPE);
5592         }
5593       else
5594         {
5595           t = make_aggr_type (TREE_CODE (template_type));
5596           CLASSTYPE_DECLARED_CLASS (t)
5597             = CLASSTYPE_DECLARED_CLASS (template_type);
5598           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
5599           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
5600
5601           /* A local class.  Make sure the decl gets registered properly.  */
5602           if (context == current_function_decl)
5603             pushtag (DECL_NAME (template), t, /*tag_scope=*/ts_current);
5604
5605           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
5606             /* This instantiation is another name for the primary
5607                template type. Set the TYPE_CANONICAL field
5608                appropriately. */
5609             TYPE_CANONICAL (t) = template_type;
5610           else if (any_template_arguments_need_structural_equality_p (arglist))
5611             /* Some of the template arguments require structural
5612                equality testing, so this template class requires
5613                structural equality testing. */
5614             SET_TYPE_STRUCTURAL_EQUALITY (t);
5615         }
5616
5617       /* If we called start_enum or pushtag above, this information
5618          will already be set up.  */
5619       if (!TYPE_NAME (t))
5620         {
5621           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
5622
5623           type_decl = create_implicit_typedef (DECL_NAME (template), t);
5624           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
5625           TYPE_STUB_DECL (t) = type_decl;
5626           DECL_SOURCE_LOCATION (type_decl)
5627             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
5628         }
5629       else
5630         type_decl = TYPE_NAME (t);
5631
5632       TREE_PRIVATE (type_decl)
5633         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
5634       TREE_PROTECTED (type_decl)
5635         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
5636       DECL_IN_SYSTEM_HEADER (type_decl)
5637         = DECL_IN_SYSTEM_HEADER (template);
5638       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
5639         {
5640           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
5641           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
5642         }
5643
5644       /* Set up the template information.  We have to figure out which
5645          template is the immediate parent if this is a full
5646          instantiation.  */
5647       if (parm_depth == 1 || is_partial_instantiation
5648           || !PRIMARY_TEMPLATE_P (template))
5649         /* This case is easy; there are no member templates involved.  */
5650         found = template;
5651       else
5652         {
5653           /* This is a full instantiation of a member template.  Look
5654              for a partial instantiation of which this is an instance.  */
5655
5656           for (found = DECL_TEMPLATE_INSTANTIATIONS (template);
5657                found; found = TREE_CHAIN (found))
5658             {
5659               int success;
5660               tree tmpl = CLASSTYPE_TI_TEMPLATE (TREE_VALUE (found));
5661
5662               /* We only want partial instantiations, here, not
5663                  specializations or full instantiations.  */
5664               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_VALUE (found))
5665                   || !uses_template_parms (TREE_VALUE (found)))
5666                 continue;
5667
5668               /* Temporarily reduce by one the number of levels in the
5669                  ARGLIST and in FOUND so as to avoid comparing the
5670                  last set of arguments.  */
5671               TREE_VEC_LENGTH (arglist)--;
5672               TREE_VEC_LENGTH (TREE_PURPOSE (found)) --;
5673
5674               /* See if the arguments match.  If they do, then TMPL is
5675                  the partial instantiation we want.  */
5676               success = comp_template_args (TREE_PURPOSE (found), arglist);
5677
5678               /* Restore the argument vectors to their full size.  */
5679               TREE_VEC_LENGTH (arglist)++;
5680               TREE_VEC_LENGTH (TREE_PURPOSE (found))++;
5681
5682               if (success)
5683                 {
5684                   found = tmpl;
5685                   break;
5686                 }
5687             }
5688
5689           if (!found)
5690             {
5691               /* There was no partial instantiation. This happens
5692                  where C<T> is a member template of A<T> and it's used
5693                  in something like
5694
5695                   template <typename T> struct B { A<T>::C<int> m; };
5696                   B<float>;
5697
5698                  Create the partial instantiation.
5699                */
5700               TREE_VEC_LENGTH (arglist)--;
5701               found = tsubst (template, arglist, complain, NULL_TREE);
5702               TREE_VEC_LENGTH (arglist)++;
5703             }
5704         }
5705
5706       SET_TYPE_TEMPLATE_INFO (t, tree_cons (found, arglist, NULL_TREE));
5707       DECL_TEMPLATE_INSTANTIATIONS (template)
5708         = tree_cons (arglist, t,
5709                      DECL_TEMPLATE_INSTANTIATIONS (template));
5710
5711       if (TREE_CODE (t) == ENUMERAL_TYPE
5712           && !is_partial_instantiation)
5713         /* Now that the type has been registered on the instantiations
5714            list, we set up the enumerators.  Because the enumeration
5715            constants may involve the enumeration type itself, we make
5716            sure to register the type first, and then create the
5717            constants.  That way, doing tsubst_expr for the enumeration
5718            constants won't result in recursive calls here; we'll find
5719            the instantiation and exit above.  */
5720         tsubst_enum (template_type, t, arglist);
5721
5722       if (is_partial_instantiation)
5723         /* If the type makes use of template parameters, the
5724            code that generates debugging information will crash.  */
5725         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
5726
5727       /* Possibly limit visibility based on template args.  */
5728       TREE_PUBLIC (type_decl) = 1;
5729       determine_visibility (type_decl);
5730
5731       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
5732     }
5733   timevar_pop (TV_NAME_LOOKUP);
5734 }
5735 \f
5736 struct pair_fn_data
5737 {
5738   tree_fn_t fn;
5739   void *data;
5740   struct pointer_set_t *visited;
5741 };
5742
5743 /* Called from for_each_template_parm via walk_tree.  */
5744
5745 static tree
5746 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
5747 {
5748   tree t = *tp;
5749   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
5750   tree_fn_t fn = pfd->fn;
5751   void *data = pfd->data;
5752
5753   if (TYPE_P (t)
5754       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited))
5755     return error_mark_node;
5756
5757   switch (TREE_CODE (t))
5758     {
5759     case RECORD_TYPE:
5760       if (TYPE_PTRMEMFUNC_P (t))
5761         break;
5762       /* Fall through.  */
5763
5764     case UNION_TYPE:
5765     case ENUMERAL_TYPE:
5766       if (!TYPE_TEMPLATE_INFO (t))
5767         *walk_subtrees = 0;
5768       else if (for_each_template_parm (TREE_VALUE (TYPE_TEMPLATE_INFO (t)),
5769                                        fn, data, pfd->visited))
5770         return error_mark_node;
5771       break;
5772
5773     case INTEGER_TYPE:
5774       if (for_each_template_parm (TYPE_MIN_VALUE (t),
5775                                   fn, data, pfd->visited)
5776           || for_each_template_parm (TYPE_MAX_VALUE (t),
5777                                      fn, data, pfd->visited))
5778         return error_mark_node;
5779       break;
5780
5781     case METHOD_TYPE:
5782       /* Since we're not going to walk subtrees, we have to do this
5783          explicitly here.  */
5784       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
5785                                   pfd->visited))
5786         return error_mark_node;
5787       /* Fall through.  */
5788
5789     case FUNCTION_TYPE:
5790       /* Check the return type.  */
5791       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited))
5792         return error_mark_node;
5793
5794       /* Check the parameter types.  Since default arguments are not
5795          instantiated until they are needed, the TYPE_ARG_TYPES may
5796          contain expressions that involve template parameters.  But,
5797          no-one should be looking at them yet.  And, once they're
5798          instantiated, they don't contain template parameters, so
5799          there's no point in looking at them then, either.  */
5800       {
5801         tree parm;
5802
5803         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
5804           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
5805                                       pfd->visited))
5806             return error_mark_node;
5807
5808         /* Since we've already handled the TYPE_ARG_TYPES, we don't
5809            want walk_tree walking into them itself.  */
5810         *walk_subtrees = 0;
5811       }
5812       break;
5813
5814     case TYPEOF_TYPE:
5815       if (for_each_template_parm (TYPE_FIELDS (t), fn, data,
5816                                   pfd->visited))
5817         return error_mark_node;
5818       break;
5819
5820     case FUNCTION_DECL:
5821     case VAR_DECL:
5822       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
5823           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
5824                                      pfd->visited))
5825         return error_mark_node;
5826       /* Fall through.  */
5827
5828     case PARM_DECL:
5829     case CONST_DECL:
5830       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
5831           && for_each_template_parm (DECL_INITIAL (t), fn, data,
5832                                      pfd->visited))
5833         return error_mark_node;
5834       if (DECL_CONTEXT (t)
5835           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
5836                                      pfd->visited))
5837         return error_mark_node;
5838       break;
5839
5840     case BOUND_TEMPLATE_TEMPLATE_PARM:
5841       /* Record template parameters such as `T' inside `TT<T>'.  */
5842       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited))
5843         return error_mark_node;
5844       /* Fall through.  */
5845
5846     case TEMPLATE_TEMPLATE_PARM:
5847     case TEMPLATE_TYPE_PARM:
5848     case TEMPLATE_PARM_INDEX:
5849       if (fn && (*fn)(t, data))
5850         return error_mark_node;
5851       else if (!fn)
5852         return error_mark_node;
5853       break;
5854
5855     case TEMPLATE_DECL:
5856       /* A template template parameter is encountered.  */
5857       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
5858           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited))
5859         return error_mark_node;
5860
5861       /* Already substituted template template parameter */
5862       *walk_subtrees = 0;
5863       break;
5864
5865     case TYPENAME_TYPE:
5866       if (!fn
5867           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
5868                                      data, pfd->visited))
5869         return error_mark_node;
5870       break;
5871
5872     case CONSTRUCTOR:
5873       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
5874           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
5875                                      (TREE_TYPE (t)), fn, data,
5876                                      pfd->visited))
5877         return error_mark_node;
5878       break;
5879
5880     case INDIRECT_REF:
5881     case COMPONENT_REF:
5882       /* If there's no type, then this thing must be some expression
5883          involving template parameters.  */
5884       if (!fn && !TREE_TYPE (t))
5885         return error_mark_node;
5886       break;
5887
5888     case MODOP_EXPR:
5889     case CAST_EXPR:
5890     case REINTERPRET_CAST_EXPR:
5891     case CONST_CAST_EXPR:
5892     case STATIC_CAST_EXPR:
5893     case DYNAMIC_CAST_EXPR:
5894     case ARROW_EXPR:
5895     case DOTSTAR_EXPR:
5896     case TYPEID_EXPR:
5897     case PSEUDO_DTOR_EXPR:
5898       if (!fn)
5899         return error_mark_node;
5900       break;
5901
5902     default:
5903       break;
5904     }
5905
5906   /* We didn't find any template parameters we liked.  */
5907   return NULL_TREE;
5908 }
5909
5910 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
5911    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
5912    call FN with the parameter and the DATA.
5913    If FN returns nonzero, the iteration is terminated, and
5914    for_each_template_parm returns 1.  Otherwise, the iteration
5915    continues.  If FN never returns a nonzero value, the value
5916    returned by for_each_template_parm is 0.  If FN is NULL, it is
5917    considered to be the function which always returns 1.  */
5918
5919 static int
5920 for_each_template_parm (tree t, tree_fn_t fn, void* data,
5921                         struct pointer_set_t *visited)
5922 {
5923   struct pair_fn_data pfd;
5924   int result;
5925
5926   /* Set up.  */
5927   pfd.fn = fn;
5928   pfd.data = data;
5929
5930   /* Walk the tree.  (Conceptually, we would like to walk without
5931      duplicates, but for_each_template_parm_r recursively calls
5932      for_each_template_parm, so we would need to reorganize a fair
5933      bit to use walk_tree_without_duplicates, so we keep our own
5934      visited list.)  */
5935   if (visited)
5936     pfd.visited = visited;
5937   else
5938     pfd.visited = pointer_set_create ();
5939   result = cp_walk_tree (&t,
5940                          for_each_template_parm_r,
5941                          &pfd,
5942                          pfd.visited) != NULL_TREE;
5943
5944   /* Clean up.  */
5945   if (!visited)
5946     {
5947       pointer_set_destroy (pfd.visited);
5948       pfd.visited = 0;
5949     }
5950
5951   return result;
5952 }
5953
5954 /* Returns true if T depends on any template parameter.  */
5955
5956 int
5957 uses_template_parms (tree t)
5958 {
5959   bool dependent_p;
5960   int saved_processing_template_decl;
5961
5962   saved_processing_template_decl = processing_template_decl;
5963   if (!saved_processing_template_decl)
5964     processing_template_decl = 1;
5965   if (TYPE_P (t))
5966     dependent_p = dependent_type_p (t);
5967   else if (TREE_CODE (t) == TREE_VEC)
5968     dependent_p = any_dependent_template_arguments_p (t);
5969   else if (TREE_CODE (t) == TREE_LIST)
5970     dependent_p = (uses_template_parms (TREE_VALUE (t))
5971                    || uses_template_parms (TREE_CHAIN (t)));
5972   else if (TREE_CODE (t) == TYPE_DECL)
5973     dependent_p = dependent_type_p (TREE_TYPE (t));
5974   else if (DECL_P (t)
5975            || EXPR_P (t)
5976            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
5977            || TREE_CODE (t) == OVERLOAD
5978            || TREE_CODE (t) == BASELINK
5979            || TREE_CODE (t) == IDENTIFIER_NODE
5980            || TREE_CODE (t) == TRAIT_EXPR
5981            || CONSTANT_CLASS_P (t))
5982     dependent_p = (type_dependent_expression_p (t)
5983                    || value_dependent_expression_p (t));
5984   else
5985     {
5986       gcc_assert (t == error_mark_node);
5987       dependent_p = false;
5988     }
5989
5990   processing_template_decl = saved_processing_template_decl;
5991
5992   return dependent_p;
5993 }
5994
5995 /* Returns true if T depends on any template parameter with level LEVEL.  */
5996
5997 int
5998 uses_template_parms_level (tree t, int level)
5999 {
6000   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL);
6001 }
6002
6003 static int tinst_depth;
6004 extern int max_tinst_depth;
6005 #ifdef GATHER_STATISTICS
6006 int depth_reached;
6007 #endif
6008 static int tinst_level_tick;
6009 static int last_template_error_tick;
6010
6011 /* We're starting to instantiate D; record the template instantiation context
6012    for diagnostics and to restore it later.  */
6013
6014 static int
6015 push_tinst_level (tree d)
6016 {
6017   struct tinst_level *new;
6018
6019   if (tinst_depth >= max_tinst_depth)
6020     {
6021       /* If the instantiation in question still has unbound template parms,
6022          we don't really care if we can't instantiate it, so just return.
6023          This happens with base instantiation for implicit `typename'.  */
6024       if (uses_template_parms (d))
6025         return 0;
6026
6027       last_template_error_tick = tinst_level_tick;
6028       error ("template instantiation depth exceeds maximum of %d (use "
6029              "-ftemplate-depth-NN to increase the maximum) instantiating %qD",
6030              max_tinst_depth, d);
6031
6032       print_instantiation_context ();
6033
6034       return 0;
6035     }
6036
6037   new = GGC_NEW (struct tinst_level);
6038   new->decl = d;
6039   new->locus = input_location;
6040   new->in_system_header_p = in_system_header;
6041   new->next = current_tinst_level;
6042   current_tinst_level = new;
6043
6044   ++tinst_depth;
6045 #ifdef GATHER_STATISTICS
6046   if (tinst_depth > depth_reached)
6047     depth_reached = tinst_depth;
6048 #endif
6049
6050   ++tinst_level_tick;
6051   return 1;
6052 }
6053
6054 /* We're done instantiating this template; return to the instantiation
6055    context.  */
6056
6057 static void
6058 pop_tinst_level (void)
6059 {
6060   /* Restore the filename and line number stashed away when we started
6061      this instantiation.  */
6062   input_location = current_tinst_level->locus;
6063   in_system_header = current_tinst_level->in_system_header_p;
6064   current_tinst_level = current_tinst_level->next;
6065   --tinst_depth;
6066   ++tinst_level_tick;
6067 }
6068
6069 /* We're instantiating a deferred template; restore the template
6070    instantiation context in which the instantiation was requested, which
6071    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
6072
6073 static tree
6074 reopen_tinst_level (struct tinst_level *level)
6075 {
6076   struct tinst_level *t;
6077
6078   tinst_depth = 0;
6079   for (t = level; t; t = t->next)
6080     ++tinst_depth;
6081
6082   current_tinst_level = level;
6083   pop_tinst_level ();
6084   return level->decl;
6085 }
6086
6087 /* Returns the TINST_LEVEL which gives the original instantiation
6088    context.  */
6089
6090 struct tinst_level *
6091 outermost_tinst_level (void)
6092 {
6093   struct tinst_level *level = current_tinst_level;
6094   if (level)
6095     while (level->next)
6096       level = level->next;
6097   return level;
6098 }
6099
6100 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
6101    vector of template arguments, as for tsubst.
6102
6103    Returns an appropriate tsubst'd friend declaration.  */
6104
6105 static tree
6106 tsubst_friend_function (tree decl, tree args)
6107 {
6108   tree new_friend;
6109
6110   if (TREE_CODE (decl) == FUNCTION_DECL
6111       && DECL_TEMPLATE_INSTANTIATION (decl)
6112       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
6113     /* This was a friend declared with an explicit template
6114        argument list, e.g.:
6115
6116        friend void f<>(T);
6117
6118        to indicate that f was a template instantiation, not a new
6119        function declaration.  Now, we have to figure out what
6120        instantiation of what template.  */
6121     {
6122       tree template_id, arglist, fns;
6123       tree new_args;
6124       tree tmpl;
6125       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
6126
6127       /* Friend functions are looked up in the containing namespace scope.
6128          We must enter that scope, to avoid finding member functions of the
6129          current cless with same name.  */
6130       push_nested_namespace (ns);
6131       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
6132                          tf_warning_or_error, NULL_TREE,
6133                          /*integral_constant_expression_p=*/false);
6134       pop_nested_namespace (ns);
6135       arglist = tsubst (DECL_TI_ARGS (decl), args,
6136                         tf_warning_or_error, NULL_TREE);
6137       template_id = lookup_template_function (fns, arglist);
6138
6139       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6140       tmpl = determine_specialization (template_id, new_friend,
6141                                        &new_args,
6142                                        /*need_member_template=*/0,
6143                                        TREE_VEC_LENGTH (args),
6144                                        tsk_none);
6145       return instantiate_template (tmpl, new_args, tf_error);
6146     }
6147
6148   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6149
6150   /* The NEW_FRIEND will look like an instantiation, to the
6151      compiler, but is not an instantiation from the point of view of
6152      the language.  For example, we might have had:
6153
6154      template <class T> struct S {
6155        template <class U> friend void f(T, U);
6156      };
6157
6158      Then, in S<int>, template <class U> void f(int, U) is not an
6159      instantiation of anything.  */
6160   if (new_friend == error_mark_node)
6161     return error_mark_node;
6162
6163   DECL_USE_TEMPLATE (new_friend) = 0;
6164   if (TREE_CODE (decl) == TEMPLATE_DECL)
6165     {
6166       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
6167       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
6168         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
6169     }
6170
6171   /* The mangled name for the NEW_FRIEND is incorrect.  The function
6172      is not a template instantiation and should not be mangled like
6173      one.  Therefore, we forget the mangling here; we'll recompute it
6174      later if we need it.  */
6175   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
6176     {
6177       SET_DECL_RTL (new_friend, NULL_RTX);
6178       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
6179     }
6180
6181   if (DECL_NAMESPACE_SCOPE_P (new_friend))
6182     {
6183       tree old_decl;
6184       tree new_friend_template_info;
6185       tree new_friend_result_template_info;
6186       tree ns;
6187       int  new_friend_is_defn;
6188
6189       /* We must save some information from NEW_FRIEND before calling
6190          duplicate decls since that function will free NEW_FRIEND if
6191          possible.  */
6192       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
6193       new_friend_is_defn =
6194             (DECL_INITIAL (DECL_TEMPLATE_RESULT
6195                            (template_for_substitution (new_friend)))
6196              != NULL_TREE);
6197       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
6198         {
6199           /* This declaration is a `primary' template.  */
6200           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
6201
6202           new_friend_result_template_info
6203             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
6204         }
6205       else
6206         new_friend_result_template_info = NULL_TREE;
6207
6208       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
6209       if (new_friend_is_defn)
6210         DECL_INITIAL (new_friend) = error_mark_node;
6211
6212       /* Inside pushdecl_namespace_level, we will push into the
6213          current namespace. However, the friend function should go
6214          into the namespace of the template.  */
6215       ns = decl_namespace_context (new_friend);
6216       push_nested_namespace (ns);
6217       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
6218       pop_nested_namespace (ns);
6219
6220       if (old_decl == error_mark_node)
6221         return error_mark_node;
6222
6223       if (old_decl != new_friend)
6224         {
6225           /* This new friend declaration matched an existing
6226              declaration.  For example, given:
6227
6228                template <class T> void f(T);
6229                template <class U> class C {
6230                  template <class T> friend void f(T) {}
6231                };
6232
6233              the friend declaration actually provides the definition
6234              of `f', once C has been instantiated for some type.  So,
6235              old_decl will be the out-of-class template declaration,
6236              while new_friend is the in-class definition.
6237
6238              But, if `f' was called before this point, the
6239              instantiation of `f' will have DECL_TI_ARGS corresponding
6240              to `T' but not to `U', references to which might appear
6241              in the definition of `f'.  Previously, the most general
6242              template for an instantiation of `f' was the out-of-class
6243              version; now it is the in-class version.  Therefore, we
6244              run through all specialization of `f', adding to their
6245              DECL_TI_ARGS appropriately.  In particular, they need a
6246              new set of outer arguments, corresponding to the
6247              arguments for this class instantiation.
6248
6249              The same situation can arise with something like this:
6250
6251                friend void f(int);
6252                template <class T> class C {
6253                  friend void f(T) {}
6254                };
6255
6256              when `C<int>' is instantiated.  Now, `f(int)' is defined
6257              in the class.  */
6258
6259           if (!new_friend_is_defn)
6260             /* On the other hand, if the in-class declaration does
6261                *not* provide a definition, then we don't want to alter
6262                existing definitions.  We can just leave everything
6263                alone.  */
6264             ;
6265           else
6266             {
6267               /* Overwrite whatever template info was there before, if
6268                  any, with the new template information pertaining to
6269                  the declaration.  */
6270               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
6271
6272               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
6273                 reregister_specialization (new_friend,
6274                                            most_general_template (old_decl),
6275                                            old_decl);
6276               else
6277                 {
6278                   tree t;
6279                   tree new_friend_args;
6280
6281                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
6282                     = new_friend_result_template_info;
6283
6284                   new_friend_args = TI_ARGS (new_friend_template_info);
6285                   for (t = DECL_TEMPLATE_SPECIALIZATIONS (old_decl);
6286                        t != NULL_TREE;
6287                        t = TREE_CHAIN (t))
6288                     {
6289                       tree spec = TREE_VALUE (t);
6290
6291                       DECL_TI_ARGS (spec)
6292                         = add_outermost_template_args (new_friend_args,
6293                                                        DECL_TI_ARGS (spec));
6294                     }
6295
6296                   /* Now, since specializations are always supposed to
6297                      hang off of the most general template, we must move
6298                      them.  */
6299                   t = most_general_template (old_decl);
6300                   if (t != old_decl)
6301                     {
6302                       DECL_TEMPLATE_SPECIALIZATIONS (t)
6303                         = chainon (DECL_TEMPLATE_SPECIALIZATIONS (t),
6304                                    DECL_TEMPLATE_SPECIALIZATIONS (old_decl));
6305                       DECL_TEMPLATE_SPECIALIZATIONS (old_decl) = NULL_TREE;
6306                     }
6307                 }
6308             }
6309
6310           /* The information from NEW_FRIEND has been merged into OLD_DECL
6311              by duplicate_decls.  */
6312           new_friend = old_decl;
6313         }
6314     }
6315   else
6316     {
6317       tree context = DECL_CONTEXT (new_friend);
6318       bool dependent_p;
6319
6320       /* In the code
6321            template <class T> class C {
6322              template <class U> friend void C1<U>::f (); // case 1
6323              friend void C2<T>::f ();                    // case 2
6324            };
6325          we only need to make sure CONTEXT is a complete type for
6326          case 2.  To distinguish between the two cases, we note that
6327          CONTEXT of case 1 remains dependent type after tsubst while
6328          this isn't true for case 2.  */
6329       ++processing_template_decl;
6330       dependent_p = dependent_type_p (context);
6331       --processing_template_decl;
6332
6333       if (!dependent_p
6334           && !complete_type_or_else (context, NULL_TREE))
6335         return error_mark_node;
6336
6337       if (COMPLETE_TYPE_P (context))
6338         {
6339           /* Check to see that the declaration is really present, and,
6340              possibly obtain an improved declaration.  */
6341           tree fn = check_classfn (context,
6342                                    new_friend, NULL_TREE);
6343
6344           if (fn)
6345             new_friend = fn;
6346         }
6347     }
6348
6349   return new_friend;
6350 }
6351
6352 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
6353    template arguments, as for tsubst.
6354
6355    Returns an appropriate tsubst'd friend type or error_mark_node on
6356    failure.  */
6357
6358 static tree
6359 tsubst_friend_class (tree friend_tmpl, tree args)
6360 {
6361   tree friend_type;
6362   tree tmpl;
6363   tree context;
6364
6365   context = DECL_CONTEXT (friend_tmpl);
6366
6367   if (context)
6368     {
6369       if (TREE_CODE (context) == NAMESPACE_DECL)
6370         push_nested_namespace (context);
6371       else
6372         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
6373     }
6374
6375   /* Look for a class template declaration.  We look for hidden names
6376      because two friend declarations of the same template are the
6377      same.  For example, in:
6378
6379        struct A { 
6380          template <typename> friend class F;
6381        };
6382        template <typename> struct B { 
6383          template <typename> friend class F;
6384        };
6385
6386      both F templates are the same.  */
6387   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
6388                            /*block_p=*/true, 0, 
6389                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
6390
6391   /* But, if we don't find one, it might be because we're in a
6392      situation like this:
6393
6394        template <class T>
6395        struct S {
6396          template <class U>
6397          friend struct S;
6398        };
6399
6400      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
6401      for `S<int>', not the TEMPLATE_DECL.  */
6402   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
6403     {
6404       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
6405       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
6406     }
6407
6408   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
6409     {
6410       /* The friend template has already been declared.  Just
6411          check to see that the declarations match, and install any new
6412          default parameters.  We must tsubst the default parameters,
6413          of course.  We only need the innermost template parameters
6414          because that is all that redeclare_class_template will look
6415          at.  */
6416       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
6417           > TMPL_ARGS_DEPTH (args))
6418         {
6419           tree parms;
6420           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
6421                                          args, tf_warning_or_error);
6422           redeclare_class_template (TREE_TYPE (tmpl), parms);
6423         }
6424
6425       friend_type = TREE_TYPE (tmpl);
6426     }
6427   else
6428     {
6429       /* The friend template has not already been declared.  In this
6430          case, the instantiation of the template class will cause the
6431          injection of this template into the global scope.  */
6432       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
6433       if (tmpl == error_mark_node)
6434         return error_mark_node;
6435
6436       /* The new TMPL is not an instantiation of anything, so we
6437          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
6438          the new type because that is supposed to be the corresponding
6439          template decl, i.e., TMPL.  */
6440       DECL_USE_TEMPLATE (tmpl) = 0;
6441       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
6442       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
6443       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
6444         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
6445
6446       /* Inject this template into the global scope.  */
6447       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
6448     }
6449
6450   if (context)
6451     {
6452       if (TREE_CODE (context) == NAMESPACE_DECL)
6453         pop_nested_namespace (context);
6454       else
6455         pop_nested_class ();
6456     }
6457
6458   return friend_type;
6459 }
6460
6461 /* Returns zero if TYPE cannot be completed later due to circularity.
6462    Otherwise returns one.  */
6463
6464 static int
6465 can_complete_type_without_circularity (tree type)
6466 {
6467   if (type == NULL_TREE || type == error_mark_node)
6468     return 0;
6469   else if (COMPLETE_TYPE_P (type))
6470     return 1;
6471   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
6472     return can_complete_type_without_circularity (TREE_TYPE (type));
6473   else if (CLASS_TYPE_P (type)
6474            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
6475     return 0;
6476   else
6477     return 1;
6478 }
6479
6480 /* Apply any attributes which had to be deferred until instantiation
6481    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
6482    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
6483
6484 static void
6485 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
6486                                 tree args, tsubst_flags_t complain, tree in_decl)
6487 {
6488   tree late_attrs = NULL_TREE;
6489   tree t;
6490
6491   if (DECL_P (*decl_p))
6492     DECL_ATTRIBUTES (*decl_p) = attributes;
6493   else
6494     TYPE_ATTRIBUTES (*decl_p) = attributes;
6495
6496   for (t = attributes; t; t = TREE_CHAIN (t))
6497     if (is_late_template_attribute (t))
6498       late_attrs = tree_cons
6499         (TREE_PURPOSE (t),
6500          tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
6501                       /*integral_constant_expression_p=*/false),
6502          late_attrs);
6503
6504   cplus_decl_attributes (decl_p, late_attrs, attr_flags);
6505 }
6506
6507 tree
6508 instantiate_class_template (tree type)
6509 {
6510   tree template, args, pattern, t, member;
6511   tree typedecl;
6512   tree pbinfo;
6513   tree base_list;
6514
6515   if (type == error_mark_node)
6516     return error_mark_node;
6517
6518   if (TYPE_BEING_DEFINED (type)
6519       || COMPLETE_TYPE_P (type)
6520       || dependent_type_p (type))
6521     return type;
6522
6523   /* Figure out which template is being instantiated.  */
6524   template = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
6525   gcc_assert (TREE_CODE (template) == TEMPLATE_DECL);
6526
6527   /* Determine what specialization of the original template to
6528      instantiate.  */
6529   t = most_specialized_class (type, template);
6530   if (t == error_mark_node)
6531     {
6532       TYPE_BEING_DEFINED (type) = 1;
6533       return error_mark_node;
6534     }
6535   else if (t)
6536     {
6537       /* This TYPE is actually an instantiation of a partial
6538          specialization.  We replace the innermost set of ARGS with
6539          the arguments appropriate for substitution.  For example,
6540          given:
6541
6542            template <class T> struct S {};
6543            template <class T> struct S<T*> {};
6544
6545          and supposing that we are instantiating S<int*>, ARGS will
6546          presently be {int*} -- but we need {int}.  */
6547       pattern = TREE_TYPE (t);
6548       args = TREE_PURPOSE (t);
6549     }
6550   else
6551     {
6552       pattern = TREE_TYPE (template);
6553       args = CLASSTYPE_TI_ARGS (type);
6554     }
6555
6556   /* If the template we're instantiating is incomplete, then clearly
6557      there's nothing we can do.  */
6558   if (!COMPLETE_TYPE_P (pattern))
6559     return type;
6560
6561   /* If we've recursively instantiated too many templates, stop.  */
6562   if (! push_tinst_level (type))
6563     return type;
6564
6565   /* Now we're really doing the instantiation.  Mark the type as in
6566      the process of being defined.  */
6567   TYPE_BEING_DEFINED (type) = 1;
6568
6569   /* We may be in the middle of deferred access check.  Disable
6570      it now.  */
6571   push_deferring_access_checks (dk_no_deferred);
6572
6573   push_to_top_level ();
6574
6575   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
6576
6577   /* Set the input location to the template definition. This is needed
6578      if tsubsting causes an error.  */
6579   typedecl = TYPE_MAIN_DECL (type);
6580   input_location = DECL_SOURCE_LOCATION (typedecl);
6581   in_system_header = DECL_IN_SYSTEM_HEADER (typedecl);
6582
6583   TYPE_HAS_CONSTRUCTOR (type) = TYPE_HAS_CONSTRUCTOR (pattern);
6584   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
6585   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
6586   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
6587   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
6588   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
6589   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
6590   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
6591   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
6592   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
6593   TYPE_PACKED (type) = TYPE_PACKED (pattern);
6594   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
6595   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
6596   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
6597   if (ANON_AGGR_TYPE_P (pattern))
6598     SET_ANON_AGGR_TYPE_P (type);
6599   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
6600     {
6601       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
6602       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
6603     }
6604
6605   pbinfo = TYPE_BINFO (pattern);
6606
6607   /* We should never instantiate a nested class before its enclosing
6608      class; we need to look up the nested class by name before we can
6609      instantiate it, and that lookup should instantiate the enclosing
6610      class.  */
6611   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
6612               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
6613               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
6614
6615   base_list = NULL_TREE;
6616   if (BINFO_N_BASE_BINFOS (pbinfo))
6617     {
6618       tree pbase_binfo;
6619       tree context = TYPE_CONTEXT (type);
6620       tree pushed_scope;
6621       int i;
6622
6623       /* We must enter the scope containing the type, as that is where
6624          the accessibility of types named in dependent bases are
6625          looked up from.  */
6626       pushed_scope = push_scope (context ? context : global_namespace);
6627
6628       /* Substitute into each of the bases to determine the actual
6629          basetypes.  */
6630       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
6631         {
6632           tree base;
6633           tree access = BINFO_BASE_ACCESS (pbinfo, i);
6634           tree expanded_bases = NULL_TREE;
6635           int idx, len = 1;
6636
6637           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
6638             {
6639               expanded_bases = 
6640                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
6641                                        args, tf_error, NULL_TREE);
6642               if (expanded_bases == error_mark_node)
6643                 continue;
6644
6645               len = TREE_VEC_LENGTH (expanded_bases);
6646             }
6647
6648           for (idx = 0; idx < len; idx++)
6649             {
6650               if (expanded_bases)
6651                 /* Extract the already-expanded base class.  */
6652                 base = TREE_VEC_ELT (expanded_bases, idx);
6653               else
6654                 /* Substitute to figure out the base class.  */
6655                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
6656                                NULL_TREE);
6657
6658               if (base == error_mark_node)
6659                 continue;
6660
6661               base_list = tree_cons (access, base, base_list);
6662               if (BINFO_VIRTUAL_P (pbase_binfo))
6663                 TREE_TYPE (base_list) = integer_type_node;
6664             }
6665         }
6666
6667       /* The list is now in reverse order; correct that.  */
6668       base_list = nreverse (base_list);
6669
6670       if (pushed_scope)
6671         pop_scope (pushed_scope);
6672     }
6673   /* Now call xref_basetypes to set up all the base-class
6674      information.  */
6675   xref_basetypes (type, base_list);
6676
6677   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
6678                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
6679                                   args, tf_error, NULL_TREE);
6680
6681   /* Now that our base classes are set up, enter the scope of the
6682      class, so that name lookups into base classes, etc. will work
6683      correctly.  This is precisely analogous to what we do in
6684      begin_class_definition when defining an ordinary non-template
6685      class.  */
6686   pushclass (type);
6687
6688   /* Now members are processed in the order of declaration.  */
6689   for (member = CLASSTYPE_DECL_LIST (pattern);
6690        member; member = TREE_CHAIN (member))
6691     {
6692       tree t = TREE_VALUE (member);
6693
6694       if (TREE_PURPOSE (member))
6695         {
6696           if (TYPE_P (t))
6697             {
6698               /* Build new CLASSTYPE_NESTED_UTDS.  */
6699
6700               tree newtag;
6701               bool class_template_p;
6702
6703               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
6704                                   && TYPE_LANG_SPECIFIC (t)
6705                                   && CLASSTYPE_IS_TEMPLATE (t));
6706               /* If the member is a class template, then -- even after
6707                  substitution -- there may be dependent types in the
6708                  template argument list for the class.  We increment
6709                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
6710                  that function will assume that no types are dependent
6711                  when outside of a template.  */
6712               if (class_template_p)
6713                 ++processing_template_decl;
6714               newtag = tsubst (t, args, tf_error, NULL_TREE);
6715               if (class_template_p)
6716                 --processing_template_decl;
6717               if (newtag == error_mark_node)
6718                 continue;
6719
6720               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
6721                 {
6722                   tree name = TYPE_IDENTIFIER (t);
6723
6724                   if (class_template_p)
6725                     /* Unfortunately, lookup_template_class sets
6726                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
6727                        instantiation (i.e., for the type of a member
6728                        template class nested within a template class.)
6729                        This behavior is required for
6730                        maybe_process_partial_specialization to work
6731                        correctly, but is not accurate in this case;
6732                        the TAG is not an instantiation of anything.
6733                        (The corresponding TEMPLATE_DECL is an
6734                        instantiation, but the TYPE is not.) */
6735                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
6736
6737                   /* Now, we call pushtag to put this NEWTAG into the scope of
6738                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
6739                      pushtag calling push_template_decl.  We don't have to do
6740                      this for enums because it will already have been done in
6741                      tsubst_enum.  */
6742                   if (name)
6743                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
6744                   pushtag (name, newtag, /*tag_scope=*/ts_current);
6745                 }
6746             }
6747           else if (TREE_CODE (t) == FUNCTION_DECL
6748                    || DECL_FUNCTION_TEMPLATE_P (t))
6749             {
6750               /* Build new TYPE_METHODS.  */
6751               tree r;
6752
6753               if (TREE_CODE (t) == TEMPLATE_DECL)
6754                 ++processing_template_decl;
6755               r = tsubst (t, args, tf_error, NULL_TREE);
6756               if (TREE_CODE (t) == TEMPLATE_DECL)
6757                 --processing_template_decl;
6758               set_current_access_from_decl (r);
6759               finish_member_declaration (r);
6760             }
6761           else
6762             {
6763               /* Build new TYPE_FIELDS.  */
6764               if (TREE_CODE (t) == STATIC_ASSERT)
6765                 {
6766                   tree condition = 
6767                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
6768                                  tf_warning_or_error, NULL_TREE,
6769                                  /*integral_constant_expression_p=*/true);
6770                   finish_static_assert (condition,
6771                                         STATIC_ASSERT_MESSAGE (t), 
6772                                         STATIC_ASSERT_SOURCE_LOCATION (t),
6773                                         /*member_p=*/true);
6774                 }
6775               else if (TREE_CODE (t) != CONST_DECL)
6776                 {
6777                   tree r;
6778
6779                   /* The the file and line for this declaration, to
6780                      assist in error message reporting.  Since we
6781                      called push_tinst_level above, we don't need to
6782                      restore these.  */
6783                   input_location = DECL_SOURCE_LOCATION (t);
6784
6785                   if (TREE_CODE (t) == TEMPLATE_DECL)
6786                     ++processing_template_decl;
6787                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
6788                   if (TREE_CODE (t) == TEMPLATE_DECL)
6789                     --processing_template_decl;
6790                   if (TREE_CODE (r) == VAR_DECL)
6791                     {
6792                       /* In [temp.inst]:
6793
6794                            [t]he initialization (and any associated
6795                            side-effects) of a static data member does
6796                            not occur unless the static data member is
6797                            itself used in a way that requires the
6798                            definition of the static data member to
6799                            exist.
6800
6801                          Therefore, we do not substitute into the
6802                          initialized for the static data member here.  */
6803                       finish_static_data_member_decl
6804                         (r,
6805                          /*init=*/NULL_TREE,
6806                          /*init_const_expr_p=*/false,
6807                          /*asmspec_tree=*/NULL_TREE,
6808                          /*flags=*/0);
6809                       if (DECL_INITIALIZED_IN_CLASS_P (r))
6810                         check_static_variable_definition (r, TREE_TYPE (r));
6811                     }
6812                   else if (TREE_CODE (r) == FIELD_DECL)
6813                     {
6814                       /* Determine whether R has a valid type and can be
6815                          completed later.  If R is invalid, then it is
6816                          replaced by error_mark_node so that it will not be
6817                          added to TYPE_FIELDS.  */
6818                       tree rtype = TREE_TYPE (r);
6819                       if (can_complete_type_without_circularity (rtype))
6820                         complete_type (rtype);
6821
6822                       if (!COMPLETE_TYPE_P (rtype))
6823                         {
6824                           cxx_incomplete_type_error (r, rtype);
6825                           r = error_mark_node;
6826                         }
6827                     }
6828
6829                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
6830                      such a thing will already have been added to the field
6831                      list by tsubst_enum in finish_member_declaration in the
6832                      CLASSTYPE_NESTED_UTDS case above.  */
6833                   if (!(TREE_CODE (r) == TYPE_DECL
6834                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
6835                         && DECL_ARTIFICIAL (r)))
6836                     {
6837                       set_current_access_from_decl (r);
6838                       finish_member_declaration (r);
6839                     }
6840                 }
6841             }
6842         }
6843       else
6844         {
6845           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
6846             {
6847               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
6848
6849               tree friend_type = t;
6850               bool adjust_processing_template_decl = false;
6851
6852               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
6853                 {
6854                   /* template <class T> friend class C;  */
6855                   friend_type = tsubst_friend_class (friend_type, args);
6856                   adjust_processing_template_decl = true;
6857                 }
6858               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
6859                 {
6860                   /* template <class T> friend class C::D;  */
6861                   friend_type = tsubst (friend_type, args,
6862                                         tf_warning_or_error, NULL_TREE);
6863                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
6864                     friend_type = TREE_TYPE (friend_type);
6865                   adjust_processing_template_decl = true;
6866                 }
6867               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
6868                 {
6869                   /* This could be either
6870
6871                        friend class T::C;
6872
6873                      when dependent_type_p is false or
6874
6875                        template <class U> friend class T::C;
6876
6877                      otherwise.  */
6878                   friend_type = tsubst (friend_type, args,
6879                                         tf_warning_or_error, NULL_TREE);
6880                   /* Bump processing_template_decl for correct
6881                      dependent_type_p calculation.  */
6882                   ++processing_template_decl;
6883                   if (dependent_type_p (friend_type))
6884                     adjust_processing_template_decl = true;
6885                   --processing_template_decl;
6886                 }
6887               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
6888                        && hidden_name_p (TYPE_NAME (friend_type)))
6889                 {
6890                   /* friend class C;
6891
6892                      where C hasn't been declared yet.  Let's lookup name
6893                      from namespace scope directly, bypassing any name that
6894                      come from dependent base class.  */
6895                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
6896
6897                   /* The call to xref_tag_from_type does injection for friend
6898                      classes.  */
6899                   push_nested_namespace (ns);
6900                   friend_type =
6901                     xref_tag_from_type (friend_type, NULL_TREE,
6902                                         /*tag_scope=*/ts_current);
6903                   pop_nested_namespace (ns);
6904                 }
6905               else if (uses_template_parms (friend_type))
6906                 /* friend class C<T>;  */
6907                 friend_type = tsubst (friend_type, args,
6908                                       tf_warning_or_error, NULL_TREE);
6909               /* Otherwise it's
6910
6911                    friend class C;
6912
6913                  where C is already declared or
6914
6915                    friend class C<int>;
6916
6917                  We don't have to do anything in these cases.  */
6918
6919               if (adjust_processing_template_decl)
6920                 /* Trick make_friend_class into realizing that the friend
6921                    we're adding is a template, not an ordinary class.  It's
6922                    important that we use make_friend_class since it will
6923                    perform some error-checking and output cross-reference
6924                    information.  */
6925                 ++processing_template_decl;
6926
6927               if (friend_type != error_mark_node)
6928                 make_friend_class (type, friend_type, /*complain=*/false);
6929
6930               if (adjust_processing_template_decl)
6931                 --processing_template_decl;
6932             }
6933           else
6934             {
6935               /* Build new DECL_FRIENDLIST.  */
6936               tree r;
6937
6938               /* The the file and line for this declaration, to
6939                  assist in error message reporting.  Since we
6940                  called push_tinst_level above, we don't need to
6941                  restore these.  */
6942               input_location = DECL_SOURCE_LOCATION (t);
6943
6944               if (TREE_CODE (t) == TEMPLATE_DECL)
6945                 {
6946                   ++processing_template_decl;
6947                   push_deferring_access_checks (dk_no_check);
6948                 }
6949
6950               r = tsubst_friend_function (t, args);
6951               add_friend (type, r, /*complain=*/false);
6952               if (TREE_CODE (t) == TEMPLATE_DECL)
6953                 {
6954                   pop_deferring_access_checks ();
6955                   --processing_template_decl;
6956                 }
6957             }
6958         }
6959     }
6960
6961   /* Set the file and line number information to whatever is given for
6962      the class itself.  This puts error messages involving generated
6963      implicit functions at a predictable point, and the same point
6964      that would be used for non-template classes.  */
6965   input_location = DECL_SOURCE_LOCATION (typedecl);
6966
6967   unreverse_member_declarations (type);
6968   finish_struct_1 (type);
6969   TYPE_BEING_DEFINED (type) = 0;
6970
6971   /* Now that the class is complete, instantiate default arguments for
6972      any member functions.  We don't do this earlier because the
6973      default arguments may reference members of the class.  */
6974   if (!PRIMARY_TEMPLATE_P (template))
6975     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
6976       if (TREE_CODE (t) == FUNCTION_DECL
6977           /* Implicitly generated member functions will not have template
6978              information; they are not instantiations, but instead are
6979              created "fresh" for each instantiation.  */
6980           && DECL_TEMPLATE_INFO (t))
6981         tsubst_default_arguments (t);
6982
6983   popclass ();
6984   pop_from_top_level ();
6985   pop_deferring_access_checks ();
6986   pop_tinst_level ();
6987
6988   /* The vtable for a template class can be emitted in any translation
6989      unit in which the class is instantiated.  When there is no key
6990      method, however, finish_struct_1 will already have added TYPE to
6991      the keyed_classes list.  */
6992   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
6993     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
6994
6995   return type;
6996 }
6997
6998 static tree
6999 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7000 {
7001   tree r;
7002
7003   if (!t)
7004     r = t;
7005   else if (TYPE_P (t))
7006     r = tsubst (t, args, complain, in_decl);
7007   else
7008     {
7009       r = tsubst_expr (t, args, complain, in_decl,
7010                        /*integral_constant_expression_p=*/true);
7011       r = fold_non_dependent_expr (r);
7012     }
7013   return r;
7014 }
7015
7016 /* Substitute ARGS into T, which is an pack expansion
7017    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
7018    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
7019    (if only a partial substitution could be performed) or
7020    ERROR_MARK_NODE if there was an error.  */
7021 tree
7022 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
7023                        tree in_decl)
7024 {
7025   tree pattern;
7026   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
7027   tree first_arg_pack; int i, len = -1;
7028   tree result;
7029   int incomplete = 0;
7030
7031   gcc_assert (PACK_EXPANSION_P (t));
7032   pattern = PACK_EXPANSION_PATTERN (t);
7033
7034   /* Determine the argument packs that will instantiate the parameter
7035      packs used in the expansion expression. While we're at it,
7036      compute the number of arguments to be expanded and make sure it
7037      is consistent.  */
7038   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
7039        pack = TREE_CHAIN (pack))
7040     {
7041       tree parm_pack = TREE_VALUE (pack);
7042       tree arg_pack = NULL_TREE;
7043       tree orig_arg = NULL_TREE;
7044
7045       if (TREE_CODE (parm_pack) == PARM_DECL)
7046         {
7047           if (local_specializations)
7048             arg_pack = retrieve_local_specialization (parm_pack);
7049         }
7050       else
7051         {
7052           int level, idx, levels;
7053           template_parm_level_and_index (parm_pack, &level, &idx);
7054
7055           levels = TMPL_ARGS_DEPTH (args);
7056           if (level <= levels)
7057             arg_pack = TMPL_ARG (args, level, idx);
7058         }
7059
7060       orig_arg = arg_pack;
7061       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
7062         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
7063       
7064       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
7065         /* This can only happen if we forget to expand an argument
7066            pack somewhere else. Just return an error, silently.  */
7067         {
7068           result = make_tree_vec (1);
7069           TREE_VEC_ELT (result, 0) = error_mark_node;
7070           return result;
7071         }
7072
7073       if (arg_pack)
7074         {
7075           int my_len = 
7076             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
7077
7078           /* It's all-or-nothing with incomplete argument packs.  */
7079           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7080             return error_mark_node;
7081           
7082           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7083             incomplete = 1;
7084
7085           if (len < 0)
7086             {
7087               len = my_len;
7088               first_arg_pack = arg_pack;
7089             }
7090           else if (len != my_len)
7091             {
7092               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
7093                 error ("mismatched argument pack lengths while expanding "
7094                        "%<%T%>",
7095                        pattern);
7096               else
7097                 error ("mismatched argument pack lengths while expanding "
7098                        "%<%E%>",
7099                        pattern);
7100               return error_mark_node;
7101             }
7102
7103           /* Keep track of the parameter packs and their corresponding
7104              argument packs.  */
7105           packs = tree_cons (parm_pack, arg_pack, packs);
7106           TREE_TYPE (packs) = orig_arg;
7107         }
7108       else
7109         /* We can't substitute for this parameter pack.  */
7110         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
7111                                          TREE_VALUE (pack),
7112                                          unsubstituted_packs);
7113     }
7114
7115   /* We cannot expand this expansion expression, because we don't have
7116      all of the argument packs we need. Substitute into the pattern
7117      and return a PACK_EXPANSION_*. The caller will need to deal with
7118      that.  */
7119   if (unsubstituted_packs)
7120     return make_pack_expansion (tsubst (pattern, args, complain, 
7121                                         in_decl));
7122
7123   /* We could not find any argument packs that work.  */
7124   if (len < 0)
7125     return error_mark_node;
7126
7127   /* For each argument in each argument pack, substitute into the
7128      pattern.  */
7129   result = make_tree_vec (len + incomplete);
7130   for (i = 0; i < len + incomplete; ++i)
7131     {
7132       /* For parameter pack, change the substitution of the parameter
7133          pack to the ith argument in its argument pack, then expand
7134          the pattern.  */
7135       for (pack = packs; pack; pack = TREE_CHAIN (pack))
7136         {
7137           tree parm = TREE_PURPOSE (pack);
7138
7139           if (TREE_CODE (parm) == PARM_DECL)
7140             {
7141               /* Select the Ith argument from the pack.  */
7142               tree arg = make_node (ARGUMENT_PACK_SELECT);
7143               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
7144               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
7145               mark_used (parm);
7146               register_local_specialization (arg, parm);
7147             }
7148           else
7149             {
7150               tree value = parm;
7151               int idx, level;
7152               template_parm_level_and_index (parm, &level, &idx);
7153               
7154               if (i < len) 
7155                 {
7156                   /* Select the Ith argument from the pack. */
7157                   value = make_node (ARGUMENT_PACK_SELECT);
7158                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
7159                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
7160                 }
7161
7162               /* Update the corresponding argument.  */
7163               TMPL_ARG (args, level, idx) = value;
7164             }
7165         }
7166
7167       /* Substitute into the PATTERN with the altered arguments.  */
7168       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
7169         TREE_VEC_ELT (result, i) = 
7170           tsubst_expr (pattern, args, complain, in_decl,
7171                        /*integral_constant_expression_p=*/false);
7172       else
7173         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
7174
7175       if (i == len)
7176         /* When we have incomplete argument packs, the last "expanded"
7177            result is itself a pack expansion, which allows us
7178            to deduce more arguments.  */
7179         TREE_VEC_ELT (result, i) = 
7180           make_pack_expansion (TREE_VEC_ELT (result, i));
7181
7182       if (TREE_VEC_ELT (result, i) == error_mark_node)
7183         {
7184           result = error_mark_node;
7185           break;
7186         }
7187     }
7188   
7189   /* Update ARGS to restore the substitution from parameter packs to
7190      their argument packs.  */
7191   for (pack = packs; pack; pack = TREE_CHAIN (pack))
7192     {
7193       tree parm = TREE_PURPOSE (pack);
7194
7195       if (TREE_CODE (parm) == PARM_DECL)
7196         register_local_specialization (TREE_TYPE (pack), parm);
7197       else
7198         {
7199           int idx, level;
7200           template_parm_level_and_index (parm, &level, &idx);
7201           
7202           /* Update the corresponding argument.  */
7203           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
7204             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
7205               TREE_TYPE (pack);
7206           else
7207             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
7208         }
7209     }
7210
7211   return result;
7212 }
7213
7214 /* Substitute ARGS into the vector or list of template arguments T.  */
7215
7216 static tree
7217 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7218 {
7219   tree orig_t = t;
7220   int len = TREE_VEC_LENGTH (t);
7221   int need_new = 0, i, expanded_len_adjust = 0, out;
7222   tree *elts = (tree *) alloca (len * sizeof (tree));
7223
7224   for (i = 0; i < len; i++)
7225     {
7226       tree orig_arg = TREE_VEC_ELT (t, i);
7227       tree new_arg;
7228
7229       if (TREE_CODE (orig_arg) == TREE_VEC)
7230         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
7231       else if (PACK_EXPANSION_P (orig_arg))
7232         {
7233           /* Substitute into an expansion expression.  */
7234           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
7235
7236           if (TREE_CODE (new_arg) == TREE_VEC)
7237             /* Add to the expanded length adjustment the number of
7238                expanded arguments. We subtract one from this
7239                measurement, because the argument pack expression
7240                itself is already counted as 1 in
7241                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
7242                the argument pack is empty.  */
7243             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
7244         }
7245       else if (ARGUMENT_PACK_P (orig_arg))
7246         {
7247           /* Substitute into each of the arguments.  */
7248           new_arg = make_node (TREE_CODE (orig_arg));
7249           
7250           SET_ARGUMENT_PACK_ARGS (
7251             new_arg,
7252             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
7253                                   args, complain, in_decl));
7254
7255           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
7256             new_arg = error_mark_node;
7257
7258           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
7259             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
7260                                           complain, in_decl);
7261             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
7262
7263             if (TREE_TYPE (new_arg) == error_mark_node)
7264               new_arg = error_mark_node;
7265           }
7266         }
7267       else
7268         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
7269
7270       if (new_arg == error_mark_node)
7271         return error_mark_node;
7272
7273       elts[i] = new_arg;
7274       if (new_arg != orig_arg)
7275         need_new = 1;
7276     }
7277
7278   if (!need_new)
7279     return t;
7280
7281   /* Make space for the expanded arguments coming from template
7282      argument packs.  */
7283   t = make_tree_vec (len + expanded_len_adjust);
7284   for (i = 0, out = 0; i < len; i++)
7285     {
7286       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
7287            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
7288           && TREE_CODE (elts[i]) == TREE_VEC)
7289         {
7290           int idx;
7291
7292           /* Now expand the template argument pack "in place".  */
7293           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
7294             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
7295         }
7296       else
7297         {
7298           TREE_VEC_ELT (t, out) = elts[i];
7299           out++;
7300         }
7301     }
7302
7303   return t;
7304 }
7305
7306 /* Return the result of substituting ARGS into the template parameters
7307    given by PARMS.  If there are m levels of ARGS and m + n levels of
7308    PARMS, then the result will contain n levels of PARMS.  For
7309    example, if PARMS is `template <class T> template <class U>
7310    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
7311    result will be `template <int*, double, class V>'.  */
7312
7313 static tree
7314 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
7315 {
7316   tree r = NULL_TREE;
7317   tree* new_parms;
7318
7319   /* When substituting into a template, we must set
7320      PROCESSING_TEMPLATE_DECL as the template parameters may be
7321      dependent if they are based on one-another, and the dependency
7322      predicates are short-circuit outside of templates.  */
7323   ++processing_template_decl;
7324
7325   for (new_parms = &r;
7326        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
7327        new_parms = &(TREE_CHAIN (*new_parms)),
7328          parms = TREE_CHAIN (parms))
7329     {
7330       tree new_vec =
7331         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
7332       int i;
7333
7334       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
7335         {
7336           tree tuple;
7337           tree default_value;
7338           tree parm_decl;
7339
7340           if (parms == error_mark_node)
7341             continue;
7342
7343           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
7344
7345           if (tuple == error_mark_node)
7346             continue;
7347
7348           default_value = TREE_PURPOSE (tuple);
7349           parm_decl = TREE_VALUE (tuple);
7350
7351           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
7352           if (TREE_CODE (parm_decl) == PARM_DECL
7353               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
7354             parm_decl = error_mark_node;
7355           default_value = tsubst_template_arg (default_value, args,
7356                                                complain, NULL_TREE);
7357
7358           tuple = build_tree_list (default_value, parm_decl);
7359           TREE_VEC_ELT (new_vec, i) = tuple;
7360         }
7361
7362       *new_parms =
7363         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
7364                              - TMPL_ARGS_DEPTH (args)),
7365                    new_vec, NULL_TREE);
7366     }
7367
7368   --processing_template_decl;
7369
7370   return r;
7371 }
7372
7373 /* Substitute the ARGS into the indicated aggregate (or enumeration)
7374    type T.  If T is not an aggregate or enumeration type, it is
7375    handled as if by tsubst.  IN_DECL is as for tsubst.  If
7376    ENTERING_SCOPE is nonzero, T is the context for a template which
7377    we are presently tsubst'ing.  Return the substituted value.  */
7378
7379 static tree
7380 tsubst_aggr_type (tree t,
7381                   tree args,
7382                   tsubst_flags_t complain,
7383                   tree in_decl,
7384                   int entering_scope)
7385 {
7386   if (t == NULL_TREE)
7387     return NULL_TREE;
7388
7389   switch (TREE_CODE (t))
7390     {
7391     case RECORD_TYPE:
7392       if (TYPE_PTRMEMFUNC_P (t))
7393         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
7394
7395       /* Else fall through.  */
7396     case ENUMERAL_TYPE:
7397     case UNION_TYPE:
7398       if (TYPE_TEMPLATE_INFO (t))
7399         {
7400           tree argvec;
7401           tree context;
7402           tree r;
7403           bool saved_skip_evaluation;
7404
7405           /* In "sizeof(X<I>)" we need to evaluate "I".  */
7406           saved_skip_evaluation = skip_evaluation;
7407           skip_evaluation = false;
7408
7409           /* First, determine the context for the type we are looking
7410              up.  */
7411           context = TYPE_CONTEXT (t);
7412           if (context)
7413             context = tsubst_aggr_type (context, args, complain,
7414                                         in_decl, /*entering_scope=*/1);
7415
7416           /* Then, figure out what arguments are appropriate for the
7417              type we are trying to find.  For example, given:
7418
7419                template <class T> struct S;
7420                template <class T, class U> void f(T, U) { S<U> su; }
7421
7422              and supposing that we are instantiating f<int, double>,
7423              then our ARGS will be {int, double}, but, when looking up
7424              S we only want {double}.  */
7425           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
7426                                          complain, in_decl);
7427           if (argvec == error_mark_node)
7428             r = error_mark_node;
7429           else
7430             {
7431               r = lookup_template_class (t, argvec, in_decl, context,
7432                                          entering_scope, complain);
7433               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
7434             }
7435
7436           skip_evaluation = saved_skip_evaluation;
7437
7438           return r;
7439         }
7440       else
7441         /* This is not a template type, so there's nothing to do.  */
7442         return t;
7443
7444     default:
7445       return tsubst (t, args, complain, in_decl);
7446     }
7447 }
7448
7449 /* Substitute into the default argument ARG (a default argument for
7450    FN), which has the indicated TYPE.  */
7451
7452 tree
7453 tsubst_default_argument (tree fn, tree type, tree arg)
7454 {
7455   tree saved_class_ptr = NULL_TREE;
7456   tree saved_class_ref = NULL_TREE;
7457
7458   /* This default argument came from a template.  Instantiate the
7459      default argument here, not in tsubst.  In the case of
7460      something like:
7461
7462        template <class T>
7463        struct S {
7464          static T t();
7465          void f(T = t());
7466        };
7467
7468      we must be careful to do name lookup in the scope of S<T>,
7469      rather than in the current class.  */
7470   push_access_scope (fn);
7471   /* The "this" pointer is not valid in a default argument.  */
7472   if (cfun)
7473     {
7474       saved_class_ptr = current_class_ptr;
7475       cp_function_chain->x_current_class_ptr = NULL_TREE;
7476       saved_class_ref = current_class_ref;
7477       cp_function_chain->x_current_class_ref = NULL_TREE;
7478     }
7479
7480   push_deferring_access_checks(dk_no_deferred);
7481   /* The default argument expression may cause implicitly defined
7482      member functions to be synthesized, which will result in garbage
7483      collection.  We must treat this situation as if we were within
7484      the body of function so as to avoid collecting live data on the
7485      stack.  */
7486   ++function_depth;
7487   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
7488                      tf_warning_or_error, NULL_TREE,
7489                      /*integral_constant_expression_p=*/false);
7490   --function_depth;
7491   pop_deferring_access_checks();
7492
7493   /* Restore the "this" pointer.  */
7494   if (cfun)
7495     {
7496       cp_function_chain->x_current_class_ptr = saved_class_ptr;
7497       cp_function_chain->x_current_class_ref = saved_class_ref;
7498     }
7499
7500   pop_access_scope (fn);
7501
7502   /* Make sure the default argument is reasonable.  */
7503   arg = check_default_argument (type, arg);
7504
7505   return arg;
7506 }
7507
7508 /* Substitute into all the default arguments for FN.  */
7509
7510 static void
7511 tsubst_default_arguments (tree fn)
7512 {
7513   tree arg;
7514   tree tmpl_args;
7515
7516   tmpl_args = DECL_TI_ARGS (fn);
7517
7518   /* If this function is not yet instantiated, we certainly don't need
7519      its default arguments.  */
7520   if (uses_template_parms (tmpl_args))
7521     return;
7522
7523   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
7524        arg;
7525        arg = TREE_CHAIN (arg))
7526     if (TREE_PURPOSE (arg))
7527       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
7528                                                     TREE_VALUE (arg),
7529                                                     TREE_PURPOSE (arg));
7530 }
7531
7532 /* Substitute the ARGS into the T, which is a _DECL.  Return the
7533    result of the substitution.  Issue error and warning messages under
7534    control of COMPLAIN.  */
7535
7536 static tree
7537 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
7538 {
7539   location_t saved_loc;
7540   tree r = NULL_TREE;
7541   tree in_decl = t;
7542
7543   /* Set the filename and linenumber to improve error-reporting.  */
7544   saved_loc = input_location;
7545   input_location = DECL_SOURCE_LOCATION (t);
7546
7547   switch (TREE_CODE (t))
7548     {
7549     case TEMPLATE_DECL:
7550       {
7551         /* We can get here when processing a member function template,
7552            member class template, and template template parameter of
7553            a template class.  */
7554         tree decl = DECL_TEMPLATE_RESULT (t);
7555         tree spec;
7556         tree tmpl_args;
7557         tree full_args;
7558
7559         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
7560           {
7561             /* Template template parameter is treated here.  */
7562             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
7563             if (new_type == error_mark_node)
7564               return error_mark_node;
7565
7566             r = copy_decl (t);
7567             TREE_CHAIN (r) = NULL_TREE;
7568             TREE_TYPE (r) = new_type;
7569             DECL_TEMPLATE_RESULT (r)
7570               = build_decl (TYPE_DECL, DECL_NAME (decl), new_type);
7571             DECL_TEMPLATE_PARMS (r)
7572               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
7573                                        complain);
7574             TYPE_NAME (new_type) = r;
7575             break;
7576           }
7577
7578         /* We might already have an instance of this template.
7579            The ARGS are for the surrounding class type, so the
7580            full args contain the tsubst'd args for the context,
7581            plus the innermost args from the template decl.  */
7582         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
7583           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
7584           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
7585         /* Because this is a template, the arguments will still be
7586            dependent, even after substitution.  If
7587            PROCESSING_TEMPLATE_DECL is not set, the dependency
7588            predicates will short-circuit.  */
7589         ++processing_template_decl;
7590         full_args = tsubst_template_args (tmpl_args, args,
7591                                           complain, in_decl);
7592         --processing_template_decl;
7593         if (full_args == error_mark_node)
7594           return error_mark_node;
7595
7596         /* tsubst_template_args doesn't copy the vector if
7597            nothing changed.  But, *something* should have
7598            changed.  */
7599         gcc_assert (full_args != tmpl_args);
7600
7601         spec = retrieve_specialization (t, full_args,
7602                                         /*class_specializations_p=*/true);
7603         if (spec != NULL_TREE)
7604           {
7605             r = spec;
7606             break;
7607           }
7608
7609         /* Make a new template decl.  It will be similar to the
7610            original, but will record the current template arguments.
7611            We also create a new function declaration, which is just
7612            like the old one, but points to this new template, rather
7613            than the old one.  */
7614         r = copy_decl (t);
7615         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
7616         TREE_CHAIN (r) = NULL_TREE;
7617
7618         DECL_TEMPLATE_INFO (r) = build_tree_list (t, args);
7619
7620         if (TREE_CODE (decl) == TYPE_DECL)
7621           {
7622             tree new_type;
7623             ++processing_template_decl;
7624             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
7625             --processing_template_decl;
7626             if (new_type == error_mark_node)
7627               return error_mark_node;
7628
7629             TREE_TYPE (r) = new_type;
7630             CLASSTYPE_TI_TEMPLATE (new_type) = r;
7631             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
7632             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
7633             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
7634           }
7635         else
7636           {
7637             tree new_decl;
7638             ++processing_template_decl;
7639             new_decl = tsubst (decl, args, complain, in_decl);
7640             --processing_template_decl;
7641             if (new_decl == error_mark_node)
7642               return error_mark_node;
7643
7644             DECL_TEMPLATE_RESULT (r) = new_decl;
7645             DECL_TI_TEMPLATE (new_decl) = r;
7646             TREE_TYPE (r) = TREE_TYPE (new_decl);
7647             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
7648             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
7649           }
7650
7651         SET_DECL_IMPLICIT_INSTANTIATION (r);
7652         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
7653         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
7654
7655         /* The template parameters for this new template are all the
7656            template parameters for the old template, except the
7657            outermost level of parameters.  */
7658         DECL_TEMPLATE_PARMS (r)
7659           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
7660                                    complain);
7661
7662         if (PRIMARY_TEMPLATE_P (t))
7663           DECL_PRIMARY_TEMPLATE (r) = r;
7664
7665         if (TREE_CODE (decl) != TYPE_DECL)
7666           /* Record this non-type partial instantiation.  */
7667           register_specialization (r, t,
7668                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
7669                                    false);
7670       }
7671       break;
7672
7673     case FUNCTION_DECL:
7674       {
7675         tree ctx;
7676         tree argvec = NULL_TREE;
7677         tree *friends;
7678         tree gen_tmpl;
7679         tree type;
7680         int member;
7681         int args_depth;
7682         int parms_depth;
7683
7684         /* Nobody should be tsubst'ing into non-template functions.  */
7685         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
7686
7687         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
7688           {
7689             tree spec;
7690             bool dependent_p;
7691
7692             /* If T is not dependent, just return it.  We have to
7693                increment PROCESSING_TEMPLATE_DECL because
7694                value_dependent_expression_p assumes that nothing is
7695                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
7696             ++processing_template_decl;
7697             dependent_p = value_dependent_expression_p (t);
7698             --processing_template_decl;
7699             if (!dependent_p)
7700               return t;
7701
7702             /* Calculate the most general template of which R is a
7703                specialization, and the complete set of arguments used to
7704                specialize R.  */
7705             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
7706             argvec = tsubst_template_args (DECL_TI_ARGS
7707                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
7708                                            args, complain, in_decl);
7709
7710             /* Check to see if we already have this specialization.  */
7711             spec = retrieve_specialization (gen_tmpl, argvec,
7712                                             /*class_specializations_p=*/false);
7713
7714             if (spec)
7715               {
7716                 r = spec;
7717                 break;
7718               }
7719
7720             /* We can see more levels of arguments than parameters if
7721                there was a specialization of a member template, like
7722                this:
7723
7724                  template <class T> struct S { template <class U> void f(); }
7725                  template <> template <class U> void S<int>::f(U);
7726
7727                Here, we'll be substituting into the specialization,
7728                because that's where we can find the code we actually
7729                want to generate, but we'll have enough arguments for
7730                the most general template.
7731
7732                We also deal with the peculiar case:
7733
7734                  template <class T> struct S {
7735                    template <class U> friend void f();
7736                  };
7737                  template <class U> void f() {}
7738                  template S<int>;
7739                  template void f<double>();
7740
7741                Here, the ARGS for the instantiation of will be {int,
7742                double}.  But, we only need as many ARGS as there are
7743                levels of template parameters in CODE_PATTERN.  We are
7744                careful not to get fooled into reducing the ARGS in
7745                situations like:
7746
7747                  template <class T> struct S { template <class U> void f(U); }
7748                  template <class T> template <> void S<T>::f(int) {}
7749
7750                which we can spot because the pattern will be a
7751                specialization in this case.  */
7752             args_depth = TMPL_ARGS_DEPTH (args);
7753             parms_depth =
7754               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
7755             if (args_depth > parms_depth
7756                 && !DECL_TEMPLATE_SPECIALIZATION (t))
7757               args = get_innermost_template_args (args, parms_depth);
7758           }
7759         else
7760           {
7761             /* This special case arises when we have something like this:
7762
7763                  template <class T> struct S {
7764                    friend void f<int>(int, double);
7765                  };
7766
7767                Here, the DECL_TI_TEMPLATE for the friend declaration
7768                will be an IDENTIFIER_NODE.  We are being called from
7769                tsubst_friend_function, and we want only to create a
7770                new decl (R) with appropriate types so that we can call
7771                determine_specialization.  */
7772             gen_tmpl = NULL_TREE;
7773           }
7774
7775         if (DECL_CLASS_SCOPE_P (t))
7776           {
7777             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
7778               member = 2;
7779             else
7780               member = 1;
7781             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
7782                                     complain, t, /*entering_scope=*/1);
7783           }
7784         else
7785           {
7786             member = 0;
7787             ctx = DECL_CONTEXT (t);
7788           }
7789         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
7790         if (type == error_mark_node)
7791           return error_mark_node;
7792
7793         /* We do NOT check for matching decls pushed separately at this
7794            point, as they may not represent instantiations of this
7795            template, and in any case are considered separate under the
7796            discrete model.  */
7797         r = copy_decl (t);
7798         DECL_USE_TEMPLATE (r) = 0;
7799         TREE_TYPE (r) = type;
7800         /* Clear out the mangled name and RTL for the instantiation.  */
7801         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
7802         SET_DECL_RTL (r, NULL_RTX);
7803         DECL_INITIAL (r) = NULL_TREE;
7804         DECL_CONTEXT (r) = ctx;
7805
7806         if (member && DECL_CONV_FN_P (r))
7807           /* Type-conversion operator.  Reconstruct the name, in
7808              case it's the name of one of the template's parameters.  */
7809           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
7810
7811         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
7812                                      complain, t);
7813         DECL_RESULT (r) = NULL_TREE;
7814
7815         TREE_STATIC (r) = 0;
7816         TREE_PUBLIC (r) = TREE_PUBLIC (t);
7817         DECL_EXTERNAL (r) = 1;
7818         /* If this is an instantiation of a function with internal
7819            linkage, we already know what object file linkage will be
7820            assigned to the instantiation.  */
7821         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
7822         DECL_DEFER_OUTPUT (r) = 0;
7823         TREE_CHAIN (r) = NULL_TREE;
7824         DECL_PENDING_INLINE_INFO (r) = 0;
7825         DECL_PENDING_INLINE_P (r) = 0;
7826         DECL_SAVED_TREE (r) = NULL_TREE;
7827         TREE_USED (r) = 0;
7828         if (DECL_CLONED_FUNCTION (r))
7829           {
7830             DECL_CLONED_FUNCTION (r) = tsubst (DECL_CLONED_FUNCTION (t),
7831                                                args, complain, t);
7832             TREE_CHAIN (r) = TREE_CHAIN (DECL_CLONED_FUNCTION (r));
7833             TREE_CHAIN (DECL_CLONED_FUNCTION (r)) = r;
7834           }
7835
7836         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
7837            this in the special friend case mentioned above where
7838            GEN_TMPL is NULL.  */
7839         if (gen_tmpl)
7840           {
7841             DECL_TEMPLATE_INFO (r)
7842               = tree_cons (gen_tmpl, argvec, NULL_TREE);
7843             SET_DECL_IMPLICIT_INSTANTIATION (r);
7844             register_specialization (r, gen_tmpl, argvec, false);
7845
7846             /* We're not supposed to instantiate default arguments
7847                until they are called, for a template.  But, for a
7848                declaration like:
7849
7850                  template <class T> void f ()
7851                  { extern void g(int i = T()); }
7852
7853                we should do the substitution when the template is
7854                instantiated.  We handle the member function case in
7855                instantiate_class_template since the default arguments
7856                might refer to other members of the class.  */
7857             if (!member
7858                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
7859                 && !uses_template_parms (argvec))
7860               tsubst_default_arguments (r);
7861           }
7862         else
7863           DECL_TEMPLATE_INFO (r) = NULL_TREE;
7864
7865         /* Copy the list of befriending classes.  */
7866         for (friends = &DECL_BEFRIENDING_CLASSES (r);
7867              *friends;
7868              friends = &TREE_CHAIN (*friends))
7869           {
7870             *friends = copy_node (*friends);
7871             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
7872                                             args, complain,
7873                                             in_decl);
7874           }
7875
7876         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
7877           {
7878             maybe_retrofit_in_chrg (r);
7879             if (DECL_CONSTRUCTOR_P (r))
7880               grok_ctor_properties (ctx, r);
7881             /* If this is an instantiation of a member template, clone it.
7882                If it isn't, that'll be handled by
7883                clone_constructors_and_destructors.  */
7884             if (PRIMARY_TEMPLATE_P (gen_tmpl))
7885               clone_function_decl (r, /*update_method_vec_p=*/0);
7886           }
7887         else if (IDENTIFIER_OPNAME_P (DECL_NAME (r))
7888                  && !grok_op_properties (r, (complain & tf_error) != 0))
7889           return error_mark_node;
7890
7891         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
7892           SET_DECL_FRIEND_CONTEXT (r,
7893                                    tsubst (DECL_FRIEND_CONTEXT (t),
7894                                             args, complain, in_decl));
7895
7896         /* Possibly limit visibility based on template args.  */
7897         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
7898         if (DECL_VISIBILITY_SPECIFIED (t))
7899           {
7900             DECL_VISIBILITY_SPECIFIED (r) = 0;
7901             DECL_ATTRIBUTES (r)
7902               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
7903           }
7904         determine_visibility (r);
7905
7906         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
7907                                         args, complain, in_decl);
7908       }
7909       break;
7910
7911     case PARM_DECL:
7912       {
7913         tree type = NULL_TREE;
7914         int i, len = 1;
7915         tree expanded_types = NULL_TREE;
7916         tree prev_r = NULL_TREE;
7917         tree first_r = NULL_TREE;
7918
7919         if (FUNCTION_PARAMETER_PACK_P (t))
7920           {
7921             /* If there is a local specialization that isn't a
7922                parameter pack, it means that we're doing a "simple"
7923                substitution from inside tsubst_pack_expansion. Just
7924                return the local specialization (which will be a single
7925                parm).  */
7926             tree spec = NULL_TREE;
7927             if (local_specializations)
7928               spec = retrieve_local_specialization (t);
7929             if (spec 
7930                 && TREE_CODE (spec) == PARM_DECL
7931                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
7932               return spec;
7933
7934             /* Expand the TYPE_PACK_EXPANSION that provides the types for
7935                the parameters in this function parameter pack.  */
7936             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
7937                                                     complain, in_decl);
7938             if (TREE_CODE (expanded_types) == TREE_VEC)
7939               {
7940                 len = TREE_VEC_LENGTH (expanded_types);
7941
7942                 /* Zero-length parameter packs are boring. Just substitute
7943                    into the chain.  */
7944                 if (len == 0)
7945                   return tsubst (TREE_CHAIN (t), args, complain, 
7946                                  TREE_CHAIN (t));
7947               }
7948             else
7949               {
7950                 /* All we did was update the type. Make a note of that.  */
7951                 type = expanded_types;
7952                 expanded_types = NULL_TREE;
7953               }
7954           }
7955
7956         /* Loop through all of the parameter's we'll build. When T is
7957            a function parameter pack, LEN is the number of expanded
7958            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
7959         r = NULL_TREE;
7960         for (i = 0; i < len; ++i)
7961           {
7962             prev_r = r;
7963             r = copy_node (t);
7964             if (DECL_TEMPLATE_PARM_P (t))
7965               SET_DECL_TEMPLATE_PARM_P (r);
7966
7967             if (expanded_types)
7968               /* We're on the Ith parameter of the function parameter
7969                  pack.  */
7970               {
7971                 /* Get the Ith type.  */
7972                 type = TREE_VEC_ELT (expanded_types, i);
7973
7974                 if (DECL_NAME (r))
7975                   /* Rename the parameter to include the index.  */
7976                   DECL_NAME (r) =
7977                     make_ith_pack_parameter_name (DECL_NAME (r), i);
7978               }
7979             else if (!type)
7980               /* We're dealing with a normal parameter.  */
7981               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
7982
7983             type = type_decays_to (type);
7984             TREE_TYPE (r) = type;
7985             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
7986
7987             if (DECL_INITIAL (r))
7988               {
7989                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
7990                   DECL_INITIAL (r) = TREE_TYPE (r);
7991                 else
7992                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
7993                                              complain, in_decl);
7994               }
7995
7996             DECL_CONTEXT (r) = NULL_TREE;
7997
7998             if (!DECL_TEMPLATE_PARM_P (r))
7999               DECL_ARG_TYPE (r) = type_passed_as (type);
8000
8001             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8002                                             args, complain, in_decl);
8003
8004             /* Keep track of the first new parameter we
8005                generate. That's what will be returned to the
8006                caller.  */
8007             if (!first_r)
8008               first_r = r;
8009
8010             /* Build a proper chain of parameters when substituting
8011                into a function parameter pack.  */
8012             if (prev_r)
8013               TREE_CHAIN (prev_r) = r;
8014           }
8015
8016         if (TREE_CHAIN (t))
8017           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
8018                                    complain, TREE_CHAIN (t));
8019
8020         /* FIRST_R contains the start of the chain we've built.  */
8021         r = first_r;
8022       }
8023       break;
8024
8025     case FIELD_DECL:
8026       {
8027         tree type;
8028
8029         r = copy_decl (t);
8030         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8031         if (type == error_mark_node)
8032           return error_mark_node;
8033         TREE_TYPE (r) = type;
8034         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8035
8036         /* DECL_INITIAL gives the number of bits in a bit-field.  */
8037         DECL_INITIAL (r)
8038           = tsubst_expr (DECL_INITIAL (t), args,
8039                          complain, in_decl,
8040                          /*integral_constant_expression_p=*/true);
8041         /* We don't have to set DECL_CONTEXT here; it is set by
8042            finish_member_declaration.  */
8043         TREE_CHAIN (r) = NULL_TREE;
8044         if (VOID_TYPE_P (type))
8045           error ("instantiation of %q+D as type %qT", r, type);
8046
8047         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8048                                         args, complain, in_decl);
8049       }
8050       break;
8051
8052     case USING_DECL:
8053       /* We reach here only for member using decls.  */
8054       if (DECL_DEPENDENT_P (t))
8055         {
8056           r = do_class_using_decl
8057             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
8058              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
8059           if (!r)
8060             r = error_mark_node;
8061         }
8062       else
8063         {
8064           r = copy_node (t);
8065           TREE_CHAIN (r) = NULL_TREE;
8066         }
8067       break;
8068
8069     case TYPE_DECL:
8070     case VAR_DECL:
8071       {
8072         tree argvec = NULL_TREE;
8073         tree gen_tmpl = NULL_TREE;
8074         tree spec;
8075         tree tmpl = NULL_TREE;
8076         tree ctx;
8077         tree type = NULL_TREE;
8078         bool local_p;
8079
8080         if (TREE_CODE (t) == TYPE_DECL)
8081           {
8082             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8083             if (TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM
8084                 || t == TYPE_MAIN_DECL (TREE_TYPE (t)))
8085               {
8086                 /* If this is the canonical decl, we don't have to
8087                    mess with instantiations, and often we can't (for
8088                    typename, template type parms and such).  Note that
8089                    TYPE_NAME is not correct for the above test if
8090                    we've copied the type for a typedef.  */
8091                 r = TYPE_NAME (type);
8092                 break;
8093               }
8094           }
8095
8096         /* Check to see if we already have the specialization we
8097            need.  */
8098         spec = NULL_TREE;
8099         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
8100           {
8101             /* T is a static data member or namespace-scope entity.
8102                We have to substitute into namespace-scope variables
8103                (even though such entities are never templates) because
8104                of cases like:
8105                
8106                  template <class T> void f() { extern T t; }
8107
8108                where the entity referenced is not known until
8109                instantiation time.  */
8110             local_p = false;
8111             ctx = DECL_CONTEXT (t);
8112             if (DECL_CLASS_SCOPE_P (t))
8113               {
8114                 ctx = tsubst_aggr_type (ctx, args,
8115                                         complain,
8116                                         in_decl, /*entering_scope=*/1);
8117                 /* If CTX is unchanged, then T is in fact the
8118                    specialization we want.  That situation occurs when
8119                    referencing a static data member within in its own
8120                    class.  We can use pointer equality, rather than
8121                    same_type_p, because DECL_CONTEXT is always
8122                    canonical.  */
8123                 if (ctx == DECL_CONTEXT (t))
8124                   spec = t;
8125               }
8126
8127             if (!spec)
8128               {
8129                 tmpl = DECL_TI_TEMPLATE (t);
8130                 gen_tmpl = most_general_template (tmpl);
8131                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
8132                 spec = (retrieve_specialization 
8133                         (gen_tmpl, argvec,
8134                          /*class_specializations_p=*/false));
8135               }
8136           }
8137         else
8138           {
8139             /* A local variable.  */
8140             local_p = true;
8141             /* Subsequent calls to pushdecl will fill this in.  */
8142             ctx = NULL_TREE;
8143             spec = retrieve_local_specialization (t);
8144           }
8145         /* If we already have the specialization we need, there is
8146            nothing more to do.  */ 
8147         if (spec)
8148           {
8149             r = spec;
8150             break;
8151           }
8152
8153         /* Create a new node for the specialization we need.  */
8154         r = copy_decl (t);
8155         if (TREE_CODE (r) == VAR_DECL)
8156           {
8157             /* Even if the original location is out of scope, the
8158                newly substituted one is not.  */
8159             DECL_DEAD_FOR_LOCAL (r) = 0;
8160             DECL_INITIALIZED_P (r) = 0;
8161             DECL_TEMPLATE_INSTANTIATED (r) = 0;
8162             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8163             if (type == error_mark_node)
8164               return error_mark_node;
8165             if (TREE_CODE (type) == FUNCTION_TYPE)
8166               {
8167                 /* It may seem that this case cannot occur, since:
8168
8169                      typedef void f();
8170                      void g() { f x; }
8171
8172                    declares a function, not a variable.  However:
8173       
8174                      typedef void f();
8175                      template <typename T> void g() { T t; }
8176                      template void g<f>();
8177
8178                    is an attempt to declare a variable with function
8179                    type.  */
8180                 error ("variable %qD has function type",
8181                        /* R is not yet sufficiently initialized, so we
8182                           just use its name.  */
8183                        DECL_NAME (r));
8184                 return error_mark_node;
8185               }
8186             type = complete_type (type);
8187             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
8188               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
8189             type = check_var_type (DECL_NAME (r), type);
8190
8191             if (DECL_HAS_VALUE_EXPR_P (t))
8192               {
8193                 tree ve = DECL_VALUE_EXPR (t);
8194                 ve = tsubst_expr (ve, args, complain, in_decl,
8195                                   /*constant_expression_p=*/false);
8196                 SET_DECL_VALUE_EXPR (r, ve);
8197               }
8198           }
8199         else if (DECL_SELF_REFERENCE_P (t))
8200           SET_DECL_SELF_REFERENCE_P (r);
8201         TREE_TYPE (r) = type;
8202         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8203         DECL_CONTEXT (r) = ctx;
8204         /* Clear out the mangled name and RTL for the instantiation.  */
8205         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8206         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8207           SET_DECL_RTL (r, NULL_RTX);
8208         /* The initializer must not be expanded until it is required;
8209            see [temp.inst].  */
8210         DECL_INITIAL (r) = NULL_TREE;
8211         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8212           SET_DECL_RTL (r, NULL_RTX);
8213         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
8214         if (TREE_CODE (r) == VAR_DECL)
8215           {
8216             /* Possibly limit visibility based on template args.  */
8217             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8218             if (DECL_VISIBILITY_SPECIFIED (t))
8219               {
8220                 DECL_VISIBILITY_SPECIFIED (r) = 0;
8221                 DECL_ATTRIBUTES (r)
8222                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8223               }
8224             determine_visibility (r);
8225           }
8226
8227         if (!local_p)
8228           {
8229             /* A static data member declaration is always marked
8230                external when it is declared in-class, even if an
8231                initializer is present.  We mimic the non-template
8232                processing here.  */
8233             DECL_EXTERNAL (r) = 1;
8234
8235             register_specialization (r, gen_tmpl, argvec, false);
8236             DECL_TEMPLATE_INFO (r) = tree_cons (tmpl, argvec, NULL_TREE);
8237             SET_DECL_IMPLICIT_INSTANTIATION (r);
8238           }
8239         else
8240           register_local_specialization (r, t);
8241
8242         TREE_CHAIN (r) = NULL_TREE;
8243
8244         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8245                                         args, complain, in_decl);
8246         layout_decl (r, 0);
8247       }
8248       break;
8249
8250     default:
8251       gcc_unreachable ();
8252     }
8253
8254   /* Restore the file and line information.  */
8255   input_location = saved_loc;
8256
8257   return r;
8258 }
8259
8260 /* Substitute into the ARG_TYPES of a function type.  */
8261
8262 static tree
8263 tsubst_arg_types (tree arg_types,
8264                   tree args,
8265                   tsubst_flags_t complain,
8266                   tree in_decl)
8267 {
8268   tree remaining_arg_types;
8269   tree type = NULL_TREE;
8270   int i = 1;
8271   tree expanded_args = NULL_TREE;
8272   tree default_arg;
8273
8274   if (!arg_types || arg_types == void_list_node)
8275     return arg_types;
8276
8277   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
8278                                           args, complain, in_decl);
8279   if (remaining_arg_types == error_mark_node)
8280     return error_mark_node;
8281
8282   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
8283     {
8284       /* For a pack expansion, perform substitution on the
8285          entire expression. Later on, we'll handle the arguments
8286          one-by-one.  */
8287       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
8288                                             args, complain, in_decl);
8289
8290       if (TREE_CODE (expanded_args) == TREE_VEC)
8291         /* So that we'll spin through the parameters, one by one.  */
8292         i = TREE_VEC_LENGTH (expanded_args);
8293       else
8294         {
8295           /* We only partially substituted into the parameter
8296              pack. Our type is TYPE_PACK_EXPANSION.  */
8297           type = expanded_args;
8298           expanded_args = NULL_TREE;
8299         }
8300     }
8301
8302   while (i > 0) {
8303     --i;
8304     
8305     if (expanded_args)
8306       type = TREE_VEC_ELT (expanded_args, i);
8307     else if (!type)
8308       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
8309
8310     if (type == error_mark_node)
8311       return error_mark_node;
8312     if (VOID_TYPE_P (type))
8313       {
8314         if (complain & tf_error)
8315           {
8316             error ("invalid parameter type %qT", type);
8317             if (in_decl)
8318               error ("in declaration %q+D", in_decl);
8319           }
8320         return error_mark_node;
8321     }
8322     
8323     /* Do array-to-pointer, function-to-pointer conversion, and ignore
8324        top-level qualifiers as required.  */
8325     type = TYPE_MAIN_VARIANT (type_decays_to (type));
8326
8327     /* We do not substitute into default arguments here.  The standard
8328        mandates that they be instantiated only when needed, which is
8329        done in build_over_call.  */
8330     default_arg = TREE_PURPOSE (arg_types);
8331
8332     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
8333       {
8334         /* We've instantiated a template before its default arguments
8335            have been parsed.  This can happen for a nested template
8336            class, and is not an error unless we require the default
8337            argument in a call of this function.  */
8338         remaining_arg_types = 
8339           tree_cons (default_arg, type, remaining_arg_types);
8340         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
8341                        remaining_arg_types);
8342       }
8343     else
8344       remaining_arg_types = 
8345         hash_tree_cons (default_arg, type, remaining_arg_types);
8346   }
8347         
8348   return remaining_arg_types;
8349 }
8350
8351 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
8352    *not* handle the exception-specification for FNTYPE, because the
8353    initial substitution of explicitly provided template parameters
8354    during argument deduction forbids substitution into the
8355    exception-specification:
8356
8357      [temp.deduct]
8358
8359      All references in the function type of the function template to  the
8360      corresponding template parameters are replaced by the specified tem-
8361      plate argument values.  If a substitution in a template parameter or
8362      in  the function type of the function template results in an invalid
8363      type, type deduction fails.  [Note: The equivalent  substitution  in
8364      exception specifications is done only when the function is instanti-
8365      ated, at which point a program is  ill-formed  if  the  substitution
8366      results in an invalid type.]  */
8367
8368 static tree
8369 tsubst_function_type (tree t,
8370                       tree args,
8371                       tsubst_flags_t complain,
8372                       tree in_decl)
8373 {
8374   tree return_type;
8375   tree arg_types;
8376   tree fntype;
8377
8378   /* The TYPE_CONTEXT is not used for function/method types.  */
8379   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
8380
8381   /* Substitute the return type.  */
8382   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8383   if (return_type == error_mark_node)
8384     return error_mark_node;
8385   /* The standard does not presently indicate that creation of a
8386      function type with an invalid return type is a deduction failure.
8387      However, that is clearly analogous to creating an array of "void"
8388      or a reference to a reference.  This is core issue #486.  */
8389   if (TREE_CODE (return_type) == ARRAY_TYPE
8390       || TREE_CODE (return_type) == FUNCTION_TYPE)
8391     {
8392       if (complain & tf_error)
8393         {
8394           if (TREE_CODE (return_type) == ARRAY_TYPE)
8395             error ("function returning an array");
8396           else
8397             error ("function returning a function");
8398         }
8399       return error_mark_node;
8400     }
8401
8402   /* Substitute the argument types.  */
8403   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
8404                                 complain, in_decl);
8405   if (arg_types == error_mark_node)
8406     return error_mark_node;
8407
8408   if (TYPE_QUALS (return_type) != TYPE_UNQUALIFIED
8409       && in_decl != NULL_TREE
8410       && !TREE_NO_WARNING (in_decl)
8411       && (SCALAR_TYPE_P (return_type) || VOID_TYPE_P (return_type)))
8412     warning (OPT_Wreturn_type,
8413             "type qualifiers ignored on function return type");
8414
8415   /* Construct a new type node and return it.  */
8416   if (TREE_CODE (t) == FUNCTION_TYPE)
8417     fntype = build_function_type (return_type, arg_types);
8418   else
8419     {
8420       tree r = TREE_TYPE (TREE_VALUE (arg_types));
8421       if (! IS_AGGR_TYPE (r))
8422         {
8423           /* [temp.deduct]
8424
8425              Type deduction may fail for any of the following
8426              reasons:
8427
8428              -- Attempting to create "pointer to member of T" when T
8429              is not a class type.  */
8430           if (complain & tf_error)
8431             error ("creating pointer to member function of non-class type %qT",
8432                       r);
8433           return error_mark_node;
8434         }
8435
8436       fntype = build_method_type_directly (r, return_type,
8437                                            TREE_CHAIN (arg_types));
8438     }
8439   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
8440   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
8441
8442   return fntype;
8443 }
8444
8445 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
8446    ARGS into that specification, and return the substituted
8447    specification.  If there is no specification, return NULL_TREE.  */
8448
8449 static tree
8450 tsubst_exception_specification (tree fntype,
8451                                 tree args,
8452                                 tsubst_flags_t complain,
8453                                 tree in_decl)
8454 {
8455   tree specs;
8456   tree new_specs;
8457
8458   specs = TYPE_RAISES_EXCEPTIONS (fntype);
8459   new_specs = NULL_TREE;
8460   if (specs)
8461     {
8462       if (! TREE_VALUE (specs))
8463         new_specs = specs;
8464       else
8465         while (specs)
8466           {
8467             tree spec;
8468             int i, len = 1;
8469             tree expanded_specs = NULL_TREE;
8470
8471             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
8472               {
8473                 /* Expand the pack expansion type.  */
8474                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
8475                                                        args, complain,
8476                                                        in_decl);
8477                 len = TREE_VEC_LENGTH (expanded_specs);
8478               }
8479
8480             for (i = 0; i < len; ++i)
8481               {
8482                 if (expanded_specs)
8483                   spec = TREE_VEC_ELT (expanded_specs, i);
8484                 else
8485                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
8486                 if (spec == error_mark_node)
8487                   return spec;
8488                 new_specs = add_exception_specifier (new_specs, spec, 
8489                                                      complain);
8490               }
8491
8492             specs = TREE_CHAIN (specs);
8493           }
8494     }
8495   return new_specs;
8496 }
8497
8498 /* Take the tree structure T and replace template parameters used
8499    therein with the argument vector ARGS.  IN_DECL is an associated
8500    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
8501    Issue error and warning messages under control of COMPLAIN.  Note
8502    that we must be relatively non-tolerant of extensions here, in
8503    order to preserve conformance; if we allow substitutions that
8504    should not be allowed, we may allow argument deductions that should
8505    not succeed, and therefore report ambiguous overload situations
8506    where there are none.  In theory, we could allow the substitution,
8507    but indicate that it should have failed, and allow our caller to
8508    make sure that the right thing happens, but we don't try to do this
8509    yet.
8510
8511    This function is used for dealing with types, decls and the like;
8512    for expressions, use tsubst_expr or tsubst_copy.  */
8513
8514 static tree
8515 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8516 {
8517   tree type, r;
8518
8519   if (t == NULL_TREE || t == error_mark_node
8520       || t == integer_type_node
8521       || t == void_type_node
8522       || t == char_type_node
8523       || t == unknown_type_node
8524       || TREE_CODE (t) == NAMESPACE_DECL)
8525     return t;
8526
8527   if (DECL_P (t))
8528     return tsubst_decl (t, args, complain);
8529
8530   if (TREE_CODE (t) == IDENTIFIER_NODE)
8531     type = IDENTIFIER_TYPE_VALUE (t);
8532   else
8533     type = TREE_TYPE (t);
8534
8535   gcc_assert (type != unknown_type_node);
8536
8537   if (type
8538       && TREE_CODE (t) != TYPENAME_TYPE
8539       && TREE_CODE (t) != IDENTIFIER_NODE
8540       && TREE_CODE (t) != FUNCTION_TYPE
8541       && TREE_CODE (t) != METHOD_TYPE)
8542     type = tsubst (type, args, complain, in_decl);
8543   if (type == error_mark_node)
8544     return error_mark_node;
8545
8546   switch (TREE_CODE (t))
8547     {
8548     case RECORD_TYPE:
8549     case UNION_TYPE:
8550     case ENUMERAL_TYPE:
8551       return tsubst_aggr_type (t, args, complain, in_decl,
8552                                /*entering_scope=*/0);
8553
8554     case ERROR_MARK:
8555     case IDENTIFIER_NODE:
8556     case VOID_TYPE:
8557     case REAL_TYPE:
8558     case COMPLEX_TYPE:
8559     case VECTOR_TYPE:
8560     case BOOLEAN_TYPE:
8561     case INTEGER_CST:
8562     case REAL_CST:
8563     case STRING_CST:
8564       return t;
8565
8566     case INTEGER_TYPE:
8567       if (t == integer_type_node)
8568         return t;
8569
8570       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
8571           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
8572         return t;
8573
8574       {
8575         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
8576
8577         max = tsubst_expr (omax, args, complain, in_decl,
8578                            /*integral_constant_expression_p=*/false);
8579         max = fold_decl_constant_value (max);
8580
8581         if (TREE_CODE (max) != INTEGER_CST 
8582             && TREE_CODE (max) != TEMPLATE_PARM_INDEX
8583             && !at_function_scope_p ())
8584           {
8585             if (complain & tf_error)
8586               error ("array bound is not an integer constant");
8587             return error_mark_node;
8588           }
8589
8590         /* [temp.deduct]
8591
8592            Type deduction may fail for any of the following
8593            reasons:
8594
8595              Attempting to create an array with a size that is
8596              zero or negative.  */
8597         if (integer_zerop (max) && !(complain & tf_error))
8598           /* We must fail if performing argument deduction (as
8599              indicated by the state of complain), so that
8600              another substitution can be found.  */
8601           return error_mark_node;
8602         else if (TREE_CODE (max) == INTEGER_CST
8603                  && INT_CST_LT (max, integer_zero_node))
8604           {
8605             if (complain & tf_error)
8606               error ("creating array with negative size (%qE)", max);
8607
8608             return error_mark_node;
8609           }
8610
8611         return compute_array_index_type (NULL_TREE, max);
8612       }
8613
8614     case TEMPLATE_TYPE_PARM:
8615     case TEMPLATE_TEMPLATE_PARM:
8616     case BOUND_TEMPLATE_TEMPLATE_PARM:
8617     case TEMPLATE_PARM_INDEX:
8618       {
8619         int idx;
8620         int level;
8621         int levels;
8622         tree arg = NULL_TREE;
8623
8624         r = NULL_TREE;
8625
8626         gcc_assert (TREE_VEC_LENGTH (args) > 0);
8627         if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
8628             || TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
8629             || TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
8630           {
8631             idx = TEMPLATE_TYPE_IDX (t);
8632             level = TEMPLATE_TYPE_LEVEL (t);
8633           }
8634         else
8635           {
8636             idx = TEMPLATE_PARM_IDX (t);
8637             level = TEMPLATE_PARM_LEVEL (t);
8638           }
8639
8640         levels = TMPL_ARGS_DEPTH (args);
8641         if (level <= levels)
8642           {
8643             arg = TMPL_ARG (args, level, idx);
8644
8645             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
8646               /* See through ARGUMENT_PACK_SELECT arguments. */
8647               arg = ARGUMENT_PACK_SELECT_ARG (arg);
8648           }
8649
8650         if (arg == error_mark_node)
8651           return error_mark_node;
8652         else if (arg != NULL_TREE)
8653           {
8654             if (ARGUMENT_PACK_P (arg))
8655               /* If ARG is an argument pack, we don't actually want to
8656                  perform a substitution here, because substitutions
8657                  for argument packs are only done
8658                  element-by-element. We can get to this point when
8659                  substituting the type of a non-type template
8660                  parameter pack, when that type actually contains
8661                  template parameter packs from an outer template, e.g.,
8662
8663                  template<typename... Types> struct A {
8664                    template<Types... Values> struct B { };
8665                  };  */
8666               return t;
8667
8668             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
8669               {
8670                 int quals;
8671                 gcc_assert (TYPE_P (arg));
8672
8673                 /* cv-quals from the template are discarded when
8674                    substituting in a function or reference type.  */
8675                 if (TREE_CODE (arg) == FUNCTION_TYPE
8676                     || TREE_CODE (arg) == METHOD_TYPE
8677                     || TREE_CODE (arg) == REFERENCE_TYPE)
8678                   quals = cp_type_quals (arg);
8679                 else
8680                   quals = cp_type_quals (arg) | cp_type_quals (t);
8681                   
8682                 return cp_build_qualified_type_real
8683                   (arg, quals, complain | tf_ignore_bad_quals);
8684               }
8685             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
8686               {
8687                 /* We are processing a type constructed from a
8688                    template template parameter.  */
8689                 tree argvec = tsubst (TYPE_TI_ARGS (t),
8690                                       args, complain, in_decl);
8691                 if (argvec == error_mark_node)
8692                   return error_mark_node;
8693
8694                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
8695                    are resolving nested-types in the signature of a
8696                    member function templates.  Otherwise ARG is a
8697                    TEMPLATE_DECL and is the real template to be
8698                    instantiated.  */
8699                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
8700                   arg = TYPE_NAME (arg);
8701
8702                 r = lookup_template_class (arg,
8703                                            argvec, in_decl,
8704                                            DECL_CONTEXT (arg),
8705                                             /*entering_scope=*/0,
8706                                            complain);
8707                 return cp_build_qualified_type_real
8708                   (r, TYPE_QUALS (t), complain);
8709               }
8710             else
8711               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
8712               return arg;
8713           }
8714
8715         if (level == 1)
8716           /* This can happen during the attempted tsubst'ing in
8717              unify.  This means that we don't yet have any information
8718              about the template parameter in question.  */
8719           return t;
8720
8721         /* If we get here, we must have been looking at a parm for a
8722            more deeply nested template.  Make a new version of this
8723            template parameter, but with a lower level.  */
8724         switch (TREE_CODE (t))
8725           {
8726           case TEMPLATE_TYPE_PARM:
8727           case TEMPLATE_TEMPLATE_PARM:
8728           case BOUND_TEMPLATE_TEMPLATE_PARM:
8729             if (cp_type_quals (t))
8730               {
8731                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
8732                 r = cp_build_qualified_type_real
8733                   (r, cp_type_quals (t),
8734                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
8735                                ? tf_ignore_bad_quals : 0));
8736               }
8737             else
8738               {
8739                 r = copy_type (t);
8740                 TEMPLATE_TYPE_PARM_INDEX (r)
8741                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
8742                                                 r, levels);
8743                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
8744                 TYPE_MAIN_VARIANT (r) = r;
8745                 TYPE_POINTER_TO (r) = NULL_TREE;
8746                 TYPE_REFERENCE_TO (r) = NULL_TREE;
8747
8748                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
8749                   /* We have reduced the level of the template
8750                      template parameter, but not the levels of its
8751                      template parameters, so canonical_type_parameter
8752                      will not be able to find the canonical template
8753                      template parameter for this level. Thus, we
8754                      require structural equality checking to compare
8755                      TEMPLATE_TEMPLATE_PARMs. */
8756                   SET_TYPE_STRUCTURAL_EQUALITY (r);
8757                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
8758                   SET_TYPE_STRUCTURAL_EQUALITY (r);
8759                 else
8760                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
8761
8762                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
8763                   {
8764                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
8765                                           complain, in_decl);
8766                     if (argvec == error_mark_node)
8767                       return error_mark_node;
8768
8769                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
8770                       = tree_cons (TYPE_TI_TEMPLATE (t), argvec, NULL_TREE);
8771                   }
8772               }
8773             break;
8774
8775           case TEMPLATE_PARM_INDEX:
8776             r = reduce_template_parm_level (t, type, levels);
8777             break;
8778
8779           default:
8780             gcc_unreachable ();
8781           }
8782
8783         return r;
8784       }
8785
8786     case TREE_LIST:
8787       {
8788         tree purpose, value, chain;
8789
8790         if (t == void_list_node)
8791           return t;
8792
8793         purpose = TREE_PURPOSE (t);
8794         if (purpose)
8795           {
8796             purpose = tsubst (purpose, args, complain, in_decl);
8797             if (purpose == error_mark_node)
8798               return error_mark_node;
8799           }
8800         value = TREE_VALUE (t);
8801         if (value)
8802           {
8803             value = tsubst (value, args, complain, in_decl);
8804             if (value == error_mark_node)
8805               return error_mark_node;
8806           }
8807         chain = TREE_CHAIN (t);
8808         if (chain && chain != void_type_node)
8809           {
8810             chain = tsubst (chain, args, complain, in_decl);
8811             if (chain == error_mark_node)
8812               return error_mark_node;
8813           }
8814         if (purpose == TREE_PURPOSE (t)
8815             && value == TREE_VALUE (t)
8816             && chain == TREE_CHAIN (t))
8817           return t;
8818         return hash_tree_cons (purpose, value, chain);
8819       }
8820
8821     case TREE_BINFO:
8822       /* We should never be tsubsting a binfo.  */
8823       gcc_unreachable ();
8824
8825     case TREE_VEC:
8826       /* A vector of template arguments.  */
8827       gcc_assert (!type);
8828       return tsubst_template_args (t, args, complain, in_decl);
8829
8830     case POINTER_TYPE:
8831     case REFERENCE_TYPE:
8832       {
8833         enum tree_code code;
8834
8835         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
8836           return t;
8837
8838         code = TREE_CODE (t);
8839
8840
8841         /* [temp.deduct]
8842
8843            Type deduction may fail for any of the following
8844            reasons:
8845
8846            -- Attempting to create a pointer to reference type.
8847            -- Attempting to create a reference to a reference type or
8848               a reference to void.
8849
8850           Core issue 106 says that creating a reference to a reference
8851           during instantiation is no longer a cause for failure. We
8852           only enforce this check in strict C++98 mode.  */
8853         if ((TREE_CODE (type) == REFERENCE_TYPE
8854              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
8855             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
8856           {
8857             static location_t last_loc;
8858
8859             /* We keep track of the last time we issued this error
8860                message to avoid spewing a ton of messages during a
8861                single bad template instantiation.  */
8862             if (complain & tf_error
8863 #ifdef USE_MAPPED_LOCATION
8864                 && last_loc != input_location
8865 #else
8866                 && (last_loc.line != input_line
8867                     || last_loc.file != input_filename)
8868 #endif
8869                   )
8870               {
8871                 if (TREE_CODE (type) == VOID_TYPE)
8872                   error ("forming reference to void");
8873                 else
8874                   error ("forming %s to reference type %qT",
8875                          (code == POINTER_TYPE) ? "pointer" : "reference",
8876                          type);
8877                 last_loc = input_location;
8878               }
8879
8880             return error_mark_node;
8881           }
8882         else if (code == POINTER_TYPE)
8883           {
8884             r = build_pointer_type (type);
8885             if (TREE_CODE (type) == METHOD_TYPE)
8886               r = build_ptrmemfunc_type (r);
8887           }
8888         else if (TREE_CODE (type) == REFERENCE_TYPE)
8889           /* In C++0x, during template argument substitution, when there is an
8890              attempt to create a reference to a reference type, reference
8891              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
8892
8893              "If a template-argument for a template-parameter T names a type
8894              that is a reference to a type A, an attempt to create the type
8895              'lvalue reference to cv T' creates the type 'lvalue reference to
8896              A,' while an attempt to create the type type rvalue reference to
8897              cv T' creates the type T"
8898           */
8899           r = cp_build_reference_type
8900               (TREE_TYPE (type),
8901                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
8902         else
8903           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
8904         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
8905
8906         if (r != error_mark_node)
8907           /* Will this ever be needed for TYPE_..._TO values?  */
8908           layout_type (r);
8909
8910         return r;
8911       }
8912     case OFFSET_TYPE:
8913       {
8914         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
8915         if (r == error_mark_node || !IS_AGGR_TYPE (r))
8916           {
8917             /* [temp.deduct]
8918
8919                Type deduction may fail for any of the following
8920                reasons:
8921
8922                -- Attempting to create "pointer to member of T" when T
8923                   is not a class type.  */
8924             if (complain & tf_error)
8925               error ("creating pointer to member of non-class type %qT", r);
8926             return error_mark_node;
8927           }
8928         if (TREE_CODE (type) == REFERENCE_TYPE)
8929           {
8930             if (complain & tf_error)
8931               error ("creating pointer to member reference type %qT", type);
8932             return error_mark_node;
8933           }
8934         if (TREE_CODE (type) == VOID_TYPE)
8935           {
8936             if (complain & tf_error)
8937               error ("creating pointer to member of type void");
8938             return error_mark_node;
8939           }
8940         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
8941         if (TREE_CODE (type) == FUNCTION_TYPE)
8942           {
8943             /* The type of the implicit object parameter gets its
8944                cv-qualifiers from the FUNCTION_TYPE. */
8945             tree method_type;
8946             tree this_type = cp_build_qualified_type (TYPE_MAIN_VARIANT (r),
8947                                                       cp_type_quals (type));
8948             tree memptr;
8949             method_type = build_method_type_directly (this_type,
8950                                                       TREE_TYPE (type),
8951                                                       TYPE_ARG_TYPES (type));
8952             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
8953             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
8954                                                  complain);
8955           }
8956         else
8957           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
8958                                                TYPE_QUALS (t),
8959                                                complain);
8960       }
8961     case FUNCTION_TYPE:
8962     case METHOD_TYPE:
8963       {
8964         tree fntype;
8965         tree specs;
8966         fntype = tsubst_function_type (t, args, complain, in_decl);
8967         if (fntype == error_mark_node)
8968           return error_mark_node;
8969
8970         /* Substitute the exception specification.  */
8971         specs = tsubst_exception_specification (t, args, complain,
8972                                                 in_decl);
8973         if (specs == error_mark_node)
8974           return error_mark_node;
8975         if (specs)
8976           fntype = build_exception_variant (fntype, specs);
8977         return fntype;
8978       }
8979     case ARRAY_TYPE:
8980       {
8981         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
8982         if (domain == error_mark_node)
8983           return error_mark_node;
8984
8985         /* As an optimization, we avoid regenerating the array type if
8986            it will obviously be the same as T.  */
8987         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
8988           return t;
8989
8990         /* These checks should match the ones in grokdeclarator.
8991
8992            [temp.deduct]
8993
8994            The deduction may fail for any of the following reasons:
8995
8996            -- Attempting to create an array with an element type that
8997               is void, a function type, or a reference type, or [DR337]
8998               an abstract class type.  */
8999         if (TREE_CODE (type) == VOID_TYPE
9000             || TREE_CODE (type) == FUNCTION_TYPE
9001             || TREE_CODE (type) == REFERENCE_TYPE)
9002           {
9003             if (complain & tf_error)
9004               error ("creating array of %qT", type);
9005             return error_mark_node;
9006           }
9007         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
9008           {
9009             if (complain & tf_error)
9010               error ("creating array of %qT, which is an abstract class type",
9011                      type);
9012             return error_mark_node;
9013           }
9014
9015         r = build_cplus_array_type (type, domain);
9016         return r;
9017       }
9018
9019     case PLUS_EXPR:
9020     case MINUS_EXPR:
9021       {
9022         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9023         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9024
9025         if (e1 == error_mark_node || e2 == error_mark_node)
9026           return error_mark_node;
9027
9028         return fold_build2 (TREE_CODE (t), TREE_TYPE (t), e1, e2);
9029       }
9030
9031     case NEGATE_EXPR:
9032     case NOP_EXPR:
9033       {
9034         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9035         if (e == error_mark_node)
9036           return error_mark_node;
9037
9038         return fold_build1 (TREE_CODE (t), TREE_TYPE (t), e);
9039       }
9040
9041     case TYPENAME_TYPE:
9042       {
9043         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9044                                      in_decl, /*entering_scope=*/1);
9045         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
9046                               complain, in_decl);
9047
9048         if (ctx == error_mark_node || f == error_mark_node)
9049           return error_mark_node;
9050
9051         if (!IS_AGGR_TYPE (ctx))
9052           {
9053             if (complain & tf_error)
9054               error ("%qT is not a class, struct, or union type", ctx);
9055             return error_mark_node;
9056           }
9057         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
9058           {
9059             /* Normally, make_typename_type does not require that the CTX
9060                have complete type in order to allow things like:
9061
9062                  template <class T> struct S { typename S<T>::X Y; };
9063
9064                But, such constructs have already been resolved by this
9065                point, so here CTX really should have complete type, unless
9066                it's a partial instantiation.  */
9067             ctx = complete_type (ctx);
9068             if (!COMPLETE_TYPE_P (ctx))
9069               {
9070                 if (complain & tf_error)
9071                   cxx_incomplete_type_error (NULL_TREE, ctx);
9072                 return error_mark_node;
9073               }
9074           }
9075
9076         f = make_typename_type (ctx, f, typename_type,
9077                                 (complain & tf_error) | tf_keep_type_decl);
9078         if (f == error_mark_node)
9079           return f;
9080         if (TREE_CODE (f) == TYPE_DECL)
9081           {
9082             complain |= tf_ignore_bad_quals;
9083             f = TREE_TYPE (f);
9084           }
9085
9086         if (TREE_CODE (f) != TYPENAME_TYPE)
9087           {
9088             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
9089               error ("%qT resolves to %qT, which is not an enumeration type",
9090                      t, f);
9091             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
9092               error ("%qT resolves to %qT, which is is not a class type",
9093                      t, f);
9094           }
9095
9096         return cp_build_qualified_type_real
9097           (f, cp_type_quals (f) | cp_type_quals (t), complain);
9098       }
9099
9100     case UNBOUND_CLASS_TEMPLATE:
9101       {
9102         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9103                                      in_decl, /*entering_scope=*/1);
9104         tree name = TYPE_IDENTIFIER (t);
9105         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
9106
9107         if (ctx == error_mark_node || name == error_mark_node)
9108           return error_mark_node;
9109
9110         if (parm_list)
9111           parm_list = tsubst_template_parms (parm_list, args, complain);
9112         return make_unbound_class_template (ctx, name, parm_list, complain);
9113       }
9114
9115     case INDIRECT_REF:
9116     case ADDR_EXPR:
9117     case CALL_EXPR:
9118       gcc_unreachable ();
9119
9120     case ARRAY_REF:
9121       {
9122         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9123         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
9124                                /*integral_constant_expression_p=*/false);
9125         if (e1 == error_mark_node || e2 == error_mark_node)
9126           return error_mark_node;
9127
9128         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
9129       }
9130
9131     case SCOPE_REF:
9132       {
9133         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9134         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9135         if (e1 == error_mark_node || e2 == error_mark_node)
9136           return error_mark_node;
9137
9138         return build_qualified_name (/*type=*/NULL_TREE,
9139                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
9140       }
9141
9142     case TYPEOF_TYPE:
9143       {
9144         tree type;
9145
9146         type = finish_typeof (tsubst_expr 
9147                               (TYPEOF_TYPE_EXPR (t), args,
9148                                complain, in_decl,
9149                                /*integral_constant_expression_p=*/false));
9150         return cp_build_qualified_type_real (type,
9151                                              cp_type_quals (t)
9152                                              | cp_type_quals (type),
9153                                              complain);
9154       }
9155
9156     case DECLTYPE_TYPE:
9157       {
9158         tree type;
9159
9160         type = 
9161           finish_decltype_type (tsubst_expr 
9162                                 (DECLTYPE_TYPE_EXPR (t), args,
9163                                  complain, in_decl,
9164                                  /*integral_constant_expression_p=*/false),
9165                                 DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
9166         return cp_build_qualified_type_real (type,
9167                                              cp_type_quals (t)
9168                                              | cp_type_quals (type),
9169                                              complain);
9170       }
9171
9172     case TYPE_ARGUMENT_PACK:
9173     case NONTYPE_ARGUMENT_PACK:
9174       {
9175         tree r = make_node (TREE_CODE (t));
9176         tree packed_out = 
9177           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
9178                                 args,
9179                                 complain,
9180                                 in_decl);
9181         SET_ARGUMENT_PACK_ARGS (r, packed_out);
9182
9183         /* For template nontype argument packs, also substitute into
9184            the type.  */
9185         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
9186           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
9187
9188         return r;
9189       }
9190       break;
9191
9192     default:
9193       sorry ("use of %qs in template",
9194              tree_code_name [(int) TREE_CODE (t)]);
9195       return error_mark_node;
9196     }
9197 }
9198
9199 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
9200    type of the expression on the left-hand side of the "." or "->"
9201    operator.  */
9202
9203 static tree
9204 tsubst_baselink (tree baselink, tree object_type,
9205                  tree args, tsubst_flags_t complain, tree in_decl)
9206 {
9207     tree name;
9208     tree qualifying_scope;
9209     tree fns;
9210     tree optype;
9211     tree template_args = 0;
9212     bool template_id_p = false;
9213
9214     /* A baselink indicates a function from a base class.  Both the
9215        BASELINK_ACCESS_BINFO and the base class referenced may
9216        indicate bases of the template class, rather than the
9217        instantiated class.  In addition, lookups that were not
9218        ambiguous before may be ambiguous now.  Therefore, we perform
9219        the lookup again.  */
9220     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
9221     qualifying_scope = tsubst (qualifying_scope, args,
9222                                complain, in_decl);
9223     fns = BASELINK_FUNCTIONS (baselink);
9224     optype = BASELINK_OPTYPE (baselink);
9225     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
9226       {
9227         template_id_p = true;
9228         template_args = TREE_OPERAND (fns, 1);
9229         fns = TREE_OPERAND (fns, 0);
9230         if (template_args)
9231           template_args = tsubst_template_args (template_args, args,
9232                                                 complain, in_decl);
9233       }
9234     name = DECL_NAME (get_first_fn (fns));
9235     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
9236
9237     /* If lookup found a single function, mark it as used at this
9238        point.  (If it lookup found multiple functions the one selected
9239        later by overload resolution will be marked as used at that
9240        point.)  */
9241     if (BASELINK_P (baselink))
9242       fns = BASELINK_FUNCTIONS (baselink);
9243     if (!template_id_p && !really_overloaded_fn (fns))
9244       mark_used (OVL_CURRENT (fns));
9245
9246     /* Add back the template arguments, if present.  */
9247     if (BASELINK_P (baselink) && template_id_p)
9248       BASELINK_FUNCTIONS (baselink)
9249         = build_nt (TEMPLATE_ID_EXPR,
9250                     BASELINK_FUNCTIONS (baselink),
9251                     template_args);
9252     /* Update the conversion operator type.  */
9253     BASELINK_OPTYPE (baselink) 
9254       = tsubst (optype, args, complain, in_decl);
9255
9256     if (!object_type)
9257       object_type = current_class_type;
9258     return adjust_result_of_qualified_name_lookup (baselink,
9259                                                    qualifying_scope,
9260                                                    object_type);
9261 }
9262
9263 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
9264    true if the qualified-id will be a postfix-expression in-and-of
9265    itself; false if more of the postfix-expression follows the
9266    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
9267    of "&".  */
9268
9269 static tree
9270 tsubst_qualified_id (tree qualified_id, tree args,
9271                      tsubst_flags_t complain, tree in_decl,
9272                      bool done, bool address_p)
9273 {
9274   tree expr;
9275   tree scope;
9276   tree name;
9277   bool is_template;
9278   tree template_args;
9279
9280   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
9281
9282   /* Figure out what name to look up.  */
9283   name = TREE_OPERAND (qualified_id, 1);
9284   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
9285     {
9286       is_template = true;
9287       template_args = TREE_OPERAND (name, 1);
9288       if (template_args)
9289         template_args = tsubst_template_args (template_args, args,
9290                                               complain, in_decl);
9291       name = TREE_OPERAND (name, 0);
9292     }
9293   else
9294     {
9295       is_template = false;
9296       template_args = NULL_TREE;
9297     }
9298
9299   /* Substitute into the qualifying scope.  When there are no ARGS, we
9300      are just trying to simplify a non-dependent expression.  In that
9301      case the qualifying scope may be dependent, and, in any case,
9302      substituting will not help.  */
9303   scope = TREE_OPERAND (qualified_id, 0);
9304   if (args)
9305     {
9306       scope = tsubst (scope, args, complain, in_decl);
9307       expr = tsubst_copy (name, args, complain, in_decl);
9308     }
9309   else
9310     expr = name;
9311
9312   if (dependent_type_p (scope))
9313     return build_qualified_name (/*type=*/NULL_TREE,
9314                                  scope, expr,
9315                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
9316
9317   if (!BASELINK_P (name) && !DECL_P (expr))
9318     {
9319       if (TREE_CODE (expr) == BIT_NOT_EXPR)
9320         /* If this were actually a destructor call, it would have been
9321            parsed as such by the parser.  */
9322         expr = error_mark_node;
9323       else
9324         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
9325       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
9326                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
9327         {
9328           if (complain & tf_error)
9329             {
9330               error ("dependent-name %qE is parsed as a non-type, but "
9331                      "instantiation yields a type", qualified_id);
9332               inform ("say %<typename %E%> if a type is meant", qualified_id);
9333             }
9334           return error_mark_node;
9335         }
9336     }
9337
9338   if (DECL_P (expr))
9339     {
9340       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
9341                                            scope);
9342       /* Remember that there was a reference to this entity.  */
9343       mark_used (expr);
9344     }
9345
9346   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
9347     {
9348       if (complain & tf_error)
9349         qualified_name_lookup_error (scope,
9350                                      TREE_OPERAND (qualified_id, 1),
9351                                      expr);
9352       return error_mark_node;
9353     }
9354
9355   if (is_template)
9356     expr = lookup_template_function (expr, template_args);
9357
9358   if (expr == error_mark_node && complain & tf_error)
9359     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
9360                                  expr);
9361   else if (TYPE_P (scope))
9362     {
9363       expr = (adjust_result_of_qualified_name_lookup
9364               (expr, scope, current_class_type));
9365       expr = (finish_qualified_id_expr
9366               (scope, expr, done, address_p,
9367                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
9368                /*template_arg_p=*/false));
9369     }
9370
9371   /* Expressions do not generally have reference type.  */
9372   if (TREE_CODE (expr) != SCOPE_REF
9373       /* However, if we're about to form a pointer-to-member, we just
9374          want the referenced member referenced.  */
9375       && TREE_CODE (expr) != OFFSET_REF)
9376     expr = convert_from_reference (expr);
9377
9378   return expr;
9379 }
9380
9381 /* Like tsubst, but deals with expressions.  This function just replaces
9382    template parms; to finish processing the resultant expression, use
9383    tsubst_expr.  */
9384
9385 static tree
9386 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9387 {
9388   enum tree_code code;
9389   tree r;
9390
9391   if (t == NULL_TREE || t == error_mark_node)
9392     return t;
9393
9394   code = TREE_CODE (t);
9395
9396   switch (code)
9397     {
9398     case PARM_DECL:
9399       r = retrieve_local_specialization (t);
9400       gcc_assert (r != NULL);
9401       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
9402         r = ARGUMENT_PACK_SELECT_ARG (r);
9403       mark_used (r);
9404       return r;
9405
9406     case CONST_DECL:
9407       {
9408         tree enum_type;
9409         tree v;
9410
9411         if (DECL_TEMPLATE_PARM_P (t))
9412           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
9413         /* There is no need to substitute into namespace-scope
9414            enumerators.  */
9415         if (DECL_NAMESPACE_SCOPE_P (t))
9416           return t;
9417         /* If ARGS is NULL, then T is known to be non-dependent.  */
9418         if (args == NULL_TREE)
9419           return integral_constant_value (t);
9420
9421         /* Unfortunately, we cannot just call lookup_name here.
9422            Consider:
9423
9424              template <int I> int f() {
9425              enum E { a = I };
9426              struct S { void g() { E e = a; } };
9427              };
9428
9429            When we instantiate f<7>::S::g(), say, lookup_name is not
9430            clever enough to find f<7>::a.  */
9431         enum_type
9432           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
9433                               /*entering_scope=*/0);
9434
9435         for (v = TYPE_VALUES (enum_type);
9436              v != NULL_TREE;
9437              v = TREE_CHAIN (v))
9438           if (TREE_PURPOSE (v) == DECL_NAME (t))
9439             return TREE_VALUE (v);
9440
9441           /* We didn't find the name.  That should never happen; if
9442              name-lookup found it during preliminary parsing, we
9443              should find it again here during instantiation.  */
9444         gcc_unreachable ();
9445       }
9446       return t;
9447
9448     case FIELD_DECL:
9449       if (DECL_CONTEXT (t))
9450         {
9451           tree ctx;
9452
9453           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
9454                                   /*entering_scope=*/1);
9455           if (ctx != DECL_CONTEXT (t))
9456             {
9457               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
9458               if (!r)
9459                 {
9460                   if (complain & tf_error)
9461                     error ("using invalid field %qD", t);
9462                   return error_mark_node;
9463                 }
9464               return r;
9465             }
9466         }
9467
9468       return t;
9469
9470     case VAR_DECL:
9471     case FUNCTION_DECL:
9472       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
9473           || local_variable_p (t))
9474         t = tsubst (t, args, complain, in_decl);
9475       mark_used (t);
9476       return t;
9477
9478     case BASELINK:
9479       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
9480
9481     case TEMPLATE_DECL:
9482       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9483         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
9484                        args, complain, in_decl);
9485       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
9486         return tsubst (t, args, complain, in_decl);
9487       else if (DECL_CLASS_SCOPE_P (t)
9488                && uses_template_parms (DECL_CONTEXT (t)))
9489         {
9490           /* Template template argument like the following example need
9491              special treatment:
9492
9493                template <template <class> class TT> struct C {};
9494                template <class T> struct D {
9495                  template <class U> struct E {};
9496                  C<E> c;                                // #1
9497                };
9498                D<int> d;                                // #2
9499
9500              We are processing the template argument `E' in #1 for
9501              the template instantiation #2.  Originally, `E' is a
9502              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
9503              have to substitute this with one having context `D<int>'.  */
9504
9505           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
9506           return lookup_field (context, DECL_NAME(t), 0, false);
9507         }
9508       else
9509         /* Ordinary template template argument.  */
9510         return t;
9511
9512     case CAST_EXPR:
9513     case REINTERPRET_CAST_EXPR:
9514     case CONST_CAST_EXPR:
9515     case STATIC_CAST_EXPR:
9516     case DYNAMIC_CAST_EXPR:
9517     case NOP_EXPR:
9518       return build1
9519         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
9520          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
9521
9522     case SIZEOF_EXPR:
9523       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
9524         {
9525           /* We only want to compute the number of arguments.  */
9526           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
9527                                                 complain, in_decl);
9528           return build_int_cst (size_type_node, TREE_VEC_LENGTH (expanded));
9529         }
9530       /* Fall through */
9531
9532     case INDIRECT_REF:
9533     case NEGATE_EXPR:
9534     case TRUTH_NOT_EXPR:
9535     case BIT_NOT_EXPR:
9536     case ADDR_EXPR:
9537     case UNARY_PLUS_EXPR:      /* Unary + */
9538     case ALIGNOF_EXPR:
9539     case ARROW_EXPR:
9540     case THROW_EXPR:
9541     case TYPEID_EXPR:
9542     case REALPART_EXPR:
9543     case IMAGPART_EXPR:
9544       return build1
9545         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
9546          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
9547
9548     case COMPONENT_REF:
9549       {
9550         tree object;
9551         tree name;
9552
9553         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
9554         name = TREE_OPERAND (t, 1);
9555         if (TREE_CODE (name) == BIT_NOT_EXPR)
9556           {
9557             name = tsubst_copy (TREE_OPERAND (name, 0), args,
9558                                 complain, in_decl);
9559             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
9560           }
9561         else if (TREE_CODE (name) == SCOPE_REF
9562                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
9563           {
9564             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
9565                                      complain, in_decl);
9566             name = TREE_OPERAND (name, 1);
9567             name = tsubst_copy (TREE_OPERAND (name, 0), args,
9568                                 complain, in_decl);
9569             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
9570             name = build_qualified_name (/*type=*/NULL_TREE,
9571                                          base, name,
9572                                          /*template_p=*/false);
9573           }
9574         else if (TREE_CODE (name) == BASELINK)
9575           name = tsubst_baselink (name,
9576                                   non_reference (TREE_TYPE (object)),
9577                                   args, complain,
9578                                   in_decl);
9579         else
9580           name = tsubst_copy (name, args, complain, in_decl);
9581         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
9582       }
9583
9584     case PLUS_EXPR:
9585     case MINUS_EXPR:
9586     case MULT_EXPR:
9587     case TRUNC_DIV_EXPR:
9588     case CEIL_DIV_EXPR:
9589     case FLOOR_DIV_EXPR:
9590     case ROUND_DIV_EXPR:
9591     case EXACT_DIV_EXPR:
9592     case BIT_AND_EXPR:
9593     case BIT_IOR_EXPR:
9594     case BIT_XOR_EXPR:
9595     case TRUNC_MOD_EXPR:
9596     case FLOOR_MOD_EXPR:
9597     case TRUTH_ANDIF_EXPR:
9598     case TRUTH_ORIF_EXPR:
9599     case TRUTH_AND_EXPR:
9600     case TRUTH_OR_EXPR:
9601     case RSHIFT_EXPR:
9602     case LSHIFT_EXPR:
9603     case RROTATE_EXPR:
9604     case LROTATE_EXPR:
9605     case EQ_EXPR:
9606     case NE_EXPR:
9607     case MAX_EXPR:
9608     case MIN_EXPR:
9609     case LE_EXPR:
9610     case GE_EXPR:
9611     case LT_EXPR:
9612     case GT_EXPR:
9613     case COMPOUND_EXPR:
9614     case DOTSTAR_EXPR:
9615     case MEMBER_REF:
9616     case PREDECREMENT_EXPR:
9617     case PREINCREMENT_EXPR:
9618     case POSTDECREMENT_EXPR:
9619     case POSTINCREMENT_EXPR:
9620       return build_nt
9621         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
9622          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
9623
9624     case SCOPE_REF:
9625       return build_qualified_name (/*type=*/NULL_TREE,
9626                                    tsubst_copy (TREE_OPERAND (t, 0),
9627                                                 args, complain, in_decl),
9628                                    tsubst_copy (TREE_OPERAND (t, 1),
9629                                                 args, complain, in_decl),
9630                                    QUALIFIED_NAME_IS_TEMPLATE (t));
9631
9632     case ARRAY_REF:
9633       return build_nt
9634         (ARRAY_REF,
9635          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
9636          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
9637          NULL_TREE, NULL_TREE);
9638
9639     case CALL_EXPR:
9640       {
9641         int n = VL_EXP_OPERAND_LENGTH (t);
9642         tree result = build_vl_exp (CALL_EXPR, n);
9643         int i;
9644         for (i = 0; i < n; i++)
9645           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
9646                                              complain, in_decl);
9647         return result;
9648       }
9649
9650     case COND_EXPR:
9651     case MODOP_EXPR:
9652     case PSEUDO_DTOR_EXPR:
9653       {
9654         r = build_nt
9655           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
9656            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
9657            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
9658         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
9659         return r;
9660       }
9661
9662     case NEW_EXPR:
9663       {
9664         r = build_nt
9665         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
9666          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
9667          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
9668         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
9669         return r;
9670       }
9671
9672     case DELETE_EXPR:
9673       {
9674         r = build_nt
9675         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
9676          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
9677         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
9678         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
9679         return r;
9680       }
9681
9682     case TEMPLATE_ID_EXPR:
9683       {
9684         /* Substituted template arguments */
9685         tree fn = TREE_OPERAND (t, 0);
9686         tree targs = TREE_OPERAND (t, 1);
9687
9688         fn = tsubst_copy (fn, args, complain, in_decl);
9689         if (targs)
9690           targs = tsubst_template_args (targs, args, complain, in_decl);
9691
9692         return lookup_template_function (fn, targs);
9693       }
9694
9695     case TREE_LIST:
9696       {
9697         tree purpose, value, chain;
9698
9699         if (t == void_list_node)
9700           return t;
9701
9702         purpose = TREE_PURPOSE (t);
9703         if (purpose)
9704           purpose = tsubst_copy (purpose, args, complain, in_decl);
9705         value = TREE_VALUE (t);
9706         if (value)
9707           value = tsubst_copy (value, args, complain, in_decl);
9708         chain = TREE_CHAIN (t);
9709         if (chain && chain != void_type_node)
9710           chain = tsubst_copy (chain, args, complain, in_decl);
9711         if (purpose == TREE_PURPOSE (t)
9712             && value == TREE_VALUE (t)
9713             && chain == TREE_CHAIN (t))
9714           return t;
9715         return tree_cons (purpose, value, chain);
9716       }
9717
9718     case RECORD_TYPE:
9719     case UNION_TYPE:
9720     case ENUMERAL_TYPE:
9721     case INTEGER_TYPE:
9722     case TEMPLATE_TYPE_PARM:
9723     case TEMPLATE_TEMPLATE_PARM:
9724     case BOUND_TEMPLATE_TEMPLATE_PARM:
9725     case TEMPLATE_PARM_INDEX:
9726     case POINTER_TYPE:
9727     case REFERENCE_TYPE:
9728     case OFFSET_TYPE:
9729     case FUNCTION_TYPE:
9730     case METHOD_TYPE:
9731     case ARRAY_TYPE:
9732     case TYPENAME_TYPE:
9733     case UNBOUND_CLASS_TEMPLATE:
9734     case TYPEOF_TYPE:
9735     case DECLTYPE_TYPE:
9736     case TYPE_DECL:
9737       return tsubst (t, args, complain, in_decl);
9738
9739     case IDENTIFIER_NODE:
9740       if (IDENTIFIER_TYPENAME_P (t))
9741         {
9742           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9743           return mangle_conv_op_name_for_type (new_type);
9744         }
9745       else
9746         return t;
9747
9748     case CONSTRUCTOR:
9749       /* This is handled by tsubst_copy_and_build.  */
9750       gcc_unreachable ();
9751
9752     case VA_ARG_EXPR:
9753       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
9754                                           in_decl),
9755                              tsubst (TREE_TYPE (t), args, complain, in_decl));
9756
9757     case CLEANUP_POINT_EXPR:
9758       /* We shouldn't have built any of these during initial template
9759          generation.  Instead, they should be built during instantiation
9760          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
9761       gcc_unreachable ();
9762
9763     case OFFSET_REF:
9764       mark_used (TREE_OPERAND (t, 1));
9765       return t;
9766
9767     case EXPR_PACK_EXPANSION:
9768       error ("invalid use of pack expansion expression");
9769       return error_mark_node;
9770
9771     case NONTYPE_ARGUMENT_PACK:
9772       error ("use %<...%> to expand argument pack");
9773       return error_mark_node;
9774
9775     default:
9776       return t;
9777     }
9778 }
9779
9780 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
9781
9782 static tree
9783 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
9784                     tree in_decl)
9785 {
9786   tree new_clauses = NULL, nc, oc;
9787
9788   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
9789     {
9790       nc = copy_node (oc);
9791       OMP_CLAUSE_CHAIN (nc) = new_clauses;
9792       new_clauses = nc;
9793
9794       switch (OMP_CLAUSE_CODE (nc))
9795         {
9796         case OMP_CLAUSE_PRIVATE:
9797         case OMP_CLAUSE_SHARED:
9798         case OMP_CLAUSE_FIRSTPRIVATE:
9799         case OMP_CLAUSE_LASTPRIVATE:
9800         case OMP_CLAUSE_REDUCTION:
9801         case OMP_CLAUSE_COPYIN:
9802         case OMP_CLAUSE_COPYPRIVATE:
9803         case OMP_CLAUSE_IF:
9804         case OMP_CLAUSE_NUM_THREADS:
9805         case OMP_CLAUSE_SCHEDULE:
9806           OMP_CLAUSE_OPERAND (nc, 0)
9807             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
9808                            in_decl, /*integral_constant_expression_p=*/false);
9809           break;
9810         case OMP_CLAUSE_NOWAIT:
9811         case OMP_CLAUSE_ORDERED:
9812         case OMP_CLAUSE_DEFAULT:
9813           break;
9814         default:
9815           gcc_unreachable ();
9816         }
9817     }
9818
9819   return finish_omp_clauses (nreverse (new_clauses));
9820 }
9821
9822 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
9823
9824 static tree
9825 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
9826                           tree in_decl)
9827 {
9828 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
9829
9830   tree purpose, value, chain;
9831
9832   if (t == NULL)
9833     return t;
9834
9835   if (TREE_CODE (t) != TREE_LIST)
9836     return tsubst_copy_and_build (t, args, complain, in_decl,
9837                                   /*function_p=*/false,
9838                                   /*integral_constant_expression_p=*/false);
9839
9840   if (t == void_list_node)
9841     return t;
9842
9843   purpose = TREE_PURPOSE (t);
9844   if (purpose)
9845     purpose = RECUR (purpose);
9846   value = TREE_VALUE (t);
9847   if (value)
9848     value = RECUR (value);
9849   chain = TREE_CHAIN (t);
9850   if (chain && chain != void_type_node)
9851     chain = RECUR (chain);
9852   return tree_cons (purpose, value, chain);
9853 #undef RECUR
9854 }
9855
9856 /* Like tsubst_copy for expressions, etc. but also does semantic
9857    processing.  */
9858
9859 static tree
9860 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
9861              bool integral_constant_expression_p)
9862 {
9863 #define RECUR(NODE)                             \
9864   tsubst_expr ((NODE), args, complain, in_decl, \
9865                integral_constant_expression_p)
9866
9867   tree stmt, tmp;
9868
9869   if (t == NULL_TREE || t == error_mark_node)
9870     return t;
9871
9872   if (EXPR_HAS_LOCATION (t))
9873     input_location = EXPR_LOCATION (t);
9874   if (STATEMENT_CODE_P (TREE_CODE (t)))
9875     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
9876
9877   switch (TREE_CODE (t))
9878     {
9879     case STATEMENT_LIST:
9880       {
9881         tree_stmt_iterator i;
9882         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
9883           RECUR (tsi_stmt (i));
9884         break;
9885       }
9886
9887     case CTOR_INITIALIZER:
9888       finish_mem_initializers (tsubst_initializer_list
9889                                (TREE_OPERAND (t, 0), args));
9890       break;
9891
9892     case RETURN_EXPR:
9893       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
9894       break;
9895
9896     case EXPR_STMT:
9897       tmp = RECUR (EXPR_STMT_EXPR (t));
9898       if (EXPR_STMT_STMT_EXPR_RESULT (t))
9899         finish_stmt_expr_expr (tmp, cur_stmt_expr);
9900       else
9901         finish_expr_stmt (tmp);
9902       break;
9903
9904     case USING_STMT:
9905       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
9906       break;
9907
9908     case DECL_EXPR:
9909       {
9910         tree decl;
9911         tree init;
9912
9913         decl = DECL_EXPR_DECL (t);
9914         if (TREE_CODE (decl) == LABEL_DECL)
9915           finish_label_decl (DECL_NAME (decl));
9916         else if (TREE_CODE (decl) == USING_DECL)
9917           {
9918             tree scope = USING_DECL_SCOPE (decl);
9919             tree name = DECL_NAME (decl);
9920             tree decl;
9921
9922             scope = RECUR (scope);
9923             decl = lookup_qualified_name (scope, name,
9924                                           /*is_type_p=*/false,
9925                                           /*complain=*/false);
9926             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
9927               qualified_name_lookup_error (scope, name, decl);
9928             else
9929               do_local_using_decl (decl, scope, name);
9930           }
9931         else
9932           {
9933             init = DECL_INITIAL (decl);
9934             decl = tsubst (decl, args, complain, in_decl);
9935             if (decl != error_mark_node)
9936               {
9937                 /* By marking the declaration as instantiated, we avoid
9938                    trying to instantiate it.  Since instantiate_decl can't
9939                    handle local variables, and since we've already done
9940                    all that needs to be done, that's the right thing to
9941                    do.  */
9942                 if (TREE_CODE (decl) == VAR_DECL)
9943                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
9944                 if (TREE_CODE (decl) == VAR_DECL
9945                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
9946                   /* Anonymous aggregates are a special case.  */
9947                   finish_anon_union (decl);
9948                 else
9949                   {
9950                     maybe_push_decl (decl);
9951                     if (TREE_CODE (decl) == VAR_DECL
9952                         && DECL_PRETTY_FUNCTION_P (decl))
9953                       {
9954                         /* For __PRETTY_FUNCTION__ we have to adjust the
9955                            initializer.  */
9956                         const char *const name
9957                           = cxx_printable_name (current_function_decl, 2);
9958                         init = cp_fname_init (name, &TREE_TYPE (decl));
9959                       }
9960                     else
9961                       {
9962                         tree t = RECUR (init);
9963
9964                         if (init && !t)
9965                           /* If we had an initializer but it
9966                              instantiated to nothing,
9967                              value-initialize the object.  This will
9968                              only occur when the initializer was a
9969                              pack expansion where the parameter packs
9970                              used in that expansion were of length
9971                              zero.  */
9972                           init = build_default_init (TREE_TYPE (decl),
9973                                                      NULL_TREE);
9974                         else
9975                           init = t;
9976                       }
9977
9978                     finish_decl (decl, init, NULL_TREE);
9979                   }
9980               }
9981           }
9982
9983         /* A DECL_EXPR can also be used as an expression, in the condition
9984            clause of an if/for/while construct.  */
9985         return decl;
9986       }
9987
9988     case FOR_STMT:
9989       stmt = begin_for_stmt ();
9990                           RECUR (FOR_INIT_STMT (t));
9991       finish_for_init_stmt (stmt);
9992       tmp = RECUR (FOR_COND (t));
9993       finish_for_cond (tmp, stmt);
9994       tmp = RECUR (FOR_EXPR (t));
9995       finish_for_expr (tmp, stmt);
9996       RECUR (FOR_BODY (t));
9997       finish_for_stmt (stmt);
9998       break;
9999
10000     case WHILE_STMT:
10001       stmt = begin_while_stmt ();
10002       tmp = RECUR (WHILE_COND (t));
10003       finish_while_stmt_cond (tmp, stmt);
10004       RECUR (WHILE_BODY (t));
10005       finish_while_stmt (stmt);
10006       break;
10007
10008     case DO_STMT:
10009       stmt = begin_do_stmt ();
10010       RECUR (DO_BODY (t));
10011       finish_do_body (stmt);
10012       tmp = RECUR (DO_COND (t));
10013       finish_do_stmt (tmp, stmt);
10014       break;
10015
10016     case IF_STMT:
10017       stmt = begin_if_stmt ();
10018       tmp = RECUR (IF_COND (t));
10019       finish_if_stmt_cond (tmp, stmt);
10020       RECUR (THEN_CLAUSE (t));
10021       finish_then_clause (stmt);
10022
10023       if (ELSE_CLAUSE (t))
10024         {
10025           begin_else_clause (stmt);
10026           RECUR (ELSE_CLAUSE (t));
10027           finish_else_clause (stmt);
10028         }
10029
10030       finish_if_stmt (stmt);
10031       break;
10032
10033     case BIND_EXPR:
10034       if (BIND_EXPR_BODY_BLOCK (t))
10035         stmt = begin_function_body ();
10036       else
10037         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
10038                                     ? BCS_TRY_BLOCK : 0);
10039
10040       RECUR (BIND_EXPR_BODY (t));
10041
10042       if (BIND_EXPR_BODY_BLOCK (t))
10043         finish_function_body (stmt);
10044       else
10045         finish_compound_stmt (stmt);
10046       break;
10047
10048     case BREAK_STMT:
10049       finish_break_stmt ();
10050       break;
10051
10052     case CONTINUE_STMT:
10053       finish_continue_stmt ();
10054       break;
10055
10056     case SWITCH_STMT:
10057       stmt = begin_switch_stmt ();
10058       tmp = RECUR (SWITCH_STMT_COND (t));
10059       finish_switch_cond (tmp, stmt);
10060       RECUR (SWITCH_STMT_BODY (t));
10061       finish_switch_stmt (stmt);
10062       break;
10063
10064     case CASE_LABEL_EXPR:
10065       finish_case_label (RECUR (CASE_LOW (t)),
10066                          RECUR (CASE_HIGH (t)));
10067       break;
10068
10069     case LABEL_EXPR:
10070       finish_label_stmt (DECL_NAME (LABEL_EXPR_LABEL (t)));
10071       break;
10072
10073     case GOTO_EXPR:
10074       tmp = GOTO_DESTINATION (t);
10075       if (TREE_CODE (tmp) != LABEL_DECL)
10076         /* Computed goto's must be tsubst'd into.  On the other hand,
10077            non-computed gotos must not be; the identifier in question
10078            will have no binding.  */
10079         tmp = RECUR (tmp);
10080       else
10081         tmp = DECL_NAME (tmp);
10082       finish_goto_stmt (tmp);
10083       break;
10084
10085     case ASM_EXPR:
10086       tmp = finish_asm_stmt
10087         (ASM_VOLATILE_P (t),
10088          RECUR (ASM_STRING (t)),
10089          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
10090          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
10091          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl));
10092       {
10093         tree asm_expr = tmp;
10094         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
10095           asm_expr = TREE_OPERAND (asm_expr, 0);
10096         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
10097       }
10098       break;
10099
10100     case TRY_BLOCK:
10101       if (CLEANUP_P (t))
10102         {
10103           stmt = begin_try_block ();
10104           RECUR (TRY_STMTS (t));
10105           finish_cleanup_try_block (stmt);
10106           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
10107         }
10108       else
10109         {
10110           tree compound_stmt = NULL_TREE;
10111
10112           if (FN_TRY_BLOCK_P (t))
10113             stmt = begin_function_try_block (&compound_stmt);
10114           else
10115             stmt = begin_try_block ();
10116
10117           RECUR (TRY_STMTS (t));
10118
10119           if (FN_TRY_BLOCK_P (t))
10120             finish_function_try_block (stmt);
10121           else
10122             finish_try_block (stmt);
10123
10124           RECUR (TRY_HANDLERS (t));
10125           if (FN_TRY_BLOCK_P (t))
10126             finish_function_handler_sequence (stmt, compound_stmt);
10127           else
10128             finish_handler_sequence (stmt);
10129         }
10130       break;
10131
10132     case HANDLER:
10133       {
10134         tree decl = HANDLER_PARMS (t);
10135
10136         if (decl)
10137           {
10138             decl = tsubst (decl, args, complain, in_decl);
10139             /* Prevent instantiate_decl from trying to instantiate
10140                this variable.  We've already done all that needs to be
10141                done.  */
10142             if (decl != error_mark_node)
10143               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10144           }
10145         stmt = begin_handler ();
10146         finish_handler_parms (decl, stmt);
10147         RECUR (HANDLER_BODY (t));
10148         finish_handler (stmt);
10149       }
10150       break;
10151
10152     case TAG_DEFN:
10153       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
10154       break;
10155
10156     case STATIC_ASSERT:
10157       {
10158         tree condition = 
10159           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
10160                        args,
10161                        complain, in_decl,
10162                        /*integral_constant_expression_p=*/true);
10163         finish_static_assert (condition,
10164                               STATIC_ASSERT_MESSAGE (t),
10165                               STATIC_ASSERT_SOURCE_LOCATION (t),
10166                               /*member_p=*/false);
10167       }
10168       break;
10169
10170     case OMP_PARALLEL:
10171       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
10172                                 args, complain, in_decl);
10173       stmt = begin_omp_parallel ();
10174       RECUR (OMP_PARALLEL_BODY (t));
10175       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
10176         = OMP_PARALLEL_COMBINED (t);
10177       break;
10178
10179     case OMP_FOR:
10180       {
10181         tree clauses, decl, init, cond, incr, body, pre_body;
10182
10183         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
10184                                       args, complain, in_decl);
10185         init = OMP_FOR_INIT (t);
10186         gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
10187         decl = RECUR (TREE_OPERAND (init, 0));
10188         init = RECUR (TREE_OPERAND (init, 1));
10189         cond = RECUR (OMP_FOR_COND (t));
10190         incr = RECUR (OMP_FOR_INCR (t));
10191
10192         stmt = begin_omp_structured_block ();
10193
10194         pre_body = push_stmt_list ();
10195         RECUR (OMP_FOR_PRE_BODY (t));
10196         pre_body = pop_stmt_list (pre_body);
10197
10198         body = push_stmt_list ();
10199         RECUR (OMP_FOR_BODY (t));
10200         body = pop_stmt_list (body);
10201
10202         t = finish_omp_for (EXPR_LOCATION (t), decl, init, cond, incr, body,
10203                             pre_body);
10204         if (t)
10205           OMP_FOR_CLAUSES (t) = clauses;
10206
10207         add_stmt (finish_omp_structured_block (stmt));
10208       }
10209       break;
10210
10211     case OMP_SECTIONS:
10212     case OMP_SINGLE:
10213       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
10214       stmt = push_stmt_list ();
10215       RECUR (OMP_BODY (t));
10216       stmt = pop_stmt_list (stmt);
10217
10218       t = copy_node (t);
10219       OMP_BODY (t) = stmt;
10220       OMP_CLAUSES (t) = tmp;
10221       add_stmt (t);
10222       break;
10223
10224     case OMP_SECTION:
10225     case OMP_CRITICAL:
10226     case OMP_MASTER:
10227     case OMP_ORDERED:
10228       stmt = push_stmt_list ();
10229       RECUR (OMP_BODY (t));
10230       stmt = pop_stmt_list (stmt);
10231
10232       t = copy_node (t);
10233       OMP_BODY (t) = stmt;
10234       add_stmt (t);
10235       break;
10236
10237     case OMP_ATOMIC:
10238       if (OMP_ATOMIC_DEPENDENT_P (t))
10239         {
10240           tree op1 = TREE_OPERAND (t, 1);
10241           tree lhs = RECUR (TREE_OPERAND (op1, 0));
10242           tree rhs = RECUR (TREE_OPERAND (op1, 1));
10243           finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
10244         }
10245       break;
10246
10247     case EXPR_PACK_EXPANSION:
10248       error ("invalid use of pack expansion expression");
10249       return error_mark_node;
10250
10251     case NONTYPE_ARGUMENT_PACK:
10252       error ("use %<...%> to expand argument pack");
10253       return error_mark_node;
10254
10255     default:
10256       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
10257
10258       return tsubst_copy_and_build (t, args, complain, in_decl,
10259                                     /*function_p=*/false,
10260                                     integral_constant_expression_p);
10261     }
10262
10263   return NULL_TREE;
10264 #undef RECUR
10265 }
10266
10267 /* T is a postfix-expression that is not being used in a function
10268    call.  Return the substituted version of T.  */
10269
10270 static tree
10271 tsubst_non_call_postfix_expression (tree t, tree args,
10272                                     tsubst_flags_t complain,
10273                                     tree in_decl)
10274 {
10275   if (TREE_CODE (t) == SCOPE_REF)
10276     t = tsubst_qualified_id (t, args, complain, in_decl,
10277                              /*done=*/false, /*address_p=*/false);
10278   else
10279     t = tsubst_copy_and_build (t, args, complain, in_decl,
10280                                /*function_p=*/false,
10281                                /*integral_constant_expression_p=*/false);
10282
10283   return t;
10284 }
10285
10286 /* Like tsubst but deals with expressions and performs semantic
10287    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
10288
10289 tree
10290 tsubst_copy_and_build (tree t,
10291                        tree args,
10292                        tsubst_flags_t complain,
10293                        tree in_decl,
10294                        bool function_p,
10295                        bool integral_constant_expression_p)
10296 {
10297 #define RECUR(NODE)                                             \
10298   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
10299                          /*function_p=*/false,                  \
10300                          integral_constant_expression_p)
10301
10302   tree op1;
10303
10304   if (t == NULL_TREE || t == error_mark_node)
10305     return t;
10306
10307   switch (TREE_CODE (t))
10308     {
10309     case USING_DECL:
10310       t = DECL_NAME (t);
10311       /* Fall through.  */
10312     case IDENTIFIER_NODE:
10313       {
10314         tree decl;
10315         cp_id_kind idk;
10316         bool non_integral_constant_expression_p;
10317         const char *error_msg;
10318
10319         if (IDENTIFIER_TYPENAME_P (t))
10320           {
10321             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10322             t = mangle_conv_op_name_for_type (new_type);
10323           }
10324
10325         /* Look up the name.  */
10326         decl = lookup_name (t);
10327
10328         /* By convention, expressions use ERROR_MARK_NODE to indicate
10329            failure, not NULL_TREE.  */
10330         if (decl == NULL_TREE)
10331           decl = error_mark_node;
10332
10333         decl = finish_id_expression (t, decl, NULL_TREE,
10334                                      &idk,
10335                                      integral_constant_expression_p,
10336                                      /*allow_non_integral_constant_expression_p=*/false,
10337                                      &non_integral_constant_expression_p,
10338                                      /*template_p=*/false,
10339                                      /*done=*/true,
10340                                      /*address_p=*/false,
10341                                      /*template_arg_p=*/false,
10342                                      &error_msg);
10343         if (error_msg)
10344           error (error_msg);
10345         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
10346           decl = unqualified_name_lookup_error (decl);
10347         return decl;
10348       }
10349
10350     case TEMPLATE_ID_EXPR:
10351       {
10352         tree object;
10353         tree template = RECUR (TREE_OPERAND (t, 0));
10354         tree targs = TREE_OPERAND (t, 1);
10355
10356         if (targs)
10357           targs = tsubst_template_args (targs, args, complain, in_decl);
10358
10359         if (TREE_CODE (template) == COMPONENT_REF)
10360           {
10361             object = TREE_OPERAND (template, 0);
10362             template = TREE_OPERAND (template, 1);
10363           }
10364         else
10365           object = NULL_TREE;
10366         template = lookup_template_function (template, targs);
10367
10368         if (object)
10369           return build3 (COMPONENT_REF, TREE_TYPE (template),
10370                          object, template, NULL_TREE);
10371         else
10372           return baselink_for_fns (template);
10373       }
10374
10375     case INDIRECT_REF:
10376       {
10377         tree r = RECUR (TREE_OPERAND (t, 0));
10378
10379         if (REFERENCE_REF_P (t))
10380           {
10381             /* A type conversion to reference type will be enclosed in
10382                such an indirect ref, but the substitution of the cast
10383                will have also added such an indirect ref.  */
10384             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
10385               r = convert_from_reference (r);
10386           }
10387         else
10388           r = build_x_indirect_ref (r, "unary *");
10389         return r;
10390       }
10391
10392     case NOP_EXPR:
10393       return build_nop
10394         (tsubst (TREE_TYPE (t), args, complain, in_decl),
10395          RECUR (TREE_OPERAND (t, 0)));
10396
10397     case CAST_EXPR:
10398     case REINTERPRET_CAST_EXPR:
10399     case CONST_CAST_EXPR:
10400     case DYNAMIC_CAST_EXPR:
10401     case STATIC_CAST_EXPR:
10402       {
10403         tree type;
10404         tree op;
10405
10406         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10407         if (integral_constant_expression_p
10408             && !cast_valid_in_integral_constant_expression_p (type))
10409           {
10410             error ("a cast to a type other than an integral or "
10411                    "enumeration type cannot appear in a constant-expression");
10412             return error_mark_node; 
10413           }
10414
10415         op = RECUR (TREE_OPERAND (t, 0));
10416
10417         switch (TREE_CODE (t))
10418           {
10419           case CAST_EXPR:
10420             return build_functional_cast (type, op);
10421           case REINTERPRET_CAST_EXPR:
10422             return build_reinterpret_cast (type, op);
10423           case CONST_CAST_EXPR:
10424             return build_const_cast (type, op);
10425           case DYNAMIC_CAST_EXPR:
10426             return build_dynamic_cast (type, op);
10427           case STATIC_CAST_EXPR:
10428             return build_static_cast (type, op);
10429           default:
10430             gcc_unreachable ();
10431           }
10432       }
10433
10434     case POSTDECREMENT_EXPR:
10435     case POSTINCREMENT_EXPR:
10436       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
10437                                                 args, complain, in_decl);
10438       return build_x_unary_op (TREE_CODE (t), op1);
10439
10440     case PREDECREMENT_EXPR:
10441     case PREINCREMENT_EXPR:
10442     case NEGATE_EXPR:
10443     case BIT_NOT_EXPR:
10444     case ABS_EXPR:
10445     case TRUTH_NOT_EXPR:
10446     case UNARY_PLUS_EXPR:  /* Unary + */
10447     case REALPART_EXPR:
10448     case IMAGPART_EXPR:
10449       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)));
10450
10451     case ADDR_EXPR:
10452       op1 = TREE_OPERAND (t, 0);
10453       if (TREE_CODE (op1) == SCOPE_REF)
10454         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
10455                                    /*done=*/true, /*address_p=*/true);
10456       else
10457         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
10458                                                   in_decl);
10459       if (TREE_CODE (op1) == LABEL_DECL)
10460         return finish_label_address_expr (DECL_NAME (op1));
10461       return build_x_unary_op (ADDR_EXPR, op1);
10462
10463     case PLUS_EXPR:
10464     case MINUS_EXPR:
10465     case MULT_EXPR:
10466     case TRUNC_DIV_EXPR:
10467     case CEIL_DIV_EXPR:
10468     case FLOOR_DIV_EXPR:
10469     case ROUND_DIV_EXPR:
10470     case EXACT_DIV_EXPR:
10471     case BIT_AND_EXPR:
10472     case BIT_IOR_EXPR:
10473     case BIT_XOR_EXPR:
10474     case TRUNC_MOD_EXPR:
10475     case FLOOR_MOD_EXPR:
10476     case TRUTH_ANDIF_EXPR:
10477     case TRUTH_ORIF_EXPR:
10478     case TRUTH_AND_EXPR:
10479     case TRUTH_OR_EXPR:
10480     case RSHIFT_EXPR:
10481     case LSHIFT_EXPR:
10482     case RROTATE_EXPR:
10483     case LROTATE_EXPR:
10484     case EQ_EXPR:
10485     case NE_EXPR:
10486     case MAX_EXPR:
10487     case MIN_EXPR:
10488     case LE_EXPR:
10489     case GE_EXPR:
10490     case LT_EXPR:
10491     case GT_EXPR:
10492     case MEMBER_REF:
10493     case DOTSTAR_EXPR:
10494       return build_x_binary_op
10495         (TREE_CODE (t),
10496          RECUR (TREE_OPERAND (t, 0)),
10497          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
10498           ? ERROR_MARK
10499           : TREE_CODE (TREE_OPERAND (t, 0))),
10500          RECUR (TREE_OPERAND (t, 1)),
10501          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
10502           ? ERROR_MARK
10503           : TREE_CODE (TREE_OPERAND (t, 1))),
10504          /*overloaded_p=*/NULL);
10505
10506     case SCOPE_REF:
10507       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
10508                                   /*address_p=*/false);
10509     case ARRAY_REF:
10510       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
10511                                                 args, complain, in_decl);
10512       return build_x_binary_op (ARRAY_REF, op1,
10513                                 (TREE_NO_WARNING (TREE_OPERAND (t, 0))
10514                                  ? ERROR_MARK
10515                                  : TREE_CODE (TREE_OPERAND (t, 0))),
10516                                 RECUR (TREE_OPERAND (t, 1)),
10517                                 (TREE_NO_WARNING (TREE_OPERAND (t, 1))
10518                                  ? ERROR_MARK
10519                                  : TREE_CODE (TREE_OPERAND (t, 1))),
10520                                 /*overloaded_p=*/NULL);
10521
10522     case SIZEOF_EXPR:
10523       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10524         {
10525           /* We only want to compute the number of arguments.  */
10526           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
10527                                                 complain, in_decl);
10528           return build_int_cst (size_type_node, TREE_VEC_LENGTH (expanded));
10529         }
10530       /* Fall through */
10531       
10532     case ALIGNOF_EXPR:
10533       op1 = TREE_OPERAND (t, 0);
10534       if (!args)
10535         {
10536           /* When there are no ARGS, we are trying to evaluate a
10537              non-dependent expression from the parser.  Trying to do
10538              the substitutions may not work.  */
10539           if (!TYPE_P (op1))
10540             op1 = TREE_TYPE (op1);
10541         }
10542       else
10543         {
10544           ++skip_evaluation;
10545           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
10546                                        /*function_p=*/false,
10547                                        /*integral_constant_expression_p=*/false);
10548           --skip_evaluation;
10549         }
10550       if (TYPE_P (op1))
10551         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), true);
10552       else
10553         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t));
10554
10555     case MODOP_EXPR:
10556       {
10557         tree r = build_x_modify_expr
10558           (RECUR (TREE_OPERAND (t, 0)),
10559            TREE_CODE (TREE_OPERAND (t, 1)),
10560            RECUR (TREE_OPERAND (t, 2)));
10561         /* TREE_NO_WARNING must be set if either the expression was
10562            parenthesized or it uses an operator such as >>= rather
10563            than plain assignment.  In the former case, it was already
10564            set and must be copied.  In the latter case,
10565            build_x_modify_expr sets it and it must not be reset
10566            here.  */
10567         if (TREE_NO_WARNING (t))
10568           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
10569         return r;
10570       }
10571
10572     case ARROW_EXPR:
10573       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
10574                                                 args, complain, in_decl);
10575       /* Remember that there was a reference to this entity.  */
10576       if (DECL_P (op1))
10577         mark_used (op1);
10578       return build_x_arrow (op1);
10579
10580     case NEW_EXPR:
10581       {
10582         tree init = RECUR (TREE_OPERAND (t, 3));
10583
10584         if (TREE_OPERAND (t, 3) && !init)
10585           /* If there was an initializer in the the original tree, but
10586              it instantiated to an empty list, then we should pass on
10587              VOID_ZERO_NODE to tell build_new that it was an empty
10588              initializer () rather than no initializer.  This can only
10589              happen when the initializer is a pack expansion whose
10590              parameter packs are of length zero.  */
10591           init = void_zero_node;
10592
10593         return build_new
10594           (RECUR (TREE_OPERAND (t, 0)),
10595            RECUR (TREE_OPERAND (t, 1)),
10596            RECUR (TREE_OPERAND (t, 2)),
10597            init,
10598            NEW_EXPR_USE_GLOBAL (t));
10599       }
10600
10601     case DELETE_EXPR:
10602      return delete_sanity
10603        (RECUR (TREE_OPERAND (t, 0)),
10604         RECUR (TREE_OPERAND (t, 1)),
10605         DELETE_EXPR_USE_VEC (t),
10606         DELETE_EXPR_USE_GLOBAL (t));
10607
10608     case COMPOUND_EXPR:
10609       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
10610                                     RECUR (TREE_OPERAND (t, 1)));
10611
10612     case CALL_EXPR:
10613       {
10614         tree function;
10615         tree call_args;
10616         bool qualified_p;
10617         bool koenig_p;
10618
10619         function = CALL_EXPR_FN (t);
10620         /* When we parsed the expression,  we determined whether or
10621            not Koenig lookup should be performed.  */
10622         koenig_p = KOENIG_LOOKUP_P (t);
10623         if (TREE_CODE (function) == SCOPE_REF)
10624           {
10625             qualified_p = true;
10626             function = tsubst_qualified_id (function, args, complain, in_decl,
10627                                             /*done=*/false,
10628                                             /*address_p=*/false);
10629           }
10630         else
10631           {
10632             if (TREE_CODE (function) == COMPONENT_REF)
10633               {
10634                 tree op = TREE_OPERAND (function, 1);
10635
10636                 qualified_p = (TREE_CODE (op) == SCOPE_REF
10637                                || (BASELINK_P (op)
10638                                    && BASELINK_QUALIFIED_P (op)));
10639               }
10640             else
10641               qualified_p = false;
10642
10643             function = tsubst_copy_and_build (function, args, complain,
10644                                               in_decl,
10645                                               !qualified_p,
10646                                               integral_constant_expression_p);
10647
10648             if (BASELINK_P (function))
10649               qualified_p = true;
10650           }
10651
10652         /* FIXME:  Rewrite this so as not to construct an arglist.  */
10653         call_args = RECUR (CALL_EXPR_ARGS (t));
10654
10655         /* We do not perform argument-dependent lookup if normal
10656            lookup finds a non-function, in accordance with the
10657            expected resolution of DR 218.  */
10658         if (koenig_p
10659             && ((is_overloaded_fn (function)
10660                  /* If lookup found a member function, the Koenig lookup is
10661                     not appropriate, even if an unqualified-name was used
10662                     to denote the function.  */
10663                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
10664                 || TREE_CODE (function) == IDENTIFIER_NODE))
10665           function = perform_koenig_lookup (function, call_args);
10666
10667         if (TREE_CODE (function) == IDENTIFIER_NODE)
10668           {
10669             unqualified_name_lookup_error (function);
10670             return error_mark_node;
10671           }
10672
10673         /* Remember that there was a reference to this entity.  */
10674         if (DECL_P (function))
10675           mark_used (function);
10676
10677         if (TREE_CODE (function) == OFFSET_REF)
10678           return build_offset_ref_call_from_tree (function, call_args);
10679         if (TREE_CODE (function) == COMPONENT_REF)
10680           {
10681             if (!BASELINK_P (TREE_OPERAND (function, 1)))
10682               return finish_call_expr (function, call_args,
10683                                        /*disallow_virtual=*/false,
10684                                        /*koenig_p=*/false);
10685             else
10686               return (build_new_method_call
10687                       (TREE_OPERAND (function, 0),
10688                        TREE_OPERAND (function, 1),
10689                        call_args, NULL_TREE,
10690                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
10691                        /*fn_p=*/NULL));
10692           }
10693         return finish_call_expr (function, call_args,
10694                                  /*disallow_virtual=*/qualified_p,
10695                                  koenig_p);
10696       }
10697
10698     case COND_EXPR:
10699       return build_x_conditional_expr
10700         (RECUR (TREE_OPERAND (t, 0)),
10701          RECUR (TREE_OPERAND (t, 1)),
10702          RECUR (TREE_OPERAND (t, 2)));
10703
10704     case PSEUDO_DTOR_EXPR:
10705       return finish_pseudo_destructor_expr
10706         (RECUR (TREE_OPERAND (t, 0)),
10707          RECUR (TREE_OPERAND (t, 1)),
10708          RECUR (TREE_OPERAND (t, 2)));
10709
10710     case TREE_LIST:
10711       {
10712         tree purpose, value, chain;
10713
10714         if (t == void_list_node)
10715           return t;
10716
10717         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
10718             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
10719           {
10720             /* We have pack expansions, so expand those and
10721                create a new list out of it.  */
10722             tree purposevec = NULL_TREE;
10723             tree valuevec = NULL_TREE;
10724             tree chain;
10725             int i, len = -1;
10726
10727             /* Expand the argument expressions.  */
10728             if (TREE_PURPOSE (t))
10729               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
10730                                                  complain, in_decl);
10731             if (TREE_VALUE (t))
10732               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
10733                                                complain, in_decl);
10734
10735             /* Build the rest of the list.  */
10736             chain = TREE_CHAIN (t);
10737             if (chain && chain != void_type_node)
10738               chain = RECUR (chain);
10739
10740             /* Determine the number of arguments.  */
10741             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
10742               {
10743                 len = TREE_VEC_LENGTH (purposevec);
10744                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
10745               }
10746             else if (TREE_CODE (valuevec) == TREE_VEC)
10747               len = TREE_VEC_LENGTH (valuevec);
10748             else
10749               {
10750                 /* Since we only performed a partial substitution into
10751                    the argument pack, we only return a single list
10752                    node.  */
10753                 if (purposevec == TREE_PURPOSE (t)
10754                     && valuevec == TREE_VALUE (t)
10755                     && chain == TREE_CHAIN (t))
10756                   return t;
10757
10758                 return tree_cons (purposevec, valuevec, chain);
10759               }
10760             
10761             /* Convert the argument vectors into a TREE_LIST */
10762             i = len;
10763             while (i > 0)
10764               {
10765                 /* Grab the Ith values.  */
10766                 i--;
10767                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
10768                                      : NULL_TREE;
10769                 value 
10770                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
10771                              : NULL_TREE;
10772
10773                 /* Build the list (backwards).  */
10774                 chain = tree_cons (purpose, value, chain);
10775               }
10776
10777             return chain;
10778           }
10779
10780         purpose = TREE_PURPOSE (t);
10781         if (purpose)
10782           purpose = RECUR (purpose);
10783         value = TREE_VALUE (t);
10784         if (value)
10785           value = RECUR (value);
10786         chain = TREE_CHAIN (t);
10787         if (chain && chain != void_type_node)
10788           chain = RECUR (chain);
10789         if (purpose == TREE_PURPOSE (t)
10790             && value == TREE_VALUE (t)
10791             && chain == TREE_CHAIN (t))
10792           return t;
10793         return tree_cons (purpose, value, chain);
10794       }
10795
10796     case COMPONENT_REF:
10797       {
10798         tree object;
10799         tree object_type;
10800         tree member;
10801
10802         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
10803                                                      args, complain, in_decl);
10804         /* Remember that there was a reference to this entity.  */
10805         if (DECL_P (object))
10806           mark_used (object);
10807         object_type = TREE_TYPE (object);
10808
10809         member = TREE_OPERAND (t, 1);
10810         if (BASELINK_P (member))
10811           member = tsubst_baselink (member,
10812                                     non_reference (TREE_TYPE (object)),
10813                                     args, complain, in_decl);
10814         else
10815           member = tsubst_copy (member, args, complain, in_decl);
10816         if (member == error_mark_node)
10817           return error_mark_node;
10818
10819         if (object_type && !CLASS_TYPE_P (object_type))
10820           {
10821             if (TREE_CODE (member) == BIT_NOT_EXPR)
10822               return finish_pseudo_destructor_expr (object,
10823                                                     NULL_TREE,
10824                                                     object_type);
10825             else if (TREE_CODE (member) == SCOPE_REF
10826                      && (TREE_CODE (TREE_OPERAND (member, 1)) == BIT_NOT_EXPR))
10827               return finish_pseudo_destructor_expr (object,
10828                                                     object,
10829                                                     object_type);
10830           }
10831         else if (TREE_CODE (member) == SCOPE_REF
10832                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
10833           {
10834             tree tmpl;
10835             tree args;
10836
10837             /* Lookup the template functions now that we know what the
10838                scope is.  */
10839             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
10840             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
10841             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
10842                                             /*is_type_p=*/false,
10843                                             /*complain=*/false);
10844             if (BASELINK_P (member))
10845               {
10846                 BASELINK_FUNCTIONS (member)
10847                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
10848                               args);
10849                 member = (adjust_result_of_qualified_name_lookup
10850                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
10851                            object_type));
10852               }
10853             else
10854               {
10855                 qualified_name_lookup_error (object_type, tmpl, member);
10856                 return error_mark_node;
10857               }
10858           }
10859         else if (TREE_CODE (member) == SCOPE_REF
10860                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
10861                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
10862           {
10863             if (complain & tf_error)
10864               {
10865                 if (TYPE_P (TREE_OPERAND (member, 0)))
10866                   error ("%qT is not a class or namespace",
10867                          TREE_OPERAND (member, 0));
10868                 else
10869                   error ("%qD is not a class or namespace",
10870                          TREE_OPERAND (member, 0));
10871               }
10872             return error_mark_node;
10873           }
10874         else if (TREE_CODE (member) == FIELD_DECL)
10875           return finish_non_static_data_member (member, object, NULL_TREE);
10876
10877         return finish_class_member_access_expr (object, member,
10878                                                 /*template_p=*/false);
10879       }
10880
10881     case THROW_EXPR:
10882       return build_throw
10883         (RECUR (TREE_OPERAND (t, 0)));
10884
10885     case CONSTRUCTOR:
10886       {
10887         VEC(constructor_elt,gc) *n;
10888         constructor_elt *ce;
10889         unsigned HOST_WIDE_INT idx;
10890         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10891         bool process_index_p;
10892         int newlen;
10893         bool need_copy_p = false;
10894
10895         if (type == error_mark_node)
10896           return error_mark_node;
10897
10898         /* digest_init will do the wrong thing if we let it.  */
10899         if (type && TYPE_PTRMEMFUNC_P (type))
10900           return t;
10901
10902         /* We do not want to process the index of aggregate
10903            initializers as they are identifier nodes which will be
10904            looked up by digest_init.  */
10905         process_index_p = !(type && IS_AGGR_TYPE (type));
10906
10907         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
10908         newlen = VEC_length (constructor_elt, n);
10909         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
10910           {
10911             if (ce->index && process_index_p)
10912               ce->index = RECUR (ce->index);
10913
10914             if (PACK_EXPANSION_P (ce->value))
10915               {
10916                 /* Substitute into the pack expansion.  */
10917                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
10918                                                   in_decl);
10919
10920                 if (TREE_VEC_LENGTH (ce->value) == 1)
10921                   /* Just move the argument into place.  */
10922                   ce->value = TREE_VEC_ELT (ce->value, 0);
10923                 else
10924                   {
10925                     /* Update the length of the final CONSTRUCTOR
10926                        arguments vector, and note that we will need to
10927                        copy.*/
10928                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
10929                     need_copy_p = true;
10930                   }
10931               }
10932             else
10933               ce->value = RECUR (ce->value);
10934           }
10935
10936         if (need_copy_p)
10937           {
10938             VEC(constructor_elt,gc) *old_n = n;
10939
10940             n = VEC_alloc (constructor_elt, gc, newlen);
10941             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
10942                  idx++)
10943               {
10944                 if (TREE_CODE (ce->value) == TREE_VEC)
10945                   {
10946                     int i, len = TREE_VEC_LENGTH (ce->value);
10947                     for (i = 0; i < len; ++i)
10948                       CONSTRUCTOR_APPEND_ELT (n, 0,
10949                                               TREE_VEC_ELT (ce->value, i));
10950                   }
10951                 else
10952                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
10953               }
10954           }
10955
10956         if (TREE_HAS_CONSTRUCTOR (t))
10957           return finish_compound_literal (type, n);
10958
10959         return build_constructor (NULL_TREE, n);
10960       }
10961
10962     case TYPEID_EXPR:
10963       {
10964         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
10965         if (TYPE_P (operand_0))
10966           return get_typeid (operand_0);
10967         return build_typeid (operand_0);
10968       }
10969
10970     case VAR_DECL:
10971       if (!args)
10972         return t;
10973       /* Fall through */
10974
10975     case PARM_DECL:
10976       {
10977         tree r = tsubst_copy (t, args, complain, in_decl);
10978
10979         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
10980           /* If the original type was a reference, we'll be wrapped in
10981              the appropriate INDIRECT_REF.  */
10982           r = convert_from_reference (r);
10983         return r;
10984       }
10985
10986     case VA_ARG_EXPR:
10987       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
10988                              tsubst_copy (TREE_TYPE (t), args, complain,
10989                                           in_decl));
10990
10991     case OFFSETOF_EXPR:
10992       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
10993
10994     case TRAIT_EXPR:
10995       {
10996         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
10997                                   complain, in_decl);
10998
10999         tree type2 = TRAIT_EXPR_TYPE2 (t);
11000         if (type2)
11001           type2 = tsubst_copy (type2, args, complain, in_decl);
11002         
11003         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
11004       }
11005
11006     case STMT_EXPR:
11007       {
11008         tree old_stmt_expr = cur_stmt_expr;
11009         tree stmt_expr = begin_stmt_expr ();
11010
11011         cur_stmt_expr = stmt_expr;
11012         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
11013                      integral_constant_expression_p);
11014         stmt_expr = finish_stmt_expr (stmt_expr, false);
11015         cur_stmt_expr = old_stmt_expr;
11016
11017         return stmt_expr;
11018       }
11019
11020     case CONST_DECL:
11021       t = tsubst_copy (t, args, complain, in_decl);
11022       /* As in finish_id_expression, we resolve enumeration constants
11023          to their underlying values.  */
11024       if (TREE_CODE (t) == CONST_DECL)
11025         {
11026           used_types_insert (TREE_TYPE (t));
11027           return DECL_INITIAL (t);
11028         }
11029       return t;
11030
11031     default:
11032       /* Handle Objective-C++ constructs, if appropriate.  */
11033       {
11034         tree subst
11035           = objcp_tsubst_copy_and_build (t, args, complain,
11036                                          in_decl, /*function_p=*/false);
11037         if (subst)
11038           return subst;
11039       }
11040       return tsubst_copy (t, args, complain, in_decl);
11041     }
11042
11043 #undef RECUR
11044 }
11045
11046 /* Verify that the instantiated ARGS are valid. For type arguments,
11047    make sure that the type's linkage is ok. For non-type arguments,
11048    make sure they are constants if they are integral or enumerations.
11049    Emit an error under control of COMPLAIN, and return TRUE on error.  */
11050
11051 static bool
11052 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
11053 {
11054   int ix, len = DECL_NTPARMS (tmpl);
11055   bool result = false;
11056
11057   for (ix = 0; ix != len; ix++)
11058     {
11059       tree t = TREE_VEC_ELT (args, ix);
11060
11061       if (TYPE_P (t))
11062         {
11063           /* [basic.link]: A name with no linkage (notably, the name
11064              of a class or enumeration declared in a local scope)
11065              shall not be used to declare an entity with linkage.
11066              This implies that names with no linkage cannot be used as
11067              template arguments.  */
11068           tree nt = no_linkage_check (t, /*relaxed_p=*/false);
11069
11070           if (nt)
11071             {
11072               /* DR 488 makes use of a type with no linkage cause
11073                  type deduction to fail.  */
11074               if (complain & tf_error)
11075                 {
11076                   if (TYPE_ANONYMOUS_P (nt))
11077                     error ("%qT is/uses anonymous type", t);
11078                   else
11079                     error ("template argument for %qD uses local type %qT",
11080                            tmpl, t);
11081                 }
11082               result = true;
11083             }
11084           /* In order to avoid all sorts of complications, we do not
11085              allow variably-modified types as template arguments.  */
11086           else if (variably_modified_type_p (t, NULL_TREE))
11087             {
11088               if (complain & tf_error)
11089                 error ("%qT is a variably modified type", t);
11090               result = true;
11091             }
11092         }
11093       /* A non-type argument of integral or enumerated type must be a
11094          constant.  */
11095       else if (TREE_TYPE (t)
11096                && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
11097                && !TREE_CONSTANT (t))
11098         {
11099           if (complain & tf_error)
11100             error ("integral expression %qE is not constant", t);
11101           result = true;
11102         }
11103     }
11104   if (result && (complain & tf_error))
11105     error ("  trying to instantiate %qD", tmpl);
11106   return result;
11107 }
11108
11109 /* Instantiate the indicated variable or function template TMPL with
11110    the template arguments in TARG_PTR.  */
11111
11112 tree
11113 instantiate_template (tree tmpl, tree targ_ptr, tsubst_flags_t complain)
11114 {
11115   tree fndecl;
11116   tree gen_tmpl;
11117   tree spec;
11118   HOST_WIDE_INT saved_processing_template_decl;
11119
11120   if (tmpl == error_mark_node)
11121     return error_mark_node;
11122
11123   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
11124
11125   /* If this function is a clone, handle it specially.  */
11126   if (DECL_CLONED_FUNCTION_P (tmpl))
11127     {
11128       tree spec;
11129       tree clone;
11130
11131       spec = instantiate_template (DECL_CLONED_FUNCTION (tmpl), targ_ptr,
11132                                    complain);
11133       if (spec == error_mark_node)
11134         return error_mark_node;
11135
11136       /* Look for the clone.  */
11137       FOR_EACH_CLONE (clone, spec)
11138         if (DECL_NAME (clone) == DECL_NAME (tmpl))
11139           return clone;
11140       /* We should always have found the clone by now.  */
11141       gcc_unreachable ();
11142       return NULL_TREE;
11143     }
11144
11145   /* Check to see if we already have this specialization.  */
11146   spec = retrieve_specialization (tmpl, targ_ptr,
11147                                   /*class_specializations_p=*/false);
11148   if (spec != NULL_TREE)
11149     return spec;
11150
11151   gen_tmpl = most_general_template (tmpl);
11152   if (tmpl != gen_tmpl)
11153     {
11154       /* The TMPL is a partial instantiation.  To get a full set of
11155          arguments we must add the arguments used to perform the
11156          partial instantiation.  */
11157       targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
11158                                               targ_ptr);
11159
11160       /* Check to see if we already have this specialization.  */
11161       spec = retrieve_specialization (gen_tmpl, targ_ptr,
11162                                       /*class_specializations_p=*/false);
11163       if (spec != NULL_TREE)
11164         return spec;
11165     }
11166
11167   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
11168                                complain))
11169     return error_mark_node;
11170
11171   /* We are building a FUNCTION_DECL, during which the access of its
11172      parameters and return types have to be checked.  However this
11173      FUNCTION_DECL which is the desired context for access checking
11174      is not built yet.  We solve this chicken-and-egg problem by
11175      deferring all checks until we have the FUNCTION_DECL.  */
11176   push_deferring_access_checks (dk_deferred);
11177
11178   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
11179      (because, for example, we have encountered a non-dependent
11180      function call in the body of a template function and must now
11181      determine which of several overloaded functions will be called),
11182      within the instantiation itself we are not processing a
11183      template.  */  
11184   saved_processing_template_decl = processing_template_decl;
11185   processing_template_decl = 0;
11186   /* Substitute template parameters to obtain the specialization.  */
11187   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
11188                    targ_ptr, complain, gen_tmpl);
11189   processing_template_decl = saved_processing_template_decl;
11190   if (fndecl == error_mark_node)
11191     return error_mark_node;
11192
11193   /* Now we know the specialization, compute access previously
11194      deferred.  */
11195   push_access_scope (fndecl);
11196   perform_deferred_access_checks ();
11197   pop_access_scope (fndecl);
11198   pop_deferring_access_checks ();
11199
11200   /* The DECL_TI_TEMPLATE should always be the immediate parent
11201      template, not the most general template.  */
11202   DECL_TI_TEMPLATE (fndecl) = tmpl;
11203
11204   /* If we've just instantiated the main entry point for a function,
11205      instantiate all the alternate entry points as well.  We do this
11206      by cloning the instantiation of the main entry point, not by
11207      instantiating the template clones.  */
11208   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
11209     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
11210
11211   return fndecl;
11212 }
11213
11214 /* The FN is a TEMPLATE_DECL for a function.  The ARGS are the
11215    arguments that are being used when calling it.  TARGS is a vector
11216    into which the deduced template arguments are placed.
11217
11218    Return zero for success, 2 for an incomplete match that doesn't resolve
11219    all the types, and 1 for complete failure.  An error message will be
11220    printed only for an incomplete match.
11221
11222    If FN is a conversion operator, or we are trying to produce a specific
11223    specialization, RETURN_TYPE is the return type desired.
11224
11225    The EXPLICIT_TARGS are explicit template arguments provided via a
11226    template-id.
11227
11228    The parameter STRICT is one of:
11229
11230    DEDUCE_CALL:
11231      We are deducing arguments for a function call, as in
11232      [temp.deduct.call].
11233
11234    DEDUCE_CONV:
11235      We are deducing arguments for a conversion function, as in
11236      [temp.deduct.conv].
11237
11238    DEDUCE_EXACT:
11239      We are deducing arguments when doing an explicit instantiation
11240      as in [temp.explicit], when determining an explicit specialization
11241      as in [temp.expl.spec], or when taking the address of a function
11242      template, as in [temp.deduct.funcaddr].  */
11243
11244 int
11245 fn_type_unification (tree fn,
11246                      tree explicit_targs,
11247                      tree targs,
11248                      tree args,
11249                      tree return_type,
11250                      unification_kind_t strict,
11251                      int flags)
11252 {
11253   tree parms;
11254   tree fntype;
11255   int result;
11256   bool incomplete_argument_packs_p = false;
11257
11258   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
11259
11260   fntype = TREE_TYPE (fn);
11261   if (explicit_targs)
11262     {
11263       /* [temp.deduct]
11264
11265          The specified template arguments must match the template
11266          parameters in kind (i.e., type, nontype, template), and there
11267          must not be more arguments than there are parameters;
11268          otherwise type deduction fails.
11269
11270          Nontype arguments must match the types of the corresponding
11271          nontype template parameters, or must be convertible to the
11272          types of the corresponding nontype parameters as specified in
11273          _temp.arg.nontype_, otherwise type deduction fails.
11274
11275          All references in the function type of the function template
11276          to the corresponding template parameters are replaced by the
11277          specified template argument values.  If a substitution in a
11278          template parameter or in the function type of the function
11279          template results in an invalid type, type deduction fails.  */
11280       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
11281       int i, len = TREE_VEC_LENGTH (tparms);
11282       tree converted_args;
11283       bool incomplete = false;
11284
11285       if (explicit_targs == error_mark_node)
11286         return 1;
11287
11288       converted_args
11289         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
11290                                   /*require_all_args=*/false,
11291                                   /*use_default_args=*/false));
11292       if (converted_args == error_mark_node)
11293         return 1;
11294
11295       /* Substitute the explicit args into the function type.  This is
11296          necessary so that, for instance, explicitly declared function
11297          arguments can match null pointed constants.  If we were given
11298          an incomplete set of explicit args, we must not do semantic
11299          processing during substitution as we could create partial
11300          instantiations.  */
11301       for (i = 0; i < len; i++)
11302         {
11303           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
11304           bool parameter_pack = false;
11305
11306           /* Dig out the actual parm.  */
11307           if (TREE_CODE (parm) == TYPE_DECL
11308               || TREE_CODE (parm) == TEMPLATE_DECL)
11309             {
11310               parm = TREE_TYPE (parm);
11311               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
11312             }
11313           else if (TREE_CODE (parm) == PARM_DECL)
11314             {
11315               parm = DECL_INITIAL (parm);
11316               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
11317             }
11318
11319           if (parameter_pack)
11320             {
11321               int level, idx;
11322               tree targ;
11323               template_parm_level_and_index (parm, &level, &idx);
11324
11325               /* Mark the argument pack as "incomplete". We could
11326                  still deduce more arguments during unification.  */
11327               targ = TMPL_ARG (converted_args, level, idx);
11328               if (targ)
11329                 {
11330                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
11331                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
11332                     = ARGUMENT_PACK_ARGS (targ);
11333                 }
11334
11335               /* We have some incomplete argument packs.  */
11336               incomplete_argument_packs_p = true;
11337             }
11338         }
11339
11340       if (incomplete_argument_packs_p)
11341         /* Any substitution is guaranteed to be incomplete if there
11342            are incomplete argument packs, because we can still deduce
11343            more arguments.  */
11344         incomplete = 1;
11345       else
11346         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
11347
11348       processing_template_decl += incomplete;
11349       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
11350       processing_template_decl -= incomplete;
11351
11352       if (fntype == error_mark_node)
11353         return 1;
11354
11355       /* Place the explicitly specified arguments in TARGS.  */
11356       for (i = NUM_TMPL_ARGS (converted_args); i--;)
11357         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
11358     }
11359
11360   /* Never do unification on the 'this' parameter.  */
11361   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
11362
11363   if (return_type)
11364     {
11365       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
11366       args = tree_cons (NULL_TREE, return_type, args);
11367     }
11368
11369   /* We allow incomplete unification without an error message here
11370      because the standard doesn't seem to explicitly prohibit it.  Our
11371      callers must be ready to deal with unification failures in any
11372      event.  */
11373   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
11374                                   targs, parms, args, /*subr=*/0,
11375                                   strict, flags);
11376
11377   if (result == 0 && incomplete_argument_packs_p)
11378     {
11379       int i, len = NUM_TMPL_ARGS (targs);
11380
11381       /* Clear the "incomplete" flags on all argument packs.  */
11382       for (i = 0; i < len; i++)
11383         {
11384           tree arg = TREE_VEC_ELT (targs, i);
11385           if (ARGUMENT_PACK_P (arg))
11386             {
11387               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
11388               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
11389             }
11390         }
11391     }
11392
11393   if (result == 0)
11394     /* All is well so far.  Now, check:
11395
11396        [temp.deduct]
11397
11398        When all template arguments have been deduced, all uses of
11399        template parameters in nondeduced contexts are replaced with
11400        the corresponding deduced argument values.  If the
11401        substitution results in an invalid type, as described above,
11402        type deduction fails.  */
11403     if (tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE)
11404         == error_mark_node)
11405       return 1;
11406
11407   return result;
11408 }
11409
11410 /* Adjust types before performing type deduction, as described in
11411    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
11412    sections are symmetric.  PARM is the type of a function parameter
11413    or the return type of the conversion function.  ARG is the type of
11414    the argument passed to the call, or the type of the value
11415    initialized with the result of the conversion function.
11416    ARG_EXPR is the original argument expression, which may be null.  */
11417
11418 static int
11419 maybe_adjust_types_for_deduction (unification_kind_t strict,
11420                                   tree* parm,
11421                                   tree* arg,
11422                                   tree arg_expr)
11423 {
11424   int result = 0;
11425
11426   switch (strict)
11427     {
11428     case DEDUCE_CALL:
11429       break;
11430
11431     case DEDUCE_CONV:
11432       {
11433         /* Swap PARM and ARG throughout the remainder of this
11434            function; the handling is precisely symmetric since PARM
11435            will initialize ARG rather than vice versa.  */
11436         tree* temp = parm;
11437         parm = arg;
11438         arg = temp;
11439         break;
11440       }
11441
11442     case DEDUCE_EXACT:
11443       /* There is nothing to do in this case.  */
11444       return 0;
11445
11446     default:
11447       gcc_unreachable ();
11448     }
11449
11450   if (TREE_CODE (*parm) != REFERENCE_TYPE)
11451     {
11452       /* [temp.deduct.call]
11453
11454          If P is not a reference type:
11455
11456          --If A is an array type, the pointer type produced by the
11457          array-to-pointer standard conversion (_conv.array_) is
11458          used in place of A for type deduction; otherwise,
11459
11460          --If A is a function type, the pointer type produced by
11461          the function-to-pointer standard conversion
11462          (_conv.func_) is used in place of A for type deduction;
11463          otherwise,
11464
11465          --If A is a cv-qualified type, the top level
11466          cv-qualifiers of A's type are ignored for type
11467          deduction.  */
11468       if (TREE_CODE (*arg) == ARRAY_TYPE)
11469         *arg = build_pointer_type (TREE_TYPE (*arg));
11470       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
11471         *arg = build_pointer_type (*arg);
11472       else
11473         *arg = TYPE_MAIN_VARIANT (*arg);
11474     }
11475
11476   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
11477      of the form T&&, where T is a template parameter, and the argument
11478      is an lvalue, T is deduced as A& */
11479   if (TREE_CODE (*parm) == REFERENCE_TYPE
11480       && TYPE_REF_IS_RVALUE (*parm)
11481       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
11482       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
11483       && arg_expr && real_lvalue_p (arg_expr))
11484     *arg = build_reference_type (*arg);
11485
11486   /* [temp.deduct.call]
11487
11488      If P is a cv-qualified type, the top level cv-qualifiers
11489      of P's type are ignored for type deduction.  If P is a
11490      reference type, the type referred to by P is used for
11491      type deduction.  */
11492   *parm = TYPE_MAIN_VARIANT (*parm);
11493   if (TREE_CODE (*parm) == REFERENCE_TYPE)
11494     {
11495       *parm = TREE_TYPE (*parm);
11496       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
11497     }
11498
11499   /* DR 322. For conversion deduction, remove a reference type on parm
11500      too (which has been swapped into ARG).  */
11501   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
11502     *arg = TREE_TYPE (*arg);
11503
11504   return result;
11505 }
11506
11507 /* Most parms like fn_type_unification.
11508
11509    If SUBR is 1, we're being called recursively (to unify the
11510    arguments of a function or method parameter of a function
11511    template). */
11512
11513 static int
11514 type_unification_real (tree tparms,
11515                        tree targs,
11516                        tree xparms,
11517                        tree xargs,
11518                        int subr,
11519                        unification_kind_t strict,
11520                        int flags)
11521 {
11522   tree parm, arg, arg_expr;
11523   int i;
11524   int ntparms = TREE_VEC_LENGTH (tparms);
11525   int sub_strict;
11526   int saw_undeduced = 0;
11527   tree parms, args;
11528
11529   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
11530   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
11531   gcc_assert (!xargs || TREE_CODE (xargs) == TREE_LIST);
11532   gcc_assert (ntparms > 0);
11533
11534   switch (strict)
11535     {
11536     case DEDUCE_CALL:
11537       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
11538                     | UNIFY_ALLOW_DERIVED);
11539       break;
11540
11541     case DEDUCE_CONV:
11542       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
11543       break;
11544
11545     case DEDUCE_EXACT:
11546       sub_strict = UNIFY_ALLOW_NONE;
11547       break;
11548
11549     default:
11550       gcc_unreachable ();
11551     }
11552
11553  again:
11554   parms = xparms;
11555   args = xargs;
11556
11557   while (parms && parms != void_list_node
11558          && args && args != void_list_node)
11559     {
11560       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
11561         break;
11562
11563       parm = TREE_VALUE (parms);
11564       parms = TREE_CHAIN (parms);
11565       arg = TREE_VALUE (args);
11566       args = TREE_CHAIN (args);
11567       arg_expr = NULL;
11568
11569       if (arg == error_mark_node)
11570         return 1;
11571       if (arg == unknown_type_node)
11572         /* We can't deduce anything from this, but we might get all the
11573            template args from other function args.  */
11574         continue;
11575
11576       /* Conversions will be performed on a function argument that
11577          corresponds with a function parameter that contains only
11578          non-deducible template parameters and explicitly specified
11579          template parameters.  */
11580       if (!uses_template_parms (parm))
11581         {
11582           tree type;
11583
11584           if (!TYPE_P (arg))
11585             type = TREE_TYPE (arg);
11586           else
11587             type = arg;
11588
11589           if (same_type_p (parm, type))
11590             continue;
11591           if (strict != DEDUCE_EXACT
11592               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
11593                                   flags))
11594             continue;
11595
11596           return 1;
11597         }
11598
11599       if (!TYPE_P (arg))
11600         {
11601           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
11602           if (type_unknown_p (arg))
11603             {
11604               /* [temp.deduct.type] 
11605
11606                  A template-argument can be deduced from a pointer to
11607                  function or pointer to member function argument if
11608                  the set of overloaded functions does not contain
11609                  function templates and at most one of a set of
11610                  overloaded functions provides a unique match.  */
11611               if (resolve_overloaded_unification
11612                   (tparms, targs, parm, arg, strict, sub_strict))
11613                 continue;
11614
11615               return 1;
11616             }
11617           arg_expr = arg;
11618           arg = unlowered_expr_type (arg);
11619           if (arg == error_mark_node)
11620             return 1;
11621         }
11622
11623       {
11624         int arg_strict = sub_strict;
11625
11626         if (!subr)
11627           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
11628                                                           arg_expr);
11629
11630         if (unify (tparms, targs, parm, arg, arg_strict))
11631           return 1;
11632       }
11633     }
11634
11635
11636   if (parms 
11637       && parms != void_list_node
11638       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
11639     {
11640       /* Unify the remaining arguments with the pack expansion type.  */
11641       tree argvec;
11642       tree parmvec = make_tree_vec (1);
11643       int len = 0;
11644       tree t;
11645
11646       /* Count the number of arguments that remain.  */
11647       for (t = args; t && t != void_list_node; t = TREE_CHAIN (t))
11648         len++;
11649         
11650       /* Allocate a TREE_VEC and copy in all of the arguments */ 
11651       argvec = make_tree_vec (len);
11652       for (i = 0; args && args != void_list_node; args = TREE_CHAIN (args))
11653         {
11654           TREE_VEC_ELT (argvec, i) = TREE_VALUE (args);
11655           ++i;
11656         }
11657
11658       /* Copy the parameter into parmvec.  */
11659       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
11660       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
11661                                 /*call_args_p=*/true, /*subr=*/subr))
11662         return 1;
11663
11664       /* Advance to the end of the list of parameters.  */
11665       parms = TREE_CHAIN (parms);
11666     }
11667
11668   /* Fail if we've reached the end of the parm list, and more args
11669      are present, and the parm list isn't variadic.  */
11670   if (args && args != void_list_node && parms == void_list_node)
11671     return 1;
11672   /* Fail if parms are left and they don't have default values.  */
11673   if (parms && parms != void_list_node
11674       && TREE_PURPOSE (parms) == NULL_TREE)
11675     return 1;
11676
11677   if (!subr)
11678     for (i = 0; i < ntparms; i++)
11679       if (!TREE_VEC_ELT (targs, i))
11680         {
11681           tree tparm;
11682
11683           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
11684             continue;
11685
11686           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
11687
11688           /* If this is an undeduced nontype parameter that depends on
11689              a type parameter, try another pass; its type may have been
11690              deduced from a later argument than the one from which
11691              this parameter can be deduced.  */
11692           if (TREE_CODE (tparm) == PARM_DECL
11693               && uses_template_parms (TREE_TYPE (tparm))
11694               && !saw_undeduced++)
11695             goto again;
11696
11697           /* Core issue #226 (C++0x) [temp.deduct]:
11698
11699                If a template argument has not been deduced, its
11700                default template argument, if any, is used. 
11701
11702              When we are in C++98 mode, TREE_PURPOSE will either
11703              be NULL_TREE or ERROR_MARK_NODE, so we do not need
11704              to explicitly check cxx_dialect here.  */
11705           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
11706             {
11707               tree arg = tsubst (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)), 
11708                                  targs, tf_none, NULL_TREE);
11709               if (arg == error_mark_node)
11710                 return 1;
11711               else
11712                 {
11713                   TREE_VEC_ELT (targs, i) = arg;
11714                   continue;
11715                 }
11716             }
11717
11718           /* If the type parameter is a parameter pack, then it will
11719              be deduced to an empty parameter pack.  */
11720           if (template_parameter_pack_p (tparm))
11721             {
11722               tree arg;
11723
11724               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
11725                 {
11726                   arg = make_node (NONTYPE_ARGUMENT_PACK);
11727                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
11728                   TREE_CONSTANT (arg) = 1;
11729                 }
11730               else
11731                 arg = make_node (TYPE_ARGUMENT_PACK);
11732
11733               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
11734
11735               TREE_VEC_ELT (targs, i) = arg;
11736               continue;
11737             }
11738
11739           return 2;
11740         }
11741
11742   return 0;
11743 }
11744
11745 /* Subroutine of type_unification_real.  Args are like the variables
11746    at the call site.  ARG is an overloaded function (or template-id);
11747    we try deducing template args from each of the overloads, and if
11748    only one succeeds, we go with that.  Modifies TARGS and returns
11749    true on success.  */
11750
11751 static bool
11752 resolve_overloaded_unification (tree tparms,
11753                                 tree targs,
11754                                 tree parm,
11755                                 tree arg,
11756                                 unification_kind_t strict,
11757                                 int sub_strict)
11758 {
11759   tree tempargs = copy_node (targs);
11760   int good = 0;
11761   bool addr_p;
11762
11763   if (TREE_CODE (arg) == ADDR_EXPR)
11764     {
11765       arg = TREE_OPERAND (arg, 0);
11766       addr_p = true;
11767     }
11768   else
11769     addr_p = false;
11770
11771   if (TREE_CODE (arg) == COMPONENT_REF)
11772     /* Handle `&x' where `x' is some static or non-static member
11773        function name.  */
11774     arg = TREE_OPERAND (arg, 1);
11775
11776   if (TREE_CODE (arg) == OFFSET_REF)
11777     arg = TREE_OPERAND (arg, 1);
11778
11779   /* Strip baselink information.  */
11780   if (BASELINK_P (arg))
11781     arg = BASELINK_FUNCTIONS (arg);
11782
11783   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
11784     {
11785       /* If we got some explicit template args, we need to plug them into
11786          the affected templates before we try to unify, in case the
11787          explicit args will completely resolve the templates in question.  */
11788
11789       tree expl_subargs = TREE_OPERAND (arg, 1);
11790       arg = TREE_OPERAND (arg, 0);
11791
11792       for (; arg; arg = OVL_NEXT (arg))
11793         {
11794           tree fn = OVL_CURRENT (arg);
11795           tree subargs, elem;
11796
11797           if (TREE_CODE (fn) != TEMPLATE_DECL)
11798             continue;
11799
11800           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
11801                                   expl_subargs, /*check_ret=*/false);
11802           if (subargs)
11803             {
11804               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
11805               good += try_one_overload (tparms, targs, tempargs, parm,
11806                                         elem, strict, sub_strict, addr_p);
11807             }
11808         }
11809     }
11810   else if (TREE_CODE (arg) != OVERLOAD
11811            && TREE_CODE (arg) != FUNCTION_DECL)
11812     /* If ARG is, for example, "(0, &f)" then its type will be unknown
11813        -- but the deduction does not succeed because the expression is
11814        not just the function on its own.  */
11815     return false;
11816   else
11817     for (; arg; arg = OVL_NEXT (arg))
11818       good += try_one_overload (tparms, targs, tempargs, parm,
11819                                 TREE_TYPE (OVL_CURRENT (arg)),
11820                                 strict, sub_strict, addr_p);
11821
11822   /* [temp.deduct.type] A template-argument can be deduced from a pointer
11823      to function or pointer to member function argument if the set of
11824      overloaded functions does not contain function templates and at most
11825      one of a set of overloaded functions provides a unique match.
11826
11827      So if we found multiple possibilities, we return success but don't
11828      deduce anything.  */
11829
11830   if (good == 1)
11831     {
11832       int i = TREE_VEC_LENGTH (targs);
11833       for (; i--; )
11834         if (TREE_VEC_ELT (tempargs, i))
11835           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
11836     }
11837   if (good)
11838     return true;
11839
11840   return false;
11841 }
11842
11843 /* Subroutine of resolve_overloaded_unification; does deduction for a single
11844    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
11845    different overloads deduce different arguments for a given parm.
11846    ADDR_P is true if the expression for which deduction is being
11847    performed was of the form "& fn" rather than simply "fn".
11848
11849    Returns 1 on success.  */
11850
11851 static int
11852 try_one_overload (tree tparms,
11853                   tree orig_targs,
11854                   tree targs,
11855                   tree parm,
11856                   tree arg,
11857                   unification_kind_t strict,
11858                   int sub_strict,
11859                   bool addr_p)
11860 {
11861   int nargs;
11862   tree tempargs;
11863   int i;
11864
11865   /* [temp.deduct.type] A template-argument can be deduced from a pointer
11866      to function or pointer to member function argument if the set of
11867      overloaded functions does not contain function templates and at most
11868      one of a set of overloaded functions provides a unique match.
11869
11870      So if this is a template, just return success.  */
11871
11872   if (uses_template_parms (arg))
11873     return 1;
11874
11875   if (TREE_CODE (arg) == METHOD_TYPE)
11876     arg = build_ptrmemfunc_type (build_pointer_type (arg));
11877   else if (addr_p)
11878     arg = build_pointer_type (arg);
11879
11880   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
11881
11882   /* We don't copy orig_targs for this because if we have already deduced
11883      some template args from previous args, unify would complain when we
11884      try to deduce a template parameter for the same argument, even though
11885      there isn't really a conflict.  */
11886   nargs = TREE_VEC_LENGTH (targs);
11887   tempargs = make_tree_vec (nargs);
11888
11889   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
11890     return 0;
11891
11892   /* First make sure we didn't deduce anything that conflicts with
11893      explicitly specified args.  */
11894   for (i = nargs; i--; )
11895     {
11896       tree elt = TREE_VEC_ELT (tempargs, i);
11897       tree oldelt = TREE_VEC_ELT (orig_targs, i);
11898
11899       if (!elt)
11900         /*NOP*/;
11901       else if (uses_template_parms (elt))
11902         /* Since we're unifying against ourselves, we will fill in
11903            template args used in the function parm list with our own
11904            template parms.  Discard them.  */
11905         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
11906       else if (oldelt && !template_args_equal (oldelt, elt))
11907         return 0;
11908     }
11909
11910   for (i = nargs; i--; )
11911     {
11912       tree elt = TREE_VEC_ELT (tempargs, i);
11913
11914       if (elt)
11915         TREE_VEC_ELT (targs, i) = elt;
11916     }
11917
11918   return 1;
11919 }
11920
11921 /* PARM is a template class (perhaps with unbound template
11922    parameters).  ARG is a fully instantiated type.  If ARG can be
11923    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
11924    TARGS are as for unify.  */
11925
11926 static tree
11927 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
11928 {
11929   tree copy_of_targs;
11930
11931   if (!CLASSTYPE_TEMPLATE_INFO (arg)
11932       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
11933           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
11934     return NULL_TREE;
11935
11936   /* We need to make a new template argument vector for the call to
11937      unify.  If we used TARGS, we'd clutter it up with the result of
11938      the attempted unification, even if this class didn't work out.
11939      We also don't want to commit ourselves to all the unifications
11940      we've already done, since unification is supposed to be done on
11941      an argument-by-argument basis.  In other words, consider the
11942      following pathological case:
11943
11944        template <int I, int J, int K>
11945        struct S {};
11946
11947        template <int I, int J>
11948        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
11949
11950        template <int I, int J, int K>
11951        void f(S<I, J, K>, S<I, I, I>);
11952
11953        void g() {
11954          S<0, 0, 0> s0;
11955          S<0, 1, 2> s2;
11956
11957          f(s0, s2);
11958        }
11959
11960      Now, by the time we consider the unification involving `s2', we
11961      already know that we must have `f<0, 0, 0>'.  But, even though
11962      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
11963      because there are two ways to unify base classes of S<0, 1, 2>
11964      with S<I, I, I>.  If we kept the already deduced knowledge, we
11965      would reject the possibility I=1.  */
11966   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
11967
11968   /* If unification failed, we're done.  */
11969   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
11970              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
11971     return NULL_TREE;
11972
11973   return arg;
11974 }
11975
11976 /* Given a template type PARM and a class type ARG, find the unique
11977    base type in ARG that is an instance of PARM.  We do not examine
11978    ARG itself; only its base-classes.  If there is not exactly one
11979    appropriate base class, return NULL_TREE.  PARM may be the type of
11980    a partial specialization, as well as a plain template type.  Used
11981    by unify.  */
11982
11983 static tree
11984 get_template_base (tree tparms, tree targs, tree parm, tree arg)
11985 {
11986   tree rval = NULL_TREE;
11987   tree binfo;
11988
11989   gcc_assert (IS_AGGR_TYPE_CODE (TREE_CODE (arg)));
11990
11991   binfo = TYPE_BINFO (complete_type (arg));
11992   if (!binfo)
11993     /* The type could not be completed.  */
11994     return NULL_TREE;
11995
11996   /* Walk in inheritance graph order.  The search order is not
11997      important, and this avoids multiple walks of virtual bases.  */
11998   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
11999     {
12000       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
12001
12002       if (r)
12003         {
12004           /* If there is more than one satisfactory baseclass, then:
12005
12006                [temp.deduct.call]
12007
12008               If they yield more than one possible deduced A, the type
12009               deduction fails.
12010
12011              applies.  */
12012           if (rval && !same_type_p (r, rval))
12013             return NULL_TREE;
12014
12015           rval = r;
12016         }
12017     }
12018
12019   return rval;
12020 }
12021
12022 /* Returns the level of DECL, which declares a template parameter.  */
12023
12024 static int
12025 template_decl_level (tree decl)
12026 {
12027   switch (TREE_CODE (decl))
12028     {
12029     case TYPE_DECL:
12030     case TEMPLATE_DECL:
12031       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
12032
12033     case PARM_DECL:
12034       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
12035
12036     default:
12037       gcc_unreachable ();
12038     }
12039   return 0;
12040 }
12041
12042 /* Decide whether ARG can be unified with PARM, considering only the
12043    cv-qualifiers of each type, given STRICT as documented for unify.
12044    Returns nonzero iff the unification is OK on that basis.  */
12045
12046 static int
12047 check_cv_quals_for_unify (int strict, tree arg, tree parm)
12048 {
12049   int arg_quals = cp_type_quals (arg);
12050   int parm_quals = cp_type_quals (parm);
12051
12052   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
12053       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
12054     {
12055       /*  Although a CVR qualifier is ignored when being applied to a
12056           substituted template parameter ([8.3.2]/1 for example), that
12057           does not apply during deduction [14.8.2.4]/1, (even though
12058           that is not explicitly mentioned, [14.8.2.4]/9 indicates
12059           this).  Except when we're allowing additional CV qualifiers
12060           at the outer level [14.8.2.1]/3,1st bullet.  */
12061       if ((TREE_CODE (arg) == REFERENCE_TYPE
12062            || TREE_CODE (arg) == FUNCTION_TYPE
12063            || TREE_CODE (arg) == METHOD_TYPE)
12064           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
12065         return 0;
12066
12067       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
12068           && (parm_quals & TYPE_QUAL_RESTRICT))
12069         return 0;
12070     }
12071
12072   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
12073       && (arg_quals & parm_quals) != parm_quals)
12074     return 0;
12075
12076   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
12077       && (parm_quals & arg_quals) != arg_quals)
12078     return 0;
12079
12080   return 1;
12081 }
12082
12083 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
12084 void 
12085 template_parm_level_and_index (tree parm, int* level, int* index)
12086 {
12087   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
12088       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
12089       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
12090     {
12091       *index = TEMPLATE_TYPE_IDX (parm);
12092       *level = TEMPLATE_TYPE_LEVEL (parm);
12093     }
12094   else
12095     {
12096       *index = TEMPLATE_PARM_IDX (parm);
12097       *level = TEMPLATE_PARM_LEVEL (parm);
12098     }
12099 }
12100
12101 /* Unifies the remaining arguments in PACKED_ARGS with the pack
12102    expansion at the end of PACKED_PARMS. Returns 0 if the type
12103    deduction succeeds, 1 otherwise. STRICT is the same as in
12104    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
12105    call argument list. We'll need to adjust the arguments to make them
12106    types. SUBR tells us if this is from a recursive call to
12107    type_unification_real.  */
12108 int
12109 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
12110                       tree packed_args, int strict, bool call_args_p,
12111                       bool subr)
12112 {
12113   tree parm 
12114     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
12115   tree pattern = PACK_EXPANSION_PATTERN (parm);
12116   tree pack, packs = NULL_TREE;
12117   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
12118   int len = TREE_VEC_LENGTH (packed_args);
12119
12120   /* Determine the parameter packs we will be deducing from the
12121      pattern, and record their current deductions.  */
12122   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
12123        pack; pack = TREE_CHAIN (pack))
12124     {
12125       tree parm_pack = TREE_VALUE (pack);
12126       int idx, level;
12127
12128       /* Determine the index and level of this parameter pack.  */
12129       template_parm_level_and_index (parm_pack, &level, &idx);
12130
12131       /* Keep track of the parameter packs and their corresponding
12132          argument packs.  */
12133       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
12134       TREE_TYPE (packs) = make_tree_vec (len - start);
12135     }
12136   
12137   /* Loop through all of the arguments that have not yet been
12138      unified and unify each with the pattern.  */
12139   for (i = start; i < len; i++)
12140     {
12141       tree parm = pattern;
12142
12143       /* For each parameter pack, clear out the deduced value so that
12144          we can deduce it again.  */
12145       for (pack = packs; pack; pack = TREE_CHAIN (pack))
12146         {
12147           int idx, level;
12148           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12149
12150           TMPL_ARG (targs, level, idx) = NULL_TREE;
12151         }
12152
12153       /* Unify the pattern with the current argument.  */
12154       {
12155         tree arg = TREE_VEC_ELT (packed_args, i);
12156         int arg_strict = strict;
12157         bool skip_arg_p = false;
12158
12159         if (call_args_p)
12160           {
12161             int sub_strict;
12162
12163             /* This mirrors what we do in type_unification_real.  */
12164             switch (strict)
12165               {
12166               case DEDUCE_CALL:
12167                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
12168                               | UNIFY_ALLOW_MORE_CV_QUAL
12169                               | UNIFY_ALLOW_DERIVED);
12170                 break;
12171                 
12172               case DEDUCE_CONV:
12173                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
12174                 break;
12175                 
12176               case DEDUCE_EXACT:
12177                 sub_strict = UNIFY_ALLOW_NONE;
12178                 break;
12179                 
12180               default:
12181                 gcc_unreachable ();
12182               }
12183
12184             if (!TYPE_P (arg))
12185               {
12186                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
12187                 if (type_unknown_p (arg))
12188                   {
12189                     /* [temp.deduct.type] A template-argument can be
12190                        deduced from a pointer to function or pointer
12191                        to member function argument if the set of
12192                        overloaded functions does not contain function
12193                        templates and at most one of a set of
12194                        overloaded functions provides a unique
12195                        match.  */
12196
12197                     if (resolve_overloaded_unification
12198                         (tparms, targs, parm, arg, strict, sub_strict)
12199                         != 0)
12200                       return 1;
12201                     skip_arg_p = true;
12202                   }
12203
12204                 if (!skip_arg_p)
12205                   {
12206                     arg = TREE_TYPE (arg);
12207                     if (arg == error_mark_node)
12208                       return 1;
12209                   }
12210               }
12211       
12212             arg_strict = sub_strict;
12213
12214             if (!subr)
12215               arg_strict |= 
12216                 maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
12217           }
12218
12219         if (!skip_arg_p)
12220           {
12221             if (unify (tparms, targs, parm, arg, arg_strict))
12222               return 1;
12223           }
12224       }
12225
12226       /* For each parameter pack, collect the deduced value.  */
12227       for (pack = packs; pack; pack = TREE_CHAIN (pack))
12228         {
12229           int idx, level;
12230           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12231
12232           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
12233             TMPL_ARG (targs, level, idx);
12234         }
12235     }
12236
12237   /* Verify that the results of unification with the parameter packs
12238      produce results consistent with what we've seen before, and make
12239      the deduced argument packs available.  */
12240   for (pack = packs; pack; pack = TREE_CHAIN (pack))
12241     {
12242       tree old_pack = TREE_VALUE (pack);
12243       tree new_args = TREE_TYPE (pack);
12244
12245       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
12246         {
12247           /* Prepend the explicit arguments onto NEW_ARGS.  */
12248           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
12249           tree old_args = new_args;
12250           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
12251           int len = explicit_len + TREE_VEC_LENGTH (old_args);
12252
12253           /* Copy the explicit arguments.  */
12254           new_args = make_tree_vec (len);
12255           for (i = 0; i < explicit_len; i++)
12256             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
12257
12258           /* Copy the deduced arguments.  */
12259           for (; i < len; i++)
12260             TREE_VEC_ELT (new_args, i) =
12261               TREE_VEC_ELT (old_args, i - explicit_len);
12262         }
12263
12264       if (!old_pack)
12265         {
12266           tree result;
12267           int idx, level;
12268           
12269           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12270
12271           /* Build the deduced *_ARGUMENT_PACK.  */
12272           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
12273             {
12274               result = make_node (NONTYPE_ARGUMENT_PACK);
12275               TREE_TYPE (result) = 
12276                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
12277               TREE_CONSTANT (result) = 1;
12278             }
12279           else
12280             result = make_node (TYPE_ARGUMENT_PACK);
12281
12282           SET_ARGUMENT_PACK_ARGS (result, new_args);
12283
12284           /* Note the deduced argument packs for this parameter
12285              pack.  */
12286           TMPL_ARG (targs, level, idx) = result;
12287         }
12288       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
12289                && (ARGUMENT_PACK_ARGS (old_pack) 
12290                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
12291         {
12292           /* We only had the explicitly-provided arguments before, but
12293              now we have a complete set of arguments.  */
12294           int idx, level;
12295           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
12296           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12297
12298           /* Keep the original deduced argument pack.  */
12299           TMPL_ARG (targs, level, idx) = old_pack;
12300
12301           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
12302           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
12303           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
12304         }
12305       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
12306                                     new_args))
12307         /* Inconsistent unification of this parameter pack.  */
12308         return 1;
12309       else
12310         {
12311           int idx, level;
12312           
12313           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12314
12315           /* Keep the original deduced argument pack.  */
12316           TMPL_ARG (targs, level, idx) = old_pack;
12317         }
12318     }
12319
12320   return 0;
12321 }
12322
12323 /* Deduce the value of template parameters.  TPARMS is the (innermost)
12324    set of template parameters to a template.  TARGS is the bindings
12325    for those template parameters, as determined thus far; TARGS may
12326    include template arguments for outer levels of template parameters
12327    as well.  PARM is a parameter to a template function, or a
12328    subcomponent of that parameter; ARG is the corresponding argument.
12329    This function attempts to match PARM with ARG in a manner
12330    consistent with the existing assignments in TARGS.  If more values
12331    are deduced, then TARGS is updated.
12332
12333    Returns 0 if the type deduction succeeds, 1 otherwise.  The
12334    parameter STRICT is a bitwise or of the following flags:
12335
12336      UNIFY_ALLOW_NONE:
12337        Require an exact match between PARM and ARG.
12338      UNIFY_ALLOW_MORE_CV_QUAL:
12339        Allow the deduced ARG to be more cv-qualified (by qualification
12340        conversion) than ARG.
12341      UNIFY_ALLOW_LESS_CV_QUAL:
12342        Allow the deduced ARG to be less cv-qualified than ARG.
12343      UNIFY_ALLOW_DERIVED:
12344        Allow the deduced ARG to be a template base class of ARG,
12345        or a pointer to a template base class of the type pointed to by
12346        ARG.
12347      UNIFY_ALLOW_INTEGER:
12348        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
12349        case for more information.
12350      UNIFY_ALLOW_OUTER_LEVEL:
12351        This is the outermost level of a deduction. Used to determine validity
12352        of qualification conversions. A valid qualification conversion must
12353        have const qualified pointers leading up to the inner type which
12354        requires additional CV quals, except at the outer level, where const
12355        is not required [conv.qual]. It would be normal to set this flag in
12356        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
12357      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
12358        This is the outermost level of a deduction, and PARM can be more CV
12359        qualified at this point.
12360      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
12361        This is the outermost level of a deduction, and PARM can be less CV
12362        qualified at this point.  */
12363
12364 static int
12365 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
12366 {
12367   int idx;
12368   tree targ;
12369   tree tparm;
12370   int strict_in = strict;
12371
12372   /* I don't think this will do the right thing with respect to types.
12373      But the only case I've seen it in so far has been array bounds, where
12374      signedness is the only information lost, and I think that will be
12375      okay.  */
12376   while (TREE_CODE (parm) == NOP_EXPR)
12377     parm = TREE_OPERAND (parm, 0);
12378
12379   if (arg == error_mark_node)
12380     return 1;
12381   if (arg == unknown_type_node)
12382     /* We can't deduce anything from this, but we might get all the
12383        template args from other function args.  */
12384     return 0;
12385
12386   /* If PARM uses template parameters, then we can't bail out here,
12387      even if ARG == PARM, since we won't record unifications for the
12388      template parameters.  We might need them if we're trying to
12389      figure out which of two things is more specialized.  */
12390   if (arg == parm && !uses_template_parms (parm))
12391     return 0;
12392
12393   /* Immediately reject some pairs that won't unify because of
12394      cv-qualification mismatches.  */
12395   if (TREE_CODE (arg) == TREE_CODE (parm)
12396       && TYPE_P (arg)
12397       /* It is the elements of the array which hold the cv quals of an array
12398          type, and the elements might be template type parms. We'll check
12399          when we recurse.  */
12400       && TREE_CODE (arg) != ARRAY_TYPE
12401       /* We check the cv-qualifiers when unifying with template type
12402          parameters below.  We want to allow ARG `const T' to unify with
12403          PARM `T' for example, when computing which of two templates
12404          is more specialized, for example.  */
12405       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
12406       && !check_cv_quals_for_unify (strict_in, arg, parm))
12407     return 1;
12408
12409   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
12410       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
12411     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
12412   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
12413   strict &= ~UNIFY_ALLOW_DERIVED;
12414   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
12415   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
12416
12417   switch (TREE_CODE (parm))
12418     {
12419     case TYPENAME_TYPE:
12420     case SCOPE_REF:
12421     case UNBOUND_CLASS_TEMPLATE:
12422       /* In a type which contains a nested-name-specifier, template
12423          argument values cannot be deduced for template parameters used
12424          within the nested-name-specifier.  */
12425       return 0;
12426
12427     case TEMPLATE_TYPE_PARM:
12428     case TEMPLATE_TEMPLATE_PARM:
12429     case BOUND_TEMPLATE_TEMPLATE_PARM:
12430       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
12431       if (tparm == error_mark_node)
12432         return 1;
12433
12434       if (TEMPLATE_TYPE_LEVEL (parm)
12435           != template_decl_level (tparm))
12436         /* The PARM is not one we're trying to unify.  Just check
12437            to see if it matches ARG.  */
12438         return (TREE_CODE (arg) == TREE_CODE (parm)
12439                 && same_type_p (parm, arg)) ? 0 : 1;
12440       idx = TEMPLATE_TYPE_IDX (parm);
12441       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
12442       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
12443
12444       /* Check for mixed types and values.  */
12445       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
12446            && TREE_CODE (tparm) != TYPE_DECL)
12447           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
12448               && TREE_CODE (tparm) != TEMPLATE_DECL))
12449         return 1;
12450
12451       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
12452         {
12453           /* ARG must be constructed from a template class or a template
12454              template parameter.  */
12455           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
12456               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
12457             return 1;
12458
12459           {
12460             tree parmvec = TYPE_TI_ARGS (parm);
12461             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
12462             tree argtmplvec
12463               = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_TI_TEMPLATE (arg));
12464             int i;
12465
12466             /* The resolution to DR150 makes clear that default
12467                arguments for an N-argument may not be used to bind T
12468                to a template template parameter with fewer than N
12469                parameters.  It is not safe to permit the binding of
12470                default arguments as an extension, as that may change
12471                the meaning of a conforming program.  Consider:
12472
12473                   struct Dense { static const unsigned int dim = 1; };
12474
12475                   template <template <typename> class View,
12476                             typename Block>
12477                   void operator+(float, View<Block> const&);
12478
12479                   template <typename Block,
12480                             unsigned int Dim = Block::dim>
12481                   struct Lvalue_proxy { operator float() const; };
12482
12483                   void
12484                   test_1d (void) {
12485                     Lvalue_proxy<Dense> p;
12486                     float b;
12487                     b + p;
12488                   }
12489
12490               Here, if Lvalue_proxy is permitted to bind to View, then
12491               the global operator+ will be used; if they are not, the
12492               Lvalue_proxy will be converted to float.  */
12493             if (coerce_template_parms (argtmplvec, parmvec,
12494                                        TYPE_TI_TEMPLATE (parm),
12495                                        tf_none,
12496                                        /*require_all_args=*/true,
12497                                        /*use_default_args=*/false)
12498                 == error_mark_node)
12499               return 1;
12500
12501             /* Deduce arguments T, i from TT<T> or TT<i>.
12502                We check each element of PARMVEC and ARGVEC individually
12503                rather than the whole TREE_VEC since they can have
12504                different number of elements.  */
12505
12506             for (i = 0; i < TREE_VEC_LENGTH (parmvec); ++i)
12507               {
12508                 if (unify (tparms, targs,
12509                            TREE_VEC_ELT (parmvec, i),
12510                            TREE_VEC_ELT (argvec, i),
12511                            UNIFY_ALLOW_NONE))
12512                   return 1;
12513               }
12514           }
12515           arg = TYPE_TI_TEMPLATE (arg);
12516
12517           /* Fall through to deduce template name.  */
12518         }
12519
12520       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
12521           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
12522         {
12523           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
12524
12525           /* Simple cases: Value already set, does match or doesn't.  */
12526           if (targ != NULL_TREE && template_args_equal (targ, arg))
12527             return 0;
12528           else if (targ)
12529             return 1;
12530         }
12531       else
12532         {
12533           /* If PARM is `const T' and ARG is only `int', we don't have
12534              a match unless we are allowing additional qualification.
12535              If ARG is `const int' and PARM is just `T' that's OK;
12536              that binds `const int' to `T'.  */
12537           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
12538                                          arg, parm))
12539             return 1;
12540
12541           /* Consider the case where ARG is `const volatile int' and
12542              PARM is `const T'.  Then, T should be `volatile int'.  */
12543           arg = cp_build_qualified_type_real
12544             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
12545           if (arg == error_mark_node)
12546             return 1;
12547
12548           /* Simple cases: Value already set, does match or doesn't.  */
12549           if (targ != NULL_TREE && same_type_p (targ, arg))
12550             return 0;
12551           else if (targ)
12552             return 1;
12553
12554           /* Make sure that ARG is not a variable-sized array.  (Note
12555              that were talking about variable-sized arrays (like
12556              `int[n]'), rather than arrays of unknown size (like
12557              `int[]').)  We'll get very confused by such a type since
12558              the bound of the array will not be computable in an
12559              instantiation.  Besides, such types are not allowed in
12560              ISO C++, so we can do as we please here.  */
12561           if (variably_modified_type_p (arg, NULL_TREE))
12562             return 1;
12563         }
12564
12565       /* If ARG is a parameter pack or an expansion, we cannot unify
12566          against it unless PARM is also a parameter pack.  */
12567       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
12568           && !template_parameter_pack_p (parm))
12569         return 1;
12570
12571       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
12572       return 0;
12573
12574     case TEMPLATE_PARM_INDEX:
12575       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
12576       if (tparm == error_mark_node)
12577         return 1;
12578
12579       if (TEMPLATE_PARM_LEVEL (parm)
12580           != template_decl_level (tparm))
12581         /* The PARM is not one we're trying to unify.  Just check
12582            to see if it matches ARG.  */
12583         return !(TREE_CODE (arg) == TREE_CODE (parm)
12584                  && cp_tree_equal (parm, arg));
12585
12586       idx = TEMPLATE_PARM_IDX (parm);
12587       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
12588
12589       if (targ)
12590         return !cp_tree_equal (targ, arg);
12591
12592       /* [temp.deduct.type] If, in the declaration of a function template
12593          with a non-type template-parameter, the non-type
12594          template-parameter is used in an expression in the function
12595          parameter-list and, if the corresponding template-argument is
12596          deduced, the template-argument type shall match the type of the
12597          template-parameter exactly, except that a template-argument
12598          deduced from an array bound may be of any integral type.
12599          The non-type parameter might use already deduced type parameters.  */
12600       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
12601       if (!TREE_TYPE (arg))
12602         /* Template-parameter dependent expression.  Just accept it for now.
12603            It will later be processed in convert_template_argument.  */
12604         ;
12605       else if (same_type_p (TREE_TYPE (arg), tparm))
12606         /* OK */;
12607       else if ((strict & UNIFY_ALLOW_INTEGER)
12608                && (TREE_CODE (tparm) == INTEGER_TYPE
12609                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
12610         /* Convert the ARG to the type of PARM; the deduced non-type
12611            template argument must exactly match the types of the
12612            corresponding parameter.  */
12613         arg = fold (build_nop (TREE_TYPE (parm), arg));
12614       else if (uses_template_parms (tparm))
12615         /* We haven't deduced the type of this parameter yet.  Try again
12616            later.  */
12617         return 0;
12618       else
12619         return 1;
12620
12621       /* If ARG is a parameter pack or an expansion, we cannot unify
12622          against it unless PARM is also a parameter pack.  */
12623       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
12624           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
12625         return 1;
12626
12627       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
12628       return 0;
12629
12630     case PTRMEM_CST:
12631      {
12632         /* A pointer-to-member constant can be unified only with
12633          another constant.  */
12634       if (TREE_CODE (arg) != PTRMEM_CST)
12635         return 1;
12636
12637       /* Just unify the class member. It would be useless (and possibly
12638          wrong, depending on the strict flags) to unify also
12639          PTRMEM_CST_CLASS, because we want to be sure that both parm and
12640          arg refer to the same variable, even if through different
12641          classes. For instance:
12642
12643          struct A { int x; };
12644          struct B : A { };
12645
12646          Unification of &A::x and &B::x must succeed.  */
12647       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
12648                     PTRMEM_CST_MEMBER (arg), strict);
12649      }
12650
12651     case POINTER_TYPE:
12652       {
12653         if (TREE_CODE (arg) != POINTER_TYPE)
12654           return 1;
12655
12656         /* [temp.deduct.call]
12657
12658            A can be another pointer or pointer to member type that can
12659            be converted to the deduced A via a qualification
12660            conversion (_conv.qual_).
12661
12662            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
12663            This will allow for additional cv-qualification of the
12664            pointed-to types if appropriate.  */
12665
12666         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
12667           /* The derived-to-base conversion only persists through one
12668              level of pointers.  */
12669           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
12670
12671         return unify (tparms, targs, TREE_TYPE (parm),
12672                       TREE_TYPE (arg), strict);
12673       }
12674
12675     case REFERENCE_TYPE:
12676       if (TREE_CODE (arg) != REFERENCE_TYPE)
12677         return 1;
12678       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
12679                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
12680
12681     case ARRAY_TYPE:
12682       if (TREE_CODE (arg) != ARRAY_TYPE)
12683         return 1;
12684       if ((TYPE_DOMAIN (parm) == NULL_TREE)
12685           != (TYPE_DOMAIN (arg) == NULL_TREE))
12686         return 1;
12687       if (TYPE_DOMAIN (parm) != NULL_TREE)
12688         {
12689           tree parm_max;
12690           tree arg_max;
12691           bool parm_cst;
12692           bool arg_cst;
12693
12694           /* Our representation of array types uses "N - 1" as the
12695              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
12696              not an integer constant.  We cannot unify arbitrarily
12697              complex expressions, so we eliminate the MINUS_EXPRs
12698              here.  */
12699           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
12700           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
12701           if (!parm_cst)
12702             {
12703               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
12704               parm_max = TREE_OPERAND (parm_max, 0);
12705             }
12706           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
12707           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
12708           if (!arg_cst)
12709             {
12710               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
12711                  trying to unify the type of a variable with the type
12712                  of a template parameter.  For example:
12713
12714                    template <unsigned int N>
12715                    void f (char (&) [N]);
12716                    int g(); 
12717                    void h(int i) {
12718                      char a[g(i)];
12719                      f(a); 
12720                    }
12721
12722                 Here, the type of the ARG will be "int [g(i)]", and
12723                 may be a SAVE_EXPR, etc.  */
12724               if (TREE_CODE (arg_max) != MINUS_EXPR)
12725                 return 1;
12726               arg_max = TREE_OPERAND (arg_max, 0);
12727             }
12728
12729           /* If only one of the bounds used a MINUS_EXPR, compensate
12730              by adding one to the other bound.  */
12731           if (parm_cst && !arg_cst)
12732             parm_max = fold_build2 (PLUS_EXPR,
12733                                     integer_type_node,
12734                                     parm_max,
12735                                     integer_one_node);
12736           else if (arg_cst && !parm_cst)
12737             arg_max = fold_build2 (PLUS_EXPR,
12738                                    integer_type_node,
12739                                    arg_max,
12740                                    integer_one_node);
12741
12742           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
12743             return 1;
12744         }
12745       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
12746                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
12747
12748     case REAL_TYPE:
12749     case COMPLEX_TYPE:
12750     case VECTOR_TYPE:
12751     case INTEGER_TYPE:
12752     case BOOLEAN_TYPE:
12753     case ENUMERAL_TYPE:
12754     case VOID_TYPE:
12755       if (TREE_CODE (arg) != TREE_CODE (parm))
12756         return 1;
12757
12758       /* We have already checked cv-qualification at the top of the
12759          function.  */
12760       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
12761         return 1;
12762
12763       /* As far as unification is concerned, this wins.  Later checks
12764          will invalidate it if necessary.  */
12765       return 0;
12766
12767       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
12768       /* Type INTEGER_CST can come from ordinary constant template args.  */
12769     case INTEGER_CST:
12770       while (TREE_CODE (arg) == NOP_EXPR)
12771         arg = TREE_OPERAND (arg, 0);
12772
12773       if (TREE_CODE (arg) != INTEGER_CST)
12774         return 1;
12775       return !tree_int_cst_equal (parm, arg);
12776
12777     case TREE_VEC:
12778       {
12779         int i;
12780         if (TREE_CODE (arg) != TREE_VEC)
12781           return 1;
12782         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
12783           return 1;
12784         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
12785           if (unify (tparms, targs,
12786                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
12787                      UNIFY_ALLOW_NONE))
12788             return 1;
12789         return 0;
12790       }
12791
12792     case RECORD_TYPE:
12793     case UNION_TYPE:
12794       if (TREE_CODE (arg) != TREE_CODE (parm))
12795         return 1;
12796
12797       if (TYPE_PTRMEMFUNC_P (parm))
12798         {
12799           if (!TYPE_PTRMEMFUNC_P (arg))
12800             return 1;
12801
12802           return unify (tparms, targs,
12803                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
12804                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
12805                         strict);
12806         }
12807
12808       if (CLASSTYPE_TEMPLATE_INFO (parm))
12809         {
12810           tree t = NULL_TREE;
12811
12812           if (strict_in & UNIFY_ALLOW_DERIVED)
12813             {
12814               /* First, we try to unify the PARM and ARG directly.  */
12815               t = try_class_unification (tparms, targs,
12816                                          parm, arg);
12817
12818               if (!t)
12819                 {
12820                   /* Fallback to the special case allowed in
12821                      [temp.deduct.call]:
12822
12823                        If P is a class, and P has the form
12824                        template-id, then A can be a derived class of
12825                        the deduced A.  Likewise, if P is a pointer to
12826                        a class of the form template-id, A can be a
12827                        pointer to a derived class pointed to by the
12828                        deduced A.  */
12829                   t = get_template_base (tparms, targs, parm, arg);
12830
12831                   if (!t)
12832                     return 1;
12833                 }
12834             }
12835           else if (CLASSTYPE_TEMPLATE_INFO (arg)
12836                    && (CLASSTYPE_TI_TEMPLATE (parm)
12837                        == CLASSTYPE_TI_TEMPLATE (arg)))
12838             /* Perhaps PARM is something like S<U> and ARG is S<int>.
12839                Then, we should unify `int' and `U'.  */
12840             t = arg;
12841           else
12842             /* There's no chance of unification succeeding.  */
12843             return 1;
12844
12845           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
12846                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
12847         }
12848       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
12849         return 1;
12850       return 0;
12851
12852     case METHOD_TYPE:
12853     case FUNCTION_TYPE:
12854       if (TREE_CODE (arg) != TREE_CODE (parm))
12855         return 1;
12856
12857       /* CV qualifications for methods can never be deduced, they must
12858          match exactly.  We need to check them explicitly here,
12859          because type_unification_real treats them as any other
12860          cvqualified parameter.  */
12861       if (TREE_CODE (parm) == METHOD_TYPE
12862           && (!check_cv_quals_for_unify
12863               (UNIFY_ALLOW_NONE,
12864                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
12865                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
12866         return 1;
12867
12868       if (unify (tparms, targs, TREE_TYPE (parm),
12869                  TREE_TYPE (arg), UNIFY_ALLOW_NONE))
12870         return 1;
12871       return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
12872                                     TYPE_ARG_TYPES (arg), 1, DEDUCE_EXACT,
12873                                     LOOKUP_NORMAL);
12874
12875     case OFFSET_TYPE:
12876       /* Unify a pointer to member with a pointer to member function, which
12877          deduces the type of the member as a function type. */
12878       if (TYPE_PTRMEMFUNC_P (arg))
12879         {
12880           tree method_type;
12881           tree fntype;
12882           cp_cv_quals cv_quals;
12883
12884           /* Check top-level cv qualifiers */
12885           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
12886             return 1;
12887
12888           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
12889                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
12890             return 1;
12891
12892           /* Determine the type of the function we are unifying against. */
12893           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
12894           fntype =
12895             build_function_type (TREE_TYPE (method_type),
12896                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
12897
12898           /* Extract the cv-qualifiers of the member function from the
12899              implicit object parameter and place them on the function
12900              type to be restored later. */
12901           cv_quals =
12902             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
12903           fntype = build_qualified_type (fntype, cv_quals);
12904           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
12905         }
12906
12907       if (TREE_CODE (arg) != OFFSET_TYPE)
12908         return 1;
12909       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
12910                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
12911         return 1;
12912       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
12913                     strict);
12914
12915     case CONST_DECL:
12916       if (DECL_TEMPLATE_PARM_P (parm))
12917         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
12918       if (arg != integral_constant_value (parm))
12919         return 1;
12920       return 0;
12921
12922     case FIELD_DECL:
12923     case TEMPLATE_DECL:
12924       /* Matched cases are handled by the ARG == PARM test above.  */
12925       return 1;
12926
12927     case TYPE_ARGUMENT_PACK:
12928     case NONTYPE_ARGUMENT_PACK:
12929       {
12930         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
12931         tree packed_args = ARGUMENT_PACK_ARGS (arg);
12932         int i, len = TREE_VEC_LENGTH (packed_parms);
12933         int argslen = TREE_VEC_LENGTH (packed_args);
12934         int parm_variadic_p = 0;
12935
12936         /* Check if the parameters end in a pack, making them variadic.  */
12937         if (len > 0 
12938             && PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, len - 1)))
12939           parm_variadic_p = 1;
12940
12941         /* If we don't have enough arguments to satisfy the parameters
12942            (not counting the pack expression at the end), or we have
12943            too many arguments for a parameter list that doesn't end in
12944            a pack expression, we can't unify.  */
12945         if (argslen < (len - parm_variadic_p)
12946             || (argslen > len && !parm_variadic_p))
12947           return 1;
12948
12949         /* Unify all of the parameters that precede the (optional)
12950            pack expression.  */
12951         for (i = 0; i < len - parm_variadic_p; ++i)
12952           {
12953             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
12954                        TREE_VEC_ELT (packed_args, i), strict))
12955               return 1;
12956           }
12957
12958         if (parm_variadic_p)
12959           return unify_pack_expansion (tparms, targs, 
12960                                        packed_parms, packed_args,
12961                                        strict, /*call_args_p=*/false,
12962                                        /*subr=*/false);
12963         return 0;
12964       }
12965
12966       break;
12967
12968     case TYPEOF_TYPE:
12969     case DECLTYPE_TYPE:
12970       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
12971          nodes.  */
12972       return 0;
12973
12974     default:
12975       gcc_assert (EXPR_P (parm));
12976
12977       /* We must be looking at an expression.  This can happen with
12978          something like:
12979
12980            template <int I>
12981            void foo(S<I>, S<I + 2>);
12982
12983          This is a "nondeduced context":
12984
12985            [deduct.type]
12986
12987            The nondeduced contexts are:
12988
12989            --A type that is a template-id in which one or more of
12990              the template-arguments is an expression that references
12991              a template-parameter.
12992
12993          In these cases, we assume deduction succeeded, but don't
12994          actually infer any unifications.  */
12995
12996       if (!uses_template_parms (parm)
12997           && !template_args_equal (parm, arg))
12998         return 1;
12999       else
13000         return 0;
13001     }
13002 }
13003 \f
13004 /* Note that DECL can be defined in this translation unit, if
13005    required.  */
13006
13007 static void
13008 mark_definable (tree decl)
13009 {
13010   tree clone;
13011   DECL_NOT_REALLY_EXTERN (decl) = 1;
13012   FOR_EACH_CLONE (clone, decl)
13013     DECL_NOT_REALLY_EXTERN (clone) = 1;
13014 }
13015
13016 /* Called if RESULT is explicitly instantiated, or is a member of an
13017    explicitly instantiated class.  */
13018
13019 void
13020 mark_decl_instantiated (tree result, int extern_p)
13021 {
13022   SET_DECL_EXPLICIT_INSTANTIATION (result);
13023
13024   /* If this entity has already been written out, it's too late to
13025      make any modifications.  */
13026   if (TREE_ASM_WRITTEN (result))
13027     return;
13028
13029   if (TREE_CODE (result) != FUNCTION_DECL)
13030     /* The TREE_PUBLIC flag for function declarations will have been
13031        set correctly by tsubst.  */
13032     TREE_PUBLIC (result) = 1;
13033
13034   /* This might have been set by an earlier implicit instantiation.  */
13035   DECL_COMDAT (result) = 0;
13036
13037   if (extern_p)
13038     DECL_NOT_REALLY_EXTERN (result) = 0;
13039   else
13040     {
13041       mark_definable (result);
13042       /* Always make artificials weak.  */
13043       if (DECL_ARTIFICIAL (result) && flag_weak)
13044         comdat_linkage (result);
13045       /* For WIN32 we also want to put explicit instantiations in
13046          linkonce sections.  */
13047       else if (TREE_PUBLIC (result))
13048         maybe_make_one_only (result);
13049     }
13050
13051   /* If EXTERN_P, then this function will not be emitted -- unless
13052      followed by an explicit instantiation, at which point its linkage
13053      will be adjusted.  If !EXTERN_P, then this function will be
13054      emitted here.  In neither circumstance do we want
13055      import_export_decl to adjust the linkage.  */
13056   DECL_INTERFACE_KNOWN (result) = 1;
13057 }
13058
13059 /* Given two function templates PAT1 and PAT2, return:
13060
13061    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
13062    -1 if PAT2 is more specialized than PAT1.
13063    0 if neither is more specialized.
13064
13065    LEN indicates the number of parameters we should consider
13066    (defaulted parameters should not be considered).
13067
13068    The 1998 std underspecified function template partial ordering, and
13069    DR214 addresses the issue.  We take pairs of arguments, one from
13070    each of the templates, and deduce them against each other.  One of
13071    the templates will be more specialized if all the *other*
13072    template's arguments deduce against its arguments and at least one
13073    of its arguments *does* *not* deduce against the other template's
13074    corresponding argument.  Deduction is done as for class templates.
13075    The arguments used in deduction have reference and top level cv
13076    qualifiers removed.  Iff both arguments were originally reference
13077    types *and* deduction succeeds in both directions, the template
13078    with the more cv-qualified argument wins for that pairing (if
13079    neither is more cv-qualified, they both are equal).  Unlike regular
13080    deduction, after all the arguments have been deduced in this way,
13081    we do *not* verify the deduced template argument values can be
13082    substituted into non-deduced contexts, nor do we have to verify
13083    that all template arguments have been deduced.  */
13084
13085 int
13086 more_specialized_fn (tree pat1, tree pat2, int len)
13087 {
13088   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
13089   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
13090   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
13091   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
13092   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
13093   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
13094   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
13095   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
13096   int better1 = 0;
13097   int better2 = 0;
13098
13099   /* Remove the this parameter from non-static member functions.  If
13100      one is a non-static member function and the other is not a static
13101      member function, remove the first parameter from that function
13102      also.  This situation occurs for operator functions where we
13103      locate both a member function (with this pointer) and non-member
13104      operator (with explicit first operand).  */
13105   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
13106     {
13107       len--; /* LEN is the number of significant arguments for DECL1 */
13108       args1 = TREE_CHAIN (args1);
13109       if (!DECL_STATIC_FUNCTION_P (decl2))
13110         args2 = TREE_CHAIN (args2);
13111     }
13112   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
13113     {
13114       args2 = TREE_CHAIN (args2);
13115       if (!DECL_STATIC_FUNCTION_P (decl1))
13116         {
13117           len--;
13118           args1 = TREE_CHAIN (args1);
13119         }
13120     }
13121
13122   /* If only one is a conversion operator, they are unordered.  */
13123   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
13124     return 0;
13125
13126   /* Consider the return type for a conversion function */
13127   if (DECL_CONV_FN_P (decl1))
13128     {
13129       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
13130       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
13131       len++;
13132     }
13133
13134   processing_template_decl++;
13135
13136   while (len--)
13137     {
13138       tree arg1 = TREE_VALUE (args1);
13139       tree arg2 = TREE_VALUE (args2);
13140       int deduce1, deduce2;
13141       int quals1 = -1;
13142       int quals2 = -1;
13143
13144       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
13145           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
13146         {
13147           /* When both arguments are pack expansions, we need only
13148              unify the patterns themselves.  */
13149           arg1 = PACK_EXPANSION_PATTERN (arg1);
13150           arg2 = PACK_EXPANSION_PATTERN (arg2);
13151
13152           /* This is the last comparison we need to do.  */
13153           len = 0;
13154         }
13155
13156       if (TREE_CODE (arg1) == REFERENCE_TYPE)
13157         {
13158           arg1 = TREE_TYPE (arg1);
13159           quals1 = cp_type_quals (arg1);
13160         }
13161
13162       if (TREE_CODE (arg2) == REFERENCE_TYPE)
13163         {
13164           arg2 = TREE_TYPE (arg2);
13165           quals2 = cp_type_quals (arg2);
13166         }
13167
13168       if ((quals1 < 0) != (quals2 < 0))
13169         {
13170           /* Only of the args is a reference, see if we should apply
13171              array/function pointer decay to it.  This is not part of
13172              DR214, but is, IMHO, consistent with the deduction rules
13173              for the function call itself, and with our earlier
13174              implementation of the underspecified partial ordering
13175              rules.  (nathan).  */
13176           if (quals1 >= 0)
13177             {
13178               switch (TREE_CODE (arg1))
13179                 {
13180                 case ARRAY_TYPE:
13181                   arg1 = TREE_TYPE (arg1);
13182                   /* FALLTHROUGH. */
13183                 case FUNCTION_TYPE:
13184                   arg1 = build_pointer_type (arg1);
13185                   break;
13186
13187                 default:
13188                   break;
13189                 }
13190             }
13191           else
13192             {
13193               switch (TREE_CODE (arg2))
13194                 {
13195                 case ARRAY_TYPE:
13196                   arg2 = TREE_TYPE (arg2);
13197                   /* FALLTHROUGH. */
13198                 case FUNCTION_TYPE:
13199                   arg2 = build_pointer_type (arg2);
13200                   break;
13201
13202                 default:
13203                   break;
13204                 }
13205             }
13206         }
13207
13208       arg1 = TYPE_MAIN_VARIANT (arg1);
13209       arg2 = TYPE_MAIN_VARIANT (arg2);
13210
13211       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
13212         {
13213           int i, len2 = list_length (args2);
13214           tree parmvec = make_tree_vec (1);
13215           tree argvec = make_tree_vec (len2);
13216           tree ta = args2;
13217
13218           /* Setup the parameter vector, which contains only ARG1.  */
13219           TREE_VEC_ELT (parmvec, 0) = arg1;
13220
13221           /* Setup the argument vector, which contains the remaining
13222              arguments.  */
13223           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
13224             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
13225
13226           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
13227                                            argvec, UNIFY_ALLOW_NONE, 
13228                                            /*call_args_p=*/false, 
13229                                            /*subr=*/0);
13230
13231           /* We cannot deduce in the other direction, because ARG1 is
13232              a pack expansion but ARG2 is not.  */
13233           deduce2 = 0;
13234         }
13235       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
13236         {
13237           int i, len1 = list_length (args1);
13238           tree parmvec = make_tree_vec (1);
13239           tree argvec = make_tree_vec (len1);
13240           tree ta = args1;
13241
13242           /* Setup the parameter vector, which contains only ARG1.  */
13243           TREE_VEC_ELT (parmvec, 0) = arg2;
13244
13245           /* Setup the argument vector, which contains the remaining
13246              arguments.  */
13247           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
13248             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
13249
13250           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
13251                                            argvec, UNIFY_ALLOW_NONE, 
13252                                            /*call_args_p=*/false, 
13253                                            /*subr=*/0);
13254
13255           /* We cannot deduce in the other direction, because ARG2 is
13256              a pack expansion but ARG1 is not.*/
13257           deduce1 = 0;
13258         }
13259
13260       else
13261         {
13262           /* The normal case, where neither argument is a pack
13263              expansion.  */
13264           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
13265           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
13266         }
13267
13268       if (!deduce1)
13269         better2 = -1;
13270       if (!deduce2)
13271         better1 = -1;
13272       if (better1 < 0 && better2 < 0)
13273         /* We've failed to deduce something in either direction.
13274            These must be unordered.  */
13275         break;
13276
13277       if (deduce1 && deduce2 && quals1 >= 0 && quals2 >= 0)
13278         {
13279           /* Deduces in both directions, see if quals can
13280              disambiguate.  Pretend the worse one failed to deduce. */
13281           if ((quals1 & quals2) == quals2)
13282             deduce1 = 0;
13283           if ((quals1 & quals2) == quals1)
13284             deduce2 = 0;
13285         }
13286       if (deduce1 && !deduce2 && !better2)
13287         better2 = 1;
13288       if (deduce2 && !deduce1 && !better1)
13289         better1 = 1;
13290
13291       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
13292           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
13293         /* We have already processed all of the arguments in our
13294            handing of the pack expansion type.  */
13295         len = 0;
13296
13297       args1 = TREE_CHAIN (args1);
13298       args2 = TREE_CHAIN (args2);
13299     }
13300
13301   processing_template_decl--;
13302
13303   /* All things being equal, if the next argument is a pack expansion
13304      for one function but not for the other, prefer the
13305      non-variadic function.  */
13306   if ((better1 > 0) - (better2 > 0) == 0
13307       && args1 && TREE_VALUE (args1)
13308       && args2 && TREE_VALUE (args2))
13309     {
13310       if (TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION)
13311         return TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION ? 0 : -1;
13312       else if (TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION)
13313         return 1;
13314     }
13315
13316   return (better1 > 0) - (better2 > 0);
13317 }
13318
13319 /* Determine which of two partial specializations is more specialized.
13320
13321    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
13322    to the first partial specialization.  The TREE_VALUE is the
13323    innermost set of template parameters for the partial
13324    specialization.  PAT2 is similar, but for the second template.
13325
13326    Return 1 if the first partial specialization is more specialized;
13327    -1 if the second is more specialized; 0 if neither is more
13328    specialized.
13329
13330    See [temp.class.order] for information about determining which of
13331    two templates is more specialized.  */
13332
13333 static int
13334 more_specialized_class (tree pat1, tree pat2)
13335 {
13336   tree targs;
13337   tree tmpl1, tmpl2;
13338   int winner = 0;
13339   bool any_deductions = false;
13340
13341   tmpl1 = TREE_TYPE (pat1);
13342   tmpl2 = TREE_TYPE (pat2);
13343
13344   /* Just like what happens for functions, if we are ordering between
13345      different class template specializations, we may encounter dependent
13346      types in the arguments, and we need our dependency check functions
13347      to behave correctly.  */
13348   ++processing_template_decl;
13349   targs = get_class_bindings (TREE_VALUE (pat1),
13350                               CLASSTYPE_TI_ARGS (tmpl1),
13351                               CLASSTYPE_TI_ARGS (tmpl2));
13352   if (targs)
13353     {
13354       --winner;
13355       any_deductions = true;
13356     }
13357
13358   targs = get_class_bindings (TREE_VALUE (pat2),
13359                               CLASSTYPE_TI_ARGS (tmpl2),
13360                               CLASSTYPE_TI_ARGS (tmpl1));
13361   if (targs)
13362     {
13363       ++winner;
13364       any_deductions = true;
13365     }
13366   --processing_template_decl;
13367
13368   /* In the case of a tie where at least one of the class templates
13369      has a parameter pack at the end, the template with the most
13370      non-packed parameters wins.  */
13371   if (winner == 0
13372       && any_deductions
13373       && (template_args_variadic_p (TREE_PURPOSE (pat1))
13374           || template_args_variadic_p (TREE_PURPOSE (pat2))))
13375     {
13376       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
13377       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
13378       int len1 = TREE_VEC_LENGTH (args1);
13379       int len2 = TREE_VEC_LENGTH (args2);
13380
13381       /* We don't count the pack expansion at the end.  */
13382       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
13383         --len1;
13384       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
13385         --len2;
13386
13387       if (len1 > len2)
13388         return 1;
13389       else if (len1 < len2)
13390         return -1;
13391     }
13392
13393   return winner;
13394 }
13395
13396 /* Return the template arguments that will produce the function signature
13397    DECL from the function template FN, with the explicit template
13398    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
13399    also match.  Return NULL_TREE if no satisfactory arguments could be
13400    found.  */
13401
13402 static tree
13403 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
13404 {
13405   int ntparms = DECL_NTPARMS (fn);
13406   tree targs = make_tree_vec (ntparms);
13407   tree decl_type;
13408   tree decl_arg_types;
13409
13410   /* Substitute the explicit template arguments into the type of DECL.
13411      The call to fn_type_unification will handle substitution into the
13412      FN.  */
13413   decl_type = TREE_TYPE (decl);
13414   if (explicit_args && uses_template_parms (decl_type))
13415     {
13416       tree tmpl;
13417       tree converted_args;
13418
13419       if (DECL_TEMPLATE_INFO (decl))
13420         tmpl = DECL_TI_TEMPLATE (decl);
13421       else
13422         /* We can get here for some invalid specializations.  */
13423         return NULL_TREE;
13424
13425       converted_args
13426         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
13427                                  explicit_args, NULL_TREE,
13428                                  tf_none,
13429                                  /*require_all_args=*/false,
13430                                  /*use_default_args=*/false);
13431       if (converted_args == error_mark_node)
13432         return NULL_TREE;
13433
13434       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
13435       if (decl_type == error_mark_node)
13436         return NULL_TREE;
13437     }
13438
13439   /* Never do unification on the 'this' parameter.  */
13440   decl_arg_types = skip_artificial_parms_for (decl, 
13441                                               TYPE_ARG_TYPES (decl_type));
13442
13443   if (fn_type_unification (fn, explicit_args, targs,
13444                            decl_arg_types,
13445                            (check_rettype || DECL_CONV_FN_P (fn)
13446                             ? TREE_TYPE (decl_type) : NULL_TREE),
13447                            DEDUCE_EXACT, LOOKUP_NORMAL))
13448     return NULL_TREE;
13449
13450   return targs;
13451 }
13452
13453 /* Return the innermost template arguments that, when applied to a
13454    template specialization whose innermost template parameters are
13455    TPARMS, and whose specialization arguments are PARMS, yield the
13456    ARGS.
13457
13458    For example, suppose we have:
13459
13460      template <class T, class U> struct S {};
13461      template <class T> struct S<T*, int> {};
13462
13463    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
13464    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
13465    int}.  The resulting vector will be {double}, indicating that `T'
13466    is bound to `double'.  */
13467
13468 static tree
13469 get_class_bindings (tree tparms, tree spec_args, tree args)
13470 {
13471   int i, ntparms = TREE_VEC_LENGTH (tparms);
13472   tree deduced_args;
13473   tree innermost_deduced_args;
13474
13475   innermost_deduced_args = make_tree_vec (ntparms);
13476   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
13477     {
13478       deduced_args = copy_node (args);
13479       SET_TMPL_ARGS_LEVEL (deduced_args,
13480                            TMPL_ARGS_DEPTH (deduced_args),
13481                            innermost_deduced_args);
13482     }
13483   else
13484     deduced_args = innermost_deduced_args;
13485
13486   if (unify (tparms, deduced_args,
13487              INNERMOST_TEMPLATE_ARGS (spec_args),
13488              INNERMOST_TEMPLATE_ARGS (args),
13489              UNIFY_ALLOW_NONE))
13490     return NULL_TREE;
13491
13492   for (i =  0; i < ntparms; ++i)
13493     if (! TREE_VEC_ELT (innermost_deduced_args, i))
13494       return NULL_TREE;
13495
13496   /* Verify that nondeduced template arguments agree with the type
13497      obtained from argument deduction.
13498
13499      For example:
13500
13501        struct A { typedef int X; };
13502        template <class T, class U> struct C {};
13503        template <class T> struct C<T, typename T::X> {};
13504
13505      Then with the instantiation `C<A, int>', we can deduce that
13506      `T' is `A' but unify () does not check whether `typename T::X'
13507      is `int'.  */
13508   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
13509   if (spec_args == error_mark_node
13510       /* We only need to check the innermost arguments; the other
13511          arguments will always agree.  */
13512       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
13513                               INNERMOST_TEMPLATE_ARGS (args)))
13514     return NULL_TREE;
13515
13516   return deduced_args;
13517 }
13518
13519 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
13520    Return the TREE_LIST node with the most specialized template, if
13521    any.  If there is no most specialized template, the error_mark_node
13522    is returned.
13523
13524    Note that this function does not look at, or modify, the
13525    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
13526    returned is one of the elements of INSTANTIATIONS, callers may
13527    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
13528    and retrieve it from the value returned.  */
13529
13530 tree
13531 most_specialized_instantiation (tree templates)
13532 {
13533   tree fn, champ;
13534
13535   ++processing_template_decl;
13536
13537   champ = templates;
13538   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
13539     {
13540       int fate = 0;
13541
13542       if (get_bindings (TREE_VALUE (champ),
13543                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
13544                         NULL_TREE, /*check_ret=*/false))
13545         fate--;
13546
13547       if (get_bindings (TREE_VALUE (fn),
13548                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
13549                         NULL_TREE, /*check_ret=*/false))
13550         fate++;
13551
13552       if (fate == -1)
13553         champ = fn;
13554       else if (!fate)
13555         {
13556           /* Equally specialized, move to next function.  If there
13557              is no next function, nothing's most specialized.  */
13558           fn = TREE_CHAIN (fn);
13559           champ = fn;
13560           if (!fn)
13561             break;
13562         }
13563     }
13564
13565   if (champ)
13566     /* Now verify that champ is better than everything earlier in the
13567        instantiation list.  */
13568     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
13569       if (get_bindings (TREE_VALUE (champ),
13570                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
13571                         NULL_TREE, /*check_ret=*/false)
13572           || !get_bindings (TREE_VALUE (fn),
13573                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
13574                             NULL_TREE, /*check_ret=*/false))
13575         {
13576           champ = NULL_TREE;
13577           break;
13578         }
13579
13580   processing_template_decl--;
13581
13582   if (!champ)
13583     return error_mark_node;
13584
13585   return champ;
13586 }
13587
13588 /* If DECL is a specialization of some template, return the most
13589    general such template.  Otherwise, returns NULL_TREE.
13590
13591    For example, given:
13592
13593      template <class T> struct S { template <class U> void f(U); };
13594
13595    if TMPL is `template <class U> void S<int>::f(U)' this will return
13596    the full template.  This function will not trace past partial
13597    specializations, however.  For example, given in addition:
13598
13599      template <class T> struct S<T*> { template <class U> void f(U); };
13600
13601    if TMPL is `template <class U> void S<int*>::f(U)' this will return
13602    `template <class T> template <class U> S<T*>::f(U)'.  */
13603
13604 tree
13605 most_general_template (tree decl)
13606 {
13607   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
13608      an immediate specialization.  */
13609   if (TREE_CODE (decl) == FUNCTION_DECL)
13610     {
13611       if (DECL_TEMPLATE_INFO (decl)) {
13612         decl = DECL_TI_TEMPLATE (decl);
13613
13614         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
13615            template friend.  */
13616         if (TREE_CODE (decl) != TEMPLATE_DECL)
13617           return NULL_TREE;
13618       } else
13619         return NULL_TREE;
13620     }
13621
13622   /* Look for more and more general templates.  */
13623   while (DECL_TEMPLATE_INFO (decl))
13624     {
13625       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
13626          (See cp-tree.h for details.)  */
13627       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
13628         break;
13629
13630       if (CLASS_TYPE_P (TREE_TYPE (decl))
13631           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
13632         break;
13633
13634       /* Stop if we run into an explicitly specialized class template.  */
13635       if (!DECL_NAMESPACE_SCOPE_P (decl)
13636           && DECL_CONTEXT (decl)
13637           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
13638         break;
13639
13640       decl = DECL_TI_TEMPLATE (decl);
13641     }
13642
13643   return decl;
13644 }
13645
13646 /* Return the most specialized of the class template partial
13647    specializations of TMPL which can produce TYPE, a specialization of
13648    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
13649    a _TYPE node corresponding to the partial specialization, while the
13650    TREE_PURPOSE is the set of template arguments that must be
13651    substituted into the TREE_TYPE in order to generate TYPE.
13652
13653    If the choice of partial specialization is ambiguous, a diagnostic
13654    is issued, and the error_mark_node is returned.  If there are no
13655    partial specializations of TMPL matching TYPE, then NULL_TREE is
13656    returned.  */
13657
13658 static tree
13659 most_specialized_class (tree type, tree tmpl)
13660 {
13661   tree list = NULL_TREE;
13662   tree t;
13663   tree champ;
13664   int fate;
13665   bool ambiguous_p;
13666   tree args;
13667   tree outer_args = NULL_TREE;
13668
13669   tmpl = most_general_template (tmpl);
13670   args = CLASSTYPE_TI_ARGS (type);
13671
13672   /* For determining which partial specialization to use, only the
13673      innermost args are interesting.  */
13674   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
13675     {
13676       outer_args = strip_innermost_template_args (args, 1);
13677       args = INNERMOST_TEMPLATE_ARGS (args);
13678     }
13679
13680   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
13681     {
13682       tree partial_spec_args;
13683       tree spec_args;
13684       tree parms = TREE_VALUE (t);
13685
13686       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
13687       if (outer_args)
13688         {
13689           int i;
13690
13691           ++processing_template_decl;
13692
13693           /* Discard the outer levels of args, and then substitute in the
13694              template args from the enclosing class.  */
13695           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
13696           partial_spec_args = tsubst_template_args
13697             (partial_spec_args, outer_args, tf_none, NULL_TREE);
13698
13699           /* PARMS already refers to just the innermost parms, but the
13700              template parms in partial_spec_args had their levels lowered
13701              by tsubst, so we need to do the same for the parm list.  We
13702              can't just tsubst the TREE_VEC itself, as tsubst wants to
13703              treat a TREE_VEC as an argument vector.  */
13704           parms = copy_node (parms);
13705           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
13706             TREE_VEC_ELT (parms, i) =
13707               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
13708
13709           --processing_template_decl;
13710         }
13711       spec_args = get_class_bindings (parms,
13712                                       partial_spec_args,
13713                                       args);
13714       if (spec_args)
13715         {
13716           if (outer_args)
13717             spec_args = add_to_template_args (outer_args, spec_args);
13718           list = tree_cons (spec_args, TREE_VALUE (t), list);
13719           TREE_TYPE (list) = TREE_TYPE (t);
13720         }
13721     }
13722
13723   if (! list)
13724     return NULL_TREE;
13725
13726   ambiguous_p = false;
13727   t = list;
13728   champ = t;
13729   t = TREE_CHAIN (t);
13730   for (; t; t = TREE_CHAIN (t))
13731     {
13732       fate = more_specialized_class (champ, t);
13733       if (fate == 1)
13734         ;
13735       else
13736         {
13737           if (fate == 0)
13738             {
13739               t = TREE_CHAIN (t);
13740               if (! t)
13741                 {
13742                   ambiguous_p = true;
13743                   break;
13744                 }
13745             }
13746           champ = t;
13747         }
13748     }
13749
13750   if (!ambiguous_p)
13751     for (t = list; t && t != champ; t = TREE_CHAIN (t))
13752       {
13753         fate = more_specialized_class (champ, t);
13754         if (fate != 1)
13755           {
13756             ambiguous_p = true;
13757             break;
13758           }
13759       }
13760
13761   if (ambiguous_p)
13762     {
13763       const char *str = "candidates are:";
13764       error ("ambiguous class template instantiation for %q#T", type);
13765       for (t = list; t; t = TREE_CHAIN (t))
13766         {
13767           error ("%s %+#T", str, TREE_TYPE (t));
13768           str = "               ";
13769         }
13770       return error_mark_node;
13771     }
13772
13773   return champ;
13774 }
13775
13776 /* Explicitly instantiate DECL.  */
13777
13778 void
13779 do_decl_instantiation (tree decl, tree storage)
13780 {
13781   tree result = NULL_TREE;
13782   int extern_p = 0;
13783
13784   if (!decl || decl == error_mark_node)
13785     /* An error occurred, for which grokdeclarator has already issued
13786        an appropriate message.  */
13787     return;
13788   else if (! DECL_LANG_SPECIFIC (decl))
13789     {
13790       error ("explicit instantiation of non-template %q#D", decl);
13791       return;
13792     }
13793   else if (TREE_CODE (decl) == VAR_DECL)
13794     {
13795       /* There is an asymmetry here in the way VAR_DECLs and
13796          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
13797          the latter, the DECL we get back will be marked as a
13798          template instantiation, and the appropriate
13799          DECL_TEMPLATE_INFO will be set up.  This does not happen for
13800          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
13801          should handle VAR_DECLs as it currently handles
13802          FUNCTION_DECLs.  */
13803       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
13804       if (!result || TREE_CODE (result) != VAR_DECL)
13805         {
13806           error ("no matching template for %qD found", decl);
13807           return;
13808         }
13809       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
13810         {
13811           error ("type %qT for explicit instantiation %qD does not match "
13812                  "declared type %qT", TREE_TYPE (result), decl,
13813                  TREE_TYPE (decl));
13814           return;
13815         }
13816     }
13817   else if (TREE_CODE (decl) != FUNCTION_DECL)
13818     {
13819       error ("explicit instantiation of %q#D", decl);
13820       return;
13821     }
13822   else
13823     result = decl;
13824
13825   /* Check for various error cases.  Note that if the explicit
13826      instantiation is valid the RESULT will currently be marked as an
13827      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
13828      until we get here.  */
13829
13830   if (DECL_TEMPLATE_SPECIALIZATION (result))
13831     {
13832       /* DR 259 [temp.spec].
13833
13834          Both an explicit instantiation and a declaration of an explicit
13835          specialization shall not appear in a program unless the explicit
13836          instantiation follows a declaration of the explicit specialization.
13837
13838          For a given set of template parameters, if an explicit
13839          instantiation of a template appears after a declaration of an
13840          explicit specialization for that template, the explicit
13841          instantiation has no effect.  */
13842       return;
13843     }
13844   else if (DECL_EXPLICIT_INSTANTIATION (result))
13845     {
13846       /* [temp.spec]
13847
13848          No program shall explicitly instantiate any template more
13849          than once.
13850
13851          We check DECL_NOT_REALLY_EXTERN so as not to complain when
13852          the first instantiation was `extern' and the second is not,
13853          and EXTERN_P for the opposite case.  */
13854       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
13855         pedwarn ("duplicate explicit instantiation of %q#D", result);
13856       /* If an "extern" explicit instantiation follows an ordinary
13857          explicit instantiation, the template is instantiated.  */
13858       if (extern_p)
13859         return;
13860     }
13861   else if (!DECL_IMPLICIT_INSTANTIATION (result))
13862     {
13863       error ("no matching template for %qD found", result);
13864       return;
13865     }
13866   else if (!DECL_TEMPLATE_INFO (result))
13867     {
13868       pedwarn ("explicit instantiation of non-template %q#D", result);
13869       return;
13870     }
13871
13872   if (storage == NULL_TREE)
13873     ;
13874   else if (storage == ridpointers[(int) RID_EXTERN])
13875     {
13876       if (pedantic && !in_system_header)
13877         pedwarn ("ISO C++ forbids the use of %<extern%> on explicit "
13878                  "instantiations");
13879       extern_p = 1;
13880     }
13881   else
13882     error ("storage class %qD applied to template instantiation", storage);
13883
13884   check_explicit_instantiation_namespace (result);
13885   mark_decl_instantiated (result, extern_p);
13886   if (! extern_p)
13887     instantiate_decl (result, /*defer_ok=*/1,
13888                       /*expl_inst_class_mem_p=*/false);
13889 }
13890
13891 static void
13892 mark_class_instantiated (tree t, int extern_p)
13893 {
13894   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
13895   SET_CLASSTYPE_INTERFACE_KNOWN (t);
13896   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
13897   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
13898   if (! extern_p)
13899     {
13900       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
13901       rest_of_type_compilation (t, 1);
13902     }
13903 }
13904
13905 /* Called from do_type_instantiation through binding_table_foreach to
13906    do recursive instantiation for the type bound in ENTRY.  */
13907 static void
13908 bt_instantiate_type_proc (binding_entry entry, void *data)
13909 {
13910   tree storage = *(tree *) data;
13911
13912   if (IS_AGGR_TYPE (entry->type)
13913       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
13914     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
13915 }
13916
13917 /* Called from do_type_instantiation to instantiate a member
13918    (a member function or a static member variable) of an
13919    explicitly instantiated class template.  */
13920 static void
13921 instantiate_class_member (tree decl, int extern_p)
13922 {
13923   mark_decl_instantiated (decl, extern_p);
13924   if (! extern_p)
13925     instantiate_decl (decl, /*defer_ok=*/1,
13926                       /*expl_inst_class_mem_p=*/true);
13927 }
13928
13929 /* Perform an explicit instantiation of template class T.  STORAGE, if
13930    non-null, is the RID for extern, inline or static.  COMPLAIN is
13931    nonzero if this is called from the parser, zero if called recursively,
13932    since the standard is unclear (as detailed below).  */
13933
13934 void
13935 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
13936 {
13937   int extern_p = 0;
13938   int nomem_p = 0;
13939   int static_p = 0;
13940   int previous_instantiation_extern_p = 0;
13941
13942   if (TREE_CODE (t) == TYPE_DECL)
13943     t = TREE_TYPE (t);
13944
13945   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
13946     {
13947       error ("explicit instantiation of non-template type %qT", t);
13948       return;
13949     }
13950
13951   complete_type (t);
13952
13953   if (!COMPLETE_TYPE_P (t))
13954     {
13955       if (complain & tf_error)
13956         error ("explicit instantiation of %q#T before definition of template",
13957                t);
13958       return;
13959     }
13960
13961   if (storage != NULL_TREE)
13962     {
13963       if (pedantic && !in_system_header)
13964         pedwarn("ISO C++ forbids the use of %qE on explicit instantiations",
13965                 storage);
13966
13967       if (storage == ridpointers[(int) RID_INLINE])
13968         nomem_p = 1;
13969       else if (storage == ridpointers[(int) RID_EXTERN])
13970         extern_p = 1;
13971       else if (storage == ridpointers[(int) RID_STATIC])
13972         static_p = 1;
13973       else
13974         {
13975           error ("storage class %qD applied to template instantiation",
13976                  storage);
13977           extern_p = 0;
13978         }
13979     }
13980
13981   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
13982     {
13983       /* DR 259 [temp.spec].
13984
13985          Both an explicit instantiation and a declaration of an explicit
13986          specialization shall not appear in a program unless the explicit
13987          instantiation follows a declaration of the explicit specialization.
13988
13989          For a given set of template parameters, if an explicit
13990          instantiation of a template appears after a declaration of an
13991          explicit specialization for that template, the explicit
13992          instantiation has no effect.  */
13993       return;
13994     }
13995   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
13996     {
13997       /* [temp.spec]
13998
13999          No program shall explicitly instantiate any template more
14000          than once.
14001
14002          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
14003          instantiation was `extern'.  If EXTERN_P then the second is.
14004          These cases are OK.  */
14005       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
14006
14007       if (!previous_instantiation_extern_p && !extern_p
14008           && (complain & tf_error))
14009         pedwarn ("duplicate explicit instantiation of %q#T", t);
14010
14011       /* If we've already instantiated the template, just return now.  */
14012       if (!CLASSTYPE_INTERFACE_ONLY (t))
14013         return;
14014     }
14015
14016   check_explicit_instantiation_namespace (TYPE_NAME (t));
14017   mark_class_instantiated (t, extern_p);
14018
14019   if (nomem_p)
14020     return;
14021
14022   {
14023     tree tmp;
14024
14025     /* In contrast to implicit instantiation, where only the
14026        declarations, and not the definitions, of members are
14027        instantiated, we have here:
14028
14029          [temp.explicit]
14030
14031          The explicit instantiation of a class template specialization
14032          implies the instantiation of all of its members not
14033          previously explicitly specialized in the translation unit
14034          containing the explicit instantiation.
14035
14036        Of course, we can't instantiate member template classes, since
14037        we don't have any arguments for them.  Note that the standard
14038        is unclear on whether the instantiation of the members are
14039        *explicit* instantiations or not.  However, the most natural
14040        interpretation is that it should be an explicit instantiation.  */
14041
14042     if (! static_p)
14043       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
14044         if (TREE_CODE (tmp) == FUNCTION_DECL
14045             && DECL_TEMPLATE_INSTANTIATION (tmp))
14046           instantiate_class_member (tmp, extern_p);
14047
14048     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
14049       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
14050         instantiate_class_member (tmp, extern_p);
14051
14052     if (CLASSTYPE_NESTED_UTDS (t))
14053       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
14054                              bt_instantiate_type_proc, &storage);
14055   }
14056 }
14057
14058 /* Given a function DECL, which is a specialization of TMPL, modify
14059    DECL to be a re-instantiation of TMPL with the same template
14060    arguments.  TMPL should be the template into which tsubst'ing
14061    should occur for DECL, not the most general template.
14062
14063    One reason for doing this is a scenario like this:
14064
14065      template <class T>
14066      void f(const T&, int i);
14067
14068      void g() { f(3, 7); }
14069
14070      template <class T>
14071      void f(const T& t, const int i) { }
14072
14073    Note that when the template is first instantiated, with
14074    instantiate_template, the resulting DECL will have no name for the
14075    first parameter, and the wrong type for the second.  So, when we go
14076    to instantiate the DECL, we regenerate it.  */
14077
14078 static void
14079 regenerate_decl_from_template (tree decl, tree tmpl)
14080 {
14081   /* The arguments used to instantiate DECL, from the most general
14082      template.  */
14083   tree args;
14084   tree code_pattern;
14085
14086   args = DECL_TI_ARGS (decl);
14087   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
14088
14089   /* Make sure that we can see identifiers, and compute access
14090      correctly.  */
14091   push_access_scope (decl);
14092
14093   if (TREE_CODE (decl) == FUNCTION_DECL)
14094     {
14095       tree decl_parm;
14096       tree pattern_parm;
14097       tree specs;
14098       int args_depth;
14099       int parms_depth;
14100
14101       args_depth = TMPL_ARGS_DEPTH (args);
14102       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
14103       if (args_depth > parms_depth)
14104         args = get_innermost_template_args (args, parms_depth);
14105
14106       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
14107                                               args, tf_error, NULL_TREE);
14108       if (specs)
14109         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
14110                                                     specs);
14111
14112       /* Merge parameter declarations.  */
14113       decl_parm = skip_artificial_parms_for (decl,
14114                                              DECL_ARGUMENTS (decl));
14115       pattern_parm
14116         = skip_artificial_parms_for (code_pattern,
14117                                      DECL_ARGUMENTS (code_pattern));
14118       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
14119         {
14120           tree parm_type;
14121           tree attributes;
14122           
14123           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
14124             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
14125           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
14126                               NULL_TREE);
14127           parm_type = type_decays_to (parm_type);
14128           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
14129             TREE_TYPE (decl_parm) = parm_type;
14130           attributes = DECL_ATTRIBUTES (pattern_parm);
14131           if (DECL_ATTRIBUTES (decl_parm) != attributes)
14132             {
14133               DECL_ATTRIBUTES (decl_parm) = attributes;
14134               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
14135             }
14136           decl_parm = TREE_CHAIN (decl_parm);
14137           pattern_parm = TREE_CHAIN (pattern_parm);
14138         }
14139       /* Merge any parameters that match with the function parameter
14140          pack.  */
14141       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
14142         {
14143           int i, len;
14144           tree expanded_types;
14145           /* Expand the TYPE_PACK_EXPANSION that provides the types for
14146              the parameters in this function parameter pack.  */
14147           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
14148                                                  args, tf_error, NULL_TREE);
14149           len = TREE_VEC_LENGTH (expanded_types);
14150           for (i = 0; i < len; i++)
14151             {
14152               tree parm_type;
14153               tree attributes;
14154           
14155               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
14156                 /* Rename the parameter to include the index.  */
14157                 DECL_NAME (decl_parm) = 
14158                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
14159               parm_type = TREE_VEC_ELT (expanded_types, i);
14160               parm_type = type_decays_to (parm_type);
14161               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
14162                 TREE_TYPE (decl_parm) = parm_type;
14163               attributes = DECL_ATTRIBUTES (pattern_parm);
14164               if (DECL_ATTRIBUTES (decl_parm) != attributes)
14165                 {
14166                   DECL_ATTRIBUTES (decl_parm) = attributes;
14167                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
14168                 }
14169               decl_parm = TREE_CHAIN (decl_parm);
14170             }
14171         }
14172       /* Merge additional specifiers from the CODE_PATTERN.  */
14173       if (DECL_DECLARED_INLINE_P (code_pattern)
14174           && !DECL_DECLARED_INLINE_P (decl))
14175         DECL_DECLARED_INLINE_P (decl) = 1;
14176       if (DECL_INLINE (code_pattern) && !DECL_INLINE (decl))
14177         DECL_INLINE (decl) = 1;
14178     }
14179   else if (TREE_CODE (decl) == VAR_DECL)
14180     DECL_INITIAL (decl) =
14181       tsubst_expr (DECL_INITIAL (code_pattern), args,
14182                    tf_error, DECL_TI_TEMPLATE (decl),
14183                    /*integral_constant_expression_p=*/false);
14184   else
14185     gcc_unreachable ();
14186
14187   pop_access_scope (decl);
14188 }
14189
14190 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
14191    substituted to get DECL.  */
14192
14193 tree
14194 template_for_substitution (tree decl)
14195 {
14196   tree tmpl = DECL_TI_TEMPLATE (decl);
14197
14198   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
14199      for the instantiation.  This is not always the most general
14200      template.  Consider, for example:
14201
14202         template <class T>
14203         struct S { template <class U> void f();
14204                    template <> void f<int>(); };
14205
14206      and an instantiation of S<double>::f<int>.  We want TD to be the
14207      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
14208   while (/* An instantiation cannot have a definition, so we need a
14209             more general template.  */
14210          DECL_TEMPLATE_INSTANTIATION (tmpl)
14211            /* We must also deal with friend templates.  Given:
14212
14213                 template <class T> struct S {
14214                   template <class U> friend void f() {};
14215                 };
14216
14217               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
14218               so far as the language is concerned, but that's still
14219               where we get the pattern for the instantiation from.  On
14220               other hand, if the definition comes outside the class, say:
14221
14222                 template <class T> struct S {
14223                   template <class U> friend void f();
14224                 };
14225                 template <class U> friend void f() {}
14226
14227               we don't need to look any further.  That's what the check for
14228               DECL_INITIAL is for.  */
14229           || (TREE_CODE (decl) == FUNCTION_DECL
14230               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
14231               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
14232     {
14233       /* The present template, TD, should not be a definition.  If it
14234          were a definition, we should be using it!  Note that we
14235          cannot restructure the loop to just keep going until we find
14236          a template with a definition, since that might go too far if
14237          a specialization was declared, but not defined.  */
14238       gcc_assert (TREE_CODE (decl) != VAR_DECL
14239                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
14240
14241       /* Fetch the more general template.  */
14242       tmpl = DECL_TI_TEMPLATE (tmpl);
14243     }
14244
14245   return tmpl;
14246 }
14247
14248 /* Produce the definition of D, a _DECL generated from a template.  If
14249    DEFER_OK is nonzero, then we don't have to actually do the
14250    instantiation now; we just have to do it sometime.  Normally it is
14251    an error if this is an explicit instantiation but D is undefined.
14252    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
14253    explicitly instantiated class template.  */
14254
14255 tree
14256 instantiate_decl (tree d, int defer_ok,
14257                   bool expl_inst_class_mem_p)
14258 {
14259   tree tmpl = DECL_TI_TEMPLATE (d);
14260   tree gen_args;
14261   tree args;
14262   tree td;
14263   tree code_pattern;
14264   tree spec;
14265   tree gen_tmpl;
14266   bool pattern_defined;
14267   int need_push;
14268   location_t saved_loc = input_location;
14269   int saved_in_system_header = in_system_header;
14270   bool external_p;
14271
14272   /* This function should only be used to instantiate templates for
14273      functions and static member variables.  */
14274   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
14275               || TREE_CODE (d) == VAR_DECL);
14276
14277   /* Variables are never deferred; if instantiation is required, they
14278      are instantiated right away.  That allows for better code in the
14279      case that an expression refers to the value of the variable --
14280      if the variable has a constant value the referring expression can
14281      take advantage of that fact.  */
14282   if (TREE_CODE (d) == VAR_DECL)
14283     defer_ok = 0;
14284
14285   /* Don't instantiate cloned functions.  Instead, instantiate the
14286      functions they cloned.  */
14287   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
14288     d = DECL_CLONED_FUNCTION (d);
14289
14290   if (DECL_TEMPLATE_INSTANTIATED (d))
14291     /* D has already been instantiated.  It might seem reasonable to
14292        check whether or not D is an explicit instantiation, and, if so,
14293        stop here.  But when an explicit instantiation is deferred
14294        until the end of the compilation, DECL_EXPLICIT_INSTANTIATION
14295        is set, even though we still need to do the instantiation.  */
14296     return d;
14297
14298   /* If we already have a specialization of this declaration, then
14299      there's no reason to instantiate it.  Note that
14300      retrieve_specialization gives us both instantiations and
14301      specializations, so we must explicitly check
14302      DECL_TEMPLATE_SPECIALIZATION.  */
14303   gen_tmpl = most_general_template (tmpl);
14304   gen_args = DECL_TI_ARGS (d);
14305   spec = retrieve_specialization (gen_tmpl, gen_args,
14306                                   /*class_specializations_p=*/false);
14307   if (spec != NULL_TREE && DECL_TEMPLATE_SPECIALIZATION (spec))
14308     return spec;
14309
14310   /* This needs to happen before any tsubsting.  */
14311   if (! push_tinst_level (d))
14312     return d;
14313
14314   timevar_push (TV_PARSE);
14315
14316   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
14317      for the instantiation.  */
14318   td = template_for_substitution (d);
14319   code_pattern = DECL_TEMPLATE_RESULT (td);
14320
14321   /* We should never be trying to instantiate a member of a class
14322      template or partial specialization.  */
14323   gcc_assert (d != code_pattern);
14324
14325   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
14326       || DECL_TEMPLATE_SPECIALIZATION (td))
14327     /* In the case of a friend template whose definition is provided
14328        outside the class, we may have too many arguments.  Drop the
14329        ones we don't need.  The same is true for specializations.  */
14330     args = get_innermost_template_args
14331       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
14332   else
14333     args = gen_args;
14334
14335   if (TREE_CODE (d) == FUNCTION_DECL)
14336     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
14337   else
14338     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
14339
14340   /* We may be in the middle of deferred access check.  Disable it now.  */
14341   push_deferring_access_checks (dk_no_deferred);
14342
14343   /* Unless an explicit instantiation directive has already determined
14344      the linkage of D, remember that a definition is available for
14345      this entity.  */
14346   if (pattern_defined
14347       && !DECL_INTERFACE_KNOWN (d)
14348       && !DECL_NOT_REALLY_EXTERN (d))
14349     mark_definable (d);
14350
14351   input_location = DECL_SOURCE_LOCATION (d);
14352   in_system_header = DECL_IN_SYSTEM_HEADER (d);
14353
14354   /* If D is a member of an explicitly instantiated class template,
14355      and no definition is available, treat it like an implicit
14356      instantiation.  */
14357   if (!pattern_defined && expl_inst_class_mem_p
14358       && DECL_EXPLICIT_INSTANTIATION (d))
14359     {
14360       DECL_NOT_REALLY_EXTERN (d) = 0;
14361       DECL_INTERFACE_KNOWN (d) = 0;
14362       SET_DECL_IMPLICIT_INSTANTIATION (d);
14363     }
14364
14365   if (!defer_ok)
14366     {
14367       /* Recheck the substitutions to obtain any warning messages
14368          about ignoring cv qualifiers.  */
14369       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
14370       tree type = TREE_TYPE (gen);
14371
14372       /* Make sure that we can see identifiers, and compute access
14373          correctly.  D is already the target FUNCTION_DECL with the
14374          right context.  */
14375       push_access_scope (d);
14376
14377       if (TREE_CODE (gen) == FUNCTION_DECL)
14378         {
14379           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
14380           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
14381                                           d);
14382           /* Don't simply tsubst the function type, as that will give
14383              duplicate warnings about poor parameter qualifications.
14384              The function arguments are the same as the decl_arguments
14385              without the top level cv qualifiers.  */
14386           type = TREE_TYPE (type);
14387         }
14388       tsubst (type, gen_args, tf_warning_or_error, d);
14389
14390       pop_access_scope (d);
14391     }
14392
14393   /* Check to see whether we know that this template will be
14394      instantiated in some other file, as with "extern template"
14395      extension.  */
14396   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
14397   /* In general, we do not instantiate such templates...  */
14398   if (external_p
14399       /* ... but we instantiate inline functions so that we can inline
14400          them and ... */
14401       && ! (TREE_CODE (d) == FUNCTION_DECL && DECL_INLINE (d))
14402       /* ... we instantiate static data members whose values are
14403          needed in integral constant expressions.  */
14404       && ! (TREE_CODE (d) == VAR_DECL
14405             && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (d)))
14406     goto out;
14407   /* Defer all other templates, unless we have been explicitly
14408      forbidden from doing so.  */
14409   if (/* If there is no definition, we cannot instantiate the
14410          template.  */
14411       ! pattern_defined
14412       /* If it's OK to postpone instantiation, do so.  */
14413       || defer_ok
14414       /* If this is a static data member that will be defined
14415          elsewhere, we don't want to instantiate the entire data
14416          member, but we do want to instantiate the initializer so that
14417          we can substitute that elsewhere.  */
14418       || (external_p && TREE_CODE (d) == VAR_DECL))
14419     {
14420       /* The definition of the static data member is now required so
14421          we must substitute the initializer.  */
14422       if (TREE_CODE (d) == VAR_DECL
14423           && !DECL_INITIAL (d)
14424           && DECL_INITIAL (code_pattern))
14425         {
14426           tree ns;
14427           tree init;
14428
14429           ns = decl_namespace_context (d);
14430           push_nested_namespace (ns);
14431           push_nested_class (DECL_CONTEXT (d));
14432           init = tsubst_expr (DECL_INITIAL (code_pattern),
14433                               args,
14434                               tf_warning_or_error, NULL_TREE,
14435                               /*integral_constant_expression_p=*/false);
14436           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
14437                           /*asmspec_tree=*/NULL_TREE,
14438                           LOOKUP_ONLYCONVERTING);
14439           pop_nested_class ();
14440           pop_nested_namespace (ns);
14441         }
14442
14443       /* We restore the source position here because it's used by
14444          add_pending_template.  */
14445       input_location = saved_loc;
14446
14447       if (at_eof && !pattern_defined
14448           && DECL_EXPLICIT_INSTANTIATION (d))
14449         /* [temp.explicit]
14450
14451            The definition of a non-exported function template, a
14452            non-exported member function template, or a non-exported
14453            member function or static data member of a class template
14454            shall be present in every translation unit in which it is
14455            explicitly instantiated.  */
14456         pedwarn
14457           ("explicit instantiation of %qD but no definition available", d);
14458
14459       /* ??? Historically, we have instantiated inline functions, even
14460          when marked as "extern template".  */
14461       if (!(external_p && TREE_CODE (d) == VAR_DECL))
14462         add_pending_template (d);
14463       goto out;
14464     }
14465   /* Tell the repository that D is available in this translation unit
14466      -- and see if it is supposed to be instantiated here.  */
14467   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
14468     {
14469       /* In a PCH file, despite the fact that the repository hasn't
14470          requested instantiation in the PCH it is still possible that
14471          an instantiation will be required in a file that includes the
14472          PCH.  */
14473       if (pch_file)
14474         add_pending_template (d);
14475       /* Instantiate inline functions so that the inliner can do its
14476          job, even though we'll not be emitting a copy of this
14477          function.  */
14478       if (!(TREE_CODE (d) == FUNCTION_DECL
14479             && flag_inline_trees
14480             && DECL_DECLARED_INLINE_P (d)))
14481         goto out;
14482     }
14483
14484   need_push = !cfun || !global_bindings_p ();
14485   if (need_push)
14486     push_to_top_level ();
14487
14488   /* Mark D as instantiated so that recursive calls to
14489      instantiate_decl do not try to instantiate it again.  */
14490   DECL_TEMPLATE_INSTANTIATED (d) = 1;
14491
14492   /* Regenerate the declaration in case the template has been modified
14493      by a subsequent redeclaration.  */
14494   regenerate_decl_from_template (d, td);
14495
14496   /* We already set the file and line above.  Reset them now in case
14497      they changed as a result of calling regenerate_decl_from_template.  */
14498   input_location = DECL_SOURCE_LOCATION (d);
14499
14500   if (TREE_CODE (d) == VAR_DECL)
14501     {
14502       tree init;
14503
14504       /* Clear out DECL_RTL; whatever was there before may not be right
14505          since we've reset the type of the declaration.  */
14506       SET_DECL_RTL (d, NULL_RTX);
14507       DECL_IN_AGGR_P (d) = 0;
14508
14509       /* The initializer is placed in DECL_INITIAL by
14510          regenerate_decl_from_template.  Pull it out so that
14511          finish_decl can process it.  */
14512       init = DECL_INITIAL (d);
14513       DECL_INITIAL (d) = NULL_TREE;
14514       DECL_INITIALIZED_P (d) = 0;
14515
14516       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
14517          initializer.  That function will defer actual emission until
14518          we have a chance to determine linkage.  */
14519       DECL_EXTERNAL (d) = 0;
14520
14521       /* Enter the scope of D so that access-checking works correctly.  */
14522       push_nested_class (DECL_CONTEXT (d));
14523       finish_decl (d, init, NULL_TREE);
14524       pop_nested_class ();
14525     }
14526   else if (TREE_CODE (d) == FUNCTION_DECL)
14527     {
14528       htab_t saved_local_specializations;
14529       tree subst_decl;
14530       tree tmpl_parm;
14531       tree spec_parm;
14532
14533       /* Save away the current list, in case we are instantiating one
14534          template from within the body of another.  */
14535       saved_local_specializations = local_specializations;
14536
14537       /* Set up the list of local specializations.  */
14538       local_specializations = htab_create (37,
14539                                            hash_local_specialization,
14540                                            eq_local_specializations,
14541                                            NULL);
14542
14543       /* Set up context.  */
14544       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
14545
14546       /* Create substitution entries for the parameters.  */
14547       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
14548       tmpl_parm = DECL_ARGUMENTS (subst_decl);
14549       spec_parm = DECL_ARGUMENTS (d);
14550       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
14551         {
14552           register_local_specialization (spec_parm, tmpl_parm);
14553           spec_parm = skip_artificial_parms_for (d, spec_parm);
14554           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
14555         }
14556       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
14557         {
14558           register_local_specialization (spec_parm, tmpl_parm);
14559           tmpl_parm = TREE_CHAIN (tmpl_parm);
14560           spec_parm = TREE_CHAIN (spec_parm);
14561         }
14562       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
14563         {
14564           /* Collect all of the extra "packed" parameters into an
14565              argument pack.  */
14566           tree parmvec;
14567           tree parmtypevec;
14568           tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
14569           tree argtypepack = make_node (TYPE_ARGUMENT_PACK);
14570           int i, len = 0;
14571           tree t;
14572           
14573           /* Count how many parameters remain.  */
14574           for (t = spec_parm; t; t = TREE_CHAIN (t))
14575             len++;
14576
14577           /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
14578           parmvec = make_tree_vec (len);
14579           parmtypevec = make_tree_vec (len);
14580           for(i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
14581             {
14582               TREE_VEC_ELT (parmvec, i) = spec_parm;
14583               TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
14584             }
14585
14586           /* Build the argument packs.  */
14587           SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
14588           SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
14589           TREE_TYPE (argpack) = argtypepack;
14590           
14591           /* Register the (value) argument pack as a specialization of
14592              TMPL_PARM, then move on.  */
14593           register_local_specialization (argpack, tmpl_parm);
14594           tmpl_parm = TREE_CHAIN (tmpl_parm);
14595         }
14596       gcc_assert (!spec_parm);
14597
14598       /* Substitute into the body of the function.  */
14599       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
14600                    tf_warning_or_error, tmpl,
14601                    /*integral_constant_expression_p=*/false);
14602
14603       /* Set the current input_location to the end of the function
14604          so that finish_function knows where we are.  */
14605       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
14606
14607       /* We don't need the local specializations any more.  */
14608       htab_delete (local_specializations);
14609       local_specializations = saved_local_specializations;
14610
14611       /* Finish the function.  */
14612       d = finish_function (0);
14613       expand_or_defer_fn (d);
14614     }
14615
14616   /* We're not deferring instantiation any more.  */
14617   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
14618
14619   if (need_push)
14620     pop_from_top_level ();
14621
14622 out:
14623   input_location = saved_loc;
14624   in_system_header = saved_in_system_header;
14625   pop_deferring_access_checks ();
14626   pop_tinst_level ();
14627
14628   timevar_pop (TV_PARSE);
14629
14630   return d;
14631 }
14632
14633 /* Run through the list of templates that we wish we could
14634    instantiate, and instantiate any we can.  RETRIES is the
14635    number of times we retry pending template instantiation.  */
14636
14637 void
14638 instantiate_pending_templates (int retries)
14639 {
14640   int reconsider;
14641   location_t saved_loc = input_location;
14642   int saved_in_system_header = in_system_header;
14643
14644   /* Instantiating templates may trigger vtable generation.  This in turn
14645      may require further template instantiations.  We place a limit here
14646      to avoid infinite loop.  */
14647   if (pending_templates && retries >= max_tinst_depth)
14648     {
14649       tree decl = pending_templates->tinst->decl;
14650
14651       error ("template instantiation depth exceeds maximum of %d"
14652              " instantiating %q+D, possibly from virtual table generation"
14653              " (use -ftemplate-depth-NN to increase the maximum)",
14654              max_tinst_depth, decl);
14655       if (TREE_CODE (decl) == FUNCTION_DECL)
14656         /* Pretend that we defined it.  */
14657         DECL_INITIAL (decl) = error_mark_node;
14658       return;
14659     }
14660
14661   do
14662     {
14663       struct pending_template **t = &pending_templates;
14664       struct pending_template *last = NULL;
14665       reconsider = 0;
14666       while (*t)
14667         {
14668           tree instantiation = reopen_tinst_level ((*t)->tinst);
14669           bool complete = false;
14670
14671           if (TYPE_P (instantiation))
14672             {
14673               tree fn;
14674
14675               if (!COMPLETE_TYPE_P (instantiation))
14676                 {
14677                   instantiate_class_template (instantiation);
14678                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
14679                     for (fn = TYPE_METHODS (instantiation);
14680                          fn;
14681                          fn = TREE_CHAIN (fn))
14682                       if (! DECL_ARTIFICIAL (fn))
14683                         instantiate_decl (fn,
14684                                           /*defer_ok=*/0,
14685                                           /*expl_inst_class_mem_p=*/false);
14686                   if (COMPLETE_TYPE_P (instantiation))
14687                     reconsider = 1;
14688                 }
14689
14690               complete = COMPLETE_TYPE_P (instantiation);
14691             }
14692           else
14693             {
14694               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
14695                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
14696                 {
14697                   instantiation
14698                     = instantiate_decl (instantiation,
14699                                         /*defer_ok=*/0,
14700                                         /*expl_inst_class_mem_p=*/false);
14701                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
14702                     reconsider = 1;
14703                 }
14704
14705               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
14706                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
14707             }
14708
14709           if (complete)
14710             /* If INSTANTIATION has been instantiated, then we don't
14711                need to consider it again in the future.  */
14712             *t = (*t)->next;
14713           else
14714             {
14715               last = *t;
14716               t = &(*t)->next;
14717             }
14718           tinst_depth = 0;
14719           current_tinst_level = NULL;
14720         }
14721       last_pending_template = last;
14722     }
14723   while (reconsider);
14724
14725   input_location = saved_loc;
14726   in_system_header = saved_in_system_header;
14727 }
14728
14729 /* Substitute ARGVEC into T, which is a list of initializers for
14730    either base class or a non-static data member.  The TREE_PURPOSEs
14731    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
14732    instantiate_decl.  */
14733
14734 static tree
14735 tsubst_initializer_list (tree t, tree argvec)
14736 {
14737   tree inits = NULL_TREE;
14738
14739   for (; t; t = TREE_CHAIN (t))
14740     {
14741       tree decl;
14742       tree init;
14743       tree expanded_bases = NULL_TREE;
14744       tree expanded_arguments = NULL_TREE;
14745       int i, len = 1;
14746
14747       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
14748         {
14749           tree expr;
14750           tree arg;
14751
14752           /* Expand the base class expansion type into separate base
14753              classes.  */
14754           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
14755                                                  tf_warning_or_error,
14756                                                  NULL_TREE);
14757           if (expanded_bases == error_mark_node)
14758             continue;
14759           
14760           /* We'll be building separate TREE_LISTs of arguments for
14761              each base.  */
14762           len = TREE_VEC_LENGTH (expanded_bases);
14763           expanded_arguments = make_tree_vec (len);
14764           for (i = 0; i < len; i++)
14765             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
14766
14767           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
14768              expand each argument in the TREE_VALUE of t.  */
14769           expr = make_node (EXPR_PACK_EXPANSION);
14770           PACK_EXPANSION_PARAMETER_PACKS (expr) =
14771             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
14772
14773           /* Substitute parameter packs into each argument in the
14774              TREE_LIST.  */
14775           in_base_initializer = 1;
14776           for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
14777             {
14778               tree expanded_exprs;
14779
14780               /* Expand the argument.  */
14781               SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
14782               expanded_exprs = tsubst_pack_expansion (expr, argvec,
14783                                                       tf_warning_or_error,
14784                                                       NULL_TREE);
14785
14786               /* Prepend each of the expanded expressions to the
14787                  corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
14788               for (i = 0; i < len; i++)
14789                 {
14790                   TREE_VEC_ELT (expanded_arguments, i) = 
14791                     tree_cons (NULL_TREE, TREE_VEC_ELT (expanded_exprs, i),
14792                                TREE_VEC_ELT (expanded_arguments, i));
14793                 }
14794             }
14795           in_base_initializer = 0;
14796
14797           /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
14798              since we built them backwards.  */
14799           for (i = 0; i < len; i++)
14800             {
14801               TREE_VEC_ELT (expanded_arguments, i) = 
14802                 nreverse (TREE_VEC_ELT (expanded_arguments, i));
14803             }
14804         }
14805
14806       for (i = 0; i < len; ++i)
14807         {
14808           if (expanded_bases)
14809             {
14810               decl = TREE_VEC_ELT (expanded_bases, i);
14811               decl = expand_member_init (decl);
14812               init = TREE_VEC_ELT (expanded_arguments, i);
14813             }
14814           else
14815             {
14816               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
14817                                   tf_warning_or_error, NULL_TREE);
14818
14819               decl = expand_member_init (decl);
14820               if (decl && !DECL_P (decl))
14821                 in_base_initializer = 1;
14822
14823               init = tsubst_expr (TREE_VALUE (t), argvec, 
14824                                   tf_warning_or_error, NULL_TREE,
14825                                   /*integral_constant_expression_p=*/false);
14826               in_base_initializer = 0;
14827             }
14828
14829           if (decl)
14830             {
14831               init = build_tree_list (decl, init);
14832               TREE_CHAIN (init) = inits;
14833               inits = init;
14834             }
14835         }
14836     }
14837   return inits;
14838 }
14839
14840 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
14841
14842 static void
14843 set_current_access_from_decl (tree decl)
14844 {
14845   if (TREE_PRIVATE (decl))
14846     current_access_specifier = access_private_node;
14847   else if (TREE_PROTECTED (decl))
14848     current_access_specifier = access_protected_node;
14849   else
14850     current_access_specifier = access_public_node;
14851 }
14852
14853 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
14854    is the instantiation (which should have been created with
14855    start_enum) and ARGS are the template arguments to use.  */
14856
14857 static void
14858 tsubst_enum (tree tag, tree newtag, tree args)
14859 {
14860   tree e;
14861
14862   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
14863     {
14864       tree value;
14865       tree decl;
14866
14867       decl = TREE_VALUE (e);
14868       /* Note that in a template enum, the TREE_VALUE is the
14869          CONST_DECL, not the corresponding INTEGER_CST.  */
14870       value = tsubst_expr (DECL_INITIAL (decl),
14871                            args, tf_warning_or_error, NULL_TREE,
14872                            /*integral_constant_expression_p=*/true);
14873
14874       /* Give this enumeration constant the correct access.  */
14875       set_current_access_from_decl (decl);
14876
14877       /* Actually build the enumerator itself.  */
14878       build_enumerator (DECL_NAME (decl), value, newtag);
14879     }
14880
14881   finish_enum (newtag);
14882   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
14883     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
14884 }
14885
14886 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
14887    its type -- but without substituting the innermost set of template
14888    arguments.  So, innermost set of template parameters will appear in
14889    the type.  */
14890
14891 tree
14892 get_mostly_instantiated_function_type (tree decl)
14893 {
14894   tree fn_type;
14895   tree tmpl;
14896   tree targs;
14897   tree tparms;
14898   int parm_depth;
14899
14900   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
14901   targs = DECL_TI_ARGS (decl);
14902   tparms = DECL_TEMPLATE_PARMS (tmpl);
14903   parm_depth = TMPL_PARMS_DEPTH (tparms);
14904
14905   /* There should be as many levels of arguments as there are levels
14906      of parameters.  */
14907   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
14908
14909   fn_type = TREE_TYPE (tmpl);
14910
14911   if (parm_depth == 1)
14912     /* No substitution is necessary.  */
14913     ;
14914   else
14915     {
14916       int i, save_access_control;
14917       tree partial_args;
14918
14919       /* Replace the innermost level of the TARGS with NULL_TREEs to
14920          let tsubst know not to substitute for those parameters.  */
14921       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
14922       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
14923         SET_TMPL_ARGS_LEVEL (partial_args, i,
14924                              TMPL_ARGS_LEVEL (targs, i));
14925       SET_TMPL_ARGS_LEVEL (partial_args,
14926                            TMPL_ARGS_DEPTH (targs),
14927                            make_tree_vec (DECL_NTPARMS (tmpl)));
14928
14929       /* Disable access control as this function is used only during
14930          name-mangling.  */
14931       save_access_control = flag_access_control;
14932       flag_access_control = 0;
14933
14934       ++processing_template_decl;
14935       /* Now, do the (partial) substitution to figure out the
14936          appropriate function type.  */
14937       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
14938       --processing_template_decl;
14939
14940       /* Substitute into the template parameters to obtain the real
14941          innermost set of parameters.  This step is important if the
14942          innermost set of template parameters contains value
14943          parameters whose types depend on outer template parameters.  */
14944       TREE_VEC_LENGTH (partial_args)--;
14945       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
14946
14947       flag_access_control = save_access_control;
14948     }
14949
14950   return fn_type;
14951 }
14952
14953 /* Return truthvalue if we're processing a template different from
14954    the last one involved in diagnostics.  */
14955 int
14956 problematic_instantiation_changed (void)
14957 {
14958   return last_template_error_tick != tinst_level_tick;
14959 }
14960
14961 /* Remember current template involved in diagnostics.  */
14962 void
14963 record_last_problematic_instantiation (void)
14964 {
14965   last_template_error_tick = tinst_level_tick;
14966 }
14967
14968 struct tinst_level *
14969 current_instantiation (void)
14970 {
14971   return current_tinst_level;
14972 }
14973
14974 /* [temp.param] Check that template non-type parm TYPE is of an allowable
14975    type. Return zero for ok, nonzero for disallowed. Issue error and
14976    warning messages under control of COMPLAIN.  */
14977
14978 static int
14979 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
14980 {
14981   if (INTEGRAL_TYPE_P (type))
14982     return 0;
14983   else if (POINTER_TYPE_P (type))
14984     return 0;
14985   else if (TYPE_PTR_TO_MEMBER_P (type))
14986     return 0;
14987   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
14988     return 0;
14989   else if (TREE_CODE (type) == TYPENAME_TYPE)
14990     return 0;
14991
14992   if (complain & tf_error)
14993     error ("%q#T is not a valid type for a template constant parameter", type);
14994   return 1;
14995 }
14996
14997 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
14998    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
14999
15000 static bool
15001 dependent_type_p_r (tree type)
15002 {
15003   tree scope;
15004
15005   /* [temp.dep.type]
15006
15007      A type is dependent if it is:
15008
15009      -- a template parameter. Template template parameters are types
15010         for us (since TYPE_P holds true for them) so we handle
15011         them here.  */
15012   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
15013       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
15014     return true;
15015   /* -- a qualified-id with a nested-name-specifier which contains a
15016         class-name that names a dependent type or whose unqualified-id
15017         names a dependent type.  */
15018   if (TREE_CODE (type) == TYPENAME_TYPE)
15019     return true;
15020   /* -- a cv-qualified type where the cv-unqualified type is
15021         dependent.  */
15022   type = TYPE_MAIN_VARIANT (type);
15023   /* -- a compound type constructed from any dependent type.  */
15024   if (TYPE_PTR_TO_MEMBER_P (type))
15025     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
15026             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
15027                                            (type)));
15028   else if (TREE_CODE (type) == POINTER_TYPE
15029            || TREE_CODE (type) == REFERENCE_TYPE)
15030     return dependent_type_p (TREE_TYPE (type));
15031   else if (TREE_CODE (type) == FUNCTION_TYPE
15032            || TREE_CODE (type) == METHOD_TYPE)
15033     {
15034       tree arg_type;
15035
15036       if (dependent_type_p (TREE_TYPE (type)))
15037         return true;
15038       for (arg_type = TYPE_ARG_TYPES (type);
15039            arg_type;
15040            arg_type = TREE_CHAIN (arg_type))
15041         if (dependent_type_p (TREE_VALUE (arg_type)))
15042           return true;
15043       return false;
15044     }
15045   /* -- an array type constructed from any dependent type or whose
15046         size is specified by a constant expression that is
15047         value-dependent.  */
15048   if (TREE_CODE (type) == ARRAY_TYPE)
15049     {
15050       if (TYPE_DOMAIN (type)
15051           && ((value_dependent_expression_p
15052                (TYPE_MAX_VALUE (TYPE_DOMAIN (type))))
15053               || (type_dependent_expression_p
15054                   (TYPE_MAX_VALUE (TYPE_DOMAIN (type))))))
15055         return true;
15056       return dependent_type_p (TREE_TYPE (type));
15057     }
15058
15059   /* -- a template-id in which either the template name is a template
15060      parameter ...  */
15061   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
15062     return true;
15063   /* ... or any of the template arguments is a dependent type or
15064         an expression that is type-dependent or value-dependent.  */
15065   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
15066            && (any_dependent_template_arguments_p
15067                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
15068     return true;
15069
15070   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
15071      argument of the `typeof' expression is not type-dependent, then
15072      it should already been have resolved.  */
15073   if (TREE_CODE (type) == TYPEOF_TYPE
15074       || TREE_CODE (type) == DECLTYPE_TYPE)
15075     return true;
15076
15077   /* A template argument pack is dependent if any of its packed
15078      arguments are.  */
15079   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
15080     {
15081       tree args = ARGUMENT_PACK_ARGS (type);
15082       int i, len = TREE_VEC_LENGTH (args);
15083       for (i = 0; i < len; ++i)
15084         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
15085           return true;
15086     }
15087
15088   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
15089      be template parameters.  */
15090   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
15091     return true;
15092
15093   /* The standard does not specifically mention types that are local
15094      to template functions or local classes, but they should be
15095      considered dependent too.  For example:
15096
15097        template <int I> void f() {
15098          enum E { a = I };
15099          S<sizeof (E)> s;
15100        }
15101
15102      The size of `E' cannot be known until the value of `I' has been
15103      determined.  Therefore, `E' must be considered dependent.  */
15104   scope = TYPE_CONTEXT (type);
15105   if (scope && TYPE_P (scope))
15106     return dependent_type_p (scope);
15107   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
15108     return type_dependent_expression_p (scope);
15109
15110   /* Other types are non-dependent.  */
15111   return false;
15112 }
15113
15114 /* Returns TRUE if TYPE is dependent, in the sense of
15115    [temp.dep.type].  */
15116
15117 bool
15118 dependent_type_p (tree type)
15119 {
15120   /* If there are no template parameters in scope, then there can't be
15121      any dependent types.  */
15122   if (!processing_template_decl)
15123     {
15124       /* If we are not processing a template, then nobody should be
15125          providing us with a dependent type.  */
15126       gcc_assert (type);
15127       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM);
15128       return false;
15129     }
15130
15131   /* If the type is NULL, we have not computed a type for the entity
15132      in question; in that case, the type is dependent.  */
15133   if (!type)
15134     return true;
15135
15136   /* Erroneous types can be considered non-dependent.  */
15137   if (type == error_mark_node)
15138     return false;
15139
15140   /* If we have not already computed the appropriate value for TYPE,
15141      do so now.  */
15142   if (!TYPE_DEPENDENT_P_VALID (type))
15143     {
15144       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
15145       TYPE_DEPENDENT_P_VALID (type) = 1;
15146     }
15147
15148   return TYPE_DEPENDENT_P (type);
15149 }
15150
15151 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
15152
15153 static bool
15154 dependent_scope_ref_p (tree expression, bool criterion (tree))
15155 {
15156   tree scope;
15157   tree name;
15158
15159   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
15160
15161   if (!TYPE_P (TREE_OPERAND (expression, 0)))
15162     return true;
15163
15164   scope = TREE_OPERAND (expression, 0);
15165   name = TREE_OPERAND (expression, 1);
15166
15167   /* [temp.dep.expr]
15168
15169      An id-expression is type-dependent if it contains a
15170      nested-name-specifier that contains a class-name that names a
15171      dependent type.  */
15172   /* The suggested resolution to Core Issue 2 implies that if the
15173      qualifying type is the current class, then we must peek
15174      inside it.  */
15175   if (DECL_P (name)
15176       && currently_open_class (scope)
15177       && !criterion (name))
15178     return false;
15179   if (dependent_type_p (scope))
15180     return true;
15181
15182   return false;
15183 }
15184
15185 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
15186    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
15187    expression.  */
15188
15189 bool
15190 value_dependent_expression_p (tree expression)
15191 {
15192   if (!processing_template_decl)
15193     return false;
15194
15195   /* A name declared with a dependent type.  */
15196   if (DECL_P (expression) && type_dependent_expression_p (expression))
15197     return true;
15198
15199   switch (TREE_CODE (expression))
15200     {
15201     case IDENTIFIER_NODE:
15202       /* A name that has not been looked up -- must be dependent.  */
15203       return true;
15204
15205     case TEMPLATE_PARM_INDEX:
15206       /* A non-type template parm.  */
15207       return true;
15208
15209     case CONST_DECL:
15210       /* A non-type template parm.  */
15211       if (DECL_TEMPLATE_PARM_P (expression))
15212         return true;
15213       return false;
15214
15215     case VAR_DECL:
15216        /* A constant with integral or enumeration type and is initialized
15217           with an expression that is value-dependent.  */
15218       if (DECL_INITIAL (expression)
15219           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
15220           && value_dependent_expression_p (DECL_INITIAL (expression)))
15221         return true;
15222       return false;
15223
15224     case DYNAMIC_CAST_EXPR:
15225     case STATIC_CAST_EXPR:
15226     case CONST_CAST_EXPR:
15227     case REINTERPRET_CAST_EXPR:
15228     case CAST_EXPR:
15229       /* These expressions are value-dependent if the type to which
15230          the cast occurs is dependent or the expression being casted
15231          is value-dependent.  */
15232       {
15233         tree type = TREE_TYPE (expression);
15234
15235         if (dependent_type_p (type))
15236           return true;
15237
15238         /* A functional cast has a list of operands.  */
15239         expression = TREE_OPERAND (expression, 0);
15240         if (!expression)
15241           {
15242             /* If there are no operands, it must be an expression such
15243                as "int()". This should not happen for aggregate types
15244                because it would form non-constant expressions.  */
15245             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
15246
15247             return false;
15248           }
15249
15250         if (TREE_CODE (expression) == TREE_LIST)
15251           return any_value_dependent_elements_p (expression);
15252
15253         return value_dependent_expression_p (expression);
15254       }
15255
15256     case SIZEOF_EXPR:
15257     case ALIGNOF_EXPR:
15258       /* A `sizeof' expression is value-dependent if the operand is
15259          type-dependent or is a pack expansion.  */
15260       expression = TREE_OPERAND (expression, 0);
15261       if (PACK_EXPANSION_P (expression))
15262         return true;
15263       else if (TYPE_P (expression))
15264         return dependent_type_p (expression);
15265       return type_dependent_expression_p (expression);
15266
15267     case SCOPE_REF:
15268       return dependent_scope_ref_p (expression, value_dependent_expression_p);
15269
15270     case COMPONENT_REF:
15271       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
15272               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
15273
15274     case CALL_EXPR:
15275       /* A CALL_EXPR may appear in a constant expression if it is a
15276          call to a builtin function, e.g., __builtin_constant_p.  All
15277          such calls are value-dependent.  */
15278       return true;
15279
15280     case NONTYPE_ARGUMENT_PACK:
15281       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
15282          is value-dependent.  */
15283       {
15284         tree values = ARGUMENT_PACK_ARGS (expression);
15285         int i, len = TREE_VEC_LENGTH (values);
15286         
15287         for (i = 0; i < len; ++i)
15288           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
15289             return true;
15290         
15291         return false;
15292       }
15293
15294     case TRAIT_EXPR:
15295       {
15296         tree type2 = TRAIT_EXPR_TYPE2 (expression);
15297         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
15298                 || (type2 ? dependent_type_p (type2) : false));
15299       }
15300
15301     case MODOP_EXPR:
15302       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
15303               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
15304
15305     default:
15306       /* A constant expression is value-dependent if any subexpression is
15307          value-dependent.  */
15308       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
15309         {
15310         case tcc_reference:
15311         case tcc_unary:
15312           return (value_dependent_expression_p
15313                   (TREE_OPERAND (expression, 0)));
15314
15315         case tcc_comparison:
15316         case tcc_binary:
15317           return ((value_dependent_expression_p
15318                    (TREE_OPERAND (expression, 0)))
15319                   || (value_dependent_expression_p
15320                       (TREE_OPERAND (expression, 1))));
15321
15322         case tcc_expression:
15323         case tcc_vl_exp:
15324           {
15325             int i;
15326             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
15327               /* In some cases, some of the operands may be missing.
15328                  (For example, in the case of PREDECREMENT_EXPR, the
15329                  amount to increment by may be missing.)  That doesn't
15330                  make the expression dependent.  */
15331               if (TREE_OPERAND (expression, i)
15332                   && (value_dependent_expression_p
15333                       (TREE_OPERAND (expression, i))))
15334                 return true;
15335             return false;
15336           }
15337
15338         default:
15339           break;
15340         }
15341     }
15342
15343   /* The expression is not value-dependent.  */
15344   return false;
15345 }
15346
15347 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
15348    [temp.dep.expr].  */
15349
15350 bool
15351 type_dependent_expression_p (tree expression)
15352 {
15353   if (!processing_template_decl)
15354     return false;
15355
15356   if (expression == error_mark_node)
15357     return false;
15358
15359   /* An unresolved name is always dependent.  */
15360   if (TREE_CODE (expression) == IDENTIFIER_NODE
15361       || TREE_CODE (expression) == USING_DECL)
15362     return true;
15363
15364   /* Some expression forms are never type-dependent.  */
15365   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
15366       || TREE_CODE (expression) == SIZEOF_EXPR
15367       || TREE_CODE (expression) == ALIGNOF_EXPR
15368       || TREE_CODE (expression) == TRAIT_EXPR
15369       || TREE_CODE (expression) == TYPEID_EXPR
15370       || TREE_CODE (expression) == DELETE_EXPR
15371       || TREE_CODE (expression) == VEC_DELETE_EXPR
15372       || TREE_CODE (expression) == THROW_EXPR)
15373     return false;
15374
15375   /* The types of these expressions depends only on the type to which
15376      the cast occurs.  */
15377   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
15378       || TREE_CODE (expression) == STATIC_CAST_EXPR
15379       || TREE_CODE (expression) == CONST_CAST_EXPR
15380       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
15381       || TREE_CODE (expression) == CAST_EXPR)
15382     return dependent_type_p (TREE_TYPE (expression));
15383
15384   /* The types of these expressions depends only on the type created
15385      by the expression.  */
15386   if (TREE_CODE (expression) == NEW_EXPR
15387       || TREE_CODE (expression) == VEC_NEW_EXPR)
15388     {
15389       /* For NEW_EXPR tree nodes created inside a template, either
15390          the object type itself or a TREE_LIST may appear as the
15391          operand 1.  */
15392       tree type = TREE_OPERAND (expression, 1);
15393       if (TREE_CODE (type) == TREE_LIST)
15394         /* This is an array type.  We need to check array dimensions
15395            as well.  */
15396         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
15397                || value_dependent_expression_p
15398                     (TREE_OPERAND (TREE_VALUE (type), 1));
15399       else
15400         return dependent_type_p (type);
15401     }
15402
15403   if (TREE_CODE (expression) == SCOPE_REF
15404       && dependent_scope_ref_p (expression,
15405                                 type_dependent_expression_p))
15406     return true;
15407
15408   if (TREE_CODE (expression) == FUNCTION_DECL
15409       && DECL_LANG_SPECIFIC (expression)
15410       && DECL_TEMPLATE_INFO (expression)
15411       && (any_dependent_template_arguments_p
15412           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
15413     return true;
15414
15415   if (TREE_CODE (expression) == TEMPLATE_DECL
15416       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
15417     return false;
15418
15419   if (TREE_CODE (expression) == STMT_EXPR)
15420     expression = stmt_expr_value_expr (expression);
15421
15422   if (TREE_TYPE (expression) == unknown_type_node)
15423     {
15424       if (TREE_CODE (expression) == ADDR_EXPR)
15425         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
15426       if (TREE_CODE (expression) == COMPONENT_REF
15427           || TREE_CODE (expression) == OFFSET_REF)
15428         {
15429           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
15430             return true;
15431           expression = TREE_OPERAND (expression, 1);
15432           if (TREE_CODE (expression) == IDENTIFIER_NODE)
15433             return false;
15434         }
15435       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
15436       if (TREE_CODE (expression) == SCOPE_REF)
15437         return false;
15438
15439       if (TREE_CODE (expression) == BASELINK)
15440         expression = BASELINK_FUNCTIONS (expression);
15441
15442       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
15443         {
15444           if (any_dependent_template_arguments_p
15445               (TREE_OPERAND (expression, 1)))
15446             return true;
15447           expression = TREE_OPERAND (expression, 0);
15448         }
15449       gcc_assert (TREE_CODE (expression) == OVERLOAD
15450                   || TREE_CODE (expression) == FUNCTION_DECL);
15451
15452       while (expression)
15453         {
15454           if (type_dependent_expression_p (OVL_CURRENT (expression)))
15455             return true;
15456           expression = OVL_NEXT (expression);
15457         }
15458       return false;
15459     }
15460
15461   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
15462
15463   return (dependent_type_p (TREE_TYPE (expression)));
15464 }
15465
15466 /* Returns TRUE if ARGS (a TREE_LIST of arguments to a function call)
15467    contains a type-dependent expression.  */
15468
15469 bool
15470 any_type_dependent_arguments_p (const_tree args)
15471 {
15472   while (args)
15473     {
15474       tree arg = TREE_VALUE (args);
15475
15476       if (type_dependent_expression_p (arg))
15477         return true;
15478       args = TREE_CHAIN (args);
15479     }
15480   return false;
15481 }
15482
15483 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
15484    expressions) contains any value-dependent expressions.  */
15485
15486 bool
15487 any_value_dependent_elements_p (const_tree list)
15488 {
15489   for (; list; list = TREE_CHAIN (list))
15490     if (value_dependent_expression_p (TREE_VALUE (list)))
15491       return true;
15492
15493   return false;
15494 }
15495
15496 /* Returns TRUE if the ARG (a template argument) is dependent.  */
15497
15498 bool
15499 dependent_template_arg_p (tree arg)
15500 {
15501   if (!processing_template_decl)
15502     return false;
15503
15504   if (TREE_CODE (arg) == TEMPLATE_DECL
15505       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
15506     return dependent_template_p (arg);
15507   else if (ARGUMENT_PACK_P (arg))
15508     {
15509       tree args = ARGUMENT_PACK_ARGS (arg);
15510       int i, len = TREE_VEC_LENGTH (args);
15511       for (i = 0; i < len; ++i)
15512         {
15513           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
15514             return true;
15515         }
15516
15517       return false;
15518     }
15519   else if (TYPE_P (arg))
15520     return dependent_type_p (arg);
15521   else
15522     return (type_dependent_expression_p (arg)
15523             || value_dependent_expression_p (arg));
15524 }
15525
15526 /* Returns true if ARGS (a collection of template arguments) contains
15527    any types that require structural equality testing.  */
15528
15529 bool
15530 any_template_arguments_need_structural_equality_p (tree args)
15531 {
15532   int i;
15533   int j;
15534
15535   if (!args)
15536     return false;
15537   if (args == error_mark_node)
15538     return true;
15539
15540   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
15541     {
15542       tree level = TMPL_ARGS_LEVEL (args, i + 1);
15543       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
15544         {
15545           tree arg = TREE_VEC_ELT (level, j);
15546           tree packed_args = NULL_TREE;
15547           int k, len = 1;
15548
15549           if (ARGUMENT_PACK_P (arg))
15550             {
15551               /* Look inside the argument pack.  */
15552               packed_args = ARGUMENT_PACK_ARGS (arg);
15553               len = TREE_VEC_LENGTH (packed_args);
15554             }
15555
15556           for (k = 0; k < len; ++k)
15557             {
15558               if (packed_args)
15559                 arg = TREE_VEC_ELT (packed_args, k);
15560
15561               if (error_operand_p (arg))
15562                 return true;
15563               else if (TREE_CODE (arg) == TEMPLATE_DECL
15564                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
15565                 continue;
15566               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
15567                 return true;
15568               else if (!TYPE_P (arg) && TREE_TYPE (arg)
15569                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
15570                 return true;
15571             }
15572         }
15573     }
15574
15575   return false;
15576 }
15577
15578 /* Returns true if ARGS (a collection of template arguments) contains
15579    any dependent arguments.  */
15580
15581 bool
15582 any_dependent_template_arguments_p (const_tree args)
15583 {
15584   int i;
15585   int j;
15586
15587   if (!args)
15588     return false;
15589   if (args == error_mark_node)
15590     return true;
15591
15592   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
15593     {
15594       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
15595       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
15596         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
15597           return true;
15598     }
15599
15600   return false;
15601 }
15602
15603 /* Returns TRUE if the template TMPL is dependent.  */
15604
15605 bool
15606 dependent_template_p (tree tmpl)
15607 {
15608   if (TREE_CODE (tmpl) == OVERLOAD)
15609     {
15610       while (tmpl)
15611         {
15612           if (dependent_template_p (OVL_FUNCTION (tmpl)))
15613             return true;
15614           tmpl = OVL_CHAIN (tmpl);
15615         }
15616       return false;
15617     }
15618
15619   /* Template template parameters are dependent.  */
15620   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
15621       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
15622     return true;
15623   /* So are names that have not been looked up.  */
15624   if (TREE_CODE (tmpl) == SCOPE_REF
15625       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
15626     return true;
15627   /* So are member templates of dependent classes.  */
15628   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
15629     return dependent_type_p (DECL_CONTEXT (tmpl));
15630   return false;
15631 }
15632
15633 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
15634
15635 bool
15636 dependent_template_id_p (tree tmpl, tree args)
15637 {
15638   return (dependent_template_p (tmpl)
15639           || any_dependent_template_arguments_p (args));
15640 }
15641
15642 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
15643    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
15644    no such TYPE can be found.  Note that this function peers inside
15645    uninstantiated templates and therefore should be used only in
15646    extremely limited situations.  ONLY_CURRENT_P restricts this
15647    peering to the currently open classes hierarchy (which is required
15648    when comparing types).  */
15649
15650 tree
15651 resolve_typename_type (tree type, bool only_current_p)
15652 {
15653   tree scope;
15654   tree name;
15655   tree decl;
15656   int quals;
15657   tree pushed_scope;
15658   tree result;
15659
15660   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
15661
15662   scope = TYPE_CONTEXT (type);
15663   name = TYPE_IDENTIFIER (type);
15664
15665   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
15666      it first before we can figure out what NAME refers to.  */
15667   if (TREE_CODE (scope) == TYPENAME_TYPE)
15668     scope = resolve_typename_type (scope, only_current_p);
15669   /* If we don't know what SCOPE refers to, then we cannot resolve the
15670      TYPENAME_TYPE.  */
15671   if (TREE_CODE (scope) == TYPENAME_TYPE)
15672     return type;
15673   /* If the SCOPE is a template type parameter, we have no way of
15674      resolving the name.  */
15675   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
15676     return type;
15677   /* If the SCOPE is not the current instantiation, there's no reason
15678      to look inside it.  */
15679   if (only_current_p && !currently_open_class (scope))
15680     return type;
15681   /* If SCOPE is a partial instantiation, it will not have a valid
15682      TYPE_FIELDS list, so use the original template.  */
15683   scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
15684   /* Enter the SCOPE so that name lookup will be resolved as if we
15685      were in the class definition.  In particular, SCOPE will no
15686      longer be considered a dependent type.  */
15687   pushed_scope = push_scope (scope);
15688   /* Look up the declaration.  */
15689   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
15690
15691   result = NULL_TREE;
15692   
15693   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
15694      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
15695   if (!decl)
15696     /*nop*/;
15697   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
15698            && TREE_CODE (decl) == TYPE_DECL)
15699     {
15700       result = TREE_TYPE (decl);
15701       if (result == error_mark_node)
15702         result = NULL_TREE;
15703     }
15704   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
15705            && DECL_CLASS_TEMPLATE_P (decl))
15706     {
15707       tree tmpl;
15708       tree args;
15709       /* Obtain the template and the arguments.  */
15710       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
15711       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
15712       /* Instantiate the template.  */
15713       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
15714                                       /*entering_scope=*/0,
15715                                       tf_error | tf_user);
15716       if (result == error_mark_node)
15717         result = NULL_TREE;
15718     }
15719   
15720   /* Leave the SCOPE.  */
15721   if (pushed_scope)
15722     pop_scope (pushed_scope);
15723
15724   /* If we failed to resolve it, return the original typename.  */
15725   if (!result)
15726     return type;
15727   
15728   /* If lookup found a typename type, resolve that too.  */
15729   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
15730     {
15731       /* Ill-formed programs can cause infinite recursion here, so we
15732          must catch that.  */
15733       TYPENAME_IS_RESOLVING_P (type) = 1;
15734       result = resolve_typename_type (result, only_current_p);
15735       TYPENAME_IS_RESOLVING_P (type) = 0;
15736     }
15737   
15738   /* Qualify the resulting type.  */
15739   quals = cp_type_quals (type);
15740   if (quals)
15741     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
15742
15743   return result;
15744 }
15745
15746 /* EXPR is an expression which is not type-dependent.  Return a proxy
15747    for EXPR that can be used to compute the types of larger
15748    expressions containing EXPR.  */
15749
15750 tree
15751 build_non_dependent_expr (tree expr)
15752 {
15753   tree inner_expr;
15754
15755   /* Preserve null pointer constants so that the type of things like
15756      "p == 0" where "p" is a pointer can be determined.  */
15757   if (null_ptr_cst_p (expr))
15758     return expr;
15759   /* Preserve OVERLOADs; the functions must be available to resolve
15760      types.  */
15761   inner_expr = expr;
15762   if (TREE_CODE (inner_expr) == STMT_EXPR)
15763     inner_expr = stmt_expr_value_expr (inner_expr);
15764   if (TREE_CODE (inner_expr) == ADDR_EXPR)
15765     inner_expr = TREE_OPERAND (inner_expr, 0);
15766   if (TREE_CODE (inner_expr) == COMPONENT_REF)
15767     inner_expr = TREE_OPERAND (inner_expr, 1);
15768   if (is_overloaded_fn (inner_expr)
15769       || TREE_CODE (inner_expr) == OFFSET_REF)
15770     return expr;
15771   /* There is no need to return a proxy for a variable.  */
15772   if (TREE_CODE (expr) == VAR_DECL)
15773     return expr;
15774   /* Preserve string constants; conversions from string constants to
15775      "char *" are allowed, even though normally a "const char *"
15776      cannot be used to initialize a "char *".  */
15777   if (TREE_CODE (expr) == STRING_CST)
15778     return expr;
15779   /* Preserve arithmetic constants, as an optimization -- there is no
15780      reason to create a new node.  */
15781   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
15782     return expr;
15783   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
15784      There is at least one place where we want to know that a
15785      particular expression is a throw-expression: when checking a ?:
15786      expression, there are special rules if the second or third
15787      argument is a throw-expression.  */
15788   if (TREE_CODE (expr) == THROW_EXPR)
15789     return expr;
15790
15791   if (TREE_CODE (expr) == COND_EXPR)
15792     return build3 (COND_EXPR,
15793                    TREE_TYPE (expr),
15794                    TREE_OPERAND (expr, 0),
15795                    (TREE_OPERAND (expr, 1)
15796                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
15797                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
15798                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
15799   if (TREE_CODE (expr) == COMPOUND_EXPR
15800       && !COMPOUND_EXPR_OVERLOADED (expr))
15801     return build2 (COMPOUND_EXPR,
15802                    TREE_TYPE (expr),
15803                    TREE_OPERAND (expr, 0),
15804                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
15805
15806   /* If the type is unknown, it can't really be non-dependent */
15807   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
15808
15809   /* Otherwise, build a NON_DEPENDENT_EXPR.
15810
15811      REFERENCE_TYPEs are not stripped for expressions in templates
15812      because doing so would play havoc with mangling.  Consider, for
15813      example:
15814
15815        template <typename T> void f<T& g>() { g(); }
15816
15817      In the body of "f", the expression for "g" will have
15818      REFERENCE_TYPE, even though the standard says that it should
15819      not.  The reason is that we must preserve the syntactic form of
15820      the expression so that mangling (say) "f<g>" inside the body of
15821      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
15822      stripped here.  */
15823   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
15824 }
15825
15826 /* ARGS is a TREE_LIST of expressions as arguments to a function call.
15827    Return a new TREE_LIST with the various arguments replaced with
15828    equivalent non-dependent expressions.  */
15829
15830 tree
15831 build_non_dependent_args (tree args)
15832 {
15833   tree a;
15834   tree new_args;
15835
15836   new_args = NULL_TREE;
15837   for (a = args; a; a = TREE_CHAIN (a))
15838     new_args = tree_cons (NULL_TREE,
15839                           build_non_dependent_expr (TREE_VALUE (a)),
15840                           new_args);
15841   return nreverse (new_args);
15842 }
15843
15844 #include "gt-cp-pt.h"