OSDN Git Service

PR c++/38950
[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, 2008, 2009
4    Free Software Foundation, Inc.
5    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
6    Rewritten by Jason Merrill (jason@cygnus.com).
7
8 This file is part of GCC.
9
10 GCC is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3, or (at your option)
13 any later version.
14
15 GCC is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 GNU General Public License for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3.  If not see
22 <http://www.gnu.org/licenses/>.  */
23
24 /* Known bugs or deficiencies include:
25
26      all methods must be provided in header files; can't use a source
27      file that contains only the method templates and "just win".  */
28
29 #include "config.h"
30 #include "system.h"
31 #include "coretypes.h"
32 #include "tm.h"
33 #include "obstack.h"
34 #include "tree.h"
35 #include "pointer-set.h"
36 #include "flags.h"
37 #include "c-common.h"
38 #include "cp-tree.h"
39 #include "cp-objcp-common.h"
40 #include "tree-inline.h"
41 #include "decl.h"
42 #include "output.h"
43 #include "except.h"
44 #include "toplev.h"
45 #include "rtl.h"
46 #include "timevar.h"
47 #include "tree-iterator.h"
48 #include "vecprim.h"
49
50 /* The type of functions taking a tree, and some additional data, and
51    returning an int.  */
52 typedef int (*tree_fn_t) (tree, void*);
53
54 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
55    instantiations have been deferred, either because their definitions
56    were not yet available, or because we were putting off doing the work.  */
57 struct pending_template GTY (()) {
58   struct pending_template *next;
59   struct tinst_level *tinst;
60 };
61
62 static GTY(()) struct pending_template *pending_templates;
63 static GTY(()) struct pending_template *last_pending_template;
64
65 int processing_template_parmlist;
66 static int template_header_count;
67
68 static GTY(()) tree saved_trees;
69 static VEC(int,heap) *inline_parm_levels;
70
71 static GTY(()) struct tinst_level *current_tinst_level;
72
73 static GTY(()) tree saved_access_scope;
74
75 /* Live only within one (recursive) call to tsubst_expr.  We use
76    this to pass the statement expression node from the STMT_EXPR
77    to the EXPR_STMT that is its result.  */
78 static tree cur_stmt_expr;
79
80 /* A map from local variable declarations in the body of the template
81    presently being instantiated to the corresponding instantiated
82    local variables.  */
83 static htab_t local_specializations;
84
85 /* Contains canonical template parameter types. The vector is indexed by
86    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
87    TREE_LIST, whose TREE_VALUEs contain the canonical template
88    parameters of various types and levels.  */
89 static GTY(()) VEC(tree,gc) *canonical_template_parms;
90
91 #define UNIFY_ALLOW_NONE 0
92 #define UNIFY_ALLOW_MORE_CV_QUAL 1
93 #define UNIFY_ALLOW_LESS_CV_QUAL 2
94 #define UNIFY_ALLOW_DERIVED 4
95 #define UNIFY_ALLOW_INTEGER 8
96 #define UNIFY_ALLOW_OUTER_LEVEL 16
97 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
98 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
99
100 static void push_access_scope (tree);
101 static void pop_access_scope (tree);
102 static bool resolve_overloaded_unification (tree, tree, tree, tree,
103                                             unification_kind_t, int);
104 static int try_one_overload (tree, tree, tree, tree, tree,
105                              unification_kind_t, int, bool);
106 static int unify (tree, tree, tree, tree, int);
107 static void add_pending_template (tree);
108 static int push_tinst_level (tree);
109 static void pop_tinst_level (void);
110 static tree reopen_tinst_level (struct tinst_level *);
111 static tree tsubst_initializer_list (tree, tree);
112 static tree get_class_bindings (tree, tree, tree);
113 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
114                                    bool, bool);
115 static void tsubst_enum (tree, tree, tree);
116 static tree add_to_template_args (tree, tree);
117 static tree add_outermost_template_args (tree, tree);
118 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
119 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
120                                              tree);
121 static int  type_unification_real (tree, tree, tree, tree,
122                                    int, unification_kind_t, int);
123 static void note_template_header (int);
124 static tree convert_nontype_argument_function (tree, tree);
125 static tree convert_nontype_argument (tree, tree);
126 static tree convert_template_argument (tree, tree, tree,
127                                        tsubst_flags_t, int, tree);
128 static int for_each_template_parm (tree, tree_fn_t, void*,
129                                    struct pointer_set_t*, bool);
130 static tree expand_template_argument_pack (tree);
131 static tree build_template_parm_index (int, int, int, tree, tree);
132 static bool inline_needs_template_parms (tree);
133 static void push_inline_template_parms_recursive (tree, int);
134 static tree retrieve_local_specialization (tree);
135 static void register_local_specialization (tree, tree);
136 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
137 static int mark_template_parm (tree, void *);
138 static int template_parm_this_level_p (tree, void *);
139 static tree tsubst_friend_function (tree, tree);
140 static tree tsubst_friend_class (tree, tree);
141 static int can_complete_type_without_circularity (tree);
142 static tree get_bindings (tree, tree, tree, bool);
143 static int template_decl_level (tree);
144 static int check_cv_quals_for_unify (int, tree, tree);
145 static void template_parm_level_and_index (tree, int*, int*);
146 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
147 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
148 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
149 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
150 static void regenerate_decl_from_template (tree, tree);
151 static tree most_specialized_class (tree, tree);
152 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
153 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
154 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
155 static bool check_specialization_scope (void);
156 static tree process_partial_specialization (tree);
157 static void set_current_access_from_decl (tree);
158 static tree get_template_base (tree, tree, tree, tree);
159 static tree try_class_unification (tree, tree, tree, tree);
160 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
161                                            tree, tree);
162 static bool template_template_parm_bindings_ok_p (tree, tree);
163 static int template_args_equal (tree, tree);
164 static void tsubst_default_arguments (tree);
165 static tree for_each_template_parm_r (tree *, int *, void *);
166 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
167 static void copy_default_args_to_explicit_spec (tree);
168 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
169 static int eq_local_specializations (const void *, const void *);
170 static bool dependent_template_arg_p (tree);
171 static bool any_template_arguments_need_structural_equality_p (tree);
172 static bool dependent_type_p_r (tree);
173 static tree tsubst (tree, tree, tsubst_flags_t, tree);
174 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
175 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
176 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
177
178 /* Make the current scope suitable for access checking when we are
179    processing T.  T can be FUNCTION_DECL for instantiated function
180    template, or VAR_DECL for static member variable (need by
181    instantiate_decl).  */
182
183 static void
184 push_access_scope (tree t)
185 {
186   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
187               || TREE_CODE (t) == VAR_DECL);
188
189   if (DECL_FRIEND_CONTEXT (t))
190     push_nested_class (DECL_FRIEND_CONTEXT (t));
191   else if (DECL_CLASS_SCOPE_P (t))
192     push_nested_class (DECL_CONTEXT (t));
193   else
194     push_to_top_level ();
195
196   if (TREE_CODE (t) == FUNCTION_DECL)
197     {
198       saved_access_scope = tree_cons
199         (NULL_TREE, current_function_decl, saved_access_scope);
200       current_function_decl = t;
201     }
202 }
203
204 /* Restore the scope set up by push_access_scope.  T is the node we
205    are processing.  */
206
207 static void
208 pop_access_scope (tree t)
209 {
210   if (TREE_CODE (t) == FUNCTION_DECL)
211     {
212       current_function_decl = TREE_VALUE (saved_access_scope);
213       saved_access_scope = TREE_CHAIN (saved_access_scope);
214     }
215
216   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
217     pop_nested_class ();
218   else
219     pop_from_top_level ();
220 }
221
222 /* Do any processing required when DECL (a member template
223    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
224    to DECL, unless it is a specialization, in which case the DECL
225    itself is returned.  */
226
227 tree
228 finish_member_template_decl (tree decl)
229 {
230   if (decl == error_mark_node)
231     return error_mark_node;
232
233   gcc_assert (DECL_P (decl));
234
235   if (TREE_CODE (decl) == TYPE_DECL)
236     {
237       tree type;
238
239       type = TREE_TYPE (decl);
240       if (type == error_mark_node)
241         return error_mark_node;
242       if (MAYBE_CLASS_TYPE_P (type)
243           && CLASSTYPE_TEMPLATE_INFO (type)
244           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
245         {
246           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
247           check_member_template (tmpl);
248           return tmpl;
249         }
250       return NULL_TREE;
251     }
252   else if (TREE_CODE (decl) == FIELD_DECL)
253     error ("data member %qD cannot be a member template", decl);
254   else if (DECL_TEMPLATE_INFO (decl))
255     {
256       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
257         {
258           check_member_template (DECL_TI_TEMPLATE (decl));
259           return DECL_TI_TEMPLATE (decl);
260         }
261       else
262         return decl;
263     }
264   else
265     error ("invalid member template declaration %qD", decl);
266
267   return error_mark_node;
268 }
269
270 /* Return the template info node corresponding to T, whatever T is.  */
271
272 tree
273 get_template_info (tree t)
274 {
275   tree tinfo = NULL_TREE;
276
277   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
278     tinfo = DECL_TEMPLATE_INFO (t);
279
280   if (!tinfo && TREE_CODE (t) == TYPE_DECL)
281     t = TREE_TYPE (t);
282
283   if (TAGGED_TYPE_P (t))
284     tinfo = TYPE_TEMPLATE_INFO (t);
285
286   return tinfo;
287 }
288
289 /* Returns the template nesting level of the indicated class TYPE.
290
291    For example, in:
292      template <class T>
293      struct A
294      {
295        template <class U>
296        struct B {};
297      };
298
299    A<T>::B<U> has depth two, while A<T> has depth one.
300    Both A<T>::B<int> and A<int>::B<U> have depth one, if
301    they are instantiations, not specializations.
302
303    This function is guaranteed to return 0 if passed NULL_TREE so
304    that, for example, `template_class_depth (current_class_type)' is
305    always safe.  */
306
307 int
308 template_class_depth (tree type)
309 {
310   int depth;
311
312   for (depth = 0;
313        type && TREE_CODE (type) != NAMESPACE_DECL;
314        type = (TREE_CODE (type) == FUNCTION_DECL)
315          ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
316     {
317       tree tinfo = get_template_info (type);
318
319       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
320           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
321         ++depth;
322     }
323
324   return depth;
325 }
326
327 /* Subroutine of maybe_begin_member_template_processing.
328    Returns true if processing DECL needs us to push template parms.  */
329
330 static bool
331 inline_needs_template_parms (tree decl)
332 {
333   if (! DECL_TEMPLATE_INFO (decl))
334     return false;
335
336   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
337           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
338 }
339
340 /* Subroutine of maybe_begin_member_template_processing.
341    Push the template parms in PARMS, starting from LEVELS steps into the
342    chain, and ending at the beginning, since template parms are listed
343    innermost first.  */
344
345 static void
346 push_inline_template_parms_recursive (tree parmlist, int levels)
347 {
348   tree parms = TREE_VALUE (parmlist);
349   int i;
350
351   if (levels > 1)
352     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
353
354   ++processing_template_decl;
355   current_template_parms
356     = tree_cons (size_int (processing_template_decl),
357                  parms, current_template_parms);
358   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
359
360   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
361                NULL);
362   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
363     {
364       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
365
366       if (parm == error_mark_node)
367         continue;
368
369       gcc_assert (DECL_P (parm));
370
371       switch (TREE_CODE (parm))
372         {
373         case TYPE_DECL:
374         case TEMPLATE_DECL:
375           pushdecl (parm);
376           break;
377
378         case PARM_DECL:
379           {
380             /* Make a CONST_DECL as is done in process_template_parm.
381                It is ugly that we recreate this here; the original
382                version built in process_template_parm is no longer
383                available.  */
384             tree decl = build_decl (CONST_DECL, DECL_NAME (parm),
385                                     TREE_TYPE (parm));
386             DECL_ARTIFICIAL (decl) = 1;
387             TREE_CONSTANT (decl) = 1;
388             TREE_READONLY (decl) = 1;
389             DECL_INITIAL (decl) = DECL_INITIAL (parm);
390             SET_DECL_TEMPLATE_PARM_P (decl);
391             pushdecl (decl);
392           }
393           break;
394
395         default:
396           gcc_unreachable ();
397         }
398     }
399 }
400
401 /* Restore the template parameter context for a member template or
402    a friend template defined in a class definition.  */
403
404 void
405 maybe_begin_member_template_processing (tree decl)
406 {
407   tree parms;
408   int levels = 0;
409
410   if (inline_needs_template_parms (decl))
411     {
412       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
413       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
414
415       if (DECL_TEMPLATE_SPECIALIZATION (decl))
416         {
417           --levels;
418           parms = TREE_CHAIN (parms);
419         }
420
421       push_inline_template_parms_recursive (parms, levels);
422     }
423
424   /* Remember how many levels of template parameters we pushed so that
425      we can pop them later.  */
426   VEC_safe_push (int, heap, inline_parm_levels, levels);
427 }
428
429 /* Undo the effects of maybe_begin_member_template_processing.  */
430
431 void
432 maybe_end_member_template_processing (void)
433 {
434   int i;
435   int last;
436
437   if (VEC_length (int, inline_parm_levels) == 0)
438     return;
439
440   last = VEC_pop (int, inline_parm_levels);
441   for (i = 0; i < last; ++i)
442     {
443       --processing_template_decl;
444       current_template_parms = TREE_CHAIN (current_template_parms);
445       poplevel (0, 0, 0);
446     }
447 }
448
449 /* Return a new template argument vector which contains all of ARGS,
450    but has as its innermost set of arguments the EXTRA_ARGS.  */
451
452 static tree
453 add_to_template_args (tree args, tree extra_args)
454 {
455   tree new_args;
456   int extra_depth;
457   int i;
458   int j;
459
460   extra_depth = TMPL_ARGS_DEPTH (extra_args);
461   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
462
463   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
464     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
465
466   for (j = 1; j <= extra_depth; ++j, ++i)
467     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
468
469   return new_args;
470 }
471
472 /* Like add_to_template_args, but only the outermost ARGS are added to
473    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
474    (EXTRA_ARGS) levels are added.  This function is used to combine
475    the template arguments from a partial instantiation with the
476    template arguments used to attain the full instantiation from the
477    partial instantiation.  */
478
479 static tree
480 add_outermost_template_args (tree args, tree extra_args)
481 {
482   tree new_args;
483
484   /* If there are more levels of EXTRA_ARGS than there are ARGS,
485      something very fishy is going on.  */
486   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
487
488   /* If *all* the new arguments will be the EXTRA_ARGS, just return
489      them.  */
490   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
491     return extra_args;
492
493   /* For the moment, we make ARGS look like it contains fewer levels.  */
494   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
495
496   new_args = add_to_template_args (args, extra_args);
497
498   /* Now, we restore ARGS to its full dimensions.  */
499   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
500
501   return new_args;
502 }
503
504 /* Return the N levels of innermost template arguments from the ARGS.  */
505
506 tree
507 get_innermost_template_args (tree args, int n)
508 {
509   tree new_args;
510   int extra_levels;
511   int i;
512
513   gcc_assert (n >= 0);
514
515   /* If N is 1, just return the innermost set of template arguments.  */
516   if (n == 1)
517     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
518
519   /* If we're not removing anything, just return the arguments we were
520      given.  */
521   extra_levels = TMPL_ARGS_DEPTH (args) - n;
522   gcc_assert (extra_levels >= 0);
523   if (extra_levels == 0)
524     return args;
525
526   /* Make a new set of arguments, not containing the outer arguments.  */
527   new_args = make_tree_vec (n);
528   for (i = 1; i <= n; ++i)
529     SET_TMPL_ARGS_LEVEL (new_args, i,
530                          TMPL_ARGS_LEVEL (args, i + extra_levels));
531
532   return new_args;
533 }
534
535 /* The inverse of get_innermost_template_args: Return all but the innermost
536    EXTRA_LEVELS levels of template arguments from the ARGS.  */
537
538 static tree
539 strip_innermost_template_args (tree args, int extra_levels)
540 {
541   tree new_args;
542   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
543   int i;
544
545   gcc_assert (n >= 0);
546
547   /* If N is 1, just return the outermost set of template arguments.  */
548   if (n == 1)
549     return TMPL_ARGS_LEVEL (args, 1);
550
551   /* If we're not removing anything, just return the arguments we were
552      given.  */
553   gcc_assert (extra_levels >= 0);
554   if (extra_levels == 0)
555     return args;
556
557   /* Make a new set of arguments, not containing the inner arguments.  */
558   new_args = make_tree_vec (n);
559   for (i = 1; i <= n; ++i)
560     SET_TMPL_ARGS_LEVEL (new_args, i,
561                          TMPL_ARGS_LEVEL (args, i));
562
563   return new_args;
564 }
565
566 /* We've got a template header coming up; push to a new level for storing
567    the parms.  */
568
569 void
570 begin_template_parm_list (void)
571 {
572   /* We use a non-tag-transparent scope here, which causes pushtag to
573      put tags in this scope, rather than in the enclosing class or
574      namespace scope.  This is the right thing, since we want
575      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
576      global template class, push_template_decl handles putting the
577      TEMPLATE_DECL into top-level scope.  For a nested template class,
578      e.g.:
579
580        template <class T> struct S1 {
581          template <class T> struct S2 {};
582        };
583
584      pushtag contains special code to call pushdecl_with_scope on the
585      TEMPLATE_DECL for S2.  */
586   begin_scope (sk_template_parms, NULL);
587   ++processing_template_decl;
588   ++processing_template_parmlist;
589   note_template_header (0);
590 }
591
592 /* This routine is called when a specialization is declared.  If it is
593    invalid to declare a specialization here, an error is reported and
594    false is returned, otherwise this routine will return true.  */
595
596 static bool
597 check_specialization_scope (void)
598 {
599   tree scope = current_scope ();
600
601   /* [temp.expl.spec]
602
603      An explicit specialization shall be declared in the namespace of
604      which the template is a member, or, for member templates, in the
605      namespace of which the enclosing class or enclosing class
606      template is a member.  An explicit specialization of a member
607      function, member class or static data member of a class template
608      shall be declared in the namespace of which the class template
609      is a member.  */
610   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
611     {
612       error ("explicit specialization in non-namespace scope %qD", scope);
613       return false;
614     }
615
616   /* [temp.expl.spec]
617
618      In an explicit specialization declaration for a member of a class
619      template or a member template that appears in namespace scope,
620      the member template and some of its enclosing class templates may
621      remain unspecialized, except that the declaration shall not
622      explicitly specialize a class member template if its enclosing
623      class templates are not explicitly specialized as well.  */
624   if (current_template_parms)
625     {
626       error ("enclosing class templates are not explicitly specialized");
627       return false;
628     }
629
630   return true;
631 }
632
633 /* We've just seen template <>.  */
634
635 bool
636 begin_specialization (void)
637 {
638   begin_scope (sk_template_spec, NULL);
639   note_template_header (1);
640   return check_specialization_scope ();
641 }
642
643 /* Called at then end of processing a declaration preceded by
644    template<>.  */
645
646 void
647 end_specialization (void)
648 {
649   finish_scope ();
650   reset_specialization ();
651 }
652
653 /* Any template <>'s that we have seen thus far are not referring to a
654    function specialization.  */
655
656 void
657 reset_specialization (void)
658 {
659   processing_specialization = 0;
660   template_header_count = 0;
661 }
662
663 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
664    it was of the form template <>.  */
665
666 static void
667 note_template_header (int specialization)
668 {
669   processing_specialization = specialization;
670   template_header_count++;
671 }
672
673 /* We're beginning an explicit instantiation.  */
674
675 void
676 begin_explicit_instantiation (void)
677 {
678   gcc_assert (!processing_explicit_instantiation);
679   processing_explicit_instantiation = true;
680 }
681
682
683 void
684 end_explicit_instantiation (void)
685 {
686   gcc_assert (processing_explicit_instantiation);
687   processing_explicit_instantiation = false;
688 }
689
690 /* An explicit specialization or partial specialization TMPL is being
691    declared.  Check that the namespace in which the specialization is
692    occurring is permissible.  Returns false iff it is invalid to
693    specialize TMPL in the current namespace.  */
694
695 static bool
696 check_specialization_namespace (tree tmpl)
697 {
698   tree tpl_ns = decl_namespace_context (tmpl);
699
700   /* [tmpl.expl.spec]
701
702      An explicit specialization shall be declared in the namespace of
703      which the template is a member, or, for member templates, in the
704      namespace of which the enclosing class or enclosing class
705      template is a member.  An explicit specialization of a member
706      function, member class or static data member of a class template
707      shall be declared in the namespace of which the class template is
708      a member.  */
709   if (is_associated_namespace (current_namespace, tpl_ns))
710     /* Same or super-using namespace.  */
711     return true;
712   else
713     {
714       permerror (input_location, "specialization of %qD in different namespace", tmpl);
715       permerror (input_location, "  from definition of %q+#D", tmpl);
716       return false;
717     }
718 }
719
720 /* SPEC is an explicit instantiation.  Check that it is valid to
721    perform this explicit instantiation in the current namespace.  */
722
723 static void
724 check_explicit_instantiation_namespace (tree spec)
725 {
726   tree ns;
727
728   /* DR 275: An explicit instantiation shall appear in an enclosing
729      namespace of its template.  */
730   ns = decl_namespace_context (spec);
731   if (!is_ancestor (current_namespace, ns))
732     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
733                "(which does not enclose namespace %qD)",
734                spec, current_namespace, ns);
735 }
736
737 /* The TYPE is being declared.  If it is a template type, that means it
738    is a partial specialization.  Do appropriate error-checking.  */
739
740 tree
741 maybe_process_partial_specialization (tree type)
742 {
743   tree context;
744
745   if (type == error_mark_node)
746     return error_mark_node;
747
748   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
749     {
750       error ("name of class shadows template template parameter %qD",
751              TYPE_NAME (type));
752       return error_mark_node;
753     }
754
755   context = TYPE_CONTEXT (type);
756
757   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
758     {
759       /* This is for ordinary explicit specialization and partial
760          specialization of a template class such as:
761
762            template <> class C<int>;
763
764          or:
765
766            template <class T> class C<T*>;
767
768          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
769
770       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
771           && !COMPLETE_TYPE_P (type))
772         {
773           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
774           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
775           if (processing_template_decl)
776             {
777               if (push_template_decl (TYPE_MAIN_DECL (type))
778                   == error_mark_node)
779                 return error_mark_node;
780             }
781         }
782       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
783         error ("specialization of %qT after instantiation", type);
784     }
785   else if (CLASS_TYPE_P (type)
786            && !CLASSTYPE_USE_TEMPLATE (type)
787            && CLASSTYPE_TEMPLATE_INFO (type)
788            && context && CLASS_TYPE_P (context)
789            && CLASSTYPE_TEMPLATE_INFO (context))
790     {
791       /* This is for an explicit specialization of member class
792          template according to [temp.expl.spec/18]:
793
794            template <> template <class U> class C<int>::D;
795
796          The context `C<int>' must be an implicit instantiation.
797          Otherwise this is just a member class template declared
798          earlier like:
799
800            template <> class C<int> { template <class U> class D; };
801            template <> template <class U> class C<int>::D;
802
803          In the first case, `C<int>::D' is a specialization of `C<T>::D'
804          while in the second case, `C<int>::D' is a primary template
805          and `C<T>::D' may not exist.  */
806
807       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
808           && !COMPLETE_TYPE_P (type))
809         {
810           tree t;
811
812           if (current_namespace
813               != decl_namespace_context (CLASSTYPE_TI_TEMPLATE (type)))
814             {
815               permerror (input_location, "specializing %q#T in different namespace", type);
816               permerror (input_location, "  from definition of %q+#D",
817                          CLASSTYPE_TI_TEMPLATE (type));
818             }
819
820           /* Check for invalid specialization after instantiation:
821
822                template <> template <> class C<int>::D<int>;
823                template <> template <class U> class C<int>::D;  */
824
825           for (t = DECL_TEMPLATE_INSTANTIATIONS
826                  (most_general_template (CLASSTYPE_TI_TEMPLATE (type)));
827                t; t = TREE_CHAIN (t))
828             if (TREE_VALUE (t) != type
829                 && TYPE_CONTEXT (TREE_VALUE (t)) == context)
830               error ("specialization %qT after instantiation %qT",
831                      type, TREE_VALUE (t));
832
833           /* Mark TYPE as a specialization.  And as a result, we only
834              have one level of template argument for the innermost
835              class template.  */
836           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
837           CLASSTYPE_TI_ARGS (type)
838             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
839         }
840     }
841   else if (processing_specialization)
842     {
843       error ("explicit specialization of non-template %qT", type);
844       return error_mark_node;
845     }
846
847   return type;
848 }
849
850 /* Returns nonzero if we can optimize the retrieval of specializations
851    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
852    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
853
854 static inline bool
855 optimize_specialization_lookup_p (tree tmpl)
856 {
857   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
858           && DECL_CLASS_SCOPE_P (tmpl)
859           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
860              parameter.  */
861           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
862           /* The optimized lookup depends on the fact that the
863              template arguments for the member function template apply
864              purely to the containing class, which is not true if the
865              containing class is an explicit or partial
866              specialization.  */
867           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
868           && !DECL_MEMBER_TEMPLATE_P (tmpl)
869           && !DECL_CONV_FN_P (tmpl)
870           /* It is possible to have a template that is not a member
871              template and is not a member of a template class:
872
873              template <typename T>
874              struct S { friend A::f(); };
875
876              Here, the friend function is a template, but the context does
877              not have template information.  The optimized lookup relies
878              on having ARGS be the template arguments for both the class
879              and the function template.  */
880           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
881 }
882
883 /* Retrieve the specialization (in the sense of [temp.spec] - a
884    specialization is either an instantiation or an explicit
885    specialization) of TMPL for the given template ARGS.  If there is
886    no such specialization, return NULL_TREE.  The ARGS are a vector of
887    arguments, or a vector of vectors of arguments, in the case of
888    templates with more than one level of parameters.
889
890    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
891    then we search for a partial specialization matching ARGS.  This
892    parameter is ignored if TMPL is not a class template.  */
893
894 static tree
895 retrieve_specialization (tree tmpl, tree args,
896                          bool class_specializations_p)
897 {
898   if (args == error_mark_node)
899     return NULL_TREE;
900
901   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
902
903   /* There should be as many levels of arguments as there are
904      levels of parameters.  */
905   gcc_assert (TMPL_ARGS_DEPTH (args)
906               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
907
908   if (optimize_specialization_lookup_p (tmpl))
909     {
910       tree class_template;
911       tree class_specialization;
912       VEC(tree,gc) *methods;
913       tree fns;
914       int idx;
915
916       /* The template arguments actually apply to the containing
917          class.  Find the class specialization with those
918          arguments.  */
919       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
920       class_specialization
921         = retrieve_specialization (class_template, args,
922                                    /*class_specializations_p=*/false);
923       if (!class_specialization)
924         return NULL_TREE;
925       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
926          for the specialization.  */
927       idx = class_method_index_for_fn (class_specialization, tmpl);
928       if (idx == -1)
929         return NULL_TREE;
930       /* Iterate through the methods with the indicated name, looking
931          for the one that has an instance of TMPL.  */
932       methods = CLASSTYPE_METHOD_VEC (class_specialization);
933       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
934         {
935           tree fn = OVL_CURRENT (fns);
936           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl)
937             return fn;
938         }
939       return NULL_TREE;
940     }
941   else
942     {
943       tree *sp;
944       tree *head;
945
946       /* Class templates store their instantiations on the
947          DECL_TEMPLATE_INSTANTIATIONS list; other templates use the
948          DECL_TEMPLATE_SPECIALIZATIONS list.  */
949       if (!class_specializations_p
950           && TREE_CODE (DECL_TEMPLATE_RESULT (tmpl)) == TYPE_DECL
951           && TAGGED_TYPE_P (TREE_TYPE (tmpl)))
952         sp = &DECL_TEMPLATE_INSTANTIATIONS (tmpl);
953       else
954         sp = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
955       head = sp;
956       /* Iterate through the list until we find a matching template.  */
957       while (*sp != NULL_TREE)
958         {
959           tree spec = *sp;
960
961           if (comp_template_args (TREE_PURPOSE (spec), args))
962             {
963               /* Use the move-to-front heuristic to speed up future
964                  searches.  */
965               if (spec != *head)
966                 {
967                   *sp = TREE_CHAIN (*sp);
968                   TREE_CHAIN (spec) = *head;
969                   *head = spec;
970                 }
971               return TREE_VALUE (spec);
972             }
973           sp = &TREE_CHAIN (spec);
974         }
975     }
976
977   return NULL_TREE;
978 }
979
980 /* Like retrieve_specialization, but for local declarations.  */
981
982 static tree
983 retrieve_local_specialization (tree tmpl)
984 {
985   tree spec;
986
987   if (local_specializations == NULL)
988     return NULL_TREE;
989
990   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
991                                      htab_hash_pointer (tmpl));
992   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
993 }
994
995 /* Returns nonzero iff DECL is a specialization of TMPL.  */
996
997 int
998 is_specialization_of (tree decl, tree tmpl)
999 {
1000   tree t;
1001
1002   if (TREE_CODE (decl) == FUNCTION_DECL)
1003     {
1004       for (t = decl;
1005            t != NULL_TREE;
1006            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1007         if (t == tmpl)
1008           return 1;
1009     }
1010   else
1011     {
1012       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1013
1014       for (t = TREE_TYPE (decl);
1015            t != NULL_TREE;
1016            t = CLASSTYPE_USE_TEMPLATE (t)
1017              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1018         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1019           return 1;
1020     }
1021
1022   return 0;
1023 }
1024
1025 /* Returns nonzero iff DECL is a specialization of friend declaration
1026    FRIEND_DECL according to [temp.friend].  */
1027
1028 bool
1029 is_specialization_of_friend (tree decl, tree friend_decl)
1030 {
1031   bool need_template = true;
1032   int template_depth;
1033
1034   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1035               || TREE_CODE (decl) == TYPE_DECL);
1036
1037   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1038      of a template class, we want to check if DECL is a specialization
1039      if this.  */
1040   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1041       && DECL_TEMPLATE_INFO (friend_decl)
1042       && !DECL_USE_TEMPLATE (friend_decl))
1043     {
1044       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1045       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1046       need_template = false;
1047     }
1048   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1049            && !PRIMARY_TEMPLATE_P (friend_decl))
1050     need_template = false;
1051
1052   /* There is nothing to do if this is not a template friend.  */
1053   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1054     return false;
1055
1056   if (is_specialization_of (decl, friend_decl))
1057     return true;
1058
1059   /* [temp.friend/6]
1060      A member of a class template may be declared to be a friend of a
1061      non-template class.  In this case, the corresponding member of
1062      every specialization of the class template is a friend of the
1063      class granting friendship.
1064
1065      For example, given a template friend declaration
1066
1067        template <class T> friend void A<T>::f();
1068
1069      the member function below is considered a friend
1070
1071        template <> struct A<int> {
1072          void f();
1073        };
1074
1075      For this type of template friend, TEMPLATE_DEPTH below will be
1076      nonzero.  To determine if DECL is a friend of FRIEND, we first
1077      check if the enclosing class is a specialization of another.  */
1078
1079   template_depth = template_class_depth (DECL_CONTEXT (friend_decl));
1080   if (template_depth
1081       && DECL_CLASS_SCOPE_P (decl)
1082       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1083                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1084     {
1085       /* Next, we check the members themselves.  In order to handle
1086          a few tricky cases, such as when FRIEND_DECL's are
1087
1088            template <class T> friend void A<T>::g(T t);
1089            template <class T> template <T t> friend void A<T>::h();
1090
1091          and DECL's are
1092
1093            void A<int>::g(int);
1094            template <int> void A<int>::h();
1095
1096          we need to figure out ARGS, the template arguments from
1097          the context of DECL.  This is required for template substitution
1098          of `T' in the function parameter of `g' and template parameter
1099          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1100
1101       tree context = DECL_CONTEXT (decl);
1102       tree args = NULL_TREE;
1103       int current_depth = 0;
1104
1105       while (current_depth < template_depth)
1106         {
1107           if (CLASSTYPE_TEMPLATE_INFO (context))
1108             {
1109               if (current_depth == 0)
1110                 args = TYPE_TI_ARGS (context);
1111               else
1112                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1113               current_depth++;
1114             }
1115           context = TYPE_CONTEXT (context);
1116         }
1117
1118       if (TREE_CODE (decl) == FUNCTION_DECL)
1119         {
1120           bool is_template;
1121           tree friend_type;
1122           tree decl_type;
1123           tree friend_args_type;
1124           tree decl_args_type;
1125
1126           /* Make sure that both DECL and FRIEND_DECL are templates or
1127              non-templates.  */
1128           is_template = DECL_TEMPLATE_INFO (decl)
1129                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1130           if (need_template ^ is_template)
1131             return false;
1132           else if (is_template)
1133             {
1134               /* If both are templates, check template parameter list.  */
1135               tree friend_parms
1136                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1137                                          args, tf_none);
1138               if (!comp_template_parms
1139                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1140                       friend_parms))
1141                 return false;
1142
1143               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1144             }
1145           else
1146             decl_type = TREE_TYPE (decl);
1147
1148           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1149                                               tf_none, NULL_TREE);
1150           if (friend_type == error_mark_node)
1151             return false;
1152
1153           /* Check if return types match.  */
1154           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1155             return false;
1156
1157           /* Check if function parameter types match, ignoring the
1158              `this' parameter.  */
1159           friend_args_type = TYPE_ARG_TYPES (friend_type);
1160           decl_args_type = TYPE_ARG_TYPES (decl_type);
1161           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1162             friend_args_type = TREE_CHAIN (friend_args_type);
1163           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1164             decl_args_type = TREE_CHAIN (decl_args_type);
1165
1166           return compparms (decl_args_type, friend_args_type);
1167         }
1168       else
1169         {
1170           /* DECL is a TYPE_DECL */
1171           bool is_template;
1172           tree decl_type = TREE_TYPE (decl);
1173
1174           /* Make sure that both DECL and FRIEND_DECL are templates or
1175              non-templates.  */
1176           is_template
1177             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1178               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1179
1180           if (need_template ^ is_template)
1181             return false;
1182           else if (is_template)
1183             {
1184               tree friend_parms;
1185               /* If both are templates, check the name of the two
1186                  TEMPLATE_DECL's first because is_friend didn't.  */
1187               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1188                   != DECL_NAME (friend_decl))
1189                 return false;
1190
1191               /* Now check template parameter list.  */
1192               friend_parms
1193                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1194                                          args, tf_none);
1195               return comp_template_parms
1196                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1197                  friend_parms);
1198             }
1199           else
1200             return (DECL_NAME (decl)
1201                     == DECL_NAME (friend_decl));
1202         }
1203     }
1204   return false;
1205 }
1206
1207 /* Register the specialization SPEC as a specialization of TMPL with
1208    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1209    is actually just a friend declaration.  Returns SPEC, or an
1210    equivalent prior declaration, if available.  */
1211
1212 static tree
1213 register_specialization (tree spec, tree tmpl, tree args, bool is_friend)
1214 {
1215   tree fn;
1216
1217   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
1218
1219   if (TREE_CODE (spec) == FUNCTION_DECL
1220       && uses_template_parms (DECL_TI_ARGS (spec)))
1221     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1222        register it; we want the corresponding TEMPLATE_DECL instead.
1223        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1224        the more obvious `uses_template_parms (spec)' to avoid problems
1225        with default function arguments.  In particular, given
1226        something like this:
1227
1228           template <class T> void f(T t1, T t = T())
1229
1230        the default argument expression is not substituted for in an
1231        instantiation unless and until it is actually needed.  */
1232     return spec;
1233
1234   fn = retrieve_specialization (tmpl, args,
1235                                 /*class_specializations_p=*/false);
1236   /* We can sometimes try to re-register a specialization that we've
1237      already got.  In particular, regenerate_decl_from_template calls
1238      duplicate_decls which will update the specialization list.  But,
1239      we'll still get called again here anyhow.  It's more convenient
1240      to simply allow this than to try to prevent it.  */
1241   if (fn == spec)
1242     return spec;
1243   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1244     {
1245       if (DECL_TEMPLATE_INSTANTIATION (fn))
1246         {
1247           if (TREE_USED (fn)
1248               || DECL_EXPLICIT_INSTANTIATION (fn))
1249             {
1250               error ("specialization of %qD after instantiation",
1251                      fn);
1252               return error_mark_node;
1253             }
1254           else
1255             {
1256               tree clone;
1257               /* This situation should occur only if the first
1258                  specialization is an implicit instantiation, the
1259                  second is an explicit specialization, and the
1260                  implicit instantiation has not yet been used.  That
1261                  situation can occur if we have implicitly
1262                  instantiated a member function and then specialized
1263                  it later.
1264
1265                  We can also wind up here if a friend declaration that
1266                  looked like an instantiation turns out to be a
1267                  specialization:
1268
1269                    template <class T> void foo(T);
1270                    class S { friend void foo<>(int) };
1271                    template <> void foo(int);
1272
1273                  We transform the existing DECL in place so that any
1274                  pointers to it become pointers to the updated
1275                  declaration.
1276
1277                  If there was a definition for the template, but not
1278                  for the specialization, we want this to look as if
1279                  there were no definition, and vice versa.  */
1280               DECL_INITIAL (fn) = NULL_TREE;
1281               duplicate_decls (spec, fn, is_friend);
1282               /* The call to duplicate_decls will have applied
1283                  [temp.expl.spec]:
1284
1285                    An explicit specialization of a function template
1286                    is inline only if it is explicitly declared to be,
1287                    and independently of whether its function template
1288                    is.
1289
1290                 to the primary function; now copy the inline bits to
1291                 the various clones.  */
1292               FOR_EACH_CLONE (clone, fn)
1293                 DECL_DECLARED_INLINE_P (clone)
1294                   = DECL_DECLARED_INLINE_P (fn);
1295               check_specialization_namespace (fn);
1296
1297               return fn;
1298             }
1299         }
1300       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1301         {
1302           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1303             /* Dup decl failed, but this is a new definition. Set the
1304                line number so any errors match this new
1305                definition.  */
1306             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1307
1308           return fn;
1309         }
1310     }
1311
1312   /* A specialization must be declared in the same namespace as the
1313      template it is specializing.  */
1314   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1315       && !check_specialization_namespace (tmpl))
1316     DECL_CONTEXT (spec) = FROB_CONTEXT (decl_namespace_context (tmpl));
1317
1318   if (!optimize_specialization_lookup_p (tmpl))
1319     DECL_TEMPLATE_SPECIALIZATIONS (tmpl)
1320       = tree_cons (args, spec, DECL_TEMPLATE_SPECIALIZATIONS (tmpl));
1321
1322   return spec;
1323 }
1324
1325 /* Unregister the specialization SPEC as a specialization of TMPL.
1326    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1327    if the SPEC was listed as a specialization of TMPL.  */
1328
1329 bool
1330 reregister_specialization (tree spec, tree tmpl, tree new_spec)
1331 {
1332   tree* s;
1333
1334   for (s = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
1335        *s != NULL_TREE;
1336        s = &TREE_CHAIN (*s))
1337     if (TREE_VALUE (*s) == spec)
1338       {
1339         if (!new_spec)
1340           *s = TREE_CHAIN (*s);
1341         else
1342           TREE_VALUE (*s) = new_spec;
1343         return 1;
1344       }
1345
1346   return 0;
1347 }
1348
1349 /* Compare an entry in the local specializations hash table P1 (which
1350    is really a pointer to a TREE_LIST) with P2 (which is really a
1351    DECL).  */
1352
1353 static int
1354 eq_local_specializations (const void *p1, const void *p2)
1355 {
1356   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1357 }
1358
1359 /* Hash P1, an entry in the local specializations table.  */
1360
1361 static hashval_t
1362 hash_local_specialization (const void* p1)
1363 {
1364   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1365 }
1366
1367 /* Like register_specialization, but for local declarations.  We are
1368    registering SPEC, an instantiation of TMPL.  */
1369
1370 static void
1371 register_local_specialization (tree spec, tree tmpl)
1372 {
1373   void **slot;
1374
1375   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1376                                    htab_hash_pointer (tmpl), INSERT);
1377   *slot = build_tree_list (spec, tmpl);
1378 }
1379
1380 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1381    specialized class.  */
1382
1383 bool
1384 explicit_class_specialization_p (tree type)
1385 {
1386   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1387     return false;
1388   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1389 }
1390
1391 /* Print the list of candidate FNS in an error message.  */
1392
1393 void
1394 print_candidates (tree fns)
1395 {
1396   tree fn;
1397
1398   const char *str = "candidates are:";
1399
1400   for (fn = fns; fn != NULL_TREE; fn = TREE_CHAIN (fn))
1401     {
1402       tree f;
1403
1404       for (f = TREE_VALUE (fn); f; f = OVL_NEXT (f))
1405         error ("%s %+#D", str, OVL_CURRENT (f));
1406       str = "               ";
1407     }
1408 }
1409
1410 /* Returns the template (one of the functions given by TEMPLATE_ID)
1411    which can be specialized to match the indicated DECL with the
1412    explicit template args given in TEMPLATE_ID.  The DECL may be
1413    NULL_TREE if none is available.  In that case, the functions in
1414    TEMPLATE_ID are non-members.
1415
1416    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1417    specialization of a member template.
1418
1419    The TEMPLATE_COUNT is the number of references to qualifying
1420    template classes that appeared in the name of the function. See
1421    check_explicit_specialization for a more accurate description.
1422
1423    TSK indicates what kind of template declaration (if any) is being
1424    declared.  TSK_TEMPLATE indicates that the declaration given by
1425    DECL, though a FUNCTION_DECL, has template parameters, and is
1426    therefore a template function.
1427
1428    The template args (those explicitly specified and those deduced)
1429    are output in a newly created vector *TARGS_OUT.
1430
1431    If it is impossible to determine the result, an error message is
1432    issued.  The error_mark_node is returned to indicate failure.  */
1433
1434 static tree
1435 determine_specialization (tree template_id,
1436                           tree decl,
1437                           tree* targs_out,
1438                           int need_member_template,
1439                           int template_count,
1440                           tmpl_spec_kind tsk)
1441 {
1442   tree fns;
1443   tree targs;
1444   tree explicit_targs;
1445   tree candidates = NULL_TREE;
1446   /* A TREE_LIST of templates of which DECL may be a specialization.
1447      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1448      corresponding TREE_PURPOSE is the set of template arguments that,
1449      when used to instantiate the template, would produce a function
1450      with the signature of DECL.  */
1451   tree templates = NULL_TREE;
1452   int header_count;
1453   struct cp_binding_level *b;
1454
1455   *targs_out = NULL_TREE;
1456
1457   if (template_id == error_mark_node || decl == error_mark_node)
1458     return error_mark_node;
1459
1460   fns = TREE_OPERAND (template_id, 0);
1461   explicit_targs = TREE_OPERAND (template_id, 1);
1462
1463   if (fns == error_mark_node)
1464     return error_mark_node;
1465
1466   /* Check for baselinks.  */
1467   if (BASELINK_P (fns))
1468     fns = BASELINK_FUNCTIONS (fns);
1469
1470   if (!is_overloaded_fn (fns))
1471     {
1472       error ("%qD is not a function template", fns);
1473       return error_mark_node;
1474     }
1475
1476   /* Count the number of template headers specified for this
1477      specialization.  */
1478   header_count = 0;
1479   for (b = current_binding_level;
1480        b->kind == sk_template_parms;
1481        b = b->level_chain)
1482     ++header_count;
1483
1484   for (; fns; fns = OVL_NEXT (fns))
1485     {
1486       tree fn = OVL_CURRENT (fns);
1487
1488       if (TREE_CODE (fn) == TEMPLATE_DECL)
1489         {
1490           tree decl_arg_types;
1491           tree fn_arg_types;
1492
1493           /* In case of explicit specialization, we need to check if
1494              the number of template headers appearing in the specialization
1495              is correct. This is usually done in check_explicit_specialization,
1496              but the check done there cannot be exhaustive when specializing
1497              member functions. Consider the following code:
1498
1499              template <> void A<int>::f(int);
1500              template <> template <> void A<int>::f(int);
1501
1502              Assuming that A<int> is not itself an explicit specialization
1503              already, the first line specializes "f" which is a non-template
1504              member function, whilst the second line specializes "f" which
1505              is a template member function. So both lines are syntactically
1506              correct, and check_explicit_specialization does not reject
1507              them.
1508
1509              Here, we can do better, as we are matching the specialization
1510              against the declarations. We count the number of template
1511              headers, and we check if they match TEMPLATE_COUNT + 1
1512              (TEMPLATE_COUNT is the number of qualifying template classes,
1513              plus there must be another header for the member template
1514              itself).
1515
1516              Notice that if header_count is zero, this is not a
1517              specialization but rather a template instantiation, so there
1518              is no check we can perform here.  */
1519           if (header_count && header_count != template_count + 1)
1520             continue;
1521
1522           /* Check that the number of template arguments at the
1523              innermost level for DECL is the same as for FN.  */
1524           if (current_binding_level->kind == sk_template_parms
1525               && !current_binding_level->explicit_spec_p
1526               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1527                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1528                                       (current_template_parms))))
1529             continue;
1530
1531           /* DECL might be a specialization of FN.  */
1532           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1533           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1534
1535           /* For a non-static member function, we need to make sure
1536              that the const qualification is the same.  Since
1537              get_bindings does not try to merge the "this" parameter,
1538              we must do the comparison explicitly.  */
1539           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1540               && !same_type_p (TREE_VALUE (fn_arg_types),
1541                                TREE_VALUE (decl_arg_types)))
1542             continue;
1543
1544           /* Skip the "this" parameter and, for constructors of
1545              classes with virtual bases, the VTT parameter.  A
1546              full specialization of a constructor will have a VTT
1547              parameter, but a template never will.  */ 
1548           decl_arg_types 
1549             = skip_artificial_parms_for (decl, decl_arg_types);
1550           fn_arg_types 
1551             = skip_artificial_parms_for (fn, fn_arg_types);
1552
1553           /* Check that the number of function parameters matches.
1554              For example,
1555                template <class T> void f(int i = 0);
1556                template <> void f<int>();
1557              The specialization f<int> is invalid but is not caught
1558              by get_bindings below.  */
1559           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1560             continue;
1561
1562           /* Function templates cannot be specializations; there are
1563              no partial specializations of functions.  Therefore, if
1564              the type of DECL does not match FN, there is no
1565              match.  */
1566           if (tsk == tsk_template)
1567             {
1568               if (compparms (fn_arg_types, decl_arg_types))
1569                 candidates = tree_cons (NULL_TREE, fn, candidates);
1570               continue;
1571             }
1572
1573           /* See whether this function might be a specialization of this
1574              template.  */
1575           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1576
1577           if (!targs)
1578             /* We cannot deduce template arguments that when used to
1579                specialize TMPL will produce DECL.  */
1580             continue;
1581
1582           /* Save this template, and the arguments deduced.  */
1583           templates = tree_cons (targs, fn, templates);
1584         }
1585       else if (need_member_template)
1586         /* FN is an ordinary member function, and we need a
1587            specialization of a member template.  */
1588         ;
1589       else if (TREE_CODE (fn) != FUNCTION_DECL)
1590         /* We can get IDENTIFIER_NODEs here in certain erroneous
1591            cases.  */
1592         ;
1593       else if (!DECL_FUNCTION_MEMBER_P (fn))
1594         /* This is just an ordinary non-member function.  Nothing can
1595            be a specialization of that.  */
1596         ;
1597       else if (DECL_ARTIFICIAL (fn))
1598         /* Cannot specialize functions that are created implicitly.  */
1599         ;
1600       else
1601         {
1602           tree decl_arg_types;
1603
1604           /* This is an ordinary member function.  However, since
1605              we're here, we can assume it's enclosing class is a
1606              template class.  For example,
1607
1608                template <typename T> struct S { void f(); };
1609                template <> void S<int>::f() {}
1610
1611              Here, S<int>::f is a non-template, but S<int> is a
1612              template class.  If FN has the same type as DECL, we
1613              might be in business.  */
1614
1615           if (!DECL_TEMPLATE_INFO (fn))
1616             /* Its enclosing class is an explicit specialization
1617                of a template class.  This is not a candidate.  */
1618             continue;
1619
1620           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1621                             TREE_TYPE (TREE_TYPE (fn))))
1622             /* The return types differ.  */
1623             continue;
1624
1625           /* Adjust the type of DECL in case FN is a static member.  */
1626           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1627           if (DECL_STATIC_FUNCTION_P (fn)
1628               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1629             decl_arg_types = TREE_CHAIN (decl_arg_types);
1630
1631           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1632                          decl_arg_types))
1633             /* They match!  */
1634             candidates = tree_cons (NULL_TREE, fn, candidates);
1635         }
1636     }
1637
1638   if (templates && TREE_CHAIN (templates))
1639     {
1640       /* We have:
1641
1642            [temp.expl.spec]
1643
1644            It is possible for a specialization with a given function
1645            signature to be instantiated from more than one function
1646            template.  In such cases, explicit specification of the
1647            template arguments must be used to uniquely identify the
1648            function template specialization being specialized.
1649
1650          Note that here, there's no suggestion that we're supposed to
1651          determine which of the candidate templates is most
1652          specialized.  However, we, also have:
1653
1654            [temp.func.order]
1655
1656            Partial ordering of overloaded function template
1657            declarations is used in the following contexts to select
1658            the function template to which a function template
1659            specialization refers:
1660
1661            -- when an explicit specialization refers to a function
1662               template.
1663
1664          So, we do use the partial ordering rules, at least for now.
1665          This extension can only serve to make invalid programs valid,
1666          so it's safe.  And, there is strong anecdotal evidence that
1667          the committee intended the partial ordering rules to apply;
1668          the EDG front end has that behavior, and John Spicer claims
1669          that the committee simply forgot to delete the wording in
1670          [temp.expl.spec].  */
1671       tree tmpl = most_specialized_instantiation (templates);
1672       if (tmpl != error_mark_node)
1673         {
1674           templates = tmpl;
1675           TREE_CHAIN (templates) = NULL_TREE;
1676         }
1677     }
1678
1679   if (templates == NULL_TREE && candidates == NULL_TREE)
1680     {
1681       error ("template-id %qD for %q+D does not match any template "
1682              "declaration", template_id, decl);
1683       return error_mark_node;
1684     }
1685   else if ((templates && TREE_CHAIN (templates))
1686            || (candidates && TREE_CHAIN (candidates))
1687            || (templates && candidates))
1688     {
1689       error ("ambiguous template specialization %qD for %q+D",
1690              template_id, decl);
1691       chainon (candidates, templates);
1692       print_candidates (candidates);
1693       return error_mark_node;
1694     }
1695
1696   /* We have one, and exactly one, match.  */
1697   if (candidates)
1698     {
1699       tree fn = TREE_VALUE (candidates);
1700       /* DECL is a re-declaration of a template function.  */
1701       if (TREE_CODE (fn) == TEMPLATE_DECL)
1702         return fn;
1703       /* It was a specialization of an ordinary member function in a
1704          template class.  */
1705       *targs_out = copy_node (DECL_TI_ARGS (fn));
1706       return DECL_TI_TEMPLATE (fn);
1707     }
1708
1709   /* It was a specialization of a template.  */
1710   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
1711   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
1712     {
1713       *targs_out = copy_node (targs);
1714       SET_TMPL_ARGS_LEVEL (*targs_out,
1715                            TMPL_ARGS_DEPTH (*targs_out),
1716                            TREE_PURPOSE (templates));
1717     }
1718   else
1719     *targs_out = TREE_PURPOSE (templates);
1720   return TREE_VALUE (templates);
1721 }
1722
1723 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
1724    but with the default argument values filled in from those in the
1725    TMPL_TYPES.  */
1726
1727 static tree
1728 copy_default_args_to_explicit_spec_1 (tree spec_types,
1729                                       tree tmpl_types)
1730 {
1731   tree new_spec_types;
1732
1733   if (!spec_types)
1734     return NULL_TREE;
1735
1736   if (spec_types == void_list_node)
1737     return void_list_node;
1738
1739   /* Substitute into the rest of the list.  */
1740   new_spec_types =
1741     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
1742                                           TREE_CHAIN (tmpl_types));
1743
1744   /* Add the default argument for this parameter.  */
1745   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
1746                          TREE_VALUE (spec_types),
1747                          new_spec_types);
1748 }
1749
1750 /* DECL is an explicit specialization.  Replicate default arguments
1751    from the template it specializes.  (That way, code like:
1752
1753      template <class T> void f(T = 3);
1754      template <> void f(double);
1755      void g () { f (); }
1756
1757    works, as required.)  An alternative approach would be to look up
1758    the correct default arguments at the call-site, but this approach
1759    is consistent with how implicit instantiations are handled.  */
1760
1761 static void
1762 copy_default_args_to_explicit_spec (tree decl)
1763 {
1764   tree tmpl;
1765   tree spec_types;
1766   tree tmpl_types;
1767   tree new_spec_types;
1768   tree old_type;
1769   tree new_type;
1770   tree t;
1771   tree object_type = NULL_TREE;
1772   tree in_charge = NULL_TREE;
1773   tree vtt = NULL_TREE;
1774
1775   /* See if there's anything we need to do.  */
1776   tmpl = DECL_TI_TEMPLATE (decl);
1777   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
1778   for (t = tmpl_types; t; t = TREE_CHAIN (t))
1779     if (TREE_PURPOSE (t))
1780       break;
1781   if (!t)
1782     return;
1783
1784   old_type = TREE_TYPE (decl);
1785   spec_types = TYPE_ARG_TYPES (old_type);
1786
1787   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1788     {
1789       /* Remove the this pointer, but remember the object's type for
1790          CV quals.  */
1791       object_type = TREE_TYPE (TREE_VALUE (spec_types));
1792       spec_types = TREE_CHAIN (spec_types);
1793       tmpl_types = TREE_CHAIN (tmpl_types);
1794
1795       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
1796         {
1797           /* DECL may contain more parameters than TMPL due to the extra
1798              in-charge parameter in constructors and destructors.  */
1799           in_charge = spec_types;
1800           spec_types = TREE_CHAIN (spec_types);
1801         }
1802       if (DECL_HAS_VTT_PARM_P (decl))
1803         {
1804           vtt = spec_types;
1805           spec_types = TREE_CHAIN (spec_types);
1806         }
1807     }
1808
1809   /* Compute the merged default arguments.  */
1810   new_spec_types =
1811     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
1812
1813   /* Compute the new FUNCTION_TYPE.  */
1814   if (object_type)
1815     {
1816       if (vtt)
1817         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
1818                                          TREE_VALUE (vtt),
1819                                          new_spec_types);
1820
1821       if (in_charge)
1822         /* Put the in-charge parameter back.  */
1823         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
1824                                          TREE_VALUE (in_charge),
1825                                          new_spec_types);
1826
1827       new_type = build_method_type_directly (object_type,
1828                                              TREE_TYPE (old_type),
1829                                              new_spec_types);
1830     }
1831   else
1832     new_type = build_function_type (TREE_TYPE (old_type),
1833                                     new_spec_types);
1834   new_type = cp_build_type_attribute_variant (new_type,
1835                                               TYPE_ATTRIBUTES (old_type));
1836   new_type = build_exception_variant (new_type,
1837                                       TYPE_RAISES_EXCEPTIONS (old_type));
1838   TREE_TYPE (decl) = new_type;
1839 }
1840
1841 /* Check to see if the function just declared, as indicated in
1842    DECLARATOR, and in DECL, is a specialization of a function
1843    template.  We may also discover that the declaration is an explicit
1844    instantiation at this point.
1845
1846    Returns DECL, or an equivalent declaration that should be used
1847    instead if all goes well.  Issues an error message if something is
1848    amiss.  Returns error_mark_node if the error is not easily
1849    recoverable.
1850
1851    FLAGS is a bitmask consisting of the following flags:
1852
1853    2: The function has a definition.
1854    4: The function is a friend.
1855
1856    The TEMPLATE_COUNT is the number of references to qualifying
1857    template classes that appeared in the name of the function.  For
1858    example, in
1859
1860      template <class T> struct S { void f(); };
1861      void S<int>::f();
1862
1863    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
1864    classes are not counted in the TEMPLATE_COUNT, so that in
1865
1866      template <class T> struct S {};
1867      template <> struct S<int> { void f(); }
1868      template <> void S<int>::f();
1869
1870    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
1871    invalid; there should be no template <>.)
1872
1873    If the function is a specialization, it is marked as such via
1874    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
1875    is set up correctly, and it is added to the list of specializations
1876    for that template.  */
1877
1878 tree
1879 check_explicit_specialization (tree declarator,
1880                                tree decl,
1881                                int template_count,
1882                                int flags)
1883 {
1884   int have_def = flags & 2;
1885   int is_friend = flags & 4;
1886   int specialization = 0;
1887   int explicit_instantiation = 0;
1888   int member_specialization = 0;
1889   tree ctype = DECL_CLASS_CONTEXT (decl);
1890   tree dname = DECL_NAME (decl);
1891   tmpl_spec_kind tsk;
1892
1893   if (is_friend)
1894     {
1895       if (!processing_specialization)
1896         tsk = tsk_none;
1897       else
1898         tsk = tsk_excessive_parms;
1899     }
1900   else
1901     tsk = current_tmpl_spec_kind (template_count);
1902
1903   switch (tsk)
1904     {
1905     case tsk_none:
1906       if (processing_specialization)
1907         {
1908           specialization = 1;
1909           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1910         }
1911       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1912         {
1913           if (is_friend)
1914             /* This could be something like:
1915
1916                template <class T> void f(T);
1917                class S { friend void f<>(int); }  */
1918             specialization = 1;
1919           else
1920             {
1921               /* This case handles bogus declarations like template <>
1922                  template <class T> void f<int>(); */
1923
1924               error ("template-id %qD in declaration of primary template",
1925                      declarator);
1926               return decl;
1927             }
1928         }
1929       break;
1930
1931     case tsk_invalid_member_spec:
1932       /* The error has already been reported in
1933          check_specialization_scope.  */
1934       return error_mark_node;
1935
1936     case tsk_invalid_expl_inst:
1937       error ("template parameter list used in explicit instantiation");
1938
1939       /* Fall through.  */
1940
1941     case tsk_expl_inst:
1942       if (have_def)
1943         error ("definition provided for explicit instantiation");
1944
1945       explicit_instantiation = 1;
1946       break;
1947
1948     case tsk_excessive_parms:
1949     case tsk_insufficient_parms:
1950       if (tsk == tsk_excessive_parms)
1951         error ("too many template parameter lists in declaration of %qD",
1952                decl);
1953       else if (template_header_count)
1954         error("too few template parameter lists in declaration of %qD", decl);
1955       else
1956         error("explicit specialization of %qD must be introduced by "
1957               "%<template <>%>", decl);
1958
1959       /* Fall through.  */
1960     case tsk_expl_spec:
1961       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1962       if (ctype)
1963         member_specialization = 1;
1964       else
1965         specialization = 1;
1966       break;
1967
1968     case tsk_template:
1969       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1970         {
1971           /* This case handles bogus declarations like template <>
1972              template <class T> void f<int>(); */
1973
1974           if (uses_template_parms (declarator))
1975             error ("function template partial specialization %qD "
1976                    "is not allowed", declarator);
1977           else
1978             error ("template-id %qD in declaration of primary template",
1979                    declarator);
1980           return decl;
1981         }
1982
1983       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
1984         /* This is a specialization of a member template, without
1985            specialization the containing class.  Something like:
1986
1987              template <class T> struct S {
1988                template <class U> void f (U);
1989              };
1990              template <> template <class U> void S<int>::f(U) {}
1991
1992            That's a specialization -- but of the entire template.  */
1993         specialization = 1;
1994       break;
1995
1996     default:
1997       gcc_unreachable ();
1998     }
1999
2000   if (specialization || member_specialization)
2001     {
2002       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2003       for (; t; t = TREE_CHAIN (t))
2004         if (TREE_PURPOSE (t))
2005           {
2006             permerror (input_location, 
2007                        "default argument specified in explicit specialization");
2008             break;
2009           }
2010     }
2011
2012   if (specialization || member_specialization || explicit_instantiation)
2013     {
2014       tree tmpl = NULL_TREE;
2015       tree targs = NULL_TREE;
2016
2017       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2018       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2019         {
2020           tree fns;
2021
2022           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2023           if (ctype)
2024             fns = dname;
2025           else
2026             {
2027               /* If there is no class context, the explicit instantiation
2028                  must be at namespace scope.  */
2029               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2030
2031               /* Find the namespace binding, using the declaration
2032                  context.  */
2033               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2034                                            false, true);
2035               if (fns == error_mark_node || !is_overloaded_fn (fns))
2036                 {
2037                   error ("%qD is not a template function", dname);
2038                   fns = error_mark_node;
2039                 }
2040               else
2041                 {
2042                   tree fn = OVL_CURRENT (fns);
2043                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2044                                                 CP_DECL_CONTEXT (fn)))
2045                     error ("%qD is not declared in %qD",
2046                            decl, current_namespace);
2047                 }
2048             }
2049
2050           declarator = lookup_template_function (fns, NULL_TREE);
2051         }
2052
2053       if (declarator == error_mark_node)
2054         return error_mark_node;
2055
2056       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2057         {
2058           if (!explicit_instantiation)
2059             /* A specialization in class scope.  This is invalid,
2060                but the error will already have been flagged by
2061                check_specialization_scope.  */
2062             return error_mark_node;
2063           else
2064             {
2065               /* It's not valid to write an explicit instantiation in
2066                  class scope, e.g.:
2067
2068                    class C { template void f(); }
2069
2070                    This case is caught by the parser.  However, on
2071                    something like:
2072
2073                    template class C { void f(); };
2074
2075                    (which is invalid) we can get here.  The error will be
2076                    issued later.  */
2077               ;
2078             }
2079
2080           return decl;
2081         }
2082       else if (ctype != NULL_TREE
2083                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2084                    IDENTIFIER_NODE))
2085         {
2086           /* Find the list of functions in ctype that have the same
2087              name as the declared function.  */
2088           tree name = TREE_OPERAND (declarator, 0);
2089           tree fns = NULL_TREE;
2090           int idx;
2091
2092           if (constructor_name_p (name, ctype))
2093             {
2094               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2095
2096               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2097                   : !CLASSTYPE_DESTRUCTORS (ctype))
2098                 {
2099                   /* From [temp.expl.spec]:
2100
2101                      If such an explicit specialization for the member
2102                      of a class template names an implicitly-declared
2103                      special member function (clause _special_), the
2104                      program is ill-formed.
2105
2106                      Similar language is found in [temp.explicit].  */
2107                   error ("specialization of implicitly-declared special member function");
2108                   return error_mark_node;
2109                 }
2110
2111               name = is_constructor ? ctor_identifier : dtor_identifier;
2112             }
2113
2114           if (!DECL_CONV_FN_P (decl))
2115             {
2116               idx = lookup_fnfields_1 (ctype, name);
2117               if (idx >= 0)
2118                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2119             }
2120           else
2121             {
2122               VEC(tree,gc) *methods;
2123               tree ovl;
2124
2125               /* For a type-conversion operator, we cannot do a
2126                  name-based lookup.  We might be looking for `operator
2127                  int' which will be a specialization of `operator T'.
2128                  So, we find *all* the conversion operators, and then
2129                  select from them.  */
2130               fns = NULL_TREE;
2131
2132               methods = CLASSTYPE_METHOD_VEC (ctype);
2133               if (methods)
2134                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2135                      VEC_iterate (tree, methods, idx, ovl);
2136                      ++idx)
2137                   {
2138                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2139                       /* There are no more conversion functions.  */
2140                       break;
2141
2142                     /* Glue all these conversion functions together
2143                        with those we already have.  */
2144                     for (; ovl; ovl = OVL_NEXT (ovl))
2145                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2146                   }
2147             }
2148
2149           if (fns == NULL_TREE)
2150             {
2151               error ("no member function %qD declared in %qT", name, ctype);
2152               return error_mark_node;
2153             }
2154           else
2155             TREE_OPERAND (declarator, 0) = fns;
2156         }
2157
2158       /* Figure out what exactly is being specialized at this point.
2159          Note that for an explicit instantiation, even one for a
2160          member function, we cannot tell apriori whether the
2161          instantiation is for a member template, or just a member
2162          function of a template class.  Even if a member template is
2163          being instantiated, the member template arguments may be
2164          elided if they can be deduced from the rest of the
2165          declaration.  */
2166       tmpl = determine_specialization (declarator, decl,
2167                                        &targs,
2168                                        member_specialization,
2169                                        template_count,
2170                                        tsk);
2171
2172       if (!tmpl || tmpl == error_mark_node)
2173         /* We couldn't figure out what this declaration was
2174            specializing.  */
2175         return error_mark_node;
2176       else
2177         {
2178           tree gen_tmpl = most_general_template (tmpl);
2179
2180           if (explicit_instantiation)
2181             {
2182               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2183                  is done by do_decl_instantiation later.  */
2184
2185               int arg_depth = TMPL_ARGS_DEPTH (targs);
2186               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2187
2188               if (arg_depth > parm_depth)
2189                 {
2190                   /* If TMPL is not the most general template (for
2191                      example, if TMPL is a friend template that is
2192                      injected into namespace scope), then there will
2193                      be too many levels of TARGS.  Remove some of them
2194                      here.  */
2195                   int i;
2196                   tree new_targs;
2197
2198                   new_targs = make_tree_vec (parm_depth);
2199                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2200                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2201                       = TREE_VEC_ELT (targs, i);
2202                   targs = new_targs;
2203                 }
2204
2205               return instantiate_template (tmpl, targs, tf_error);
2206             }
2207
2208           /* If we thought that the DECL was a member function, but it
2209              turns out to be specializing a static member function,
2210              make DECL a static member function as well.  */
2211           if (DECL_STATIC_FUNCTION_P (tmpl)
2212               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2213             revert_static_member_fn (decl);
2214
2215           /* If this is a specialization of a member template of a
2216              template class, we want to return the TEMPLATE_DECL, not
2217              the specialization of it.  */
2218           if (tsk == tsk_template)
2219             {
2220               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2221               DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl)) = NULL_TREE;
2222               if (have_def)
2223                 {
2224                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2225                   DECL_SOURCE_LOCATION (DECL_TEMPLATE_RESULT (tmpl))
2226                     = DECL_SOURCE_LOCATION (decl);
2227                   /* We want to use the argument list specified in the
2228                      definition, not in the original declaration.  */
2229                   DECL_ARGUMENTS (DECL_TEMPLATE_RESULT (tmpl))
2230                     = DECL_ARGUMENTS (decl);
2231                 }
2232               return tmpl;
2233             }
2234
2235           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2236           DECL_TEMPLATE_INFO (decl) = tree_cons (tmpl, targs, NULL_TREE);
2237
2238           /* Inherit default function arguments from the template
2239              DECL is specializing.  */
2240           copy_default_args_to_explicit_spec (decl);
2241
2242           /* This specialization has the same protection as the
2243              template it specializes.  */
2244           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2245           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2246
2247           /* 7.1.1-1 [dcl.stc]
2248
2249              A storage-class-specifier shall not be specified in an
2250              explicit specialization...
2251
2252              The parser rejects these, so unless action is taken here,
2253              explicit function specializations will always appear with
2254              global linkage.
2255
2256              The action recommended by the C++ CWG in response to C++
2257              defect report 605 is to make the storage class and linkage
2258              of the explicit specialization match the templated function:
2259
2260              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2261            */
2262           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2263             {
2264               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2265               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2266
2267               /* This specialization has the same linkage and visibility as
2268                  the function template it specializes.  */
2269               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2270               if (! TREE_PUBLIC (decl))
2271                 {
2272                   DECL_INTERFACE_KNOWN (decl) = 1;
2273                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2274                 }
2275               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2276               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2277                 {
2278                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2279                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2280                 }
2281             }
2282
2283           /* If DECL is a friend declaration, declared using an
2284              unqualified name, the namespace associated with DECL may
2285              have been set incorrectly.  For example, in:
2286
2287                template <typename T> void f(T);
2288                namespace N {
2289                  struct S { friend void f<int>(int); }
2290                }
2291
2292              we will have set the DECL_CONTEXT for the friend
2293              declaration to N, rather than to the global namespace.  */
2294           if (DECL_NAMESPACE_SCOPE_P (decl))
2295             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2296
2297           if (is_friend && !have_def)
2298             /* This is not really a declaration of a specialization.
2299                It's just the name of an instantiation.  But, it's not
2300                a request for an instantiation, either.  */
2301             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2302           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2303             /* This is indeed a specialization.  In case of constructors
2304                and destructors, we need in-charge and not-in-charge
2305                versions in V3 ABI.  */
2306             clone_function_decl (decl, /*update_method_vec_p=*/0);
2307
2308           /* Register this specialization so that we can find it
2309              again.  */
2310           decl = register_specialization (decl, gen_tmpl, targs, is_friend);
2311         }
2312     }
2313
2314   return decl;
2315 }
2316
2317 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2318    parameters.  These are represented in the same format used for
2319    DECL_TEMPLATE_PARMS.  */
2320
2321 int
2322 comp_template_parms (const_tree parms1, const_tree parms2)
2323 {
2324   const_tree p1;
2325   const_tree p2;
2326
2327   if (parms1 == parms2)
2328     return 1;
2329
2330   for (p1 = parms1, p2 = parms2;
2331        p1 != NULL_TREE && p2 != NULL_TREE;
2332        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2333     {
2334       tree t1 = TREE_VALUE (p1);
2335       tree t2 = TREE_VALUE (p2);
2336       int i;
2337
2338       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2339       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2340
2341       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2342         return 0;
2343
2344       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2345         {
2346           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2347           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2348
2349           /* If either of the template parameters are invalid, assume
2350              they match for the sake of error recovery. */
2351           if (parm1 == error_mark_node || parm2 == error_mark_node)
2352             return 1;
2353
2354           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2355             return 0;
2356
2357           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2358               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2359                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2360             continue;
2361           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2362             return 0;
2363         }
2364     }
2365
2366   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2367     /* One set of parameters has more parameters lists than the
2368        other.  */
2369     return 0;
2370
2371   return 1;
2372 }
2373
2374 /* Determine whether PARM is a parameter pack.  */
2375 bool 
2376 template_parameter_pack_p (const_tree parm)
2377 {
2378   /* Determine if we have a non-type template parameter pack.  */
2379   if (TREE_CODE (parm) == PARM_DECL)
2380     return (DECL_TEMPLATE_PARM_P (parm) 
2381             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2382
2383   /* If this is a list of template parameters, we could get a
2384      TYPE_DECL or a TEMPLATE_DECL.  */ 
2385   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2386     parm = TREE_TYPE (parm);
2387
2388   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2389            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2390           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2391 }
2392
2393 /* Determine whether ARGS describes a variadic template args list,
2394    i.e., one that is terminated by a template argument pack.  */
2395 static bool 
2396 template_args_variadic_p (tree args)
2397 {
2398   int nargs;
2399   tree last_parm;
2400
2401   if (args == NULL_TREE)
2402     return false;
2403
2404   args = INNERMOST_TEMPLATE_ARGS (args);
2405   nargs = TREE_VEC_LENGTH (args);
2406
2407   if (nargs == 0)
2408     return false;
2409
2410   last_parm = TREE_VEC_ELT (args, nargs - 1);
2411
2412   return ARGUMENT_PACK_P (last_parm);
2413 }
2414
2415 /* Generate a new name for the parameter pack name NAME (an
2416    IDENTIFIER_NODE) that incorporates its */
2417 static tree
2418 make_ith_pack_parameter_name (tree name, int i)
2419 {
2420   /* Munge the name to include the parameter index.  */
2421   char numbuf[128];
2422   char* newname;
2423   
2424   sprintf(numbuf, "%i", i);
2425   newname = (char*)alloca (IDENTIFIER_LENGTH (name) + strlen(numbuf) + 2);
2426   sprintf(newname, "%s#%i", IDENTIFIER_POINTER (name), i);
2427   return get_identifier (newname);
2428 }
2429
2430 /* Structure used to track the progress of find_parameter_packs_r.  */
2431 struct find_parameter_pack_data 
2432 {
2433   /* TREE_LIST that will contain all of the parameter packs found by
2434      the traversal.  */
2435   tree* parameter_packs;
2436
2437   /* Set of AST nodes that have been visited by the traversal.  */
2438   struct pointer_set_t *visited;
2439 };
2440
2441 /* Identifies all of the argument packs that occur in a template
2442    argument and appends them to the TREE_LIST inside DATA, which is a
2443    find_parameter_pack_data structure. This is a subroutine of
2444    make_pack_expansion and uses_parameter_packs.  */
2445 static tree
2446 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2447 {
2448   tree t = *tp;
2449   struct find_parameter_pack_data* ppd = 
2450     (struct find_parameter_pack_data*)data;
2451   bool parameter_pack_p = false;
2452
2453   /* Identify whether this is a parameter pack or not.  */
2454   switch (TREE_CODE (t))
2455     {
2456     case TEMPLATE_PARM_INDEX:
2457       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2458         parameter_pack_p = true;
2459       break;
2460
2461     case TEMPLATE_TYPE_PARM:
2462     case TEMPLATE_TEMPLATE_PARM:
2463       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2464         parameter_pack_p = true;
2465       break;
2466
2467     case PARM_DECL:
2468       if (FUNCTION_PARAMETER_PACK_P (t))
2469         {
2470           /* We don't want to walk into the type of a PARM_DECL,
2471              because we don't want to see the type parameter pack.  */
2472           *walk_subtrees = 0;
2473           parameter_pack_p = true;
2474         }
2475       break;
2476
2477     default:
2478       /* Not a parameter pack.  */
2479       break;
2480     }
2481
2482   if (parameter_pack_p)
2483     {
2484       /* Add this parameter pack to the list.  */
2485       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2486     }
2487
2488   if (TYPE_P (t))
2489     cp_walk_tree (&TYPE_CONTEXT (t), 
2490                   &find_parameter_packs_r, ppd, ppd->visited);
2491
2492   /* This switch statement will return immediately if we don't find a
2493      parameter pack.  */
2494   switch (TREE_CODE (t)) 
2495     {
2496     case TEMPLATE_PARM_INDEX:
2497       return NULL_TREE;
2498
2499     case BOUND_TEMPLATE_TEMPLATE_PARM:
2500       /* Check the template itself.  */
2501       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2502                     &find_parameter_packs_r, ppd, ppd->visited);
2503       /* Check the template arguments.  */
2504       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2505                     ppd->visited);
2506       *walk_subtrees = 0;
2507       return NULL_TREE;
2508
2509     case TEMPLATE_TYPE_PARM:
2510     case TEMPLATE_TEMPLATE_PARM:
2511       return NULL_TREE;
2512
2513     case PARM_DECL:
2514       return NULL_TREE;
2515
2516     case RECORD_TYPE:
2517       if (TYPE_PTRMEMFUNC_P (t))
2518         return NULL_TREE;
2519       /* Fall through.  */
2520
2521     case UNION_TYPE:
2522     case ENUMERAL_TYPE:
2523       if (TYPE_TEMPLATE_INFO (t))
2524         cp_walk_tree (&TREE_VALUE (TYPE_TEMPLATE_INFO (t)), 
2525                       &find_parameter_packs_r, ppd, ppd->visited);
2526
2527       *walk_subtrees = 0;
2528       return NULL_TREE;
2529
2530     case TEMPLATE_DECL:
2531       cp_walk_tree (&TREE_TYPE (t),
2532                     &find_parameter_packs_r, ppd, ppd->visited);
2533       return NULL_TREE;
2534  
2535     case TYPENAME_TYPE:
2536       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
2537                    ppd, ppd->visited);
2538       *walk_subtrees = 0;
2539       return NULL_TREE;
2540       
2541     case TYPE_PACK_EXPANSION:
2542     case EXPR_PACK_EXPANSION:
2543       *walk_subtrees = 0;
2544       return NULL_TREE;
2545
2546     case INTEGER_TYPE:
2547       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
2548                     ppd, ppd->visited);
2549       *walk_subtrees = 0;
2550       return NULL_TREE;
2551
2552     case IDENTIFIER_NODE:
2553       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
2554                     ppd->visited);
2555       *walk_subtrees = 0;
2556       return NULL_TREE;
2557
2558     default:
2559       return NULL_TREE;
2560     }
2561
2562   return NULL_TREE;
2563 }
2564
2565 /* Determines if the expression or type T uses any parameter packs.  */
2566 bool
2567 uses_parameter_packs (tree t)
2568 {
2569   tree parameter_packs = NULL_TREE;
2570   struct find_parameter_pack_data ppd;
2571   ppd.parameter_packs = &parameter_packs;
2572   ppd.visited = pointer_set_create ();
2573   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2574   pointer_set_destroy (ppd.visited);
2575   return parameter_packs != NULL_TREE;
2576 }
2577
2578 /* Turn ARG, which may be an expression, type, or a TREE_LIST
2579    representation a base-class initializer into a parameter pack
2580    expansion. If all goes well, the resulting node will be an
2581    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
2582    respectively.  */
2583 tree 
2584 make_pack_expansion (tree arg)
2585 {
2586   tree result;
2587   tree parameter_packs = NULL_TREE;
2588   bool for_types = false;
2589   struct find_parameter_pack_data ppd;
2590
2591   if (!arg || arg == error_mark_node)
2592     return arg;
2593
2594   if (TREE_CODE (arg) == TREE_LIST)
2595     {
2596       /* The only time we will see a TREE_LIST here is for a base
2597          class initializer.  In this case, the TREE_PURPOSE will be a
2598          _TYPE node (representing the base class expansion we're
2599          initializing) and the TREE_VALUE will be a TREE_LIST
2600          containing the initialization arguments. 
2601
2602          The resulting expansion looks somewhat different from most
2603          expansions. Rather than returning just one _EXPANSION, we
2604          return a TREE_LIST whose TREE_PURPOSE is a
2605          TYPE_PACK_EXPANSION containing the bases that will be
2606          initialized.  The TREE_VALUE will be identical to the
2607          original TREE_VALUE, which is a list of arguments that will
2608          be passed to each base.  We do not introduce any new pack
2609          expansion nodes into the TREE_VALUE (although it is possible
2610          that some already exist), because the TREE_PURPOSE and
2611          TREE_VALUE all need to be expanded together with the same
2612          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
2613          resulting TREE_PURPOSE will mention the parameter packs in
2614          both the bases and the arguments to the bases.  */
2615       tree purpose;
2616       tree value;
2617       tree parameter_packs = NULL_TREE;
2618
2619       /* Determine which parameter packs will be used by the base
2620          class expansion.  */
2621       ppd.visited = pointer_set_create ();
2622       ppd.parameter_packs = &parameter_packs;
2623       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
2624                     &ppd, ppd.visited);
2625
2626       if (parameter_packs == NULL_TREE)
2627         {
2628           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
2629           pointer_set_destroy (ppd.visited);
2630           return error_mark_node;
2631         }
2632
2633       if (TREE_VALUE (arg) != void_type_node)
2634         {
2635           /* Collect the sets of parameter packs used in each of the
2636              initialization arguments.  */
2637           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
2638             {
2639               /* Determine which parameter packs will be expanded in this
2640                  argument.  */
2641               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
2642                             &ppd, ppd.visited);
2643             }
2644         }
2645
2646       pointer_set_destroy (ppd.visited);
2647
2648       /* Create the pack expansion type for the base type.  */
2649       purpose = make_node (TYPE_PACK_EXPANSION);
2650       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
2651       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
2652
2653       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2654          they will rarely be compared to anything.  */
2655       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
2656
2657       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
2658     }
2659
2660   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
2661     for_types = true;
2662
2663   /* Build the PACK_EXPANSION_* node.  */
2664   result = make_node (for_types ? TYPE_PACK_EXPANSION : EXPR_PACK_EXPANSION);
2665   SET_PACK_EXPANSION_PATTERN (result, arg);
2666   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
2667     {
2668       /* Propagate type and const-expression information.  */
2669       TREE_TYPE (result) = TREE_TYPE (arg);
2670       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
2671     }
2672   else
2673     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2674        they will rarely be compared to anything.  */
2675     SET_TYPE_STRUCTURAL_EQUALITY (result);
2676
2677   /* Determine which parameter packs will be expanded.  */
2678   ppd.parameter_packs = &parameter_packs;
2679   ppd.visited = pointer_set_create ();
2680   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
2681   pointer_set_destroy (ppd.visited);
2682
2683   /* Make sure we found some parameter packs.  */
2684   if (parameter_packs == NULL_TREE)
2685     {
2686       if (TYPE_P (arg))
2687         error ("expansion pattern %<%T%> contains no argument packs", arg);
2688       else
2689         error ("expansion pattern %<%E%> contains no argument packs", arg);
2690       return error_mark_node;
2691     }
2692   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
2693
2694   return result;
2695 }
2696
2697 /* Checks T for any "bare" parameter packs, which have not yet been
2698    expanded, and issues an error if any are found. This operation can
2699    only be done on full expressions or types (e.g., an expression
2700    statement, "if" condition, etc.), because we could have expressions like:
2701
2702      foo(f(g(h(args)))...)
2703
2704    where "args" is a parameter pack. check_for_bare_parameter_packs
2705    should not be called for the subexpressions args, h(args),
2706    g(h(args)), or f(g(h(args))), because we would produce erroneous
2707    error messages. 
2708
2709    Returns TRUE and emits an error if there were bare parameter packs,
2710    returns FALSE otherwise.  */
2711 bool 
2712 check_for_bare_parameter_packs (tree t)
2713 {
2714   tree parameter_packs = NULL_TREE;
2715   struct find_parameter_pack_data ppd;
2716
2717   if (!processing_template_decl || !t || t == error_mark_node)
2718     return false;
2719
2720   if (TREE_CODE (t) == TYPE_DECL)
2721     t = TREE_TYPE (t);
2722
2723   ppd.parameter_packs = &parameter_packs;
2724   ppd.visited = pointer_set_create ();
2725   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2726   pointer_set_destroy (ppd.visited);
2727
2728   if (parameter_packs) 
2729     {
2730       error ("parameter packs not expanded with %<...%>:");
2731       while (parameter_packs)
2732         {
2733           tree pack = TREE_VALUE (parameter_packs);
2734           tree name = NULL_TREE;
2735
2736           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
2737               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
2738             name = TYPE_NAME (pack);
2739           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
2740             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
2741           else
2742             name = DECL_NAME (pack);
2743
2744           if (name)
2745             inform (input_location, "        %qD", name);
2746           else
2747             inform (input_location, "        <anonymous>");
2748
2749           parameter_packs = TREE_CHAIN (parameter_packs);
2750         }
2751
2752       return true;
2753     }
2754
2755   return false;
2756 }
2757
2758 /* Expand any parameter packs that occur in the template arguments in
2759    ARGS.  */
2760 tree
2761 expand_template_argument_pack (tree args)
2762 {
2763   tree result_args = NULL_TREE;
2764   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
2765   int num_result_args = -1;
2766
2767   /* First, determine if we need to expand anything, and the number of
2768      slots we'll need.  */
2769   for (in_arg = 0; in_arg < nargs; ++in_arg)
2770     {
2771       tree arg = TREE_VEC_ELT (args, in_arg);
2772       if (ARGUMENT_PACK_P (arg))
2773         {
2774           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
2775           if (num_result_args < 0)
2776             num_result_args = in_arg + num_packed;
2777           else
2778             num_result_args += num_packed;
2779         }
2780       else
2781         {
2782           if (num_result_args >= 0)
2783             num_result_args++;
2784         }
2785     }
2786
2787   /* If no expansion is necessary, we're done.  */
2788   if (num_result_args < 0)
2789     return args;
2790
2791   /* Expand arguments.  */
2792   result_args = make_tree_vec (num_result_args);
2793   for (in_arg = 0; in_arg < nargs; ++in_arg)
2794     {
2795       tree arg = TREE_VEC_ELT (args, in_arg);
2796       if (ARGUMENT_PACK_P (arg))
2797         {
2798           tree packed = ARGUMENT_PACK_ARGS (arg);
2799           int i, num_packed = TREE_VEC_LENGTH (packed);
2800           for (i = 0; i < num_packed; ++i, ++out_arg)
2801             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
2802         }
2803       else
2804         {
2805           TREE_VEC_ELT (result_args, out_arg) = arg;
2806           ++out_arg;
2807         }
2808     }
2809
2810   return result_args;
2811 }
2812
2813 /* Checks if DECL shadows a template parameter.
2814
2815    [temp.local]: A template-parameter shall not be redeclared within its
2816    scope (including nested scopes).
2817
2818    Emits an error and returns TRUE if the DECL shadows a parameter,
2819    returns FALSE otherwise.  */
2820
2821 bool
2822 check_template_shadow (tree decl)
2823 {
2824   tree olddecl;
2825
2826   /* If we're not in a template, we can't possibly shadow a template
2827      parameter.  */
2828   if (!current_template_parms)
2829     return true;
2830
2831   /* Figure out what we're shadowing.  */
2832   if (TREE_CODE (decl) == OVERLOAD)
2833     decl = OVL_CURRENT (decl);
2834   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
2835
2836   /* If there's no previous binding for this name, we're not shadowing
2837      anything, let alone a template parameter.  */
2838   if (!olddecl)
2839     return true;
2840
2841   /* If we're not shadowing a template parameter, we're done.  Note
2842      that OLDDECL might be an OVERLOAD (or perhaps even an
2843      ERROR_MARK), so we can't just blithely assume it to be a _DECL
2844      node.  */
2845   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
2846     return true;
2847
2848   /* We check for decl != olddecl to avoid bogus errors for using a
2849      name inside a class.  We check TPFI to avoid duplicate errors for
2850      inline member templates.  */
2851   if (decl == olddecl
2852       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
2853     return true;
2854
2855   error ("declaration of %q+#D", decl);
2856   error (" shadows template parm %q+#D", olddecl);
2857   return false;
2858 }
2859
2860 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
2861    ORIG_LEVEL, DECL, and TYPE.  */
2862
2863 static tree
2864 build_template_parm_index (int index,
2865                            int level,
2866                            int orig_level,
2867                            tree decl,
2868                            tree type)
2869 {
2870   tree t = make_node (TEMPLATE_PARM_INDEX);
2871   TEMPLATE_PARM_IDX (t) = index;
2872   TEMPLATE_PARM_LEVEL (t) = level;
2873   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
2874   TEMPLATE_PARM_DECL (t) = decl;
2875   TREE_TYPE (t) = type;
2876   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
2877   TREE_READONLY (t) = TREE_READONLY (decl);
2878
2879   return t;
2880 }
2881
2882 /* Find the canonical type parameter for the given template type
2883    parameter.  Returns the canonical type parameter, which may be TYPE
2884    if no such parameter existed.  */
2885 static tree
2886 canonical_type_parameter (tree type)
2887 {
2888   tree list;
2889   int idx = TEMPLATE_TYPE_IDX (type);
2890   if (!canonical_template_parms)
2891     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
2892
2893   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
2894     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
2895
2896   list = VEC_index (tree, canonical_template_parms, idx);
2897   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
2898     list = TREE_CHAIN (list);
2899
2900   if (list)
2901     return TREE_VALUE (list);
2902   else
2903     {
2904       VEC_replace(tree, canonical_template_parms, idx,
2905                   tree_cons (NULL_TREE, type, 
2906                              VEC_index (tree, canonical_template_parms, idx)));
2907       return type;
2908     }
2909 }
2910
2911 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
2912    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
2913    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
2914    new one is created.  */
2915
2916 static tree
2917 reduce_template_parm_level (tree index, tree type, int levels, tree args,
2918                             tsubst_flags_t complain)
2919 {
2920   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
2921       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
2922           != TEMPLATE_PARM_LEVEL (index) - levels))
2923     {
2924       tree orig_decl = TEMPLATE_PARM_DECL (index);
2925       tree decl, t;
2926
2927       decl = build_decl (TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
2928       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
2929       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
2930       DECL_ARTIFICIAL (decl) = 1;
2931       SET_DECL_TEMPLATE_PARM_P (decl);
2932
2933       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
2934                                      TEMPLATE_PARM_LEVEL (index) - levels,
2935                                      TEMPLATE_PARM_ORIG_LEVEL (index),
2936                                      decl, type);
2937       TEMPLATE_PARM_DESCENDANTS (index) = t;
2938       TEMPLATE_PARM_PARAMETER_PACK (t) 
2939         = TEMPLATE_PARM_PARAMETER_PACK (index);
2940
2941         /* Template template parameters need this.  */
2942       if (TREE_CODE (decl) == TEMPLATE_DECL)
2943         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
2944           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
2945            args, complain);
2946     }
2947
2948   return TEMPLATE_PARM_DESCENDANTS (index);
2949 }
2950
2951 /* Process information from new template parameter PARM and append it to the
2952    LIST being built.  This new parameter is a non-type parameter iff
2953    IS_NON_TYPE is true. This new parameter is a parameter
2954    pack iff IS_PARAMETER_PACK is true.  */
2955
2956 tree
2957 process_template_parm (tree list, tree parm, bool is_non_type, 
2958                        bool is_parameter_pack)
2959 {
2960   tree decl = 0;
2961   tree defval;
2962   tree err_parm_list;
2963   int idx = 0;
2964
2965   gcc_assert (TREE_CODE (parm) == TREE_LIST);
2966   defval = TREE_PURPOSE (parm);
2967
2968   if (list)
2969     {
2970       tree p = tree_last (list);
2971
2972       if (p && TREE_VALUE (p) != error_mark_node)
2973         {
2974           p = TREE_VALUE (p);
2975           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
2976             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
2977           else
2978             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
2979         }
2980
2981       ++idx;
2982     }
2983   else
2984     idx = 0;
2985
2986   if (is_non_type)
2987     {
2988       parm = TREE_VALUE (parm);
2989
2990       SET_DECL_TEMPLATE_PARM_P (parm);
2991
2992       if (TREE_TYPE (parm) == error_mark_node)
2993         {
2994           err_parm_list = build_tree_list (defval, parm);
2995           TREE_VALUE (err_parm_list) = error_mark_node;
2996            return chainon (list, err_parm_list);
2997         }
2998       else
2999       {
3000         /* [temp.param]
3001
3002            The top-level cv-qualifiers on the template-parameter are
3003            ignored when determining its type.  */
3004         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3005         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3006           {
3007             err_parm_list = build_tree_list (defval, parm);
3008             TREE_VALUE (err_parm_list) = error_mark_node;
3009              return chainon (list, err_parm_list);
3010           }
3011
3012         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3013           {
3014             /* This template parameter is not a parameter pack, but it
3015                should be. Complain about "bare" parameter packs.  */
3016             check_for_bare_parameter_packs (TREE_TYPE (parm));
3017             
3018             /* Recover by calling this a parameter pack.  */
3019             is_parameter_pack = true;
3020           }
3021       }
3022
3023       /* A template parameter is not modifiable.  */
3024       TREE_CONSTANT (parm) = 1;
3025       TREE_READONLY (parm) = 1;
3026       decl = build_decl (CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3027       TREE_CONSTANT (decl) = 1;
3028       TREE_READONLY (decl) = 1;
3029       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3030         = build_template_parm_index (idx, processing_template_decl,
3031                                      processing_template_decl,
3032                                      decl, TREE_TYPE (parm));
3033
3034       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3035         = is_parameter_pack;
3036     }
3037   else
3038     {
3039       tree t;
3040       parm = TREE_VALUE (TREE_VALUE (parm));
3041
3042       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3043         {
3044           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3045           /* This is for distinguishing between real templates and template
3046              template parameters */
3047           TREE_TYPE (parm) = t;
3048           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3049           decl = parm;
3050         }
3051       else
3052         {
3053           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3054           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3055           decl = build_decl (TYPE_DECL, parm, t);
3056         }
3057
3058       TYPE_NAME (t) = decl;
3059       TYPE_STUB_DECL (t) = decl;
3060       parm = decl;
3061       TEMPLATE_TYPE_PARM_INDEX (t)
3062         = build_template_parm_index (idx, processing_template_decl,
3063                                      processing_template_decl,
3064                                      decl, TREE_TYPE (parm));
3065       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3066       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3067     }
3068   DECL_ARTIFICIAL (decl) = 1;
3069   SET_DECL_TEMPLATE_PARM_P (decl);
3070   pushdecl (decl);
3071   parm = build_tree_list (defval, parm);
3072   return chainon (list, parm);
3073 }
3074
3075 /* The end of a template parameter list has been reached.  Process the
3076    tree list into a parameter vector, converting each parameter into a more
3077    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3078    as PARM_DECLs.  */
3079
3080 tree
3081 end_template_parm_list (tree parms)
3082 {
3083   int nparms;
3084   tree parm, next;
3085   tree saved_parmlist = make_tree_vec (list_length (parms));
3086
3087   current_template_parms
3088     = tree_cons (size_int (processing_template_decl),
3089                  saved_parmlist, current_template_parms);
3090
3091   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3092     {
3093       next = TREE_CHAIN (parm);
3094       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3095       TREE_CHAIN (parm) = NULL_TREE;
3096     }
3097
3098   --processing_template_parmlist;
3099
3100   return saved_parmlist;
3101 }
3102
3103 /* end_template_decl is called after a template declaration is seen.  */
3104
3105 void
3106 end_template_decl (void)
3107 {
3108   reset_specialization ();
3109
3110   if (! processing_template_decl)
3111     return;
3112
3113   /* This matches the pushlevel in begin_template_parm_list.  */
3114   finish_scope ();
3115
3116   --processing_template_decl;
3117   current_template_parms = TREE_CHAIN (current_template_parms);
3118 }
3119
3120 /* Within the declaration of a template, return all levels of template
3121    parameters that apply.  The template parameters are represented as
3122    a TREE_VEC, in the form documented in cp-tree.h for template
3123    arguments.  */
3124
3125 static tree
3126 current_template_args (void)
3127 {
3128   tree header;
3129   tree args = NULL_TREE;
3130   int length = TMPL_PARMS_DEPTH (current_template_parms);
3131   int l = length;
3132
3133   /* If there is only one level of template parameters, we do not
3134      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3135      TREE_VEC containing the arguments.  */
3136   if (length > 1)
3137     args = make_tree_vec (length);
3138
3139   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3140     {
3141       tree a = copy_node (TREE_VALUE (header));
3142       int i;
3143
3144       TREE_TYPE (a) = NULL_TREE;
3145       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3146         {
3147           tree t = TREE_VEC_ELT (a, i);
3148
3149           /* T will be a list if we are called from within a
3150              begin/end_template_parm_list pair, but a vector directly
3151              if within a begin/end_member_template_processing pair.  */
3152           if (TREE_CODE (t) == TREE_LIST)
3153             {
3154               t = TREE_VALUE (t);
3155
3156               if (!error_operand_p (t))
3157                 {
3158                   if (TREE_CODE (t) == TYPE_DECL
3159                       || TREE_CODE (t) == TEMPLATE_DECL)
3160                     {
3161                       t = TREE_TYPE (t);
3162                       
3163                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3164                         {
3165                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3166                              with a single element, which expands T.  */
3167                           tree vec = make_tree_vec (1);
3168                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3169                           
3170                           t = make_node (TYPE_ARGUMENT_PACK);
3171                           SET_ARGUMENT_PACK_ARGS (t, vec);
3172                         }
3173                     }
3174                   else
3175                     {
3176                       t = DECL_INITIAL (t);
3177                       
3178                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3179                         {
3180                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3181                              with a single element, which expands T.  */
3182                           tree vec = make_tree_vec (1);
3183                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3184                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3185                           
3186                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3187                           SET_ARGUMENT_PACK_ARGS (t, vec);
3188                           TREE_TYPE (t) = type;
3189                         }
3190                     }
3191                   TREE_VEC_ELT (a, i) = t;
3192                 }
3193             }
3194         }
3195
3196       if (length > 1)
3197         TREE_VEC_ELT (args, --l) = a;
3198       else
3199         args = a;
3200     }
3201
3202   return args;
3203 }
3204
3205 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3206    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3207    a member template.  Used by push_template_decl below.  */
3208
3209 static tree
3210 build_template_decl (tree decl, tree parms, bool member_template_p)
3211 {
3212   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3213   DECL_TEMPLATE_PARMS (tmpl) = parms;
3214   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3215   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3216   if (DECL_LANG_SPECIFIC (decl))
3217     {
3218       DECL_STATIC_FUNCTION_P (tmpl) = DECL_STATIC_FUNCTION_P (decl);
3219       DECL_CONSTRUCTOR_P (tmpl) = DECL_CONSTRUCTOR_P (decl);
3220       DECL_DESTRUCTOR_P (tmpl) = DECL_DESTRUCTOR_P (decl);
3221       DECL_NONCONVERTING_P (tmpl) = DECL_NONCONVERTING_P (decl);
3222       DECL_ASSIGNMENT_OPERATOR_P (tmpl) = DECL_ASSIGNMENT_OPERATOR_P (decl);
3223       if (DECL_OVERLOADED_OPERATOR_P (decl))
3224         SET_OVERLOADED_OPERATOR_CODE (tmpl,
3225                                       DECL_OVERLOADED_OPERATOR_P (decl));
3226     }
3227
3228   return tmpl;
3229 }
3230
3231 struct template_parm_data
3232 {
3233   /* The level of the template parameters we are currently
3234      processing.  */
3235   int level;
3236
3237   /* The index of the specialization argument we are currently
3238      processing.  */
3239   int current_arg;
3240
3241   /* An array whose size is the number of template parameters.  The
3242      elements are nonzero if the parameter has been used in any one
3243      of the arguments processed so far.  */
3244   int* parms;
3245
3246   /* An array whose size is the number of template arguments.  The
3247      elements are nonzero if the argument makes use of template
3248      parameters of this level.  */
3249   int* arg_uses_template_parms;
3250 };
3251
3252 /* Subroutine of push_template_decl used to see if each template
3253    parameter in a partial specialization is used in the explicit
3254    argument list.  If T is of the LEVEL given in DATA (which is
3255    treated as a template_parm_data*), then DATA->PARMS is marked
3256    appropriately.  */
3257
3258 static int
3259 mark_template_parm (tree t, void* data)
3260 {
3261   int level;
3262   int idx;
3263   struct template_parm_data* tpd = (struct template_parm_data*) data;
3264
3265   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3266     {
3267       level = TEMPLATE_PARM_LEVEL (t);
3268       idx = TEMPLATE_PARM_IDX (t);
3269     }
3270   else
3271     {
3272       level = TEMPLATE_TYPE_LEVEL (t);
3273       idx = TEMPLATE_TYPE_IDX (t);
3274     }
3275
3276   if (level == tpd->level)
3277     {
3278       tpd->parms[idx] = 1;
3279       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3280     }
3281
3282   /* Return zero so that for_each_template_parm will continue the
3283      traversal of the tree; we want to mark *every* template parm.  */
3284   return 0;
3285 }
3286
3287 /* Process the partial specialization DECL.  */
3288
3289 static tree
3290 process_partial_specialization (tree decl)
3291 {
3292   tree type = TREE_TYPE (decl);
3293   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3294   tree specargs = CLASSTYPE_TI_ARGS (type);
3295   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3296   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3297   tree inner_parms;
3298   int nargs = TREE_VEC_LENGTH (inner_args);
3299   int ntparms;
3300   int  i;
3301   int did_error_intro = 0;
3302   struct template_parm_data tpd;
3303   struct template_parm_data tpd2;
3304
3305   gcc_assert (current_template_parms);
3306
3307   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3308   ntparms = TREE_VEC_LENGTH (inner_parms);
3309
3310   /* We check that each of the template parameters given in the
3311      partial specialization is used in the argument list to the
3312      specialization.  For example:
3313
3314        template <class T> struct S;
3315        template <class T> struct S<T*>;
3316
3317      The second declaration is OK because `T*' uses the template
3318      parameter T, whereas
3319
3320        template <class T> struct S<int>;
3321
3322      is no good.  Even trickier is:
3323
3324        template <class T>
3325        struct S1
3326        {
3327           template <class U>
3328           struct S2;
3329           template <class U>
3330           struct S2<T>;
3331        };
3332
3333      The S2<T> declaration is actually invalid; it is a
3334      full-specialization.  Of course,
3335
3336           template <class U>
3337           struct S2<T (*)(U)>;
3338
3339      or some such would have been OK.  */
3340   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3341   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3342   memset (tpd.parms, 0, sizeof (int) * ntparms);
3343
3344   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3345   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3346   for (i = 0; i < nargs; ++i)
3347     {
3348       tpd.current_arg = i;
3349       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3350                               &mark_template_parm,
3351                               &tpd,
3352                               NULL,
3353                               /*include_nondeduced_p=*/false);
3354     }
3355   for (i = 0; i < ntparms; ++i)
3356     if (tpd.parms[i] == 0)
3357       {
3358         /* One of the template parms was not used in the
3359            specialization.  */
3360         if (!did_error_intro)
3361           {
3362             error ("template parameters not used in partial specialization:");
3363             did_error_intro = 1;
3364           }
3365
3366         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3367       }
3368
3369   /* [temp.class.spec]
3370
3371      The argument list of the specialization shall not be identical to
3372      the implicit argument list of the primary template.  */
3373   if (comp_template_args
3374       (inner_args,
3375        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3376                                                    (maintmpl)))))
3377     error ("partial specialization %qT does not specialize any template arguments", type);
3378
3379   /* [temp.class.spec]
3380
3381      A partially specialized non-type argument expression shall not
3382      involve template parameters of the partial specialization except
3383      when the argument expression is a simple identifier.
3384
3385      The type of a template parameter corresponding to a specialized
3386      non-type argument shall not be dependent on a parameter of the
3387      specialization. 
3388
3389      Also, we verify that pack expansions only occur at the
3390      end of the argument list.  */
3391   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3392   tpd2.parms = 0;
3393   for (i = 0; i < nargs; ++i)
3394     {
3395       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3396       tree arg = TREE_VEC_ELT (inner_args, i);
3397       tree packed_args = NULL_TREE;
3398       int j, len = 1;
3399
3400       if (ARGUMENT_PACK_P (arg))
3401         {
3402           /* Extract the arguments from the argument pack. We'll be
3403              iterating over these in the following loop.  */
3404           packed_args = ARGUMENT_PACK_ARGS (arg);
3405           len = TREE_VEC_LENGTH (packed_args);
3406         }
3407
3408       for (j = 0; j < len; j++)
3409         {
3410           if (packed_args)
3411             /* Get the Jth argument in the parameter pack.  */
3412             arg = TREE_VEC_ELT (packed_args, j);
3413
3414           if (PACK_EXPANSION_P (arg))
3415             {
3416               /* Pack expansions must come at the end of the
3417                  argument list.  */
3418               if ((packed_args && j < len - 1)
3419                   || (!packed_args && i < nargs - 1))
3420                 {
3421                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3422                     error ("parameter pack argument %qE must be at the end of the template argument list", arg);
3423                   else
3424                     error ("parameter pack argument %qT must be at the end of the template argument list", arg);
3425
3426                   if (packed_args)
3427                     TREE_VEC_ELT (packed_args, j) = error_mark_node;
3428                 }
3429             }
3430
3431           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3432             /* We only care about the pattern.  */
3433             arg = PACK_EXPANSION_PATTERN (arg);
3434
3435           if (/* These first two lines are the `non-type' bit.  */
3436               !TYPE_P (arg)
3437               && TREE_CODE (arg) != TEMPLATE_DECL
3438               /* This next line is the `argument expression is not just a
3439                  simple identifier' condition and also the `specialized
3440                  non-type argument' bit.  */
3441               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3442             {
3443               if ((!packed_args && tpd.arg_uses_template_parms[i])
3444                   || (packed_args && uses_template_parms (arg)))
3445                 error ("template argument %qE involves template parameter(s)",
3446                        arg);
3447               else 
3448                 {
3449                   /* Look at the corresponding template parameter,
3450                      marking which template parameters its type depends
3451                      upon.  */
3452                   tree type = TREE_TYPE (parm);
3453
3454                   if (!tpd2.parms)
3455                     {
3456                       /* We haven't yet initialized TPD2.  Do so now.  */
3457                       tpd2.arg_uses_template_parms 
3458                         = (int *) alloca (sizeof (int) * nargs);
3459                       /* The number of parameters here is the number in the
3460                          main template, which, as checked in the assertion
3461                          above, is NARGS.  */
3462                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3463                       tpd2.level = 
3464                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3465                     }
3466
3467                   /* Mark the template parameters.  But this time, we're
3468                      looking for the template parameters of the main
3469                      template, not in the specialization.  */
3470                   tpd2.current_arg = i;
3471                   tpd2.arg_uses_template_parms[i] = 0;
3472                   memset (tpd2.parms, 0, sizeof (int) * nargs);
3473                   for_each_template_parm (type,
3474                                           &mark_template_parm,
3475                                           &tpd2,
3476                                           NULL,
3477                                           /*include_nondeduced_p=*/false);
3478
3479                   if (tpd2.arg_uses_template_parms [i])
3480                     {
3481                       /* The type depended on some template parameters.
3482                          If they are fully specialized in the
3483                          specialization, that's OK.  */
3484                       int j;
3485                       for (j = 0; j < nargs; ++j)
3486                         if (tpd2.parms[j] != 0
3487                             && tpd.arg_uses_template_parms [j])
3488                           {
3489                             error ("type %qT of template argument %qE depends "
3490                                    "on template parameter(s)", 
3491                                    type,
3492                                    arg);
3493                             break;
3494                           }
3495                     }
3496                 }
3497             }
3498         }
3499     }
3500
3501   if (retrieve_specialization (maintmpl, specargs,
3502                                /*class_specializations_p=*/true))
3503     /* We've already got this specialization.  */
3504     return decl;
3505
3506   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
3507     = tree_cons (specargs, inner_parms,
3508                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
3509   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
3510   return decl;
3511 }
3512
3513 /* Check that a template declaration's use of default arguments and
3514    parameter packs is not invalid.  Here, PARMS are the template
3515    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
3516    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
3517    specialization.
3518    
3519
3520    IS_FRIEND_DECL is nonzero if DECL is a friend function template
3521    declaration (but not a definition); 1 indicates a declaration, 2
3522    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
3523    emitted for extraneous default arguments.
3524
3525    Returns TRUE if there were no errors found, FALSE otherwise. */
3526
3527 bool
3528 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
3529                          int is_partial, int is_friend_decl)
3530 {
3531   const char *msg;
3532   int last_level_to_check;
3533   tree parm_level;
3534   bool no_errors = true;
3535
3536   /* [temp.param]
3537
3538      A default template-argument shall not be specified in a
3539      function template declaration or a function template definition, nor
3540      in the template-parameter-list of the definition of a member of a
3541      class template.  */
3542
3543   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
3544     /* You can't have a function template declaration in a local
3545        scope, nor you can you define a member of a class template in a
3546        local scope.  */
3547     return true;
3548
3549   if (current_class_type
3550       && !TYPE_BEING_DEFINED (current_class_type)
3551       && DECL_LANG_SPECIFIC (decl)
3552       /* If this is either a friend defined in the scope of the class
3553          or a member function.  */
3554       && (DECL_FUNCTION_MEMBER_P (decl)
3555           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
3556           : DECL_FRIEND_CONTEXT (decl)
3557           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
3558           : false)
3559       /* And, if it was a member function, it really was defined in
3560          the scope of the class.  */
3561       && (!DECL_FUNCTION_MEMBER_P (decl)
3562           || DECL_INITIALIZED_IN_CLASS_P (decl)))
3563     /* We already checked these parameters when the template was
3564        declared, so there's no need to do it again now.  This function
3565        was defined in class scope, but we're processing it's body now
3566        that the class is complete.  */
3567     return true;
3568
3569   /* Core issue 226 (C++0x only): the following only applies to class
3570      templates.  */
3571   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
3572     {
3573       /* [temp.param]
3574
3575          If a template-parameter has a default template-argument, all
3576          subsequent template-parameters shall have a default
3577          template-argument supplied.  */
3578       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
3579         {
3580           tree inner_parms = TREE_VALUE (parm_level);
3581           int ntparms = TREE_VEC_LENGTH (inner_parms);
3582           int seen_def_arg_p = 0;
3583           int i;
3584
3585           for (i = 0; i < ntparms; ++i)
3586             {
3587               tree parm = TREE_VEC_ELT (inner_parms, i);
3588
3589               if (parm == error_mark_node)
3590                 continue;
3591
3592               if (TREE_PURPOSE (parm))
3593                 seen_def_arg_p = 1;
3594               else if (seen_def_arg_p
3595                        && !template_parameter_pack_p (TREE_VALUE (parm)))
3596                 {
3597                   error ("no default argument for %qD", TREE_VALUE (parm));
3598                   /* For better subsequent error-recovery, we indicate that
3599                      there should have been a default argument.  */
3600                   TREE_PURPOSE (parm) = error_mark_node;
3601                   no_errors = false;
3602                 }
3603               else if (is_primary
3604                        && !is_partial
3605                        && !is_friend_decl
3606                        /* Don't complain about an enclosing partial
3607                           specialization.  */
3608                        && parm_level == parms
3609                        && TREE_CODE (decl) == TYPE_DECL
3610                        && i < ntparms - 1
3611                        && template_parameter_pack_p (TREE_VALUE (parm)))
3612                 {
3613                   /* A primary class template can only have one
3614                      parameter pack, at the end of the template
3615                      parameter list.  */
3616
3617                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
3618                     error ("parameter pack %qE must be at the end of the"
3619                            " template parameter list", TREE_VALUE (parm));
3620                   else
3621                     error ("parameter pack %qT must be at the end of the"
3622                            " template parameter list", 
3623                            TREE_TYPE (TREE_VALUE (parm)));
3624
3625                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
3626                     = error_mark_node;
3627                   no_errors = false;
3628                 }
3629             }
3630         }
3631     }
3632
3633   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
3634       || is_partial 
3635       || !is_primary
3636       || is_friend_decl)
3637     /* For an ordinary class template, default template arguments are
3638        allowed at the innermost level, e.g.:
3639          template <class T = int>
3640          struct S {};
3641        but, in a partial specialization, they're not allowed even
3642        there, as we have in [temp.class.spec]:
3643
3644          The template parameter list of a specialization shall not
3645          contain default template argument values.
3646
3647        So, for a partial specialization, or for a function template
3648        (in C++98/C++03), we look at all of them.  */
3649     ;
3650   else
3651     /* But, for a primary class template that is not a partial
3652        specialization we look at all template parameters except the
3653        innermost ones.  */
3654     parms = TREE_CHAIN (parms);
3655
3656   /* Figure out what error message to issue.  */
3657   if (is_friend_decl == 2)
3658     msg = "default template arguments may not be used in function template friend re-declaration";
3659   else if (is_friend_decl)
3660     msg = "default template arguments may not be used in function template friend declarations";
3661   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
3662     msg = "default template arguments may not be used in function templates";
3663   else if (is_partial)
3664     msg = "default template arguments may not be used in partial specializations";
3665   else
3666     msg = "default argument for template parameter for class enclosing %qD";
3667
3668   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
3669     /* If we're inside a class definition, there's no need to
3670        examine the parameters to the class itself.  On the one
3671        hand, they will be checked when the class is defined, and,
3672        on the other, default arguments are valid in things like:
3673          template <class T = double>
3674          struct S { template <class U> void f(U); };
3675        Here the default argument for `S' has no bearing on the
3676        declaration of `f'.  */
3677     last_level_to_check = template_class_depth (current_class_type) + 1;
3678   else
3679     /* Check everything.  */
3680     last_level_to_check = 0;
3681
3682   for (parm_level = parms;
3683        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
3684        parm_level = TREE_CHAIN (parm_level))
3685     {
3686       tree inner_parms = TREE_VALUE (parm_level);
3687       int i;
3688       int ntparms;
3689
3690       ntparms = TREE_VEC_LENGTH (inner_parms);
3691       for (i = 0; i < ntparms; ++i)
3692         {
3693           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
3694             continue;
3695
3696           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
3697             {
3698               if (msg)
3699                 {
3700                   no_errors = false;
3701                   if (is_friend_decl == 2)
3702                     return no_errors;
3703
3704                   error (msg, decl);
3705                   msg = 0;
3706                 }
3707
3708               /* Clear out the default argument so that we are not
3709                  confused later.  */
3710               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
3711             }
3712         }
3713
3714       /* At this point, if we're still interested in issuing messages,
3715          they must apply to classes surrounding the object declared.  */
3716       if (msg)
3717         msg = "default argument for template parameter for class enclosing %qD";
3718     }
3719
3720   return no_errors;
3721 }
3722
3723 /* Worker for push_template_decl_real, called via
3724    for_each_template_parm.  DATA is really an int, indicating the
3725    level of the parameters we are interested in.  If T is a template
3726    parameter of that level, return nonzero.  */
3727
3728 static int
3729 template_parm_this_level_p (tree t, void* data)
3730 {
3731   int this_level = *(int *)data;
3732   int level;
3733
3734   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3735     level = TEMPLATE_PARM_LEVEL (t);
3736   else
3737     level = TEMPLATE_TYPE_LEVEL (t);
3738   return level == this_level;
3739 }
3740
3741 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
3742    parameters given by current_template_args, or reuses a
3743    previously existing one, if appropriate.  Returns the DECL, or an
3744    equivalent one, if it is replaced via a call to duplicate_decls.
3745
3746    If IS_FRIEND is true, DECL is a friend declaration.  */
3747
3748 tree
3749 push_template_decl_real (tree decl, bool is_friend)
3750 {
3751   tree tmpl;
3752   tree args;
3753   tree info;
3754   tree ctx;
3755   int primary;
3756   int is_partial;
3757   int new_template_p = 0;
3758   /* True if the template is a member template, in the sense of
3759      [temp.mem].  */
3760   bool member_template_p = false;
3761
3762   if (decl == error_mark_node || !current_template_parms)
3763     return error_mark_node;
3764
3765   /* See if this is a partial specialization.  */
3766   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
3767                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
3768                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
3769
3770   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
3771     is_friend = true;
3772
3773   if (is_friend)
3774     /* For a friend, we want the context of the friend function, not
3775        the type of which it is a friend.  */
3776     ctx = DECL_CONTEXT (decl);
3777   else if (CP_DECL_CONTEXT (decl)
3778            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
3779     /* In the case of a virtual function, we want the class in which
3780        it is defined.  */
3781     ctx = CP_DECL_CONTEXT (decl);
3782   else
3783     /* Otherwise, if we're currently defining some class, the DECL
3784        is assumed to be a member of the class.  */
3785     ctx = current_scope ();
3786
3787   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
3788     ctx = NULL_TREE;
3789
3790   if (!DECL_CONTEXT (decl))
3791     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
3792
3793   /* See if this is a primary template.  */
3794   if (is_friend && ctx)
3795     /* A friend template that specifies a class context, i.e.
3796          template <typename T> friend void A<T>::f();
3797        is not primary.  */
3798     primary = 0;
3799   else
3800     primary = template_parm_scope_p ();
3801
3802   if (primary)
3803     {
3804       if (DECL_CLASS_SCOPE_P (decl))
3805         member_template_p = true;
3806       if (TREE_CODE (decl) == TYPE_DECL
3807           && ANON_AGGRNAME_P (DECL_NAME (decl)))
3808         {
3809           error ("template class without a name");
3810           return error_mark_node;
3811         }
3812       else if (TREE_CODE (decl) == FUNCTION_DECL)
3813         {
3814           if (DECL_DESTRUCTOR_P (decl))
3815             {
3816               /* [temp.mem]
3817
3818                  A destructor shall not be a member template.  */
3819               error ("destructor %qD declared as member template", decl);
3820               return error_mark_node;
3821             }
3822           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
3823               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
3824                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
3825                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
3826                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
3827                       == void_list_node)))
3828             {
3829               /* [basic.stc.dynamic.allocation]
3830
3831                  An allocation function can be a function
3832                  template. ... Template allocation functions shall
3833                  have two or more parameters.  */
3834               error ("invalid template declaration of %qD", decl);
3835               return error_mark_node;
3836             }
3837         }
3838       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3839                && CLASS_TYPE_P (TREE_TYPE (decl)))
3840         /* OK */;
3841       else
3842         {
3843           error ("template declaration of %q#D", decl);
3844           return error_mark_node;
3845         }
3846     }
3847
3848   /* Check to see that the rules regarding the use of default
3849      arguments are not being violated.  */
3850   check_default_tmpl_args (decl, current_template_parms,
3851                            primary, is_partial, /*is_friend_decl=*/0);
3852
3853   /* Ensure that there are no parameter packs in the type of this
3854      declaration that have not been expanded.  */
3855   if (TREE_CODE (decl) == FUNCTION_DECL)
3856     {
3857       /* Check each of the arguments individually to see if there are
3858          any bare parameter packs.  */
3859       tree type = TREE_TYPE (decl);
3860       tree arg = DECL_ARGUMENTS (decl);
3861       tree argtype = TYPE_ARG_TYPES (type);
3862
3863       while (arg && argtype)
3864         {
3865           if (!FUNCTION_PARAMETER_PACK_P (arg)
3866               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
3867             {
3868             /* This is a PARM_DECL that contains unexpanded parameter
3869                packs. We have already complained about this in the
3870                check_for_bare_parameter_packs call, so just replace
3871                these types with ERROR_MARK_NODE.  */
3872               TREE_TYPE (arg) = error_mark_node;
3873               TREE_VALUE (argtype) = error_mark_node;
3874             }
3875
3876           arg = TREE_CHAIN (arg);
3877           argtype = TREE_CHAIN (argtype);
3878         }
3879
3880       /* Check for bare parameter packs in the return type and the
3881          exception specifiers.  */
3882       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
3883         /* Errors were already issued, set return type to int
3884            as the frontend doesn't expect error_mark_node as
3885            the return type.  */
3886         TREE_TYPE (type) = integer_type_node;
3887       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
3888         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
3889     }
3890   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
3891     {
3892       TREE_TYPE (decl) = error_mark_node;
3893       return error_mark_node;
3894     }
3895
3896   if (is_partial)
3897     return process_partial_specialization (decl);
3898
3899   args = current_template_args ();
3900
3901   if (!ctx
3902       || TREE_CODE (ctx) == FUNCTION_DECL
3903       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
3904       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
3905     {
3906       if (DECL_LANG_SPECIFIC (decl)
3907           && DECL_TEMPLATE_INFO (decl)
3908           && DECL_TI_TEMPLATE (decl))
3909         tmpl = DECL_TI_TEMPLATE (decl);
3910       /* If DECL is a TYPE_DECL for a class-template, then there won't
3911          be DECL_LANG_SPECIFIC.  The information equivalent to
3912          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
3913       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3914                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
3915                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
3916         {
3917           /* Since a template declaration already existed for this
3918              class-type, we must be redeclaring it here.  Make sure
3919              that the redeclaration is valid.  */
3920           redeclare_class_template (TREE_TYPE (decl),
3921                                     current_template_parms);
3922           /* We don't need to create a new TEMPLATE_DECL; just use the
3923              one we already had.  */
3924           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
3925         }
3926       else
3927         {
3928           tmpl = build_template_decl (decl, current_template_parms,
3929                                       member_template_p);
3930           new_template_p = 1;
3931
3932           if (DECL_LANG_SPECIFIC (decl)
3933               && DECL_TEMPLATE_SPECIALIZATION (decl))
3934             {
3935               /* A specialization of a member template of a template
3936                  class.  */
3937               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3938               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
3939               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
3940             }
3941         }
3942     }
3943   else
3944     {
3945       tree a, t, current, parms;
3946       int i;
3947       tree tinfo = get_template_info (decl);
3948
3949       if (!tinfo)
3950         {
3951           error ("template definition of non-template %q#D", decl);
3952           return error_mark_node;
3953         }
3954
3955       tmpl = TI_TEMPLATE (tinfo);
3956
3957       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3958           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
3959           && DECL_TEMPLATE_SPECIALIZATION (decl)
3960           && DECL_MEMBER_TEMPLATE_P (tmpl))
3961         {
3962           tree new_tmpl;
3963
3964           /* The declaration is a specialization of a member
3965              template, declared outside the class.  Therefore, the
3966              innermost template arguments will be NULL, so we
3967              replace them with the arguments determined by the
3968              earlier call to check_explicit_specialization.  */
3969           args = DECL_TI_ARGS (decl);
3970
3971           new_tmpl
3972             = build_template_decl (decl, current_template_parms,
3973                                    member_template_p);
3974           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
3975           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
3976           DECL_TI_TEMPLATE (decl) = new_tmpl;
3977           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
3978           DECL_TEMPLATE_INFO (new_tmpl)
3979             = tree_cons (tmpl, args, NULL_TREE);
3980
3981           register_specialization (new_tmpl,
3982                                    most_general_template (tmpl),
3983                                    args,
3984                                    is_friend);
3985           return decl;
3986         }
3987
3988       /* Make sure the template headers we got make sense.  */
3989
3990       parms = DECL_TEMPLATE_PARMS (tmpl);
3991       i = TMPL_PARMS_DEPTH (parms);
3992       if (TMPL_ARGS_DEPTH (args) != i)
3993         {
3994           error ("expected %d levels of template parms for %q#D, got %d",
3995                  i, decl, TMPL_ARGS_DEPTH (args));
3996         }
3997       else
3998         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
3999           {
4000             a = TMPL_ARGS_LEVEL (args, i);
4001             t = INNERMOST_TEMPLATE_PARMS (parms);
4002
4003             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4004               {
4005                 if (current == decl)
4006                   error ("got %d template parameters for %q#D",
4007                          TREE_VEC_LENGTH (a), decl);
4008                 else
4009                   error ("got %d template parameters for %q#T",
4010                          TREE_VEC_LENGTH (a), current);
4011                 error ("  but %d required", TREE_VEC_LENGTH (t));
4012                 return error_mark_node;
4013               }
4014
4015             if (current == decl)
4016               current = ctx;
4017             else
4018               current = (TYPE_P (current)
4019                          ? TYPE_CONTEXT (current)
4020                          : DECL_CONTEXT (current));
4021           }
4022
4023       /* Check that the parms are used in the appropriate qualifying scopes
4024          in the declarator.  */
4025       if (!comp_template_args
4026           (TI_ARGS (tinfo),
4027            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4028         {
4029           error ("\
4030 template arguments to %qD do not match original template %qD",
4031                  decl, DECL_TEMPLATE_RESULT (tmpl));
4032           if (!uses_template_parms (TI_ARGS (tinfo)))
4033             inform (input_location, "use template<> for an explicit specialization");
4034           /* Avoid crash in import_export_decl.  */
4035           DECL_INTERFACE_KNOWN (decl) = 1;
4036           return error_mark_node;
4037         }
4038     }
4039
4040   DECL_TEMPLATE_RESULT (tmpl) = decl;
4041   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4042
4043   /* Push template declarations for global functions and types.  Note
4044      that we do not try to push a global template friend declared in a
4045      template class; such a thing may well depend on the template
4046      parameters of the class.  */
4047   if (new_template_p && !ctx
4048       && !(is_friend && template_class_depth (current_class_type) > 0))
4049     {
4050       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4051       if (tmpl == error_mark_node)
4052         return error_mark_node;
4053
4054       /* Hide template friend classes that haven't been declared yet.  */
4055       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4056         {
4057           DECL_ANTICIPATED (tmpl) = 1;
4058           DECL_FRIEND_P (tmpl) = 1;
4059         }
4060     }
4061
4062   if (primary)
4063     {
4064       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4065       int i;
4066
4067       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4068       if (DECL_CONV_FN_P (tmpl))
4069         {
4070           int depth = TMPL_PARMS_DEPTH (parms);
4071
4072           /* It is a conversion operator. See if the type converted to
4073              depends on innermost template operands.  */
4074
4075           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4076                                          depth))
4077             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4078         }
4079
4080       /* Give template template parms a DECL_CONTEXT of the template
4081          for which they are a parameter.  */
4082       parms = INNERMOST_TEMPLATE_PARMS (parms);
4083       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4084         {
4085           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4086           if (TREE_CODE (parm) == TEMPLATE_DECL)
4087             DECL_CONTEXT (parm) = tmpl;
4088         }
4089     }
4090
4091   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4092      back to its most general template.  If TMPL is a specialization,
4093      ARGS may only have the innermost set of arguments.  Add the missing
4094      argument levels if necessary.  */
4095   if (DECL_TEMPLATE_INFO (tmpl))
4096     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4097
4098   info = tree_cons (tmpl, args, NULL_TREE);
4099
4100   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4101     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4102   else if (DECL_LANG_SPECIFIC (decl))
4103     DECL_TEMPLATE_INFO (decl) = info;
4104
4105   return DECL_TEMPLATE_RESULT (tmpl);
4106 }
4107
4108 tree
4109 push_template_decl (tree decl)
4110 {
4111   return push_template_decl_real (decl, false);
4112 }
4113
4114 /* Called when a class template TYPE is redeclared with the indicated
4115    template PARMS, e.g.:
4116
4117      template <class T> struct S;
4118      template <class T> struct S {};  */
4119
4120 bool
4121 redeclare_class_template (tree type, tree parms)
4122 {
4123   tree tmpl;
4124   tree tmpl_parms;
4125   int i;
4126
4127   if (!TYPE_TEMPLATE_INFO (type))
4128     {
4129       error ("%qT is not a template type", type);
4130       return false;
4131     }
4132
4133   tmpl = TYPE_TI_TEMPLATE (type);
4134   if (!PRIMARY_TEMPLATE_P (tmpl))
4135     /* The type is nested in some template class.  Nothing to worry
4136        about here; there are no new template parameters for the nested
4137        type.  */
4138     return true;
4139
4140   if (!parms)
4141     {
4142       error ("template specifiers not specified in declaration of %qD",
4143              tmpl);
4144       return false;
4145     }
4146
4147   parms = INNERMOST_TEMPLATE_PARMS (parms);
4148   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4149
4150   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4151     {
4152       error ("redeclared with %d template parameter(s)", 
4153              TREE_VEC_LENGTH (parms));
4154       inform (input_location, "previous declaration %q+D used %d template parameter(s)", 
4155              tmpl, TREE_VEC_LENGTH (tmpl_parms));
4156       return false;
4157     }
4158
4159   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4160     {
4161       tree tmpl_parm;
4162       tree parm;
4163       tree tmpl_default;
4164       tree parm_default;
4165
4166       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4167           || TREE_VEC_ELT (parms, i) == error_mark_node)
4168         continue;
4169
4170       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4171       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4172       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4173       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4174
4175       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4176          TEMPLATE_DECL.  */
4177       if (tmpl_parm != error_mark_node
4178           && (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4179               || (TREE_CODE (tmpl_parm) != TYPE_DECL
4180                   && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4181               || (TREE_CODE (tmpl_parm) != PARM_DECL
4182                   && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4183                       != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4184               || (TREE_CODE (tmpl_parm) == PARM_DECL
4185                   && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4186                       != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))))))
4187         {
4188           error ("template parameter %q+#D", tmpl_parm);
4189           error ("redeclared here as %q#D", parm);
4190           return false;
4191         }
4192
4193       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4194         {
4195           /* We have in [temp.param]:
4196
4197              A template-parameter may not be given default arguments
4198              by two different declarations in the same scope.  */
4199           error ("redefinition of default argument for %q#D", parm);
4200           inform (input_location, "%Joriginal definition appeared here", tmpl_parm);
4201           return false;
4202         }
4203
4204       if (parm_default != NULL_TREE)
4205         /* Update the previous template parameters (which are the ones
4206            that will really count) with the new default value.  */
4207         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4208       else if (tmpl_default != NULL_TREE)
4209         /* Update the new parameters, too; they'll be used as the
4210            parameters for any members.  */
4211         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4212     }
4213
4214     return true;
4215 }
4216
4217 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4218    (possibly simplified) expression.  */
4219
4220 tree
4221 fold_non_dependent_expr (tree expr)
4222 {
4223   if (expr == NULL_TREE)
4224     return NULL_TREE;
4225
4226   /* If we're in a template, but EXPR isn't value dependent, simplify
4227      it.  We're supposed to treat:
4228
4229        template <typename T> void f(T[1 + 1]);
4230        template <typename T> void f(T[2]);
4231
4232      as two declarations of the same function, for example.  */
4233   if (processing_template_decl
4234       && !type_dependent_expression_p (expr)
4235       && !value_dependent_expression_p (expr))
4236     {
4237       HOST_WIDE_INT saved_processing_template_decl;
4238
4239       saved_processing_template_decl = processing_template_decl;
4240       processing_template_decl = 0;
4241       expr = tsubst_copy_and_build (expr,
4242                                     /*args=*/NULL_TREE,
4243                                     tf_error,
4244                                     /*in_decl=*/NULL_TREE,
4245                                     /*function_p=*/false,
4246                                     /*integral_constant_expression_p=*/true);
4247       processing_template_decl = saved_processing_template_decl;
4248     }
4249   return expr;
4250 }
4251
4252 /* EXPR is an expression which is used in a constant-expression context.
4253    For instance, it could be a VAR_DECL with a constant initializer.
4254    Extract the innermost constant expression.
4255
4256    This is basically a more powerful version of
4257    integral_constant_value, which can be used also in templates where
4258    initializers can maintain a syntactic rather than semantic form
4259    (even if they are non-dependent, for access-checking purposes).  */
4260
4261 static tree
4262 fold_decl_constant_value (tree expr)
4263 {
4264   tree const_expr = expr;
4265   do
4266     {
4267       expr = fold_non_dependent_expr (const_expr);
4268       const_expr = integral_constant_value (expr);
4269     }
4270   while (expr != const_expr);
4271
4272   return expr;
4273 }
4274
4275 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4276    must be a function or a pointer-to-function type, as specified
4277    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4278    and check that the resulting function has external linkage.  */
4279
4280 static tree
4281 convert_nontype_argument_function (tree type, tree expr)
4282 {
4283   tree fns = expr;
4284   tree fn, fn_no_ptr;
4285
4286   fn = instantiate_type (type, fns, tf_none);
4287   if (fn == error_mark_node)
4288     return error_mark_node;
4289
4290   fn_no_ptr = fn;
4291   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4292     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4293   if (TREE_CODE (fn_no_ptr) == BASELINK)
4294     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4295  
4296   /* [temp.arg.nontype]/1
4297
4298      A template-argument for a non-type, non-template template-parameter
4299      shall be one of:
4300      [...]
4301      -- the address of an object or function with external linkage.  */
4302   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4303     {
4304       error ("%qE is not a valid template argument for type %qT "
4305              "because function %qD has not external linkage",
4306              expr, type, fn_no_ptr);
4307       return NULL_TREE;
4308     }
4309
4310   return fn;
4311 }
4312
4313 /* Attempt to convert the non-type template parameter EXPR to the
4314    indicated TYPE.  If the conversion is successful, return the
4315    converted value.  If the conversion is unsuccessful, return
4316    NULL_TREE if we issued an error message, or error_mark_node if we
4317    did not.  We issue error messages for out-and-out bad template
4318    parameters, but not simply because the conversion failed, since we
4319    might be just trying to do argument deduction.  Both TYPE and EXPR
4320    must be non-dependent.
4321
4322    The conversion follows the special rules described in
4323    [temp.arg.nontype], and it is much more strict than an implicit
4324    conversion.
4325
4326    This function is called twice for each template argument (see
4327    lookup_template_class for a more accurate description of this
4328    problem). This means that we need to handle expressions which
4329    are not valid in a C++ source, but can be created from the
4330    first call (for instance, casts to perform conversions). These
4331    hacks can go away after we fix the double coercion problem.  */
4332
4333 static tree
4334 convert_nontype_argument (tree type, tree expr)
4335 {
4336   tree expr_type;
4337
4338   /* Detect immediately string literals as invalid non-type argument.
4339      This special-case is not needed for correctness (we would easily
4340      catch this later), but only to provide better diagnostic for this
4341      common user mistake. As suggested by DR 100, we do not mention
4342      linkage issues in the diagnostic as this is not the point.  */
4343   if (TREE_CODE (expr) == STRING_CST)
4344     {
4345       error ("%qE is not a valid template argument for type %qT "
4346              "because string literals can never be used in this context",
4347              expr, type);
4348       return NULL_TREE;
4349     }
4350
4351   /* If we are in a template, EXPR may be non-dependent, but still
4352      have a syntactic, rather than semantic, form.  For example, EXPR
4353      might be a SCOPE_REF, rather than the VAR_DECL to which the
4354      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4355      so that access checking can be performed when the template is
4356      instantiated -- but here we need the resolved form so that we can
4357      convert the argument.  */
4358   expr = fold_non_dependent_expr (expr);
4359   if (error_operand_p (expr))
4360     return error_mark_node;
4361   expr_type = TREE_TYPE (expr);
4362
4363   /* HACK: Due to double coercion, we can get a
4364      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4365      which is the tree that we built on the first call (see
4366      below when coercing to reference to object or to reference to
4367      function). We just strip everything and get to the arg.
4368      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4369      for examples.  */
4370   if (TREE_CODE (expr) == NOP_EXPR)
4371     {
4372       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4373         {
4374           /* ??? Maybe we could use convert_from_reference here, but we
4375              would need to relax its constraints because the NOP_EXPR
4376              could actually change the type to something more cv-qualified,
4377              and this is not folded by convert_from_reference.  */
4378           tree addr = TREE_OPERAND (expr, 0);
4379           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4380           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4381           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4382           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4383                       (TREE_TYPE (expr_type),
4384                        TREE_TYPE (TREE_TYPE (addr))));
4385
4386           expr = TREE_OPERAND (addr, 0);
4387           expr_type = TREE_TYPE (expr);
4388         }
4389
4390       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4391          parameter is a pointer to object, through decay and
4392          qualification conversion. Let's strip everything.  */
4393       else if (TYPE_PTROBV_P (type))
4394         {
4395           STRIP_NOPS (expr);
4396           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4397           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4398           /* Skip the ADDR_EXPR only if it is part of the decay for
4399              an array. Otherwise, it is part of the original argument
4400              in the source code.  */
4401           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4402             expr = TREE_OPERAND (expr, 0);
4403           expr_type = TREE_TYPE (expr);
4404         }
4405     }
4406
4407   /* [temp.arg.nontype]/5, bullet 1
4408
4409      For a non-type template-parameter of integral or enumeration type,
4410      integral promotions (_conv.prom_) and integral conversions
4411      (_conv.integral_) are applied.  */
4412   if (INTEGRAL_TYPE_P (type))
4413     {
4414       if (!INTEGRAL_TYPE_P (expr_type))
4415         return error_mark_node;
4416
4417       expr = fold_decl_constant_value (expr);
4418       /* Notice that there are constant expressions like '4 % 0' which
4419          do not fold into integer constants.  */
4420       if (TREE_CODE (expr) != INTEGER_CST)
4421         {
4422           error ("%qE is not a valid template argument for type %qT "
4423                  "because it is a non-constant expression", expr, type);
4424           return NULL_TREE;
4425         }
4426
4427       /* At this point, an implicit conversion does what we want,
4428          because we already know that the expression is of integral
4429          type.  */
4430       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4431       if (expr == error_mark_node)
4432         return error_mark_node;
4433
4434       /* Conversion was allowed: fold it to a bare integer constant.  */
4435       expr = fold (expr);
4436     }
4437   /* [temp.arg.nontype]/5, bullet 2
4438
4439      For a non-type template-parameter of type pointer to object,
4440      qualification conversions (_conv.qual_) and the array-to-pointer
4441      conversion (_conv.array_) are applied.  */
4442   else if (TYPE_PTROBV_P (type))
4443     {
4444       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
4445
4446          A template-argument for a non-type, non-template template-parameter
4447          shall be one of: [...]
4448
4449          -- the name of a non-type template-parameter;
4450          -- the address of an object or function with external linkage, [...]
4451             expressed as "& id-expression" where the & is optional if the name
4452             refers to a function or array, or if the corresponding
4453             template-parameter is a reference.
4454
4455         Here, we do not care about functions, as they are invalid anyway
4456         for a parameter of type pointer-to-object.  */
4457
4458       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
4459         /* Non-type template parameters are OK.  */
4460         ;
4461       else if (TREE_CODE (expr) != ADDR_EXPR
4462                && TREE_CODE (expr_type) != ARRAY_TYPE)
4463         {
4464           if (TREE_CODE (expr) == VAR_DECL)
4465             {
4466               error ("%qD is not a valid template argument "
4467                      "because %qD is a variable, not the address of "
4468                      "a variable",
4469                      expr, expr);
4470               return NULL_TREE;
4471             }
4472           /* Other values, like integer constants, might be valid
4473              non-type arguments of some other type.  */
4474           return error_mark_node;
4475         }
4476       else
4477         {
4478           tree decl;
4479
4480           decl = ((TREE_CODE (expr) == ADDR_EXPR)
4481                   ? TREE_OPERAND (expr, 0) : expr);
4482           if (TREE_CODE (decl) != VAR_DECL)
4483             {
4484               error ("%qE is not a valid template argument of type %qT "
4485                      "because %qE is not a variable",
4486                      expr, type, decl);
4487               return NULL_TREE;
4488             }
4489           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
4490             {
4491               error ("%qE is not a valid template argument of type %qT "
4492                      "because %qD does not have external linkage",
4493                      expr, type, decl);
4494               return NULL_TREE;
4495             }
4496         }
4497
4498       expr = decay_conversion (expr);
4499       if (expr == error_mark_node)
4500         return error_mark_node;
4501
4502       expr = perform_qualification_conversions (type, expr);
4503       if (expr == error_mark_node)
4504         return error_mark_node;
4505     }
4506   /* [temp.arg.nontype]/5, bullet 3
4507
4508      For a non-type template-parameter of type reference to object, no
4509      conversions apply. The type referred to by the reference may be more
4510      cv-qualified than the (otherwise identical) type of the
4511      template-argument. The template-parameter is bound directly to the
4512      template-argument, which must be an lvalue.  */
4513   else if (TYPE_REF_OBJ_P (type))
4514     {
4515       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
4516                                                       expr_type))
4517         return error_mark_node;
4518
4519       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
4520         {
4521           error ("%qE is not a valid template argument for type %qT "
4522                  "because of conflicts in cv-qualification", expr, type);
4523           return NULL_TREE;
4524         }
4525
4526       if (!real_lvalue_p (expr))
4527         {
4528           error ("%qE is not a valid template argument for type %qT "
4529                  "because it is not an lvalue", expr, type);
4530           return NULL_TREE;
4531         }
4532
4533       /* [temp.arg.nontype]/1
4534
4535          A template-argument for a non-type, non-template template-parameter
4536          shall be one of: [...]
4537
4538          -- the address of an object or function with external linkage.  */
4539       if (!DECL_EXTERNAL_LINKAGE_P (expr))
4540         {
4541           error ("%qE is not a valid template argument for type %qT "
4542                  "because object %qD has not external linkage",
4543                  expr, type, expr);
4544           return NULL_TREE;
4545         }
4546
4547       expr = build_nop (type, build_address (expr));
4548     }
4549   /* [temp.arg.nontype]/5, bullet 4
4550
4551      For a non-type template-parameter of type pointer to function, only
4552      the function-to-pointer conversion (_conv.func_) is applied. If the
4553      template-argument represents a set of overloaded functions (or a
4554      pointer to such), the matching function is selected from the set
4555      (_over.over_).  */
4556   else if (TYPE_PTRFN_P (type))
4557     {
4558       /* If the argument is a template-id, we might not have enough
4559          context information to decay the pointer.  */
4560       if (!type_unknown_p (expr_type))
4561         {
4562           expr = decay_conversion (expr);
4563           if (expr == error_mark_node)
4564             return error_mark_node;
4565         }
4566
4567       expr = convert_nontype_argument_function (type, expr);
4568       if (!expr || expr == error_mark_node)
4569         return expr;
4570
4571       if (TREE_CODE (expr) != ADDR_EXPR)
4572         {
4573           error ("%qE is not a valid template argument for type %qT", expr, type);
4574           error ("it must be the address of a function with external linkage");
4575           return NULL_TREE;
4576         }
4577     }
4578   /* [temp.arg.nontype]/5, bullet 5
4579
4580      For a non-type template-parameter of type reference to function, no
4581      conversions apply. If the template-argument represents a set of
4582      overloaded functions, the matching function is selected from the set
4583      (_over.over_).  */
4584   else if (TYPE_REFFN_P (type))
4585     {
4586       if (TREE_CODE (expr) == ADDR_EXPR)
4587         {
4588           error ("%qE is not a valid template argument for type %qT "
4589                  "because it is a pointer", expr, type);
4590           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
4591           return NULL_TREE;
4592         }
4593
4594       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
4595       if (!expr || expr == error_mark_node)
4596         return expr;
4597
4598       expr = build_nop (type, build_address (expr));
4599     }
4600   /* [temp.arg.nontype]/5, bullet 6
4601
4602      For a non-type template-parameter of type pointer to member function,
4603      no conversions apply. If the template-argument represents a set of
4604      overloaded member functions, the matching member function is selected
4605      from the set (_over.over_).  */
4606   else if (TYPE_PTRMEMFUNC_P (type))
4607     {
4608       expr = instantiate_type (type, expr, tf_none);
4609       if (expr == error_mark_node)
4610         return error_mark_node;
4611
4612       /* There is no way to disable standard conversions in
4613          resolve_address_of_overloaded_function (called by
4614          instantiate_type). It is possible that the call succeeded by
4615          converting &B::I to &D::I (where B is a base of D), so we need
4616          to reject this conversion here.
4617
4618          Actually, even if there was a way to disable standard conversions,
4619          it would still be better to reject them here so that we can
4620          provide a superior diagnostic.  */
4621       if (!same_type_p (TREE_TYPE (expr), type))
4622         {
4623           /* Make sure we are just one standard conversion off.  */
4624           gcc_assert (can_convert (type, TREE_TYPE (expr)));
4625           error ("%qE is not a valid template argument for type %qT "
4626                  "because it is of type %qT", expr, type,
4627                  TREE_TYPE (expr));
4628           inform (input_location, "standard conversions are not allowed in this context");
4629           return NULL_TREE;
4630         }
4631     }
4632   /* [temp.arg.nontype]/5, bullet 7
4633
4634      For a non-type template-parameter of type pointer to data member,
4635      qualification conversions (_conv.qual_) are applied.  */
4636   else if (TYPE_PTRMEM_P (type))
4637     {
4638       expr = perform_qualification_conversions (type, expr);
4639       if (expr == error_mark_node)
4640         return expr;
4641     }
4642   /* A template non-type parameter must be one of the above.  */
4643   else
4644     gcc_unreachable ();
4645
4646   /* Sanity check: did we actually convert the argument to the
4647      right type?  */
4648   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
4649   return expr;
4650 }
4651
4652 /* Subroutine of coerce_template_template_parms, which returns 1 if
4653    PARM_PARM and ARG_PARM match using the rule for the template
4654    parameters of template template parameters. Both PARM and ARG are
4655    template parameters; the rest of the arguments are the same as for
4656    coerce_template_template_parms.
4657  */
4658 static int
4659 coerce_template_template_parm (tree parm,
4660                               tree arg,
4661                               tsubst_flags_t complain,
4662                               tree in_decl,
4663                               tree outer_args)
4664 {
4665   if (arg == NULL_TREE || arg == error_mark_node
4666       || parm == NULL_TREE || parm == error_mark_node)
4667     return 0;
4668   
4669   if (TREE_CODE (arg) != TREE_CODE (parm))
4670     return 0;
4671   
4672   switch (TREE_CODE (parm))
4673     {
4674     case TEMPLATE_DECL:
4675       /* We encounter instantiations of templates like
4676          template <template <template <class> class> class TT>
4677          class C;  */
4678       {
4679         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
4680         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
4681         
4682         if (!coerce_template_template_parms
4683             (parmparm, argparm, complain, in_decl, outer_args))
4684           return 0;
4685       }
4686       /* Fall through.  */
4687       
4688     case TYPE_DECL:
4689       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
4690           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
4691         /* Argument is a parameter pack but parameter is not.  */
4692         return 0;
4693       break;
4694       
4695     case PARM_DECL:
4696       /* The tsubst call is used to handle cases such as
4697          
4698            template <int> class C {};
4699            template <class T, template <T> class TT> class D {};
4700            D<int, C> d;
4701
4702          i.e. the parameter list of TT depends on earlier parameters.  */
4703       if (!uses_template_parms (TREE_TYPE (arg))
4704           && !same_type_p
4705                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
4706                  TREE_TYPE (arg)))
4707         return 0;
4708       
4709       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
4710           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
4711         /* Argument is a parameter pack but parameter is not.  */
4712         return 0;
4713       
4714       break;
4715
4716     default:
4717       gcc_unreachable ();
4718     }
4719
4720   return 1;
4721 }
4722
4723
4724 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
4725    template template parameters.  Both PARM_PARMS and ARG_PARMS are
4726    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
4727    or PARM_DECL.
4728
4729    Consider the example:
4730      template <class T> class A;
4731      template<template <class U> class TT> class B;
4732
4733    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
4734    the parameters to A, and OUTER_ARGS contains A.  */
4735
4736 static int
4737 coerce_template_template_parms (tree parm_parms,
4738                                 tree arg_parms,
4739                                 tsubst_flags_t complain,
4740                                 tree in_decl,
4741                                 tree outer_args)
4742 {
4743   int nparms, nargs, i;
4744   tree parm, arg;
4745   int variadic_p = 0;
4746
4747   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
4748   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
4749
4750   nparms = TREE_VEC_LENGTH (parm_parms);
4751   nargs = TREE_VEC_LENGTH (arg_parms);
4752
4753   /* Determine whether we have a parameter pack at the end of the
4754      template template parameter's template parameter list.  */
4755   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
4756     {
4757       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
4758       
4759       switch (TREE_CODE (parm))
4760         {
4761         case TEMPLATE_DECL:
4762         case TYPE_DECL:
4763           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
4764             variadic_p = 1;
4765           break;
4766           
4767         case PARM_DECL:
4768           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
4769             variadic_p = 1;
4770           break;
4771           
4772         default:
4773           gcc_unreachable ();
4774         }
4775     }
4776  
4777   if (nargs != nparms
4778       && !(variadic_p && nargs >= nparms - 1))
4779     return 0;
4780
4781   /* Check all of the template parameters except the parameter pack at
4782      the end (if any).  */
4783   for (i = 0; i < nparms - variadic_p; ++i)
4784     {
4785       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
4786           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
4787         continue;
4788
4789       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
4790       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
4791
4792       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
4793                                           outer_args))
4794         return 0;
4795
4796     }
4797
4798   if (variadic_p)
4799     {
4800       /* Check each of the template parameters in the template
4801          argument against the template parameter pack at the end of
4802          the template template parameter.  */
4803       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
4804         return 0;
4805
4806       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
4807
4808       for (; i < nargs; ++i)
4809         {
4810           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
4811             continue;
4812  
4813           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
4814  
4815           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
4816                                               outer_args))
4817             return 0;
4818         }
4819     }
4820
4821   return 1;
4822 }
4823
4824 /* Verifies that the deduced template arguments (in TARGS) for the
4825    template template parameters (in TPARMS) represent valid bindings,
4826    by comparing the template parameter list of each template argument
4827    to the template parameter list of its corresponding template
4828    template parameter, in accordance with DR150. This
4829    routine can only be called after all template arguments have been
4830    deduced. It will return TRUE if all of the template template
4831    parameter bindings are okay, FALSE otherwise.  */
4832 bool 
4833 template_template_parm_bindings_ok_p (tree tparms, tree targs)
4834 {
4835   int i, ntparms = TREE_VEC_LENGTH (tparms);
4836   bool ret = true;
4837
4838   /* We're dealing with template parms in this process.  */
4839   ++processing_template_decl;
4840
4841   targs = INNERMOST_TEMPLATE_ARGS (targs);
4842
4843   for (i = 0; i < ntparms; ++i)
4844     {
4845       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
4846       tree targ = TREE_VEC_ELT (targs, i);
4847
4848       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
4849         {
4850           tree packed_args = NULL_TREE;
4851           int idx, len = 1;
4852
4853           if (ARGUMENT_PACK_P (targ))
4854             {
4855               /* Look inside the argument pack.  */
4856               packed_args = ARGUMENT_PACK_ARGS (targ);
4857               len = TREE_VEC_LENGTH (packed_args);
4858             }
4859
4860           for (idx = 0; idx < len; ++idx)
4861             {
4862               tree targ_parms = NULL_TREE;
4863
4864               if (packed_args)
4865                 /* Extract the next argument from the argument
4866                    pack.  */
4867                 targ = TREE_VEC_ELT (packed_args, idx);
4868
4869               if (PACK_EXPANSION_P (targ))
4870                 /* Look at the pattern of the pack expansion.  */
4871                 targ = PACK_EXPANSION_PATTERN (targ);
4872
4873               /* Extract the template parameters from the template
4874                  argument.  */
4875               if (TREE_CODE (targ) == TEMPLATE_DECL)
4876                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
4877               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
4878                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
4879
4880               /* Verify that we can coerce the template template
4881                  parameters from the template argument to the template
4882                  parameter.  This requires an exact match.  */
4883               if (targ_parms
4884                   && !coerce_template_template_parms
4885                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
4886                         targ_parms,
4887                         tf_none,
4888                         tparm,
4889                         targs))
4890                 {
4891                   ret = false;
4892                   goto out;
4893                 }
4894             }
4895         }
4896     }
4897
4898  out:
4899
4900   --processing_template_decl;
4901   return ret;
4902 }
4903
4904 /* Convert the indicated template ARG as necessary to match the
4905    indicated template PARM.  Returns the converted ARG, or
4906    error_mark_node if the conversion was unsuccessful.  Error and
4907    warning messages are issued under control of COMPLAIN.  This
4908    conversion is for the Ith parameter in the parameter list.  ARGS is
4909    the full set of template arguments deduced so far.  */
4910
4911 static tree
4912 convert_template_argument (tree parm,
4913                            tree arg,
4914                            tree args,
4915                            tsubst_flags_t complain,
4916                            int i,
4917                            tree in_decl)
4918 {
4919   tree orig_arg;
4920   tree val;
4921   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
4922
4923   if (TREE_CODE (arg) == TREE_LIST
4924       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
4925     {
4926       /* The template argument was the name of some
4927          member function.  That's usually
4928          invalid, but static members are OK.  In any
4929          case, grab the underlying fields/functions
4930          and issue an error later if required.  */
4931       orig_arg = TREE_VALUE (arg);
4932       TREE_TYPE (arg) = unknown_type_node;
4933     }
4934
4935   orig_arg = arg;
4936
4937   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
4938   requires_type = (TREE_CODE (parm) == TYPE_DECL
4939                    || requires_tmpl_type);
4940
4941   /* When determining whether an argument pack expansion is a template,
4942      look at the pattern.  */
4943   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
4944     arg = PACK_EXPANSION_PATTERN (arg);
4945
4946   is_tmpl_type = 
4947     ((TREE_CODE (arg) == TEMPLATE_DECL
4948       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
4949      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4950      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
4951
4952   if (is_tmpl_type
4953       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4954           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
4955     arg = TYPE_STUB_DECL (arg);
4956
4957   is_type = TYPE_P (arg) || is_tmpl_type;
4958
4959   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
4960       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
4961     {
4962       permerror (input_location, "to refer to a type member of a template parameter, "
4963                  "use %<typename %E%>", orig_arg);
4964
4965       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
4966                                      TREE_OPERAND (arg, 1),
4967                                      typename_type,
4968                                      complain & tf_error);
4969       arg = orig_arg;
4970       is_type = 1;
4971     }
4972   if (is_type != requires_type)
4973     {
4974       if (in_decl)
4975         {
4976           if (complain & tf_error)
4977             {
4978               error ("type/value mismatch at argument %d in template "
4979                      "parameter list for %qD",
4980                      i + 1, in_decl);
4981               if (is_type)
4982                 error ("  expected a constant of type %qT, got %qT",
4983                        TREE_TYPE (parm),
4984                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
4985               else if (requires_tmpl_type)
4986                 error ("  expected a class template, got %qE", orig_arg);
4987               else
4988                 error ("  expected a type, got %qE", orig_arg);
4989             }
4990         }
4991       return error_mark_node;
4992     }
4993   if (is_tmpl_type ^ requires_tmpl_type)
4994     {
4995       if (in_decl && (complain & tf_error))
4996         {
4997           error ("type/value mismatch at argument %d in template "
4998                  "parameter list for %qD",
4999                  i + 1, in_decl);
5000           if (is_tmpl_type)
5001             error ("  expected a type, got %qT", DECL_NAME (arg));
5002           else
5003             error ("  expected a class template, got %qT", orig_arg);
5004         }
5005       return error_mark_node;
5006     }
5007
5008   if (is_type)
5009     {
5010       if (requires_tmpl_type)
5011         {
5012           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5013             /* The number of argument required is not known yet.
5014                Just accept it for now.  */
5015             val = TREE_TYPE (arg);
5016           else
5017             {
5018               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5019               tree argparm;
5020
5021               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5022
5023               if (coerce_template_template_parms (parmparm, argparm,
5024                                                   complain, in_decl,
5025                                                   args))
5026                 {
5027                   val = orig_arg;
5028
5029                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5030                      TEMPLATE_DECL.  */
5031                   if (val != error_mark_node)
5032                     {
5033                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5034                         val = TREE_TYPE (val);
5035                       else if (TREE_CODE (val) == TYPE_PACK_EXPANSION
5036                                && DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
5037                         {
5038                           val = TREE_TYPE (arg);
5039                           val = make_pack_expansion (val);
5040                         }
5041                     }
5042                 }
5043               else
5044                 {
5045                   if (in_decl && (complain & tf_error))
5046                     {
5047                       error ("type/value mismatch at argument %d in "
5048                              "template parameter list for %qD",
5049                              i + 1, in_decl);
5050                       error ("  expected a template of type %qD, got %qD",
5051                              parm, orig_arg);
5052                     }
5053
5054                   val = error_mark_node;
5055                 }
5056             }
5057         }
5058       else
5059         val = orig_arg;
5060       /* We only form one instance of each template specialization.
5061          Therefore, if we use a non-canonical variant (i.e., a
5062          typedef), any future messages referring to the type will use
5063          the typedef, which is confusing if those future uses do not
5064          themselves also use the typedef.  */
5065       if (TYPE_P (val))
5066         val = canonical_type_variant (val);
5067     }
5068   else
5069     {
5070       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5071
5072       if (invalid_nontype_parm_type_p (t, complain))
5073         return error_mark_node;
5074
5075       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5076         {
5077           if (same_type_p (t, TREE_TYPE (orig_arg)))
5078             val = orig_arg;
5079           else
5080             {
5081               /* Not sure if this is reachable, but it doesn't hurt
5082                  to be robust.  */
5083               error ("type mismatch in nontype parameter pack");
5084               val = error_mark_node;
5085             }
5086         }
5087       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5088         /* We used to call digest_init here.  However, digest_init
5089            will report errors, which we don't want when complain
5090            is zero.  More importantly, digest_init will try too
5091            hard to convert things: for example, `0' should not be
5092            converted to pointer type at this point according to
5093            the standard.  Accepting this is not merely an
5094            extension, since deciding whether or not these
5095            conversions can occur is part of determining which
5096            function template to call, or whether a given explicit
5097            argument specification is valid.  */
5098         val = convert_nontype_argument (t, orig_arg);
5099       else
5100         val = orig_arg;
5101
5102       if (val == NULL_TREE)
5103         val = error_mark_node;
5104       else if (val == error_mark_node && (complain & tf_error))
5105         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5106     }
5107
5108   return val;
5109 }
5110
5111 /* Coerces the remaining template arguments in INNER_ARGS (from
5112    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5113    Returns the coerced argument pack. PARM_IDX is the position of this
5114    parameter in the template parameter list. ARGS is the original
5115    template argument list.  */
5116 static tree
5117 coerce_template_parameter_pack (tree parms,
5118                                 int parm_idx,
5119                                 tree args,
5120                                 tree inner_args,
5121                                 int arg_idx,
5122                                 tree new_args,
5123                                 int* lost,
5124                                 tree in_decl,
5125                                 tsubst_flags_t complain)
5126 {
5127   tree parm = TREE_VEC_ELT (parms, parm_idx);
5128   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5129   tree packed_args;
5130   tree argument_pack;
5131   tree packed_types = NULL_TREE;
5132
5133   if (arg_idx > nargs)
5134     arg_idx = nargs;
5135
5136   packed_args = make_tree_vec (nargs - arg_idx);
5137
5138   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5139       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5140     {
5141       /* When the template parameter is a non-type template
5142          parameter pack whose type uses parameter packs, we need
5143          to look at each of the template arguments
5144          separately. Build a vector of the types for these
5145          non-type template parameters in PACKED_TYPES.  */
5146       tree expansion 
5147         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5148       packed_types = tsubst_pack_expansion (expansion, args,
5149                                             complain, in_decl);
5150
5151       if (packed_types == error_mark_node)
5152         return error_mark_node;
5153
5154       /* Check that we have the right number of arguments.  */
5155       if (arg_idx < nargs
5156           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5157           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5158         {
5159           int needed_parms 
5160             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5161           error ("wrong number of template arguments (%d, should be %d)",
5162                  nargs, needed_parms);
5163           return error_mark_node;
5164         }
5165
5166       /* If we aren't able to check the actual arguments now
5167          (because they haven't been expanded yet), we can at least
5168          verify that all of the types used for the non-type
5169          template parameter pack are, in fact, valid for non-type
5170          template parameters.  */
5171       if (arg_idx < nargs 
5172           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5173         {
5174           int j, len = TREE_VEC_LENGTH (packed_types);
5175           for (j = 0; j < len; ++j)
5176             {
5177               tree t = TREE_VEC_ELT (packed_types, j);
5178               if (invalid_nontype_parm_type_p (t, complain))
5179                 return error_mark_node;
5180             }
5181         }
5182     }
5183
5184   /* Convert the remaining arguments, which will be a part of the
5185      parameter pack "parm".  */
5186   for (; arg_idx < nargs; ++arg_idx)
5187     {
5188       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5189       tree actual_parm = TREE_VALUE (parm);
5190
5191       if (packed_types && !PACK_EXPANSION_P (arg))
5192         {
5193           /* When we have a vector of types (corresponding to the
5194              non-type template parameter pack that uses parameter
5195              packs in its type, as mention above), and the
5196              argument is not an expansion (which expands to a
5197              currently unknown number of arguments), clone the
5198              parm and give it the next type in PACKED_TYPES.  */
5199           actual_parm = copy_node (actual_parm);
5200           TREE_TYPE (actual_parm) = 
5201             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5202         }
5203
5204       if (arg != error_mark_node)
5205         arg = convert_template_argument (actual_parm, 
5206                                          arg, new_args, complain, parm_idx,
5207                                          in_decl);
5208       if (arg == error_mark_node)
5209         (*lost)++;
5210       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5211     }
5212
5213   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5214       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5215     argument_pack = make_node (TYPE_ARGUMENT_PACK);
5216   else
5217     {
5218       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5219       TREE_TYPE (argument_pack) 
5220         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5221       TREE_CONSTANT (argument_pack) = 1;
5222     }
5223
5224   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5225   return argument_pack;
5226 }
5227
5228 /* Convert all template arguments to their appropriate types, and
5229    return a vector containing the innermost resulting template
5230    arguments.  If any error occurs, return error_mark_node. Error and
5231    warning messages are issued under control of COMPLAIN.
5232
5233    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5234    for arguments not specified in ARGS.  Otherwise, if
5235    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5236    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5237    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5238    ARGS.  */
5239
5240 static tree
5241 coerce_template_parms (tree parms,
5242                        tree args,
5243                        tree in_decl,
5244                        tsubst_flags_t complain,
5245                        bool require_all_args,
5246                        bool use_default_args)
5247 {
5248   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5249   tree inner_args;
5250   tree new_args;
5251   tree new_inner_args;
5252   bool saved_skip_evaluation;
5253
5254   /* When used as a boolean value, indicates whether this is a
5255      variadic template parameter list. Since it's an int, we can also
5256      subtract it from nparms to get the number of non-variadic
5257      parameters.  */
5258   int variadic_p = 0;
5259
5260   nparms = TREE_VEC_LENGTH (parms);
5261
5262   /* Determine if there are any parameter packs.  */
5263   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5264     {
5265       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5266       if (template_parameter_pack_p (tparm))
5267         ++variadic_p;
5268     }
5269
5270   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5271   /* If there are 0 or 1 parameter packs, we need to expand any argument
5272      packs so that we can deduce a parameter pack from some non-packed args
5273      followed by an argument pack, as in variadic85.C.  If there are more
5274      than that, we need to leave argument packs intact so the arguments are
5275      assigned to the right parameter packs.  This should only happen when
5276      dealing with a nested class inside a partial specialization of a class
5277      template, as in variadic92.C.  */
5278   if (variadic_p <= 1)
5279     inner_args = expand_template_argument_pack (inner_args);
5280
5281   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5282   if ((nargs > nparms && !variadic_p)
5283       || (nargs < nparms - variadic_p
5284           && require_all_args
5285           && (!use_default_args
5286               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5287                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5288     {
5289       if (complain & tf_error)
5290         {
5291           const char *or_more = "";
5292           if (variadic_p)
5293             {
5294               or_more = " or more";
5295               --nparms;
5296             }
5297
5298           error ("wrong number of template arguments (%d, should be %d%s)",
5299                  nargs, nparms, or_more);
5300
5301           if (in_decl)
5302             error ("provided for %q+D", in_decl);
5303         }
5304
5305       return error_mark_node;
5306     }
5307
5308   /* We need to evaluate the template arguments, even though this
5309      template-id may be nested within a "sizeof".  */
5310   saved_skip_evaluation = skip_evaluation;
5311   skip_evaluation = false;
5312   new_inner_args = make_tree_vec (nparms);
5313   new_args = add_outermost_template_args (args, new_inner_args);
5314   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5315     {
5316       tree arg;
5317       tree parm;
5318
5319       /* Get the Ith template parameter.  */
5320       parm = TREE_VEC_ELT (parms, parm_idx);
5321  
5322       if (parm == error_mark_node)
5323       {
5324         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5325         continue;
5326       }
5327
5328       /* Calculate the next argument.  */
5329       if (arg_idx < nargs)
5330         arg = TREE_VEC_ELT (inner_args, arg_idx);
5331       else
5332         arg = NULL_TREE;
5333
5334       if (template_parameter_pack_p (TREE_VALUE (parm))
5335           && !(arg && ARGUMENT_PACK_P (arg)))
5336         {
5337           /* All remaining arguments will be placed in the
5338              template parameter pack PARM.  */
5339           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5340                                                 inner_args, arg_idx,
5341                                                 new_args, &lost,
5342                                                 in_decl, complain);
5343
5344           /* Store this argument.  */
5345           if (arg == error_mark_node)
5346             lost++;
5347           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5348
5349           /* We are done with all of the arguments.  */
5350           arg_idx = nargs;
5351           
5352           continue;
5353         }
5354       else if (arg)
5355         {
5356           if (PACK_EXPANSION_P (arg))
5357             {
5358               if (complain & tf_error)
5359                 {
5360                   /* FIXME this restriction was removed by N2555; see
5361                      bug 35722.  */
5362                   /* If ARG is a pack expansion, but PARM is not a
5363                      template parameter pack (if it were, we would have
5364                      handled it above), we're trying to expand into a
5365                      fixed-length argument list.  */
5366                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5367                     sorry ("cannot expand %<%E%> into a fixed-length "
5368                            "argument list", arg);
5369                   else
5370                     sorry ("cannot expand %<%T%> into a fixed-length "
5371                            "argument list", arg);
5372                 }
5373               return error_mark_node;
5374             }
5375         }
5376       else if (require_all_args)
5377         /* There must be a default arg in this case.  */
5378         arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
5379                                    complain, in_decl);
5380       else
5381         break;
5382
5383       if (arg == error_mark_node)
5384         {
5385           if (complain & tf_error)
5386             error ("template argument %d is invalid", arg_idx + 1);
5387         }
5388       else if (!arg)
5389         /* This only occurs if there was an error in the template
5390            parameter list itself (which we would already have
5391            reported) that we are trying to recover from, e.g., a class
5392            template with a parameter list such as
5393            template<typename..., typename>.  */
5394         return error_mark_node;
5395       else
5396         arg = convert_template_argument (TREE_VALUE (parm),
5397                                          arg, new_args, complain, 
5398                                          parm_idx, in_decl);
5399
5400       if (arg == error_mark_node)
5401         lost++;
5402       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
5403     }
5404   skip_evaluation = saved_skip_evaluation;
5405
5406   if (lost)
5407     return error_mark_node;
5408
5409   return new_inner_args;
5410 }
5411
5412 /* Returns 1 if template args OT and NT are equivalent.  */
5413
5414 static int
5415 template_args_equal (tree ot, tree nt)
5416 {
5417   if (nt == ot)
5418     return 1;
5419
5420   if (TREE_CODE (nt) == TREE_VEC)
5421     /* For member templates */
5422     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
5423   else if (PACK_EXPANSION_P (ot))
5424     return PACK_EXPANSION_P (nt) 
5425       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
5426                               PACK_EXPANSION_PATTERN (nt));
5427   else if (ARGUMENT_PACK_P (ot))
5428     {
5429       int i, len;
5430       tree opack, npack;
5431
5432       if (!ARGUMENT_PACK_P (nt))
5433         return 0;
5434
5435       opack = ARGUMENT_PACK_ARGS (ot);
5436       npack = ARGUMENT_PACK_ARGS (nt);
5437       len = TREE_VEC_LENGTH (opack);
5438       if (TREE_VEC_LENGTH (npack) != len)
5439         return 0;
5440       for (i = 0; i < len; ++i)
5441         if (!template_args_equal (TREE_VEC_ELT (opack, i),
5442                                   TREE_VEC_ELT (npack, i)))
5443           return 0;
5444       return 1;
5445     }
5446   else if (TYPE_P (nt))
5447     return TYPE_P (ot) && same_type_p (ot, nt);
5448   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
5449     return 0;
5450   else
5451     return cp_tree_equal (ot, nt);
5452 }
5453
5454 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
5455    of template arguments.  Returns 0 otherwise.  */
5456
5457 int
5458 comp_template_args (tree oldargs, tree newargs)
5459 {
5460   int i;
5461
5462   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
5463     return 0;
5464
5465   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
5466     {
5467       tree nt = TREE_VEC_ELT (newargs, i);
5468       tree ot = TREE_VEC_ELT (oldargs, i);
5469
5470       if (! template_args_equal (ot, nt))
5471         return 0;
5472     }
5473   return 1;
5474 }
5475
5476 static void
5477 add_pending_template (tree d)
5478 {
5479   tree ti = (TYPE_P (d)
5480              ? CLASSTYPE_TEMPLATE_INFO (d)
5481              : DECL_TEMPLATE_INFO (d));
5482   struct pending_template *pt;
5483   int level;
5484
5485   if (TI_PENDING_TEMPLATE_FLAG (ti))
5486     return;
5487
5488   /* We are called both from instantiate_decl, where we've already had a
5489      tinst_level pushed, and instantiate_template, where we haven't.
5490      Compensate.  */
5491   level = !current_tinst_level || current_tinst_level->decl != d;
5492
5493   if (level)
5494     push_tinst_level (d);
5495
5496   pt = GGC_NEW (struct pending_template);
5497   pt->next = NULL;
5498   pt->tinst = current_tinst_level;
5499   if (last_pending_template)
5500     last_pending_template->next = pt;
5501   else
5502     pending_templates = pt;
5503
5504   last_pending_template = pt;
5505
5506   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
5507
5508   if (level)
5509     pop_tinst_level ();
5510 }
5511
5512
5513 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
5514    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
5515    documentation for TEMPLATE_ID_EXPR.  */
5516
5517 tree
5518 lookup_template_function (tree fns, tree arglist)
5519 {
5520   tree type;
5521
5522   if (fns == error_mark_node || arglist == error_mark_node)
5523     return error_mark_node;
5524
5525   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
5526   gcc_assert (fns && (is_overloaded_fn (fns)
5527                       || TREE_CODE (fns) == IDENTIFIER_NODE));
5528
5529   if (BASELINK_P (fns))
5530     {
5531       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
5532                                          unknown_type_node,
5533                                          BASELINK_FUNCTIONS (fns),
5534                                          arglist);
5535       return fns;
5536     }
5537
5538   type = TREE_TYPE (fns);
5539   if (TREE_CODE (fns) == OVERLOAD || !type)
5540     type = unknown_type_node;
5541
5542   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
5543 }
5544
5545 /* Within the scope of a template class S<T>, the name S gets bound
5546    (in build_self_reference) to a TYPE_DECL for the class, not a
5547    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
5548    or one of its enclosing classes, and that type is a template,
5549    return the associated TEMPLATE_DECL.  Otherwise, the original
5550    DECL is returned.  */
5551
5552 tree
5553 maybe_get_template_decl_from_type_decl (tree decl)
5554 {
5555   return (decl != NULL_TREE
5556           && TREE_CODE (decl) == TYPE_DECL
5557           && DECL_ARTIFICIAL (decl)
5558           && CLASS_TYPE_P (TREE_TYPE (decl))
5559           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
5560     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
5561 }
5562
5563 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
5564    parameters, find the desired type.
5565
5566    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
5567
5568    IN_DECL, if non-NULL, is the template declaration we are trying to
5569    instantiate.
5570
5571    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
5572    the class we are looking up.
5573
5574    Issue error and warning messages under control of COMPLAIN.
5575
5576    If the template class is really a local class in a template
5577    function, then the FUNCTION_CONTEXT is the function in which it is
5578    being instantiated.
5579
5580    ??? Note that this function is currently called *twice* for each
5581    template-id: the first time from the parser, while creating the
5582    incomplete type (finish_template_type), and the second type during the
5583    real instantiation (instantiate_template_class). This is surely something
5584    that we want to avoid. It also causes some problems with argument
5585    coercion (see convert_nontype_argument for more information on this).  */
5586
5587 tree
5588 lookup_template_class (tree d1,
5589                        tree arglist,
5590                        tree in_decl,
5591                        tree context,
5592                        int entering_scope,
5593                        tsubst_flags_t complain)
5594 {
5595   tree templ = NULL_TREE, parmlist;
5596   tree t;
5597
5598   timevar_push (TV_NAME_LOOKUP);
5599
5600   if (TREE_CODE (d1) == IDENTIFIER_NODE)
5601     {
5602       tree value = innermost_non_namespace_value (d1);
5603       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
5604         templ = value;
5605       else
5606         {
5607           if (context)
5608             push_decl_namespace (context);
5609           templ = lookup_name (d1);
5610           templ = maybe_get_template_decl_from_type_decl (templ);
5611           if (context)
5612             pop_decl_namespace ();
5613         }
5614       if (templ)
5615         context = DECL_CONTEXT (templ);
5616     }
5617   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
5618     {
5619       tree type = TREE_TYPE (d1);
5620
5621       /* If we are declaring a constructor, say A<T>::A<T>, we will get
5622          an implicit typename for the second A.  Deal with it.  */
5623       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
5624         type = TREE_TYPE (type);
5625
5626       if (CLASSTYPE_TEMPLATE_INFO (type))
5627         {
5628           templ = CLASSTYPE_TI_TEMPLATE (type);
5629           d1 = DECL_NAME (templ);
5630         }
5631     }
5632   else if (TREE_CODE (d1) == ENUMERAL_TYPE
5633            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
5634     {
5635       templ = TYPE_TI_TEMPLATE (d1);
5636       d1 = DECL_NAME (templ);
5637     }
5638   else if (TREE_CODE (d1) == TEMPLATE_DECL
5639            && DECL_TEMPLATE_RESULT (d1)
5640            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
5641     {
5642       templ = d1;
5643       d1 = DECL_NAME (templ);
5644       context = DECL_CONTEXT (templ);
5645     }
5646
5647   /* Issue an error message if we didn't find a template.  */
5648   if (! templ)
5649     {
5650       if (complain & tf_error)
5651         error ("%qT is not a template", d1);
5652       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5653     }
5654
5655   if (TREE_CODE (templ) != TEMPLATE_DECL
5656          /* Make sure it's a user visible template, if it was named by
5657             the user.  */
5658       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
5659           && !PRIMARY_TEMPLATE_P (templ)))
5660     {
5661       if (complain & tf_error)
5662         {
5663           error ("non-template type %qT used as a template", d1);
5664           if (in_decl)
5665             error ("for template declaration %q+D", in_decl);
5666         }
5667       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5668     }
5669
5670   complain &= ~tf_user;
5671
5672   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
5673     {
5674       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
5675          template arguments */
5676
5677       tree parm;
5678       tree arglist2;
5679       tree outer;
5680
5681       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
5682
5683       /* Consider an example where a template template parameter declared as
5684
5685            template <class T, class U = std::allocator<T> > class TT
5686
5687          The template parameter level of T and U are one level larger than
5688          of TT.  To proper process the default argument of U, say when an
5689          instantiation `TT<int>' is seen, we need to build the full
5690          arguments containing {int} as the innermost level.  Outer levels,
5691          available when not appearing as default template argument, can be
5692          obtained from the arguments of the enclosing template.
5693
5694          Suppose that TT is later substituted with std::vector.  The above
5695          instantiation is `TT<int, std::allocator<T> >' with TT at
5696          level 1, and T at level 2, while the template arguments at level 1
5697          becomes {std::vector} and the inner level 2 is {int}.  */
5698
5699       outer = DECL_CONTEXT (templ);
5700       if (outer)
5701         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
5702       else if (current_template_parms)
5703         /* This is an argument of the current template, so we haven't set
5704            DECL_CONTEXT yet.  */
5705         outer = current_template_args ();
5706
5707       if (outer)
5708         arglist = add_to_template_args (outer, arglist);
5709
5710       arglist2 = coerce_template_parms (parmlist, arglist, templ,
5711                                         complain,
5712                                         /*require_all_args=*/true,
5713                                         /*use_default_args=*/true);
5714       if (arglist2 == error_mark_node
5715           || (!uses_template_parms (arglist2)
5716               && check_instantiated_args (templ, arglist2, complain)))
5717         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5718
5719       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
5720       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
5721     }
5722   else
5723     {
5724       tree template_type = TREE_TYPE (templ);
5725       tree gen_tmpl;
5726       tree type_decl;
5727       tree found = NULL_TREE;
5728       int arg_depth;
5729       int parm_depth;
5730       int is_partial_instantiation;
5731
5732       gen_tmpl = most_general_template (templ);
5733       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
5734       parm_depth = TMPL_PARMS_DEPTH (parmlist);
5735       arg_depth = TMPL_ARGS_DEPTH (arglist);
5736
5737       if (arg_depth == 1 && parm_depth > 1)
5738         {
5739           /* We've been given an incomplete set of template arguments.
5740              For example, given:
5741
5742                template <class T> struct S1 {
5743                  template <class U> struct S2 {};
5744                  template <class U> struct S2<U*> {};
5745                 };
5746
5747              we will be called with an ARGLIST of `U*', but the
5748              TEMPLATE will be `template <class T> template
5749              <class U> struct S1<T>::S2'.  We must fill in the missing
5750              arguments.  */
5751           arglist
5752             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
5753                                            arglist);
5754           arg_depth = TMPL_ARGS_DEPTH (arglist);
5755         }
5756
5757       /* Now we should have enough arguments.  */
5758       gcc_assert (parm_depth == arg_depth);
5759
5760       /* From here on, we're only interested in the most general
5761          template.  */
5762       templ = gen_tmpl;
5763
5764       /* Calculate the BOUND_ARGS.  These will be the args that are
5765          actually tsubst'd into the definition to create the
5766          instantiation.  */
5767       if (parm_depth > 1)
5768         {
5769           /* We have multiple levels of arguments to coerce, at once.  */
5770           int i;
5771           int saved_depth = TMPL_ARGS_DEPTH (arglist);
5772
5773           tree bound_args = make_tree_vec (parm_depth);
5774
5775           for (i = saved_depth,
5776                  t = DECL_TEMPLATE_PARMS (templ);
5777                i > 0 && t != NULL_TREE;
5778                --i, t = TREE_CHAIN (t))
5779             {
5780               tree a = coerce_template_parms (TREE_VALUE (t),
5781                                               arglist, templ,
5782                                               complain,
5783                                               /*require_all_args=*/true,
5784                                               /*use_default_args=*/true);
5785
5786               /* Don't process further if one of the levels fails.  */
5787               if (a == error_mark_node)
5788                 {
5789                   /* Restore the ARGLIST to its full size.  */
5790                   TREE_VEC_LENGTH (arglist) = saved_depth;
5791                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5792                 }
5793
5794               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
5795
5796               /* We temporarily reduce the length of the ARGLIST so
5797                  that coerce_template_parms will see only the arguments
5798                  corresponding to the template parameters it is
5799                  examining.  */
5800               TREE_VEC_LENGTH (arglist)--;
5801             }
5802
5803           /* Restore the ARGLIST to its full size.  */
5804           TREE_VEC_LENGTH (arglist) = saved_depth;
5805
5806           arglist = bound_args;
5807         }
5808       else
5809         arglist
5810           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
5811                                    INNERMOST_TEMPLATE_ARGS (arglist),
5812                                    templ,
5813                                    complain,
5814                                    /*require_all_args=*/true,
5815                                    /*use_default_args=*/true);
5816
5817       if (arglist == error_mark_node)
5818         /* We were unable to bind the arguments.  */
5819         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5820
5821       /* In the scope of a template class, explicit references to the
5822          template class refer to the type of the template, not any
5823          instantiation of it.  For example, in:
5824
5825            template <class T> class C { void f(C<T>); }
5826
5827          the `C<T>' is just the same as `C'.  Outside of the
5828          class, however, such a reference is an instantiation.  */
5829       if (comp_template_args (TYPE_TI_ARGS (template_type),
5830                               arglist))
5831         {
5832           found = template_type;
5833
5834           if (!entering_scope && PRIMARY_TEMPLATE_P (templ))
5835             {
5836               tree ctx;
5837
5838               for (ctx = current_class_type;
5839                    ctx && TREE_CODE (ctx) != NAMESPACE_DECL;
5840                    ctx = (TYPE_P (ctx)
5841                           ? TYPE_CONTEXT (ctx)
5842                           : DECL_CONTEXT (ctx)))
5843                 if (TYPE_P (ctx) && same_type_p (ctx, template_type))
5844                   goto found_ctx;
5845
5846               /* We're not in the scope of the class, so the
5847                  TEMPLATE_TYPE is not the type we want after all.  */
5848               found = NULL_TREE;
5849             found_ctx:;
5850             }
5851         }
5852       if (found)
5853         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5854
5855       /* If we already have this specialization, return it.  */
5856       found = retrieve_specialization (templ, arglist,
5857                                        /*class_specializations_p=*/false);
5858       if (found)
5859         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5860
5861       /* This type is a "partial instantiation" if any of the template
5862          arguments still involve template parameters.  Note that we set
5863          IS_PARTIAL_INSTANTIATION for partial specializations as
5864          well.  */
5865       is_partial_instantiation = uses_template_parms (arglist);
5866
5867       /* If the deduced arguments are invalid, then the binding
5868          failed.  */
5869       if (!is_partial_instantiation
5870           && check_instantiated_args (templ,
5871                                       INNERMOST_TEMPLATE_ARGS (arglist),
5872                                       complain))
5873         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5874
5875       if (!is_partial_instantiation
5876           && !PRIMARY_TEMPLATE_P (templ)
5877           && TREE_CODE (CP_DECL_CONTEXT (templ)) == NAMESPACE_DECL)
5878         {
5879           found = xref_tag_from_type (TREE_TYPE (templ),
5880                                       DECL_NAME (templ),
5881                                       /*tag_scope=*/ts_global);
5882           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5883         }
5884
5885       context = tsubst (DECL_CONTEXT (templ), arglist,
5886                         complain, in_decl);
5887       if (!context)
5888         context = global_namespace;
5889
5890       /* Create the type.  */
5891       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
5892         {
5893           if (!is_partial_instantiation)
5894             {
5895               set_current_access_from_decl (TYPE_NAME (template_type));
5896               t = start_enum (TYPE_IDENTIFIER (template_type),
5897                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
5898                                       arglist, complain, in_decl),
5899                               SCOPED_ENUM_P (template_type));
5900             }
5901           else
5902             {
5903               /* We don't want to call start_enum for this type, since
5904                  the values for the enumeration constants may involve
5905                  template parameters.  And, no one should be interested
5906                  in the enumeration constants for such a type.  */
5907               t = make_node (ENUMERAL_TYPE);
5908               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
5909             }
5910         }
5911       else
5912         {
5913           t = make_class_type (TREE_CODE (template_type));
5914           CLASSTYPE_DECLARED_CLASS (t)
5915             = CLASSTYPE_DECLARED_CLASS (template_type);
5916           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
5917           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
5918
5919           /* A local class.  Make sure the decl gets registered properly.  */
5920           if (context == current_function_decl)
5921             pushtag (DECL_NAME (templ), t, /*tag_scope=*/ts_current);
5922
5923           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
5924             /* This instantiation is another name for the primary
5925                template type. Set the TYPE_CANONICAL field
5926                appropriately. */
5927             TYPE_CANONICAL (t) = template_type;
5928           else if (any_template_arguments_need_structural_equality_p (arglist))
5929             /* Some of the template arguments require structural
5930                equality testing, so this template class requires
5931                structural equality testing. */
5932             SET_TYPE_STRUCTURAL_EQUALITY (t);
5933         }
5934
5935       /* If we called start_enum or pushtag above, this information
5936          will already be set up.  */
5937       if (!TYPE_NAME (t))
5938         {
5939           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
5940
5941           type_decl = create_implicit_typedef (DECL_NAME (templ), t);
5942           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
5943           TYPE_STUB_DECL (t) = type_decl;
5944           DECL_SOURCE_LOCATION (type_decl)
5945             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
5946         }
5947       else
5948         type_decl = TYPE_NAME (t);
5949
5950       TREE_PRIVATE (type_decl)
5951         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
5952       TREE_PROTECTED (type_decl)
5953         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
5954       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
5955         {
5956           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
5957           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
5958         }
5959
5960       /* Set up the template information.  We have to figure out which
5961          template is the immediate parent if this is a full
5962          instantiation.  */
5963       if (parm_depth == 1 || is_partial_instantiation
5964           || !PRIMARY_TEMPLATE_P (templ))
5965         /* This case is easy; there are no member templates involved.  */
5966         found = templ;
5967       else
5968         {
5969           /* This is a full instantiation of a member template.  Look
5970              for a partial instantiation of which this is an instance.  */
5971
5972           for (found = DECL_TEMPLATE_INSTANTIATIONS (templ);
5973                found; found = TREE_CHAIN (found))
5974             {
5975               int success;
5976               tree tmpl = CLASSTYPE_TI_TEMPLATE (TREE_VALUE (found));
5977
5978               /* We only want partial instantiations, here, not
5979                  specializations or full instantiations.  */
5980               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_VALUE (found))
5981                   || !uses_template_parms (TREE_VALUE (found)))
5982                 continue;
5983
5984               /* Temporarily reduce by one the number of levels in the
5985                  ARGLIST and in FOUND so as to avoid comparing the
5986                  last set of arguments.  */
5987               TREE_VEC_LENGTH (arglist)--;
5988               TREE_VEC_LENGTH (TREE_PURPOSE (found)) --;
5989
5990               /* See if the arguments match.  If they do, then TMPL is
5991                  the partial instantiation we want.  */
5992               success = comp_template_args (TREE_PURPOSE (found), arglist);
5993
5994               /* Restore the argument vectors to their full size.  */
5995               TREE_VEC_LENGTH (arglist)++;
5996               TREE_VEC_LENGTH (TREE_PURPOSE (found))++;
5997
5998               if (success)
5999                 {
6000                   found = tmpl;
6001                   break;
6002                 }
6003             }
6004
6005           if (!found)
6006             {
6007               /* There was no partial instantiation. This happens
6008                  where C<T> is a member template of A<T> and it's used
6009                  in something like
6010
6011                   template <typename T> struct B { A<T>::C<int> m; };
6012                   B<float>;
6013
6014                  Create the partial instantiation.
6015                */
6016               TREE_VEC_LENGTH (arglist)--;
6017               found = tsubst (templ, arglist, complain, NULL_TREE);
6018               TREE_VEC_LENGTH (arglist)++;
6019             }
6020         }
6021
6022       SET_TYPE_TEMPLATE_INFO (t, tree_cons (found, arglist, NULL_TREE));
6023       DECL_TEMPLATE_INSTANTIATIONS (templ)
6024         = tree_cons (arglist, t,
6025                      DECL_TEMPLATE_INSTANTIATIONS (templ));
6026
6027       if (TREE_CODE (t) == ENUMERAL_TYPE
6028           && !is_partial_instantiation)
6029         /* Now that the type has been registered on the instantiations
6030            list, we set up the enumerators.  Because the enumeration
6031            constants may involve the enumeration type itself, we make
6032            sure to register the type first, and then create the
6033            constants.  That way, doing tsubst_expr for the enumeration
6034            constants won't result in recursive calls here; we'll find
6035            the instantiation and exit above.  */
6036         tsubst_enum (template_type, t, arglist);
6037
6038       if (is_partial_instantiation)
6039         /* If the type makes use of template parameters, the
6040            code that generates debugging information will crash.  */
6041         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6042
6043       /* Possibly limit visibility based on template args.  */
6044       TREE_PUBLIC (type_decl) = 1;
6045       determine_visibility (type_decl);
6046
6047       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6048     }
6049   timevar_pop (TV_NAME_LOOKUP);
6050 }
6051 \f
6052 struct pair_fn_data
6053 {
6054   tree_fn_t fn;
6055   void *data;
6056   /* True when we should also visit template parameters that occur in
6057      non-deduced contexts.  */
6058   bool include_nondeduced_p;
6059   struct pointer_set_t *visited;
6060 };
6061
6062 /* Called from for_each_template_parm via walk_tree.  */
6063
6064 static tree
6065 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6066 {
6067   tree t = *tp;
6068   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6069   tree_fn_t fn = pfd->fn;
6070   void *data = pfd->data;
6071
6072   if (TYPE_P (t)
6073       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6074       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6075                                  pfd->include_nondeduced_p))
6076     return error_mark_node;
6077
6078   switch (TREE_CODE (t))
6079     {
6080     case RECORD_TYPE:
6081       if (TYPE_PTRMEMFUNC_P (t))
6082         break;
6083       /* Fall through.  */
6084
6085     case UNION_TYPE:
6086     case ENUMERAL_TYPE:
6087       if (!TYPE_TEMPLATE_INFO (t))
6088         *walk_subtrees = 0;
6089       else if (for_each_template_parm (TREE_VALUE (TYPE_TEMPLATE_INFO (t)),
6090                                        fn, data, pfd->visited, 
6091                                        pfd->include_nondeduced_p))
6092         return error_mark_node;
6093       break;
6094
6095     case INTEGER_TYPE:
6096       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6097                                   fn, data, pfd->visited, 
6098                                   pfd->include_nondeduced_p)
6099           || for_each_template_parm (TYPE_MAX_VALUE (t),
6100                                      fn, data, pfd->visited,
6101                                      pfd->include_nondeduced_p))
6102         return error_mark_node;
6103       break;
6104
6105     case METHOD_TYPE:
6106       /* Since we're not going to walk subtrees, we have to do this
6107          explicitly here.  */
6108       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6109                                   pfd->visited, pfd->include_nondeduced_p))
6110         return error_mark_node;
6111       /* Fall through.  */
6112
6113     case FUNCTION_TYPE:
6114       /* Check the return type.  */
6115       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6116                                   pfd->include_nondeduced_p))
6117         return error_mark_node;
6118
6119       /* Check the parameter types.  Since default arguments are not
6120          instantiated until they are needed, the TYPE_ARG_TYPES may
6121          contain expressions that involve template parameters.  But,
6122          no-one should be looking at them yet.  And, once they're
6123          instantiated, they don't contain template parameters, so
6124          there's no point in looking at them then, either.  */
6125       {
6126         tree parm;
6127
6128         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6129           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6130                                       pfd->visited, pfd->include_nondeduced_p))
6131             return error_mark_node;
6132
6133         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6134            want walk_tree walking into them itself.  */
6135         *walk_subtrees = 0;
6136       }
6137       break;
6138
6139     case TYPEOF_TYPE:
6140       if (pfd->include_nondeduced_p
6141           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6142                                      pfd->visited, 
6143                                      pfd->include_nondeduced_p))
6144         return error_mark_node;
6145       break;
6146
6147     case FUNCTION_DECL:
6148     case VAR_DECL:
6149       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6150           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6151                                      pfd->visited, pfd->include_nondeduced_p))
6152         return error_mark_node;
6153       /* Fall through.  */
6154
6155     case PARM_DECL:
6156     case CONST_DECL:
6157       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6158           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6159                                      pfd->visited, pfd->include_nondeduced_p))
6160         return error_mark_node;
6161       if (DECL_CONTEXT (t)
6162           && pfd->include_nondeduced_p
6163           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6164                                      pfd->visited, pfd->include_nondeduced_p))
6165         return error_mark_node;
6166       break;
6167
6168     case BOUND_TEMPLATE_TEMPLATE_PARM:
6169       /* Record template parameters such as `T' inside `TT<T>'.  */
6170       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6171                                   pfd->include_nondeduced_p))
6172         return error_mark_node;
6173       /* Fall through.  */
6174
6175     case TEMPLATE_TEMPLATE_PARM:
6176     case TEMPLATE_TYPE_PARM:
6177     case TEMPLATE_PARM_INDEX:
6178       if (fn && (*fn)(t, data))
6179         return error_mark_node;
6180       else if (!fn)
6181         return error_mark_node;
6182       break;
6183
6184     case TEMPLATE_DECL:
6185       /* A template template parameter is encountered.  */
6186       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6187           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6188                                      pfd->include_nondeduced_p))
6189         return error_mark_node;
6190
6191       /* Already substituted template template parameter */
6192       *walk_subtrees = 0;
6193       break;
6194
6195     case TYPENAME_TYPE:
6196       if (!fn
6197           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6198                                      data, pfd->visited, 
6199                                      pfd->include_nondeduced_p))
6200         return error_mark_node;
6201       break;
6202
6203     case CONSTRUCTOR:
6204       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6205           && pfd->include_nondeduced_p
6206           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6207                                      (TREE_TYPE (t)), fn, data,
6208                                      pfd->visited, pfd->include_nondeduced_p))
6209         return error_mark_node;
6210       break;
6211
6212     case INDIRECT_REF:
6213     case COMPONENT_REF:
6214       /* If there's no type, then this thing must be some expression
6215          involving template parameters.  */
6216       if (!fn && !TREE_TYPE (t))
6217         return error_mark_node;
6218       break;
6219
6220     case MODOP_EXPR:
6221     case CAST_EXPR:
6222     case REINTERPRET_CAST_EXPR:
6223     case CONST_CAST_EXPR:
6224     case STATIC_CAST_EXPR:
6225     case DYNAMIC_CAST_EXPR:
6226     case ARROW_EXPR:
6227     case DOTSTAR_EXPR:
6228     case TYPEID_EXPR:
6229     case PSEUDO_DTOR_EXPR:
6230       if (!fn)
6231         return error_mark_node;
6232       break;
6233
6234     default:
6235       break;
6236     }
6237
6238   /* We didn't find any template parameters we liked.  */
6239   return NULL_TREE;
6240 }
6241
6242 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6243    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6244    call FN with the parameter and the DATA.
6245    If FN returns nonzero, the iteration is terminated, and
6246    for_each_template_parm returns 1.  Otherwise, the iteration
6247    continues.  If FN never returns a nonzero value, the value
6248    returned by for_each_template_parm is 0.  If FN is NULL, it is
6249    considered to be the function which always returns 1.
6250
6251    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6252    parameters that occur in non-deduced contexts.  When false, only
6253    visits those template parameters that can be deduced.  */
6254
6255 static int
6256 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6257                         struct pointer_set_t *visited,
6258                         bool include_nondeduced_p)
6259 {
6260   struct pair_fn_data pfd;
6261   int result;
6262
6263   /* Set up.  */
6264   pfd.fn = fn;
6265   pfd.data = data;
6266   pfd.include_nondeduced_p = include_nondeduced_p;
6267
6268   /* Walk the tree.  (Conceptually, we would like to walk without
6269      duplicates, but for_each_template_parm_r recursively calls
6270      for_each_template_parm, so we would need to reorganize a fair
6271      bit to use walk_tree_without_duplicates, so we keep our own
6272      visited list.)  */
6273   if (visited)
6274     pfd.visited = visited;
6275   else
6276     pfd.visited = pointer_set_create ();
6277   result = cp_walk_tree (&t,
6278                          for_each_template_parm_r,
6279                          &pfd,
6280                          pfd.visited) != NULL_TREE;
6281
6282   /* Clean up.  */
6283   if (!visited)
6284     {
6285       pointer_set_destroy (pfd.visited);
6286       pfd.visited = 0;
6287     }
6288
6289   return result;
6290 }
6291
6292 /* Returns true if T depends on any template parameter.  */
6293
6294 int
6295 uses_template_parms (tree t)
6296 {
6297   bool dependent_p;
6298   int saved_processing_template_decl;
6299
6300   saved_processing_template_decl = processing_template_decl;
6301   if (!saved_processing_template_decl)
6302     processing_template_decl = 1;
6303   if (TYPE_P (t))
6304     dependent_p = dependent_type_p (t);
6305   else if (TREE_CODE (t) == TREE_VEC)
6306     dependent_p = any_dependent_template_arguments_p (t);
6307   else if (TREE_CODE (t) == TREE_LIST)
6308     dependent_p = (uses_template_parms (TREE_VALUE (t))
6309                    || uses_template_parms (TREE_CHAIN (t)));
6310   else if (TREE_CODE (t) == TYPE_DECL)
6311     dependent_p = dependent_type_p (TREE_TYPE (t));
6312   else if (DECL_P (t)
6313            || EXPR_P (t)
6314            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
6315            || TREE_CODE (t) == OVERLOAD
6316            || TREE_CODE (t) == BASELINK
6317            || TREE_CODE (t) == IDENTIFIER_NODE
6318            || TREE_CODE (t) == TRAIT_EXPR
6319            || CONSTANT_CLASS_P (t))
6320     dependent_p = (type_dependent_expression_p (t)
6321                    || value_dependent_expression_p (t));
6322   else
6323     {
6324       gcc_assert (t == error_mark_node);
6325       dependent_p = false;
6326     }
6327
6328   processing_template_decl = saved_processing_template_decl;
6329
6330   return dependent_p;
6331 }
6332
6333 /* Returns true if T depends on any template parameter with level LEVEL.  */
6334
6335 int
6336 uses_template_parms_level (tree t, int level)
6337 {
6338   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
6339                                  /*include_nondeduced_p=*/true);
6340 }
6341
6342 static int tinst_depth;
6343 extern int max_tinst_depth;
6344 #ifdef GATHER_STATISTICS
6345 int depth_reached;
6346 #endif
6347 static int tinst_level_tick;
6348 static int last_template_error_tick;
6349
6350 /* We're starting to instantiate D; record the template instantiation context
6351    for diagnostics and to restore it later.  */
6352
6353 static int
6354 push_tinst_level (tree d)
6355 {
6356   struct tinst_level *new_level;
6357
6358   if (tinst_depth >= max_tinst_depth)
6359     {
6360       /* If the instantiation in question still has unbound template parms,
6361          we don't really care if we can't instantiate it, so just return.
6362          This happens with base instantiation for implicit `typename'.  */
6363       if (uses_template_parms (d))
6364         return 0;
6365
6366       last_template_error_tick = tinst_level_tick;
6367       error ("template instantiation depth exceeds maximum of %d (use "
6368              "-ftemplate-depth-NN to increase the maximum) instantiating %qD",
6369              max_tinst_depth, d);
6370
6371       print_instantiation_context ();
6372
6373       return 0;
6374     }
6375
6376   new_level = GGC_NEW (struct tinst_level);
6377   new_level->decl = d;
6378   new_level->locus = input_location;
6379   new_level->in_system_header_p = in_system_header;
6380   new_level->next = current_tinst_level;
6381   current_tinst_level = new_level;
6382
6383   ++tinst_depth;
6384 #ifdef GATHER_STATISTICS
6385   if (tinst_depth > depth_reached)
6386     depth_reached = tinst_depth;
6387 #endif
6388
6389   ++tinst_level_tick;
6390   return 1;
6391 }
6392
6393 /* We're done instantiating this template; return to the instantiation
6394    context.  */
6395
6396 static void
6397 pop_tinst_level (void)
6398 {
6399   /* Restore the filename and line number stashed away when we started
6400      this instantiation.  */
6401   input_location = current_tinst_level->locus;
6402   current_tinst_level = current_tinst_level->next;
6403   --tinst_depth;
6404   ++tinst_level_tick;
6405 }
6406
6407 /* We're instantiating a deferred template; restore the template
6408    instantiation context in which the instantiation was requested, which
6409    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
6410
6411 static tree
6412 reopen_tinst_level (struct tinst_level *level)
6413 {
6414   struct tinst_level *t;
6415
6416   tinst_depth = 0;
6417   for (t = level; t; t = t->next)
6418     ++tinst_depth;
6419
6420   current_tinst_level = level;
6421   pop_tinst_level ();
6422   return level->decl;
6423 }
6424
6425 /* Returns the TINST_LEVEL which gives the original instantiation
6426    context.  */
6427
6428 struct tinst_level *
6429 outermost_tinst_level (void)
6430 {
6431   struct tinst_level *level = current_tinst_level;
6432   if (level)
6433     while (level->next)
6434       level = level->next;
6435   return level;
6436 }
6437
6438 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
6439
6440 bool
6441 parameter_of_template_p (tree parm, tree templ)
6442 {
6443   tree parms;
6444   int i;
6445
6446   if (!parm || !templ)
6447     return false;
6448
6449   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
6450   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
6451
6452   parms = DECL_TEMPLATE_PARMS (templ);
6453   parms = INNERMOST_TEMPLATE_PARMS (parms);
6454
6455   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
6456     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
6457       return true;
6458
6459   return false;
6460 }
6461
6462 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
6463    vector of template arguments, as for tsubst.
6464
6465    Returns an appropriate tsubst'd friend declaration.  */
6466
6467 static tree
6468 tsubst_friend_function (tree decl, tree args)
6469 {
6470   tree new_friend;
6471
6472   if (TREE_CODE (decl) == FUNCTION_DECL
6473       && DECL_TEMPLATE_INSTANTIATION (decl)
6474       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
6475     /* This was a friend declared with an explicit template
6476        argument list, e.g.:
6477
6478        friend void f<>(T);
6479
6480        to indicate that f was a template instantiation, not a new
6481        function declaration.  Now, we have to figure out what
6482        instantiation of what template.  */
6483     {
6484       tree template_id, arglist, fns;
6485       tree new_args;
6486       tree tmpl;
6487       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
6488
6489       /* Friend functions are looked up in the containing namespace scope.
6490          We must enter that scope, to avoid finding member functions of the
6491          current class with same name.  */
6492       push_nested_namespace (ns);
6493       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
6494                          tf_warning_or_error, NULL_TREE,
6495                          /*integral_constant_expression_p=*/false);
6496       pop_nested_namespace (ns);
6497       arglist = tsubst (DECL_TI_ARGS (decl), args,
6498                         tf_warning_or_error, NULL_TREE);
6499       template_id = lookup_template_function (fns, arglist);
6500
6501       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6502       tmpl = determine_specialization (template_id, new_friend,
6503                                        &new_args,
6504                                        /*need_member_template=*/0,
6505                                        TREE_VEC_LENGTH (args),
6506                                        tsk_none);
6507       return instantiate_template (tmpl, new_args, tf_error);
6508     }
6509
6510   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6511
6512   /* The NEW_FRIEND will look like an instantiation, to the
6513      compiler, but is not an instantiation from the point of view of
6514      the language.  For example, we might have had:
6515
6516      template <class T> struct S {
6517        template <class U> friend void f(T, U);
6518      };
6519
6520      Then, in S<int>, template <class U> void f(int, U) is not an
6521      instantiation of anything.  */
6522   if (new_friend == error_mark_node)
6523     return error_mark_node;
6524
6525   DECL_USE_TEMPLATE (new_friend) = 0;
6526   if (TREE_CODE (decl) == TEMPLATE_DECL)
6527     {
6528       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
6529       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
6530         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
6531     }
6532
6533   /* The mangled name for the NEW_FRIEND is incorrect.  The function
6534      is not a template instantiation and should not be mangled like
6535      one.  Therefore, we forget the mangling here; we'll recompute it
6536      later if we need it.  */
6537   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
6538     {
6539       SET_DECL_RTL (new_friend, NULL_RTX);
6540       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
6541     }
6542
6543   if (DECL_NAMESPACE_SCOPE_P (new_friend))
6544     {
6545       tree old_decl;
6546       tree new_friend_template_info;
6547       tree new_friend_result_template_info;
6548       tree ns;
6549       int  new_friend_is_defn;
6550
6551       /* We must save some information from NEW_FRIEND before calling
6552          duplicate decls since that function will free NEW_FRIEND if
6553          possible.  */
6554       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
6555       new_friend_is_defn =
6556             (DECL_INITIAL (DECL_TEMPLATE_RESULT
6557                            (template_for_substitution (new_friend)))
6558              != NULL_TREE);
6559       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
6560         {
6561           /* This declaration is a `primary' template.  */
6562           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
6563
6564           new_friend_result_template_info
6565             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
6566         }
6567       else
6568         new_friend_result_template_info = NULL_TREE;
6569
6570       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
6571       if (new_friend_is_defn)
6572         DECL_INITIAL (new_friend) = error_mark_node;
6573
6574       /* Inside pushdecl_namespace_level, we will push into the
6575          current namespace. However, the friend function should go
6576          into the namespace of the template.  */
6577       ns = decl_namespace_context (new_friend);
6578       push_nested_namespace (ns);
6579       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
6580       pop_nested_namespace (ns);
6581
6582       if (old_decl == error_mark_node)
6583         return error_mark_node;
6584
6585       if (old_decl != new_friend)
6586         {
6587           /* This new friend declaration matched an existing
6588              declaration.  For example, given:
6589
6590                template <class T> void f(T);
6591                template <class U> class C {
6592                  template <class T> friend void f(T) {}
6593                };
6594
6595              the friend declaration actually provides the definition
6596              of `f', once C has been instantiated for some type.  So,
6597              old_decl will be the out-of-class template declaration,
6598              while new_friend is the in-class definition.
6599
6600              But, if `f' was called before this point, the
6601              instantiation of `f' will have DECL_TI_ARGS corresponding
6602              to `T' but not to `U', references to which might appear
6603              in the definition of `f'.  Previously, the most general
6604              template for an instantiation of `f' was the out-of-class
6605              version; now it is the in-class version.  Therefore, we
6606              run through all specialization of `f', adding to their
6607              DECL_TI_ARGS appropriately.  In particular, they need a
6608              new set of outer arguments, corresponding to the
6609              arguments for this class instantiation.
6610
6611              The same situation can arise with something like this:
6612
6613                friend void f(int);
6614                template <class T> class C {
6615                  friend void f(T) {}
6616                };
6617
6618              when `C<int>' is instantiated.  Now, `f(int)' is defined
6619              in the class.  */
6620
6621           if (!new_friend_is_defn)
6622             /* On the other hand, if the in-class declaration does
6623                *not* provide a definition, then we don't want to alter
6624                existing definitions.  We can just leave everything
6625                alone.  */
6626             ;
6627           else
6628             {
6629               /* Overwrite whatever template info was there before, if
6630                  any, with the new template information pertaining to
6631                  the declaration.  */
6632               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
6633
6634               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
6635                 reregister_specialization (new_friend,
6636                                            most_general_template (old_decl),
6637                                            old_decl);
6638               else
6639                 {
6640                   tree t;
6641                   tree new_friend_args;
6642
6643                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
6644                     = new_friend_result_template_info;
6645
6646                   new_friend_args = TI_ARGS (new_friend_template_info);
6647                   for (t = DECL_TEMPLATE_SPECIALIZATIONS (old_decl);
6648                        t != NULL_TREE;
6649                        t = TREE_CHAIN (t))
6650                     {
6651                       tree spec = TREE_VALUE (t);
6652
6653                       DECL_TI_ARGS (spec)
6654                         = add_outermost_template_args (new_friend_args,
6655                                                        DECL_TI_ARGS (spec));
6656                     }
6657
6658                   /* Now, since specializations are always supposed to
6659                      hang off of the most general template, we must move
6660                      them.  */
6661                   t = most_general_template (old_decl);
6662                   if (t != old_decl)
6663                     {
6664                       DECL_TEMPLATE_SPECIALIZATIONS (t)
6665                         = chainon (DECL_TEMPLATE_SPECIALIZATIONS (t),
6666                                    DECL_TEMPLATE_SPECIALIZATIONS (old_decl));
6667                       DECL_TEMPLATE_SPECIALIZATIONS (old_decl) = NULL_TREE;
6668                     }
6669                 }
6670             }
6671
6672           /* The information from NEW_FRIEND has been merged into OLD_DECL
6673              by duplicate_decls.  */
6674           new_friend = old_decl;
6675         }
6676     }
6677   else
6678     {
6679       tree context = DECL_CONTEXT (new_friend);
6680       bool dependent_p;
6681
6682       /* In the code
6683            template <class T> class C {
6684              template <class U> friend void C1<U>::f (); // case 1
6685              friend void C2<T>::f ();                    // case 2
6686            };
6687          we only need to make sure CONTEXT is a complete type for
6688          case 2.  To distinguish between the two cases, we note that
6689          CONTEXT of case 1 remains dependent type after tsubst while
6690          this isn't true for case 2.  */
6691       ++processing_template_decl;
6692       dependent_p = dependent_type_p (context);
6693       --processing_template_decl;
6694
6695       if (!dependent_p
6696           && !complete_type_or_else (context, NULL_TREE))
6697         return error_mark_node;
6698
6699       if (COMPLETE_TYPE_P (context))
6700         {
6701           /* Check to see that the declaration is really present, and,
6702              possibly obtain an improved declaration.  */
6703           tree fn = check_classfn (context,
6704                                    new_friend, NULL_TREE);
6705
6706           if (fn)
6707             new_friend = fn;
6708         }
6709     }
6710
6711   return new_friend;
6712 }
6713
6714 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
6715    template arguments, as for tsubst.
6716
6717    Returns an appropriate tsubst'd friend type or error_mark_node on
6718    failure.  */
6719
6720 static tree
6721 tsubst_friend_class (tree friend_tmpl, tree args)
6722 {
6723   tree friend_type;
6724   tree tmpl;
6725   tree context;
6726
6727   context = DECL_CONTEXT (friend_tmpl);
6728
6729   if (context)
6730     {
6731       if (TREE_CODE (context) == NAMESPACE_DECL)
6732         push_nested_namespace (context);
6733       else
6734         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
6735     }
6736
6737   /* Look for a class template declaration.  We look for hidden names
6738      because two friend declarations of the same template are the
6739      same.  For example, in:
6740
6741        struct A { 
6742          template <typename> friend class F;
6743        };
6744        template <typename> struct B { 
6745          template <typename> friend class F;
6746        };
6747
6748      both F templates are the same.  */
6749   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
6750                            /*block_p=*/true, 0, 
6751                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
6752
6753   /* But, if we don't find one, it might be because we're in a
6754      situation like this:
6755
6756        template <class T>
6757        struct S {
6758          template <class U>
6759          friend struct S;
6760        };
6761
6762      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
6763      for `S<int>', not the TEMPLATE_DECL.  */
6764   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
6765     {
6766       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
6767       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
6768     }
6769
6770   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
6771     {
6772       /* The friend template has already been declared.  Just
6773          check to see that the declarations match, and install any new
6774          default parameters.  We must tsubst the default parameters,
6775          of course.  We only need the innermost template parameters
6776          because that is all that redeclare_class_template will look
6777          at.  */
6778       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
6779           > TMPL_ARGS_DEPTH (args))
6780         {
6781           tree parms;
6782           location_t saved_input_location;
6783           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
6784                                          args, tf_warning_or_error);
6785
6786           saved_input_location = input_location;
6787           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
6788           redeclare_class_template (TREE_TYPE (tmpl), parms);
6789           input_location = saved_input_location;
6790           
6791         }
6792
6793       friend_type = TREE_TYPE (tmpl);
6794     }
6795   else
6796     {
6797       /* The friend template has not already been declared.  In this
6798          case, the instantiation of the template class will cause the
6799          injection of this template into the global scope.  */
6800       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
6801       if (tmpl == error_mark_node)
6802         return error_mark_node;
6803
6804       /* The new TMPL is not an instantiation of anything, so we
6805          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
6806          the new type because that is supposed to be the corresponding
6807          template decl, i.e., TMPL.  */
6808       DECL_USE_TEMPLATE (tmpl) = 0;
6809       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
6810       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
6811       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
6812         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
6813
6814       /* Inject this template into the global scope.  */
6815       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
6816     }
6817
6818   if (context)
6819     {
6820       if (TREE_CODE (context) == NAMESPACE_DECL)
6821         pop_nested_namespace (context);
6822       else
6823         pop_nested_class ();
6824     }
6825
6826   return friend_type;
6827 }
6828
6829 /* Returns zero if TYPE cannot be completed later due to circularity.
6830    Otherwise returns one.  */
6831
6832 static int
6833 can_complete_type_without_circularity (tree type)
6834 {
6835   if (type == NULL_TREE || type == error_mark_node)
6836     return 0;
6837   else if (COMPLETE_TYPE_P (type))
6838     return 1;
6839   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
6840     return can_complete_type_without_circularity (TREE_TYPE (type));
6841   else if (CLASS_TYPE_P (type)
6842            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
6843     return 0;
6844   else
6845     return 1;
6846 }
6847
6848 /* Apply any attributes which had to be deferred until instantiation
6849    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
6850    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
6851
6852 static void
6853 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
6854                                 tree args, tsubst_flags_t complain, tree in_decl)
6855 {
6856   tree last_dep = NULL_TREE;
6857   tree t;
6858   tree *p;
6859
6860   for (t = attributes; t; t = TREE_CHAIN (t))
6861     if (ATTR_IS_DEPENDENT (t))
6862       {
6863         last_dep = t;
6864         attributes = copy_list (attributes);
6865         break;
6866       }
6867
6868   if (DECL_P (*decl_p))
6869     {
6870       if (TREE_TYPE (*decl_p) == error_mark_node)
6871         return;
6872       p = &DECL_ATTRIBUTES (*decl_p);
6873     }
6874   else
6875     p = &TYPE_ATTRIBUTES (*decl_p);
6876
6877   if (last_dep)
6878     {
6879       tree late_attrs = NULL_TREE;
6880       tree *q = &late_attrs;
6881
6882       for (*p = attributes; *p; )
6883         {
6884           t = *p;
6885           if (ATTR_IS_DEPENDENT (t))
6886             {
6887               *p = TREE_CHAIN (t);
6888               TREE_CHAIN (t) = NULL_TREE;
6889               /* If the first attribute argument is an identifier, don't
6890                  pass it through tsubst.  Attributes like mode, format,
6891                  cleanup and several target specific attributes expect it
6892                  unmodified.  */
6893               if (TREE_VALUE (t)
6894                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
6895                   && TREE_VALUE (TREE_VALUE (t))
6896                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
6897                       == IDENTIFIER_NODE))
6898                 {
6899                   tree chain
6900                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
6901                                    in_decl,
6902                                    /*integral_constant_expression_p=*/false);
6903                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
6904                     TREE_VALUE (t)
6905                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
6906                                    chain);
6907                 }
6908               else
6909                 TREE_VALUE (t)
6910                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
6911                                  /*integral_constant_expression_p=*/false);
6912               *q = t;
6913               q = &TREE_CHAIN (t);
6914             }
6915           else
6916             p = &TREE_CHAIN (t);
6917         }
6918
6919       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
6920     }
6921 }
6922
6923 tree
6924 instantiate_class_template (tree type)
6925 {
6926   tree templ, args, pattern, t, member;
6927   tree typedecl;
6928   tree pbinfo;
6929   tree base_list;
6930
6931   if (type == error_mark_node)
6932     return error_mark_node;
6933
6934   if (TYPE_BEING_DEFINED (type)
6935       || COMPLETE_TYPE_P (type)
6936       || dependent_type_p (type))
6937     return type;
6938
6939   /* Figure out which template is being instantiated.  */
6940   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
6941   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
6942
6943   /* Determine what specialization of the original template to
6944      instantiate.  */
6945   t = most_specialized_class (type, templ);
6946   if (t == error_mark_node)
6947     {
6948       TYPE_BEING_DEFINED (type) = 1;
6949       return error_mark_node;
6950     }
6951   else if (t)
6952     {
6953       /* This TYPE is actually an instantiation of a partial
6954          specialization.  We replace the innermost set of ARGS with
6955          the arguments appropriate for substitution.  For example,
6956          given:
6957
6958            template <class T> struct S {};
6959            template <class T> struct S<T*> {};
6960
6961          and supposing that we are instantiating S<int*>, ARGS will
6962          presently be {int*} -- but we need {int}.  */
6963       pattern = TREE_TYPE (t);
6964       args = TREE_PURPOSE (t);
6965     }
6966   else
6967     {
6968       pattern = TREE_TYPE (templ);
6969       args = CLASSTYPE_TI_ARGS (type);
6970     }
6971
6972   /* If the template we're instantiating is incomplete, then clearly
6973      there's nothing we can do.  */
6974   if (!COMPLETE_TYPE_P (pattern))
6975     return type;
6976
6977   /* If we've recursively instantiated too many templates, stop.  */
6978   if (! push_tinst_level (type))
6979     return type;
6980
6981   /* Now we're really doing the instantiation.  Mark the type as in
6982      the process of being defined.  */
6983   TYPE_BEING_DEFINED (type) = 1;
6984
6985   /* We may be in the middle of deferred access check.  Disable
6986      it now.  */
6987   push_deferring_access_checks (dk_no_deferred);
6988
6989   push_to_top_level ();
6990
6991   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
6992
6993   /* Set the input location to the template definition. This is needed
6994      if tsubsting causes an error.  */
6995   typedecl = TYPE_MAIN_DECL (type);
6996   input_location = DECL_SOURCE_LOCATION (typedecl);
6997
6998   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
6999   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7000   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7001   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7002   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
7003   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
7004   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
7005   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
7006   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7007   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7008   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7009   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7010   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7011   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7012   if (ANON_AGGR_TYPE_P (pattern))
7013     SET_ANON_AGGR_TYPE_P (type);
7014   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7015     {
7016       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7017       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7018     }
7019
7020   pbinfo = TYPE_BINFO (pattern);
7021
7022   /* We should never instantiate a nested class before its enclosing
7023      class; we need to look up the nested class by name before we can
7024      instantiate it, and that lookup should instantiate the enclosing
7025      class.  */
7026   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7027               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
7028               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
7029
7030   base_list = NULL_TREE;
7031   if (BINFO_N_BASE_BINFOS (pbinfo))
7032     {
7033       tree pbase_binfo;
7034       tree context = TYPE_CONTEXT (type);
7035       tree pushed_scope;
7036       int i;
7037
7038       /* We must enter the scope containing the type, as that is where
7039          the accessibility of types named in dependent bases are
7040          looked up from.  */
7041       pushed_scope = push_scope (context ? context : global_namespace);
7042
7043       /* Substitute into each of the bases to determine the actual
7044          basetypes.  */
7045       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7046         {
7047           tree base;
7048           tree access = BINFO_BASE_ACCESS (pbinfo, i);
7049           tree expanded_bases = NULL_TREE;
7050           int idx, len = 1;
7051
7052           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7053             {
7054               expanded_bases = 
7055                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7056                                        args, tf_error, NULL_TREE);
7057               if (expanded_bases == error_mark_node)
7058                 continue;
7059
7060               len = TREE_VEC_LENGTH (expanded_bases);
7061             }
7062
7063           for (idx = 0; idx < len; idx++)
7064             {
7065               if (expanded_bases)
7066                 /* Extract the already-expanded base class.  */
7067                 base = TREE_VEC_ELT (expanded_bases, idx);
7068               else
7069                 /* Substitute to figure out the base class.  */
7070                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
7071                                NULL_TREE);
7072
7073               if (base == error_mark_node)
7074                 continue;
7075
7076               base_list = tree_cons (access, base, base_list);
7077               if (BINFO_VIRTUAL_P (pbase_binfo))
7078                 TREE_TYPE (base_list) = integer_type_node;
7079             }
7080         }
7081
7082       /* The list is now in reverse order; correct that.  */
7083       base_list = nreverse (base_list);
7084
7085       if (pushed_scope)
7086         pop_scope (pushed_scope);
7087     }
7088   /* Now call xref_basetypes to set up all the base-class
7089      information.  */
7090   xref_basetypes (type, base_list);
7091
7092   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7093                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7094                                   args, tf_error, NULL_TREE);
7095
7096   /* Now that our base classes are set up, enter the scope of the
7097      class, so that name lookups into base classes, etc. will work
7098      correctly.  This is precisely analogous to what we do in
7099      begin_class_definition when defining an ordinary non-template
7100      class, except we also need to push the enclosing classes.  */
7101   push_nested_class (type);
7102
7103   /* Now members are processed in the order of declaration.  */
7104   for (member = CLASSTYPE_DECL_LIST (pattern);
7105        member; member = TREE_CHAIN (member))
7106     {
7107       tree t = TREE_VALUE (member);
7108
7109       if (TREE_PURPOSE (member))
7110         {
7111           if (TYPE_P (t))
7112             {
7113               /* Build new CLASSTYPE_NESTED_UTDS.  */
7114
7115               tree newtag;
7116               bool class_template_p;
7117
7118               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7119                                   && TYPE_LANG_SPECIFIC (t)
7120                                   && CLASSTYPE_IS_TEMPLATE (t));
7121               /* If the member is a class template, then -- even after
7122                  substitution -- there may be dependent types in the
7123                  template argument list for the class.  We increment
7124                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7125                  that function will assume that no types are dependent
7126                  when outside of a template.  */
7127               if (class_template_p)
7128                 ++processing_template_decl;
7129               newtag = tsubst (t, args, tf_error, NULL_TREE);
7130               if (class_template_p)
7131                 --processing_template_decl;
7132               if (newtag == error_mark_node)
7133                 continue;
7134
7135               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7136                 {
7137                   tree name = TYPE_IDENTIFIER (t);
7138
7139                   if (class_template_p)
7140                     /* Unfortunately, lookup_template_class sets
7141                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7142                        instantiation (i.e., for the type of a member
7143                        template class nested within a template class.)
7144                        This behavior is required for
7145                        maybe_process_partial_specialization to work
7146                        correctly, but is not accurate in this case;
7147                        the TAG is not an instantiation of anything.
7148                        (The corresponding TEMPLATE_DECL is an
7149                        instantiation, but the TYPE is not.) */
7150                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7151
7152                   /* Now, we call pushtag to put this NEWTAG into the scope of
7153                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7154                      pushtag calling push_template_decl.  We don't have to do
7155                      this for enums because it will already have been done in
7156                      tsubst_enum.  */
7157                   if (name)
7158                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7159                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7160                 }
7161             }
7162           else if (TREE_CODE (t) == FUNCTION_DECL
7163                    || DECL_FUNCTION_TEMPLATE_P (t))
7164             {
7165               /* Build new TYPE_METHODS.  */
7166               tree r;
7167
7168               if (TREE_CODE (t) == TEMPLATE_DECL)
7169                 ++processing_template_decl;
7170               r = tsubst (t, args, tf_error, NULL_TREE);
7171               if (TREE_CODE (t) == TEMPLATE_DECL)
7172                 --processing_template_decl;
7173               set_current_access_from_decl (r);
7174               finish_member_declaration (r);
7175             }
7176           else
7177             {
7178               /* Build new TYPE_FIELDS.  */
7179               if (TREE_CODE (t) == STATIC_ASSERT)
7180                 {
7181                   tree condition = 
7182                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7183                                  tf_warning_or_error, NULL_TREE,
7184                                  /*integral_constant_expression_p=*/true);
7185                   finish_static_assert (condition,
7186                                         STATIC_ASSERT_MESSAGE (t), 
7187                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7188                                         /*member_p=*/true);
7189                 }
7190               else if (TREE_CODE (t) != CONST_DECL)
7191                 {
7192                   tree r;
7193
7194                   /* The file and line for this declaration, to
7195                      assist in error message reporting.  Since we
7196                      called push_tinst_level above, we don't need to
7197                      restore these.  */
7198                   input_location = DECL_SOURCE_LOCATION (t);
7199
7200                   if (TREE_CODE (t) == TEMPLATE_DECL)
7201                     ++processing_template_decl;
7202                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7203                   if (TREE_CODE (t) == TEMPLATE_DECL)
7204                     --processing_template_decl;
7205                   if (TREE_CODE (r) == VAR_DECL)
7206                     {
7207                       /* In [temp.inst]:
7208
7209                            [t]he initialization (and any associated
7210                            side-effects) of a static data member does
7211                            not occur unless the static data member is
7212                            itself used in a way that requires the
7213                            definition of the static data member to
7214                            exist.
7215
7216                          Therefore, we do not substitute into the
7217                          initialized for the static data member here.  */
7218                       finish_static_data_member_decl
7219                         (r,
7220                          /*init=*/NULL_TREE,
7221                          /*init_const_expr_p=*/false,
7222                          /*asmspec_tree=*/NULL_TREE,
7223                          /*flags=*/0);
7224                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7225                         check_static_variable_definition (r, TREE_TYPE (r));
7226                     }
7227                   else if (TREE_CODE (r) == FIELD_DECL)
7228                     {
7229                       /* Determine whether R has a valid type and can be
7230                          completed later.  If R is invalid, then it is
7231                          replaced by error_mark_node so that it will not be
7232                          added to TYPE_FIELDS.  */
7233                       tree rtype = TREE_TYPE (r);
7234                       if (can_complete_type_without_circularity (rtype))
7235                         complete_type (rtype);
7236
7237                       if (!COMPLETE_TYPE_P (rtype))
7238                         {
7239                           cxx_incomplete_type_error (r, rtype);
7240                           r = error_mark_node;
7241                         }
7242                     }
7243
7244                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
7245                      such a thing will already have been added to the field
7246                      list by tsubst_enum in finish_member_declaration in the
7247                      CLASSTYPE_NESTED_UTDS case above.  */
7248                   if (!(TREE_CODE (r) == TYPE_DECL
7249                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
7250                         && DECL_ARTIFICIAL (r)))
7251                     {
7252                       set_current_access_from_decl (r);
7253                       finish_member_declaration (r);
7254                     }
7255                 }
7256             }
7257         }
7258       else
7259         {
7260           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
7261             {
7262               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
7263
7264               tree friend_type = t;
7265               bool adjust_processing_template_decl = false;
7266
7267               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7268                 {
7269                   /* template <class T> friend class C;  */
7270                   friend_type = tsubst_friend_class (friend_type, args);
7271                   adjust_processing_template_decl = true;
7272                 }
7273               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
7274                 {
7275                   /* template <class T> friend class C::D;  */
7276                   friend_type = tsubst (friend_type, args,
7277                                         tf_warning_or_error, NULL_TREE);
7278                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7279                     friend_type = TREE_TYPE (friend_type);
7280                   adjust_processing_template_decl = true;
7281                 }
7282               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
7283                 {
7284                   /* This could be either
7285
7286                        friend class T::C;
7287
7288                      when dependent_type_p is false or
7289
7290                        template <class U> friend class T::C;
7291
7292                      otherwise.  */
7293                   friend_type = tsubst (friend_type, args,
7294                                         tf_warning_or_error, NULL_TREE);
7295                   /* Bump processing_template_decl for correct
7296                      dependent_type_p calculation.  */
7297                   ++processing_template_decl;
7298                   if (dependent_type_p (friend_type))
7299                     adjust_processing_template_decl = true;
7300                   --processing_template_decl;
7301                 }
7302               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
7303                        && hidden_name_p (TYPE_NAME (friend_type)))
7304                 {
7305                   /* friend class C;
7306
7307                      where C hasn't been declared yet.  Let's lookup name
7308                      from namespace scope directly, bypassing any name that
7309                      come from dependent base class.  */
7310                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
7311
7312                   /* The call to xref_tag_from_type does injection for friend
7313                      classes.  */
7314                   push_nested_namespace (ns);
7315                   friend_type =
7316                     xref_tag_from_type (friend_type, NULL_TREE,
7317                                         /*tag_scope=*/ts_current);
7318                   pop_nested_namespace (ns);
7319                 }
7320               else if (uses_template_parms (friend_type))
7321                 /* friend class C<T>;  */
7322                 friend_type = tsubst (friend_type, args,
7323                                       tf_warning_or_error, NULL_TREE);
7324               /* Otherwise it's
7325
7326                    friend class C;
7327
7328                  where C is already declared or
7329
7330                    friend class C<int>;
7331
7332                  We don't have to do anything in these cases.  */
7333
7334               if (adjust_processing_template_decl)
7335                 /* Trick make_friend_class into realizing that the friend
7336                    we're adding is a template, not an ordinary class.  It's
7337                    important that we use make_friend_class since it will
7338                    perform some error-checking and output cross-reference
7339                    information.  */
7340                 ++processing_template_decl;
7341
7342               if (friend_type != error_mark_node)
7343                 make_friend_class (type, friend_type, /*complain=*/false);
7344
7345               if (adjust_processing_template_decl)
7346                 --processing_template_decl;
7347             }
7348           else
7349             {
7350               /* Build new DECL_FRIENDLIST.  */
7351               tree r;
7352
7353               /* The file and line for this declaration, to
7354                  assist in error message reporting.  Since we
7355                  called push_tinst_level above, we don't need to
7356                  restore these.  */
7357               input_location = DECL_SOURCE_LOCATION (t);
7358
7359               if (TREE_CODE (t) == TEMPLATE_DECL)
7360                 {
7361                   ++processing_template_decl;
7362                   push_deferring_access_checks (dk_no_check);
7363                 }
7364
7365               r = tsubst_friend_function (t, args);
7366               add_friend (type, r, /*complain=*/false);
7367               if (TREE_CODE (t) == TEMPLATE_DECL)
7368                 {
7369                   pop_deferring_access_checks ();
7370                   --processing_template_decl;
7371                 }
7372             }
7373         }
7374     }
7375
7376   /* Set the file and line number information to whatever is given for
7377      the class itself.  This puts error messages involving generated
7378      implicit functions at a predictable point, and the same point
7379      that would be used for non-template classes.  */
7380   input_location = DECL_SOURCE_LOCATION (typedecl);
7381
7382   unreverse_member_declarations (type);
7383   finish_struct_1 (type);
7384   TYPE_BEING_DEFINED (type) = 0;
7385
7386   /* Now that the class is complete, instantiate default arguments for
7387      any member functions.  We don't do this earlier because the
7388      default arguments may reference members of the class.  */
7389   if (!PRIMARY_TEMPLATE_P (templ))
7390     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
7391       if (TREE_CODE (t) == FUNCTION_DECL
7392           /* Implicitly generated member functions will not have template
7393              information; they are not instantiations, but instead are
7394              created "fresh" for each instantiation.  */
7395           && DECL_TEMPLATE_INFO (t))
7396         tsubst_default_arguments (t);
7397
7398   pop_nested_class ();
7399   pop_from_top_level ();
7400   pop_deferring_access_checks ();
7401   pop_tinst_level ();
7402
7403   /* The vtable for a template class can be emitted in any translation
7404      unit in which the class is instantiated.  When there is no key
7405      method, however, finish_struct_1 will already have added TYPE to
7406      the keyed_classes list.  */
7407   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
7408     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
7409
7410   return type;
7411 }
7412
7413 static tree
7414 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7415 {
7416   tree r;
7417
7418   if (!t)
7419     r = t;
7420   else if (TYPE_P (t))
7421     r = tsubst (t, args, complain, in_decl);
7422   else
7423     {
7424       r = tsubst_expr (t, args, complain, in_decl,
7425                        /*integral_constant_expression_p=*/true);
7426       r = fold_non_dependent_expr (r);
7427     }
7428   return r;
7429 }
7430
7431 /* Substitute ARGS into T, which is an pack expansion
7432    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
7433    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
7434    (if only a partial substitution could be performed) or
7435    ERROR_MARK_NODE if there was an error.  */
7436 tree
7437 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
7438                        tree in_decl)
7439 {
7440   tree pattern;
7441   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
7442   tree first_arg_pack; int i, len = -1;
7443   tree result;
7444   int incomplete = 0;
7445
7446   gcc_assert (PACK_EXPANSION_P (t));
7447   pattern = PACK_EXPANSION_PATTERN (t);
7448
7449   /* Determine the argument packs that will instantiate the parameter
7450      packs used in the expansion expression. While we're at it,
7451      compute the number of arguments to be expanded and make sure it
7452      is consistent.  */
7453   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
7454        pack = TREE_CHAIN (pack))
7455     {
7456       tree parm_pack = TREE_VALUE (pack);
7457       tree arg_pack = NULL_TREE;
7458       tree orig_arg = NULL_TREE;
7459
7460       if (TREE_CODE (parm_pack) == PARM_DECL)
7461         arg_pack = retrieve_local_specialization (parm_pack);
7462       else
7463         {
7464           int level, idx, levels;
7465           template_parm_level_and_index (parm_pack, &level, &idx);
7466
7467           levels = TMPL_ARGS_DEPTH (args);
7468           if (level <= levels)
7469             arg_pack = TMPL_ARG (args, level, idx);
7470         }
7471
7472       orig_arg = arg_pack;
7473       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
7474         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
7475       
7476       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
7477         /* This can only happen if we forget to expand an argument
7478            pack somewhere else. Just return an error, silently.  */
7479         {
7480           result = make_tree_vec (1);
7481           TREE_VEC_ELT (result, 0) = error_mark_node;
7482           return result;
7483         }
7484
7485       if (arg_pack
7486           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
7487           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
7488         {
7489           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
7490           tree pattern = PACK_EXPANSION_PATTERN (expansion);
7491           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
7492               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
7493             /* The argument pack that the parameter maps to is just an
7494                expansion of the parameter itself, such as one would
7495                find in the implicit typedef of a class inside the
7496                class itself.  Consider this parameter "unsubstituted",
7497                so that we will maintain the outer pack expansion.  */
7498             arg_pack = NULL_TREE;
7499         }
7500           
7501       if (arg_pack)
7502         {
7503           int my_len = 
7504             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
7505
7506           /* It's all-or-nothing with incomplete argument packs.  */
7507           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7508             return error_mark_node;
7509           
7510           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7511             incomplete = 1;
7512
7513           if (len < 0)
7514             {
7515               len = my_len;
7516               first_arg_pack = arg_pack;
7517             }
7518           else if (len != my_len)
7519             {
7520               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
7521                 error ("mismatched argument pack lengths while expanding "
7522                        "%<%T%>",
7523                        pattern);
7524               else
7525                 error ("mismatched argument pack lengths while expanding "
7526                        "%<%E%>",
7527                        pattern);
7528               return error_mark_node;
7529             }
7530
7531           /* Keep track of the parameter packs and their corresponding
7532              argument packs.  */
7533           packs = tree_cons (parm_pack, arg_pack, packs);
7534           TREE_TYPE (packs) = orig_arg;
7535         }
7536       else
7537         /* We can't substitute for this parameter pack.  */
7538         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
7539                                          TREE_VALUE (pack),
7540                                          unsubstituted_packs);
7541     }
7542
7543   /* We cannot expand this expansion expression, because we don't have
7544      all of the argument packs we need. Substitute into the pattern
7545      and return a PACK_EXPANSION_*. The caller will need to deal with
7546      that.  */
7547   if (unsubstituted_packs)
7548     return make_pack_expansion (tsubst (pattern, args, complain, 
7549                                         in_decl));
7550
7551   /* We could not find any argument packs that work.  */
7552   if (len < 0)
7553     return error_mark_node;
7554
7555   /* For each argument in each argument pack, substitute into the
7556      pattern.  */
7557   result = make_tree_vec (len + incomplete);
7558   for (i = 0; i < len + incomplete; ++i)
7559     {
7560       /* For parameter pack, change the substitution of the parameter
7561          pack to the ith argument in its argument pack, then expand
7562          the pattern.  */
7563       for (pack = packs; pack; pack = TREE_CHAIN (pack))
7564         {
7565           tree parm = TREE_PURPOSE (pack);
7566
7567           if (TREE_CODE (parm) == PARM_DECL)
7568             {
7569               /* Select the Ith argument from the pack.  */
7570               tree arg = make_node (ARGUMENT_PACK_SELECT);
7571               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
7572               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
7573               mark_used (parm);
7574               register_local_specialization (arg, parm);
7575             }
7576           else
7577             {
7578               tree value = parm;
7579               int idx, level;
7580               template_parm_level_and_index (parm, &level, &idx);
7581               
7582               if (i < len) 
7583                 {
7584                   /* Select the Ith argument from the pack. */
7585                   value = make_node (ARGUMENT_PACK_SELECT);
7586                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
7587                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
7588                 }
7589
7590               /* Update the corresponding argument.  */
7591               TMPL_ARG (args, level, idx) = value;
7592             }
7593         }
7594
7595       /* Substitute into the PATTERN with the altered arguments.  */
7596       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
7597         TREE_VEC_ELT (result, i) = 
7598           tsubst_expr (pattern, args, complain, in_decl,
7599                        /*integral_constant_expression_p=*/false);
7600       else
7601         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
7602
7603       if (i == len)
7604         /* When we have incomplete argument packs, the last "expanded"
7605            result is itself a pack expansion, which allows us
7606            to deduce more arguments.  */
7607         TREE_VEC_ELT (result, i) = 
7608           make_pack_expansion (TREE_VEC_ELT (result, i));
7609
7610       if (TREE_VEC_ELT (result, i) == error_mark_node)
7611         {
7612           result = error_mark_node;
7613           break;
7614         }
7615     }
7616   
7617   /* Update ARGS to restore the substitution from parameter packs to
7618      their argument packs.  */
7619   for (pack = packs; pack; pack = TREE_CHAIN (pack))
7620     {
7621       tree parm = TREE_PURPOSE (pack);
7622
7623       if (TREE_CODE (parm) == PARM_DECL)
7624         register_local_specialization (TREE_TYPE (pack), parm);
7625       else
7626         {
7627           int idx, level;
7628           template_parm_level_and_index (parm, &level, &idx);
7629           
7630           /* Update the corresponding argument.  */
7631           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
7632             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
7633               TREE_TYPE (pack);
7634           else
7635             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
7636         }
7637     }
7638
7639   return result;
7640 }
7641
7642 /* Substitute ARGS into the vector or list of template arguments T.  */
7643
7644 static tree
7645 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7646 {
7647   tree orig_t = t;
7648   int len = TREE_VEC_LENGTH (t);
7649   int need_new = 0, i, expanded_len_adjust = 0, out;
7650   tree *elts = (tree *) alloca (len * sizeof (tree));
7651
7652   for (i = 0; i < len; i++)
7653     {
7654       tree orig_arg = TREE_VEC_ELT (t, i);
7655       tree new_arg;
7656
7657       if (TREE_CODE (orig_arg) == TREE_VEC)
7658         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
7659       else if (PACK_EXPANSION_P (orig_arg))
7660         {
7661           /* Substitute into an expansion expression.  */
7662           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
7663
7664           if (TREE_CODE (new_arg) == TREE_VEC)
7665             /* Add to the expanded length adjustment the number of
7666                expanded arguments. We subtract one from this
7667                measurement, because the argument pack expression
7668                itself is already counted as 1 in
7669                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
7670                the argument pack is empty.  */
7671             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
7672         }
7673       else if (ARGUMENT_PACK_P (orig_arg))
7674         {
7675           /* Substitute into each of the arguments.  */
7676           new_arg = make_node (TREE_CODE (orig_arg));
7677           
7678           SET_ARGUMENT_PACK_ARGS (
7679             new_arg,
7680             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
7681                                   args, complain, in_decl));
7682
7683           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
7684             new_arg = error_mark_node;
7685
7686           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
7687             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
7688                                           complain, in_decl);
7689             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
7690
7691             if (TREE_TYPE (new_arg) == error_mark_node)
7692               new_arg = error_mark_node;
7693           }
7694         }
7695       else
7696         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
7697
7698       if (new_arg == error_mark_node)
7699         return error_mark_node;
7700
7701       elts[i] = new_arg;
7702       if (new_arg != orig_arg)
7703         need_new = 1;
7704     }
7705
7706   if (!need_new)
7707     return t;
7708
7709   /* Make space for the expanded arguments coming from template
7710      argument packs.  */
7711   t = make_tree_vec (len + expanded_len_adjust);
7712   for (i = 0, out = 0; i < len; i++)
7713     {
7714       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
7715            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
7716           && TREE_CODE (elts[i]) == TREE_VEC)
7717         {
7718           int idx;
7719
7720           /* Now expand the template argument pack "in place".  */
7721           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
7722             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
7723         }
7724       else
7725         {
7726           TREE_VEC_ELT (t, out) = elts[i];
7727           out++;
7728         }
7729     }
7730
7731   return t;
7732 }
7733
7734 /* Return the result of substituting ARGS into the template parameters
7735    given by PARMS.  If there are m levels of ARGS and m + n levels of
7736    PARMS, then the result will contain n levels of PARMS.  For
7737    example, if PARMS is `template <class T> template <class U>
7738    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
7739    result will be `template <int*, double, class V>'.  */
7740
7741 static tree
7742 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
7743 {
7744   tree r = NULL_TREE;
7745   tree* new_parms;
7746
7747   /* When substituting into a template, we must set
7748      PROCESSING_TEMPLATE_DECL as the template parameters may be
7749      dependent if they are based on one-another, and the dependency
7750      predicates are short-circuit outside of templates.  */
7751   ++processing_template_decl;
7752
7753   for (new_parms = &r;
7754        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
7755        new_parms = &(TREE_CHAIN (*new_parms)),
7756          parms = TREE_CHAIN (parms))
7757     {
7758       tree new_vec =
7759         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
7760       int i;
7761
7762       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
7763         {
7764           tree tuple;
7765           tree default_value;
7766           tree parm_decl;
7767
7768           if (parms == error_mark_node)
7769             continue;
7770
7771           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
7772
7773           if (tuple == error_mark_node)
7774             continue;
7775
7776           default_value = TREE_PURPOSE (tuple);
7777           parm_decl = TREE_VALUE (tuple);
7778
7779           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
7780           if (TREE_CODE (parm_decl) == PARM_DECL
7781               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
7782             parm_decl = error_mark_node;
7783           default_value = tsubst_template_arg (default_value, args,
7784                                                complain, NULL_TREE);
7785
7786           tuple = build_tree_list (default_value, parm_decl);
7787           TREE_VEC_ELT (new_vec, i) = tuple;
7788         }
7789
7790       *new_parms =
7791         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
7792                              - TMPL_ARGS_DEPTH (args)),
7793                    new_vec, NULL_TREE);
7794     }
7795
7796   --processing_template_decl;
7797
7798   return r;
7799 }
7800
7801 /* Substitute the ARGS into the indicated aggregate (or enumeration)
7802    type T.  If T is not an aggregate or enumeration type, it is
7803    handled as if by tsubst.  IN_DECL is as for tsubst.  If
7804    ENTERING_SCOPE is nonzero, T is the context for a template which
7805    we are presently tsubst'ing.  Return the substituted value.  */
7806
7807 static tree
7808 tsubst_aggr_type (tree t,
7809                   tree args,
7810                   tsubst_flags_t complain,
7811                   tree in_decl,
7812                   int entering_scope)
7813 {
7814   if (t == NULL_TREE)
7815     return NULL_TREE;
7816
7817   switch (TREE_CODE (t))
7818     {
7819     case RECORD_TYPE:
7820       if (TYPE_PTRMEMFUNC_P (t))
7821         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
7822
7823       /* Else fall through.  */
7824     case ENUMERAL_TYPE:
7825     case UNION_TYPE:
7826       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
7827         {
7828           tree argvec;
7829           tree context;
7830           tree r;
7831           bool saved_skip_evaluation;
7832
7833           /* In "sizeof(X<I>)" we need to evaluate "I".  */
7834           saved_skip_evaluation = skip_evaluation;
7835           skip_evaluation = false;
7836
7837           /* First, determine the context for the type we are looking
7838              up.  */
7839           context = TYPE_CONTEXT (t);
7840           if (context)
7841             {
7842               context = tsubst_aggr_type (context, args, complain,
7843                                           in_decl, /*entering_scope=*/1);
7844               /* If context is a nested class inside a class template,
7845                  it may still need to be instantiated (c++/33959).  */
7846               if (TYPE_P (context))
7847                 context = complete_type (context);
7848             }
7849
7850           /* Then, figure out what arguments are appropriate for the
7851              type we are trying to find.  For example, given:
7852
7853                template <class T> struct S;
7854                template <class T, class U> void f(T, U) { S<U> su; }
7855
7856              and supposing that we are instantiating f<int, double>,
7857              then our ARGS will be {int, double}, but, when looking up
7858              S we only want {double}.  */
7859           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
7860                                          complain, in_decl);
7861           if (argvec == error_mark_node)
7862             r = error_mark_node;
7863           else
7864             {
7865               r = lookup_template_class (t, argvec, in_decl, context,
7866                                          entering_scope, complain);
7867               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
7868             }
7869
7870           skip_evaluation = saved_skip_evaluation;
7871
7872           return r;
7873         }
7874       else
7875         /* This is not a template type, so there's nothing to do.  */
7876         return t;
7877
7878     default:
7879       return tsubst (t, args, complain, in_decl);
7880     }
7881 }
7882
7883 /* Substitute into the default argument ARG (a default argument for
7884    FN), which has the indicated TYPE.  */
7885
7886 tree
7887 tsubst_default_argument (tree fn, tree type, tree arg)
7888 {
7889   tree saved_class_ptr = NULL_TREE;
7890   tree saved_class_ref = NULL_TREE;
7891
7892   /* This default argument came from a template.  Instantiate the
7893      default argument here, not in tsubst.  In the case of
7894      something like:
7895
7896        template <class T>
7897        struct S {
7898          static T t();
7899          void f(T = t());
7900        };
7901
7902      we must be careful to do name lookup in the scope of S<T>,
7903      rather than in the current class.  */
7904   push_access_scope (fn);
7905   /* The "this" pointer is not valid in a default argument.  */
7906   if (cfun)
7907     {
7908       saved_class_ptr = current_class_ptr;
7909       cp_function_chain->x_current_class_ptr = NULL_TREE;
7910       saved_class_ref = current_class_ref;
7911       cp_function_chain->x_current_class_ref = NULL_TREE;
7912     }
7913
7914   push_deferring_access_checks(dk_no_deferred);
7915   /* The default argument expression may cause implicitly defined
7916      member functions to be synthesized, which will result in garbage
7917      collection.  We must treat this situation as if we were within
7918      the body of function so as to avoid collecting live data on the
7919      stack.  */
7920   ++function_depth;
7921   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
7922                      tf_warning_or_error, NULL_TREE,
7923                      /*integral_constant_expression_p=*/false);
7924   --function_depth;
7925   pop_deferring_access_checks();
7926
7927   /* Restore the "this" pointer.  */
7928   if (cfun)
7929     {
7930       cp_function_chain->x_current_class_ptr = saved_class_ptr;
7931       cp_function_chain->x_current_class_ref = saved_class_ref;
7932     }
7933
7934   pop_access_scope (fn);
7935
7936   /* Make sure the default argument is reasonable.  */
7937   arg = check_default_argument (type, arg);
7938
7939   return arg;
7940 }
7941
7942 /* Substitute into all the default arguments for FN.  */
7943
7944 static void
7945 tsubst_default_arguments (tree fn)
7946 {
7947   tree arg;
7948   tree tmpl_args;
7949
7950   tmpl_args = DECL_TI_ARGS (fn);
7951
7952   /* If this function is not yet instantiated, we certainly don't need
7953      its default arguments.  */
7954   if (uses_template_parms (tmpl_args))
7955     return;
7956
7957   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
7958        arg;
7959        arg = TREE_CHAIN (arg))
7960     if (TREE_PURPOSE (arg))
7961       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
7962                                                     TREE_VALUE (arg),
7963                                                     TREE_PURPOSE (arg));
7964 }
7965
7966 /* Substitute the ARGS into the T, which is a _DECL.  Return the
7967    result of the substitution.  Issue error and warning messages under
7968    control of COMPLAIN.  */
7969
7970 static tree
7971 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
7972 {
7973   location_t saved_loc;
7974   tree r = NULL_TREE;
7975   tree in_decl = t;
7976
7977   /* Set the filename and linenumber to improve error-reporting.  */
7978   saved_loc = input_location;
7979   input_location = DECL_SOURCE_LOCATION (t);
7980
7981   switch (TREE_CODE (t))
7982     {
7983     case TEMPLATE_DECL:
7984       {
7985         /* We can get here when processing a member function template,
7986            member class template, and template template parameter of
7987            a template class.  */
7988         tree decl = DECL_TEMPLATE_RESULT (t);
7989         tree spec;
7990         tree tmpl_args;
7991         tree full_args;
7992
7993         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
7994           {
7995             /* Template template parameter is treated here.  */
7996             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
7997             if (new_type == error_mark_node)
7998               return error_mark_node;
7999
8000             r = copy_decl (t);
8001             TREE_CHAIN (r) = NULL_TREE;
8002             TREE_TYPE (r) = new_type;
8003             DECL_TEMPLATE_RESULT (r)
8004               = build_decl (TYPE_DECL, DECL_NAME (decl), new_type);
8005             DECL_TEMPLATE_PARMS (r)
8006               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8007                                        complain);
8008             TYPE_NAME (new_type) = r;
8009             break;
8010           }
8011
8012         /* We might already have an instance of this template.
8013            The ARGS are for the surrounding class type, so the
8014            full args contain the tsubst'd args for the context,
8015            plus the innermost args from the template decl.  */
8016         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8017           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8018           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8019         /* Because this is a template, the arguments will still be
8020            dependent, even after substitution.  If
8021            PROCESSING_TEMPLATE_DECL is not set, the dependency
8022            predicates will short-circuit.  */
8023         ++processing_template_decl;
8024         full_args = tsubst_template_args (tmpl_args, args,
8025                                           complain, in_decl);
8026         --processing_template_decl;
8027         if (full_args == error_mark_node)
8028           return error_mark_node;
8029
8030         /* tsubst_template_args doesn't copy the vector if
8031            nothing changed.  But, *something* should have
8032            changed.  */
8033         gcc_assert (full_args != tmpl_args);
8034
8035         spec = retrieve_specialization (t, full_args,
8036                                         /*class_specializations_p=*/true);
8037         if (spec != NULL_TREE)
8038           {
8039             r = spec;
8040             break;
8041           }
8042
8043         /* Make a new template decl.  It will be similar to the
8044            original, but will record the current template arguments.
8045            We also create a new function declaration, which is just
8046            like the old one, but points to this new template, rather
8047            than the old one.  */
8048         r = copy_decl (t);
8049         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
8050         TREE_CHAIN (r) = NULL_TREE;
8051
8052         DECL_TEMPLATE_INFO (r) = build_tree_list (t, args);
8053
8054         if (TREE_CODE (decl) == TYPE_DECL)
8055           {
8056             tree new_type;
8057             ++processing_template_decl;
8058             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8059             --processing_template_decl;
8060             if (new_type == error_mark_node)
8061               return error_mark_node;
8062
8063             TREE_TYPE (r) = new_type;
8064             CLASSTYPE_TI_TEMPLATE (new_type) = r;
8065             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
8066             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
8067             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
8068           }
8069         else
8070           {
8071             tree new_decl;
8072             ++processing_template_decl;
8073             new_decl = tsubst (decl, args, complain, in_decl);
8074             --processing_template_decl;
8075             if (new_decl == error_mark_node)
8076               return error_mark_node;
8077
8078             DECL_TEMPLATE_RESULT (r) = new_decl;
8079             DECL_TI_TEMPLATE (new_decl) = r;
8080             TREE_TYPE (r) = TREE_TYPE (new_decl);
8081             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
8082             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
8083           }
8084
8085         SET_DECL_IMPLICIT_INSTANTIATION (r);
8086         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
8087         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
8088
8089         /* The template parameters for this new template are all the
8090            template parameters for the old template, except the
8091            outermost level of parameters.  */
8092         DECL_TEMPLATE_PARMS (r)
8093           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8094                                    complain);
8095
8096         if (PRIMARY_TEMPLATE_P (t))
8097           DECL_PRIMARY_TEMPLATE (r) = r;
8098
8099         if (TREE_CODE (decl) != TYPE_DECL)
8100           /* Record this non-type partial instantiation.  */
8101           register_specialization (r, t,
8102                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
8103                                    false);
8104       }
8105       break;
8106
8107     case FUNCTION_DECL:
8108       {
8109         tree ctx;
8110         tree argvec = NULL_TREE;
8111         tree *friends;
8112         tree gen_tmpl;
8113         tree type;
8114         int member;
8115         int args_depth;
8116         int parms_depth;
8117
8118         /* Nobody should be tsubst'ing into non-template functions.  */
8119         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
8120
8121         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
8122           {
8123             tree spec;
8124             bool dependent_p;
8125
8126             /* If T is not dependent, just return it.  We have to
8127                increment PROCESSING_TEMPLATE_DECL because
8128                value_dependent_expression_p assumes that nothing is
8129                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
8130             ++processing_template_decl;
8131             dependent_p = value_dependent_expression_p (t);
8132             --processing_template_decl;
8133             if (!dependent_p)
8134               return t;
8135
8136             /* Calculate the most general template of which R is a
8137                specialization, and the complete set of arguments used to
8138                specialize R.  */
8139             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
8140             argvec = tsubst_template_args (DECL_TI_ARGS
8141                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
8142                                            args, complain, in_decl);
8143
8144             /* Check to see if we already have this specialization.  */
8145             spec = retrieve_specialization (gen_tmpl, argvec,
8146                                             /*class_specializations_p=*/false);
8147
8148             if (spec)
8149               {
8150                 r = spec;
8151                 break;
8152               }
8153
8154             /* We can see more levels of arguments than parameters if
8155                there was a specialization of a member template, like
8156                this:
8157
8158                  template <class T> struct S { template <class U> void f(); }
8159                  template <> template <class U> void S<int>::f(U);
8160
8161                Here, we'll be substituting into the specialization,
8162                because that's where we can find the code we actually
8163                want to generate, but we'll have enough arguments for
8164                the most general template.
8165
8166                We also deal with the peculiar case:
8167
8168                  template <class T> struct S {
8169                    template <class U> friend void f();
8170                  };
8171                  template <class U> void f() {}
8172                  template S<int>;
8173                  template void f<double>();
8174
8175                Here, the ARGS for the instantiation of will be {int,
8176                double}.  But, we only need as many ARGS as there are
8177                levels of template parameters in CODE_PATTERN.  We are
8178                careful not to get fooled into reducing the ARGS in
8179                situations like:
8180
8181                  template <class T> struct S { template <class U> void f(U); }
8182                  template <class T> template <> void S<T>::f(int) {}
8183
8184                which we can spot because the pattern will be a
8185                specialization in this case.  */
8186             args_depth = TMPL_ARGS_DEPTH (args);
8187             parms_depth =
8188               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
8189             if (args_depth > parms_depth
8190                 && !DECL_TEMPLATE_SPECIALIZATION (t))
8191               args = get_innermost_template_args (args, parms_depth);
8192           }
8193         else
8194           {
8195             /* This special case arises when we have something like this:
8196
8197                  template <class T> struct S {
8198                    friend void f<int>(int, double);
8199                  };
8200
8201                Here, the DECL_TI_TEMPLATE for the friend declaration
8202                will be an IDENTIFIER_NODE.  We are being called from
8203                tsubst_friend_function, and we want only to create a
8204                new decl (R) with appropriate types so that we can call
8205                determine_specialization.  */
8206             gen_tmpl = NULL_TREE;
8207           }
8208
8209         if (DECL_CLASS_SCOPE_P (t))
8210           {
8211             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
8212               member = 2;
8213             else
8214               member = 1;
8215             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
8216                                     complain, t, /*entering_scope=*/1);
8217           }
8218         else
8219           {
8220             member = 0;
8221             ctx = DECL_CONTEXT (t);
8222           }
8223         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8224         if (type == error_mark_node)
8225           return error_mark_node;
8226
8227         /* We do NOT check for matching decls pushed separately at this
8228            point, as they may not represent instantiations of this
8229            template, and in any case are considered separate under the
8230            discrete model.  */
8231         r = copy_decl (t);
8232         DECL_USE_TEMPLATE (r) = 0;
8233         TREE_TYPE (r) = type;
8234         /* Clear out the mangled name and RTL for the instantiation.  */
8235         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8236         SET_DECL_RTL (r, NULL_RTX);
8237         /* Leave DECL_INITIAL set on deleted instantiations.  */
8238         if (!DECL_DELETED_FN (r))
8239           DECL_INITIAL (r) = NULL_TREE;
8240         DECL_CONTEXT (r) = ctx;
8241
8242         if (member && DECL_CONV_FN_P (r))
8243           /* Type-conversion operator.  Reconstruct the name, in
8244              case it's the name of one of the template's parameters.  */
8245           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
8246
8247         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
8248                                      complain, t);
8249         DECL_RESULT (r) = NULL_TREE;
8250
8251         TREE_STATIC (r) = 0;
8252         TREE_PUBLIC (r) = TREE_PUBLIC (t);
8253         DECL_EXTERNAL (r) = 1;
8254         /* If this is an instantiation of a function with internal
8255            linkage, we already know what object file linkage will be
8256            assigned to the instantiation.  */
8257         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
8258         DECL_DEFER_OUTPUT (r) = 0;
8259         TREE_CHAIN (r) = NULL_TREE;
8260         DECL_PENDING_INLINE_INFO (r) = 0;
8261         DECL_PENDING_INLINE_P (r) = 0;
8262         DECL_SAVED_TREE (r) = NULL_TREE;
8263         DECL_STRUCT_FUNCTION (r) = NULL;
8264         TREE_USED (r) = 0;
8265         if (DECL_CLONED_FUNCTION (r))
8266           {
8267             DECL_CLONED_FUNCTION (r) = tsubst (DECL_CLONED_FUNCTION (t),
8268                                                args, complain, t);
8269             TREE_CHAIN (r) = TREE_CHAIN (DECL_CLONED_FUNCTION (r));
8270             TREE_CHAIN (DECL_CLONED_FUNCTION (r)) = r;
8271           }
8272
8273         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
8274            this in the special friend case mentioned above where
8275            GEN_TMPL is NULL.  */
8276         if (gen_tmpl)
8277           {
8278             DECL_TEMPLATE_INFO (r)
8279               = tree_cons (gen_tmpl, argvec, NULL_TREE);
8280             SET_DECL_IMPLICIT_INSTANTIATION (r);
8281             register_specialization (r, gen_tmpl, argvec, false);
8282
8283             /* We're not supposed to instantiate default arguments
8284                until they are called, for a template.  But, for a
8285                declaration like:
8286
8287                  template <class T> void f ()
8288                  { extern void g(int i = T()); }
8289
8290                we should do the substitution when the template is
8291                instantiated.  We handle the member function case in
8292                instantiate_class_template since the default arguments
8293                might refer to other members of the class.  */
8294             if (!member
8295                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
8296                 && !uses_template_parms (argvec))
8297               tsubst_default_arguments (r);
8298           }
8299         else
8300           DECL_TEMPLATE_INFO (r) = NULL_TREE;
8301
8302         /* Copy the list of befriending classes.  */
8303         for (friends = &DECL_BEFRIENDING_CLASSES (r);
8304              *friends;
8305              friends = &TREE_CHAIN (*friends))
8306           {
8307             *friends = copy_node (*friends);
8308             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
8309                                             args, complain,
8310                                             in_decl);
8311           }
8312
8313         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
8314           {
8315             maybe_retrofit_in_chrg (r);
8316             if (DECL_CONSTRUCTOR_P (r))
8317               grok_ctor_properties (ctx, r);
8318             /* If this is an instantiation of a member template, clone it.
8319                If it isn't, that'll be handled by
8320                clone_constructors_and_destructors.  */
8321             if (PRIMARY_TEMPLATE_P (gen_tmpl))
8322               clone_function_decl (r, /*update_method_vec_p=*/0);
8323           }
8324         else if (IDENTIFIER_OPNAME_P (DECL_NAME (r))
8325                  && !grok_op_properties (r, (complain & tf_error) != 0))
8326           return error_mark_node;
8327
8328         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
8329           SET_DECL_FRIEND_CONTEXT (r,
8330                                    tsubst (DECL_FRIEND_CONTEXT (t),
8331                                             args, complain, in_decl));
8332
8333         /* Possibly limit visibility based on template args.  */
8334         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8335         if (DECL_VISIBILITY_SPECIFIED (t))
8336           {
8337             DECL_VISIBILITY_SPECIFIED (r) = 0;
8338             DECL_ATTRIBUTES (r)
8339               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8340           }
8341         determine_visibility (r);
8342
8343         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8344                                         args, complain, in_decl);
8345       }
8346       break;
8347
8348     case PARM_DECL:
8349       {
8350         tree type = NULL_TREE;
8351         int i, len = 1;
8352         tree expanded_types = NULL_TREE;
8353         tree prev_r = NULL_TREE;
8354         tree first_r = NULL_TREE;
8355
8356         if (FUNCTION_PARAMETER_PACK_P (t))
8357           {
8358             /* If there is a local specialization that isn't a
8359                parameter pack, it means that we're doing a "simple"
8360                substitution from inside tsubst_pack_expansion. Just
8361                return the local specialization (which will be a single
8362                parm).  */
8363             tree spec = retrieve_local_specialization (t);
8364             if (spec 
8365                 && TREE_CODE (spec) == PARM_DECL
8366                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
8367               return spec;
8368
8369             /* Expand the TYPE_PACK_EXPANSION that provides the types for
8370                the parameters in this function parameter pack.  */
8371             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
8372                                                     complain, in_decl);
8373             if (TREE_CODE (expanded_types) == TREE_VEC)
8374               {
8375                 len = TREE_VEC_LENGTH (expanded_types);
8376
8377                 /* Zero-length parameter packs are boring. Just substitute
8378                    into the chain.  */
8379                 if (len == 0)
8380                   return tsubst (TREE_CHAIN (t), args, complain, 
8381                                  TREE_CHAIN (t));
8382               }
8383             else
8384               {
8385                 /* All we did was update the type. Make a note of that.  */
8386                 type = expanded_types;
8387                 expanded_types = NULL_TREE;
8388               }
8389           }
8390
8391         /* Loop through all of the parameter's we'll build. When T is
8392            a function parameter pack, LEN is the number of expanded
8393            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
8394         r = NULL_TREE;
8395         for (i = 0; i < len; ++i)
8396           {
8397             prev_r = r;
8398             r = copy_node (t);
8399             if (DECL_TEMPLATE_PARM_P (t))
8400               SET_DECL_TEMPLATE_PARM_P (r);
8401
8402             if (expanded_types)
8403               /* We're on the Ith parameter of the function parameter
8404                  pack.  */
8405               {
8406                 /* Get the Ith type.  */
8407                 type = TREE_VEC_ELT (expanded_types, i);
8408
8409                 if (DECL_NAME (r))
8410                   /* Rename the parameter to include the index.  */
8411                   DECL_NAME (r) =
8412                     make_ith_pack_parameter_name (DECL_NAME (r), i);
8413               }
8414             else if (!type)
8415               /* We're dealing with a normal parameter.  */
8416               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8417
8418             type = type_decays_to (type);
8419             TREE_TYPE (r) = type;
8420             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8421
8422             if (DECL_INITIAL (r))
8423               {
8424                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
8425                   DECL_INITIAL (r) = TREE_TYPE (r);
8426                 else
8427                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
8428                                              complain, in_decl);
8429               }
8430
8431             DECL_CONTEXT (r) = NULL_TREE;
8432
8433             if (!DECL_TEMPLATE_PARM_P (r))
8434               DECL_ARG_TYPE (r) = type_passed_as (type);
8435
8436             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8437                                             args, complain, in_decl);
8438
8439             /* Keep track of the first new parameter we
8440                generate. That's what will be returned to the
8441                caller.  */
8442             if (!first_r)
8443               first_r = r;
8444
8445             /* Build a proper chain of parameters when substituting
8446                into a function parameter pack.  */
8447             if (prev_r)
8448               TREE_CHAIN (prev_r) = r;
8449           }
8450
8451         if (TREE_CHAIN (t))
8452           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
8453                                    complain, TREE_CHAIN (t));
8454
8455         /* FIRST_R contains the start of the chain we've built.  */
8456         r = first_r;
8457       }
8458       break;
8459
8460     case FIELD_DECL:
8461       {
8462         tree type;
8463
8464         r = copy_decl (t);
8465         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8466         if (type == error_mark_node)
8467           return error_mark_node;
8468         TREE_TYPE (r) = type;
8469         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8470
8471         /* DECL_INITIAL gives the number of bits in a bit-field.  */
8472         DECL_INITIAL (r)
8473           = tsubst_expr (DECL_INITIAL (t), args,
8474                          complain, in_decl,
8475                          /*integral_constant_expression_p=*/true);
8476         /* We don't have to set DECL_CONTEXT here; it is set by
8477            finish_member_declaration.  */
8478         TREE_CHAIN (r) = NULL_TREE;
8479         if (VOID_TYPE_P (type))
8480           error ("instantiation of %q+D as type %qT", r, type);
8481
8482         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8483                                         args, complain, in_decl);
8484       }
8485       break;
8486
8487     case USING_DECL:
8488       /* We reach here only for member using decls.  */
8489       if (DECL_DEPENDENT_P (t))
8490         {
8491           r = do_class_using_decl
8492             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
8493              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
8494           if (!r)
8495             r = error_mark_node;
8496           else
8497             {
8498               TREE_PROTECTED (r) = TREE_PROTECTED (t);
8499               TREE_PRIVATE (r) = TREE_PRIVATE (t);
8500             }
8501         }
8502       else
8503         {
8504           r = copy_node (t);
8505           TREE_CHAIN (r) = NULL_TREE;
8506         }
8507       break;
8508
8509     case TYPE_DECL:
8510     case VAR_DECL:
8511       {
8512         tree argvec = NULL_TREE;
8513         tree gen_tmpl = NULL_TREE;
8514         tree spec;
8515         tree tmpl = NULL_TREE;
8516         tree ctx;
8517         tree type = NULL_TREE;
8518         bool local_p;
8519
8520         if (TREE_CODE (t) == TYPE_DECL
8521             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
8522           {
8523             /* If this is the canonical decl, we don't have to
8524                mess with instantiations, and often we can't (for
8525                typename, template type parms and such).  Note that
8526                TYPE_NAME is not correct for the above test if
8527                we've copied the type for a typedef.  */
8528             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8529             if (type == error_mark_node)
8530               return error_mark_node;
8531             r = TYPE_NAME (type);
8532             break;
8533           }
8534
8535         /* Check to see if we already have the specialization we
8536            need.  */
8537         spec = NULL_TREE;
8538         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
8539           {
8540             /* T is a static data member or namespace-scope entity.
8541                We have to substitute into namespace-scope variables
8542                (even though such entities are never templates) because
8543                of cases like:
8544                
8545                  template <class T> void f() { extern T t; }
8546
8547                where the entity referenced is not known until
8548                instantiation time.  */
8549             local_p = false;
8550             ctx = DECL_CONTEXT (t);
8551             if (DECL_CLASS_SCOPE_P (t))
8552               {
8553                 ctx = tsubst_aggr_type (ctx, args,
8554                                         complain,
8555                                         in_decl, /*entering_scope=*/1);
8556                 /* If CTX is unchanged, then T is in fact the
8557                    specialization we want.  That situation occurs when
8558                    referencing a static data member within in its own
8559                    class.  We can use pointer equality, rather than
8560                    same_type_p, because DECL_CONTEXT is always
8561                    canonical.  */
8562                 if (ctx == DECL_CONTEXT (t))
8563                   spec = t;
8564               }
8565
8566             if (!spec)
8567               {
8568                 tmpl = DECL_TI_TEMPLATE (t);
8569                 gen_tmpl = most_general_template (tmpl);
8570                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
8571                 spec = (retrieve_specialization 
8572                         (gen_tmpl, argvec,
8573                          /*class_specializations_p=*/false));
8574               }
8575           }
8576         else
8577           {
8578             /* A local variable.  */
8579             local_p = true;
8580             /* Subsequent calls to pushdecl will fill this in.  */
8581             ctx = NULL_TREE;
8582             spec = retrieve_local_specialization (t);
8583           }
8584         /* If we already have the specialization we need, there is
8585            nothing more to do.  */ 
8586         if (spec)
8587           {
8588             r = spec;
8589             break;
8590           }
8591
8592         /* Create a new node for the specialization we need.  */
8593         r = copy_decl (t);
8594         if (type == NULL_TREE)
8595           type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8596         if (TREE_CODE (r) == VAR_DECL)
8597           {
8598             /* Even if the original location is out of scope, the
8599                newly substituted one is not.  */
8600             DECL_DEAD_FOR_LOCAL (r) = 0;
8601             DECL_INITIALIZED_P (r) = 0;
8602             DECL_TEMPLATE_INSTANTIATED (r) = 0;
8603             if (type == error_mark_node)
8604               return error_mark_node;
8605             if (TREE_CODE (type) == FUNCTION_TYPE)
8606               {
8607                 /* It may seem that this case cannot occur, since:
8608
8609                      typedef void f();
8610                      void g() { f x; }
8611
8612                    declares a function, not a variable.  However:
8613       
8614                      typedef void f();
8615                      template <typename T> void g() { T t; }
8616                      template void g<f>();
8617
8618                    is an attempt to declare a variable with function
8619                    type.  */
8620                 error ("variable %qD has function type",
8621                        /* R is not yet sufficiently initialized, so we
8622                           just use its name.  */
8623                        DECL_NAME (r));
8624                 return error_mark_node;
8625               }
8626             type = complete_type (type);
8627             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
8628               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
8629             type = check_var_type (DECL_NAME (r), type);
8630
8631             if (DECL_HAS_VALUE_EXPR_P (t))
8632               {
8633                 tree ve = DECL_VALUE_EXPR (t);
8634                 ve = tsubst_expr (ve, args, complain, in_decl,
8635                                   /*constant_expression_p=*/false);
8636                 SET_DECL_VALUE_EXPR (r, ve);
8637               }
8638           }
8639         else if (DECL_SELF_REFERENCE_P (t))
8640           SET_DECL_SELF_REFERENCE_P (r);
8641         TREE_TYPE (r) = type;
8642         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8643         DECL_CONTEXT (r) = ctx;
8644         /* Clear out the mangled name and RTL for the instantiation.  */
8645         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8646         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8647           SET_DECL_RTL (r, NULL_RTX);
8648         /* The initializer must not be expanded until it is required;
8649            see [temp.inst].  */
8650         DECL_INITIAL (r) = NULL_TREE;
8651         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8652           SET_DECL_RTL (r, NULL_RTX);
8653         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
8654         if (TREE_CODE (r) == VAR_DECL)
8655           {
8656             /* Possibly limit visibility based on template args.  */
8657             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8658             if (DECL_VISIBILITY_SPECIFIED (t))
8659               {
8660                 DECL_VISIBILITY_SPECIFIED (r) = 0;
8661                 DECL_ATTRIBUTES (r)
8662                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8663               }
8664             determine_visibility (r);
8665           }
8666         /* Preserve a typedef that names a type.  */
8667         else if (TREE_CODE (r) == TYPE_DECL
8668                  && DECL_ORIGINAL_TYPE (t)
8669                  && type != error_mark_node)
8670           {
8671             DECL_ORIGINAL_TYPE (r) = tsubst (DECL_ORIGINAL_TYPE (t),
8672                                              args, complain, in_decl);
8673             TREE_TYPE (r) = type = build_variant_type_copy (type);
8674             TYPE_NAME (type) = r;
8675           }
8676
8677         if (!local_p)
8678           {
8679             /* A static data member declaration is always marked
8680                external when it is declared in-class, even if an
8681                initializer is present.  We mimic the non-template
8682                processing here.  */
8683             DECL_EXTERNAL (r) = 1;
8684
8685             register_specialization (r, gen_tmpl, argvec, false);
8686             DECL_TEMPLATE_INFO (r) = tree_cons (tmpl, argvec, NULL_TREE);
8687             SET_DECL_IMPLICIT_INSTANTIATION (r);
8688           }
8689         else
8690           register_local_specialization (r, t);
8691
8692         TREE_CHAIN (r) = NULL_TREE;
8693
8694         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
8695                                         (int) ATTR_FLAG_TYPE_IN_PLACE,
8696                                         args, complain, in_decl);
8697         layout_decl (r, 0);
8698       }
8699       break;
8700
8701     default:
8702       gcc_unreachable ();
8703     }
8704
8705   /* Restore the file and line information.  */
8706   input_location = saved_loc;
8707
8708   return r;
8709 }
8710
8711 /* Substitute into the ARG_TYPES of a function type.  */
8712
8713 static tree
8714 tsubst_arg_types (tree arg_types,
8715                   tree args,
8716                   tsubst_flags_t complain,
8717                   tree in_decl)
8718 {
8719   tree remaining_arg_types;
8720   tree type = NULL_TREE;
8721   int i = 1;
8722   tree expanded_args = NULL_TREE;
8723   tree default_arg;
8724
8725   if (!arg_types || arg_types == void_list_node)
8726     return arg_types;
8727
8728   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
8729                                           args, complain, in_decl);
8730   if (remaining_arg_types == error_mark_node)
8731     return error_mark_node;
8732
8733   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
8734     {
8735       /* For a pack expansion, perform substitution on the
8736          entire expression. Later on, we'll handle the arguments
8737          one-by-one.  */
8738       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
8739                                             args, complain, in_decl);
8740
8741       if (TREE_CODE (expanded_args) == TREE_VEC)
8742         /* So that we'll spin through the parameters, one by one.  */
8743         i = TREE_VEC_LENGTH (expanded_args);
8744       else
8745         {
8746           /* We only partially substituted into the parameter
8747              pack. Our type is TYPE_PACK_EXPANSION.  */
8748           type = expanded_args;
8749           expanded_args = NULL_TREE;
8750         }
8751     }
8752
8753   while (i > 0) {
8754     --i;
8755     
8756     if (expanded_args)
8757       type = TREE_VEC_ELT (expanded_args, i);
8758     else if (!type)
8759       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
8760
8761     if (type == error_mark_node)
8762       return error_mark_node;
8763     if (VOID_TYPE_P (type))
8764       {
8765         if (complain & tf_error)
8766           {
8767             error ("invalid parameter type %qT", type);
8768             if (in_decl)
8769               error ("in declaration %q+D", in_decl);
8770           }
8771         return error_mark_node;
8772     }
8773     
8774     /* Do array-to-pointer, function-to-pointer conversion, and ignore
8775        top-level qualifiers as required.  */
8776     type = TYPE_MAIN_VARIANT (type_decays_to (type));
8777
8778     /* We do not substitute into default arguments here.  The standard
8779        mandates that they be instantiated only when needed, which is
8780        done in build_over_call.  */
8781     default_arg = TREE_PURPOSE (arg_types);
8782
8783     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
8784       {
8785         /* We've instantiated a template before its default arguments
8786            have been parsed.  This can happen for a nested template
8787            class, and is not an error unless we require the default
8788            argument in a call of this function.  */
8789         remaining_arg_types = 
8790           tree_cons (default_arg, type, remaining_arg_types);
8791         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
8792                        remaining_arg_types);
8793       }
8794     else
8795       remaining_arg_types = 
8796         hash_tree_cons (default_arg, type, remaining_arg_types);
8797   }
8798         
8799   return remaining_arg_types;
8800 }
8801
8802 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
8803    *not* handle the exception-specification for FNTYPE, because the
8804    initial substitution of explicitly provided template parameters
8805    during argument deduction forbids substitution into the
8806    exception-specification:
8807
8808      [temp.deduct]
8809
8810      All references in the function type of the function template to  the
8811      corresponding template parameters are replaced by the specified tem-
8812      plate argument values.  If a substitution in a template parameter or
8813      in  the function type of the function template results in an invalid
8814      type, type deduction fails.  [Note: The equivalent  substitution  in
8815      exception specifications is done only when the function is instanti-
8816      ated, at which point a program is  ill-formed  if  the  substitution
8817      results in an invalid type.]  */
8818
8819 static tree
8820 tsubst_function_type (tree t,
8821                       tree args,
8822                       tsubst_flags_t complain,
8823                       tree in_decl)
8824 {
8825   tree return_type;
8826   tree arg_types;
8827   tree fntype;
8828
8829   /* The TYPE_CONTEXT is not used for function/method types.  */
8830   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
8831
8832   /* Substitute the return type.  */
8833   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8834   if (return_type == error_mark_node)
8835     return error_mark_node;
8836   /* The standard does not presently indicate that creation of a
8837      function type with an invalid return type is a deduction failure.
8838      However, that is clearly analogous to creating an array of "void"
8839      or a reference to a reference.  This is core issue #486.  */
8840   if (TREE_CODE (return_type) == ARRAY_TYPE
8841       || TREE_CODE (return_type) == FUNCTION_TYPE)
8842     {
8843       if (complain & tf_error)
8844         {
8845           if (TREE_CODE (return_type) == ARRAY_TYPE)
8846             error ("function returning an array");
8847           else
8848             error ("function returning a function");
8849         }
8850       return error_mark_node;
8851     }
8852
8853   /* Substitute the argument types.  */
8854   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
8855                                 complain, in_decl);
8856   if (arg_types == error_mark_node)
8857     return error_mark_node;
8858
8859   /* Construct a new type node and return it.  */
8860   if (TREE_CODE (t) == FUNCTION_TYPE)
8861     fntype = build_function_type (return_type, arg_types);
8862   else
8863     {
8864       tree r = TREE_TYPE (TREE_VALUE (arg_types));
8865       if (! MAYBE_CLASS_TYPE_P (r))
8866         {
8867           /* [temp.deduct]
8868
8869              Type deduction may fail for any of the following
8870              reasons:
8871
8872              -- Attempting to create "pointer to member of T" when T
8873              is not a class type.  */
8874           if (complain & tf_error)
8875             error ("creating pointer to member function of non-class type %qT",
8876                       r);
8877           return error_mark_node;
8878         }
8879
8880       fntype = build_method_type_directly (r, return_type,
8881                                            TREE_CHAIN (arg_types));
8882     }
8883   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
8884   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
8885
8886   return fntype;
8887 }
8888
8889 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
8890    ARGS into that specification, and return the substituted
8891    specification.  If there is no specification, return NULL_TREE.  */
8892
8893 static tree
8894 tsubst_exception_specification (tree fntype,
8895                                 tree args,
8896                                 tsubst_flags_t complain,
8897                                 tree in_decl)
8898 {
8899   tree specs;
8900   tree new_specs;
8901
8902   specs = TYPE_RAISES_EXCEPTIONS (fntype);
8903   new_specs = NULL_TREE;
8904   if (specs)
8905     {
8906       if (! TREE_VALUE (specs))
8907         new_specs = specs;
8908       else
8909         while (specs)
8910           {
8911             tree spec;
8912             int i, len = 1;
8913             tree expanded_specs = NULL_TREE;
8914
8915             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
8916               {
8917                 /* Expand the pack expansion type.  */
8918                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
8919                                                        args, complain,
8920                                                        in_decl);
8921
8922                 if (expanded_specs == error_mark_node)
8923                   return error_mark_node;
8924                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
8925                   len = TREE_VEC_LENGTH (expanded_specs);
8926                 else
8927                   {
8928                     /* We're substituting into a member template, so
8929                        we got a TYPE_PACK_EXPANSION back.  Add that
8930                        expansion and move on.  */
8931                     gcc_assert (TREE_CODE (expanded_specs) 
8932                                 == TYPE_PACK_EXPANSION);
8933                     new_specs = add_exception_specifier (new_specs,
8934                                                          expanded_specs,
8935                                                          complain);
8936                     specs = TREE_CHAIN (specs);
8937                     continue;
8938                   }
8939               }
8940
8941             for (i = 0; i < len; ++i)
8942               {
8943                 if (expanded_specs)
8944                   spec = TREE_VEC_ELT (expanded_specs, i);
8945                 else
8946                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
8947                 if (spec == error_mark_node)
8948                   return spec;
8949                 new_specs = add_exception_specifier (new_specs, spec, 
8950                                                      complain);
8951               }
8952
8953             specs = TREE_CHAIN (specs);
8954           }
8955     }
8956   return new_specs;
8957 }
8958
8959 /* Take the tree structure T and replace template parameters used
8960    therein with the argument vector ARGS.  IN_DECL is an associated
8961    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
8962    Issue error and warning messages under control of COMPLAIN.  Note
8963    that we must be relatively non-tolerant of extensions here, in
8964    order to preserve conformance; if we allow substitutions that
8965    should not be allowed, we may allow argument deductions that should
8966    not succeed, and therefore report ambiguous overload situations
8967    where there are none.  In theory, we could allow the substitution,
8968    but indicate that it should have failed, and allow our caller to
8969    make sure that the right thing happens, but we don't try to do this
8970    yet.
8971
8972    This function is used for dealing with types, decls and the like;
8973    for expressions, use tsubst_expr or tsubst_copy.  */
8974
8975 static tree
8976 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8977 {
8978   tree type, r;
8979
8980   if (t == NULL_TREE || t == error_mark_node
8981       || t == integer_type_node
8982       || t == void_type_node
8983       || t == char_type_node
8984       || t == unknown_type_node
8985       || TREE_CODE (t) == NAMESPACE_DECL)
8986     return t;
8987
8988   if (DECL_P (t))
8989     return tsubst_decl (t, args, complain);
8990
8991   if (args == NULL_TREE)
8992     return t;
8993
8994   if (TREE_CODE (t) == IDENTIFIER_NODE)
8995     type = IDENTIFIER_TYPE_VALUE (t);
8996   else
8997     type = TREE_TYPE (t);
8998
8999   gcc_assert (type != unknown_type_node);
9000
9001   /* Reuse typedefs.  We need to do this to handle dependent attributes,
9002      such as attribute aligned.  */
9003   if (TYPE_P (t)
9004       && TYPE_NAME (t)
9005       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
9006     {
9007       tree decl = TYPE_NAME (t);
9008       
9009       if (DECL_CLASS_SCOPE_P (decl)
9010           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
9011           && uses_template_parms (DECL_CONTEXT (decl)))
9012         {
9013           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
9014           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
9015           r = retrieve_specialization (tmpl, gen_args, false);
9016         }
9017       else if (DECL_FUNCTION_SCOPE_P (decl)
9018                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
9019                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
9020         r = retrieve_local_specialization (decl);
9021       else
9022         /* The typedef is from a non-template context.  */
9023         return t;
9024
9025       if (r)
9026         {
9027           r = TREE_TYPE (r);
9028           r = cp_build_qualified_type_real
9029             (r, cp_type_quals (t) | cp_type_quals (r),
9030              complain | tf_ignore_bad_quals);
9031           return r;
9032         }
9033       /* Else we must be instantiating the typedef, so fall through.  */
9034     }
9035
9036   if (type
9037       && TREE_CODE (t) != TYPENAME_TYPE
9038       && TREE_CODE (t) != IDENTIFIER_NODE
9039       && TREE_CODE (t) != FUNCTION_TYPE
9040       && TREE_CODE (t) != METHOD_TYPE)
9041     type = tsubst (type, args, complain, in_decl);
9042   if (type == error_mark_node)
9043     return error_mark_node;
9044
9045   switch (TREE_CODE (t))
9046     {
9047     case RECORD_TYPE:
9048     case UNION_TYPE:
9049     case ENUMERAL_TYPE:
9050       return tsubst_aggr_type (t, args, complain, in_decl,
9051                                /*entering_scope=*/0);
9052
9053     case ERROR_MARK:
9054     case IDENTIFIER_NODE:
9055     case VOID_TYPE:
9056     case REAL_TYPE:
9057     case COMPLEX_TYPE:
9058     case VECTOR_TYPE:
9059     case BOOLEAN_TYPE:
9060     case INTEGER_CST:
9061     case REAL_CST:
9062     case STRING_CST:
9063       return t;
9064
9065     case INTEGER_TYPE:
9066       if (t == integer_type_node)
9067         return t;
9068
9069       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
9070           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
9071         return t;
9072
9073       {
9074         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
9075
9076         max = tsubst_expr (omax, args, complain, in_decl,
9077                            /*integral_constant_expression_p=*/false);
9078         max = fold_decl_constant_value (max);
9079
9080         if (TREE_CODE (max) != INTEGER_CST
9081             && !at_function_scope_p ()
9082             && !value_dependent_expression_p (max))
9083           {
9084             if (complain & tf_error)
9085               error ("array bound is not an integer constant");
9086             return error_mark_node;
9087           }
9088
9089         /* [temp.deduct]
9090
9091            Type deduction may fail for any of the following
9092            reasons:
9093
9094              Attempting to create an array with a size that is
9095              zero or negative.  */
9096         if (integer_zerop (max) && !(complain & tf_error))
9097           /* We must fail if performing argument deduction (as
9098              indicated by the state of complain), so that
9099              another substitution can be found.  */
9100           return error_mark_node;
9101         else if (TREE_CODE (max) == INTEGER_CST
9102                  && INT_CST_LT (max, integer_zero_node))
9103           {
9104             if (complain & tf_error)
9105               error ("creating array with negative size (%qE)", max);
9106
9107             return error_mark_node;
9108           }
9109
9110         return compute_array_index_type (NULL_TREE, max);
9111       }
9112
9113     case TEMPLATE_TYPE_PARM:
9114     case TEMPLATE_TEMPLATE_PARM:
9115     case BOUND_TEMPLATE_TEMPLATE_PARM:
9116     case TEMPLATE_PARM_INDEX:
9117       {
9118         int idx;
9119         int level;
9120         int levels;
9121         tree arg = NULL_TREE;
9122
9123         r = NULL_TREE;
9124
9125         gcc_assert (TREE_VEC_LENGTH (args) > 0);
9126         template_parm_level_and_index (t, &level, &idx); 
9127
9128         levels = TMPL_ARGS_DEPTH (args);
9129         if (level <= levels)
9130           {
9131             arg = TMPL_ARG (args, level, idx);
9132
9133             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
9134               /* See through ARGUMENT_PACK_SELECT arguments. */
9135               arg = ARGUMENT_PACK_SELECT_ARG (arg);
9136           }
9137
9138         if (arg == error_mark_node)
9139           return error_mark_node;
9140         else if (arg != NULL_TREE)
9141           {
9142             if (ARGUMENT_PACK_P (arg))
9143               /* If ARG is an argument pack, we don't actually want to
9144                  perform a substitution here, because substitutions
9145                  for argument packs are only done
9146                  element-by-element. We can get to this point when
9147                  substituting the type of a non-type template
9148                  parameter pack, when that type actually contains
9149                  template parameter packs from an outer template, e.g.,
9150
9151                  template<typename... Types> struct A {
9152                    template<Types... Values> struct B { };
9153                  };  */
9154               return t;
9155
9156             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
9157               {
9158                 int quals;
9159                 gcc_assert (TYPE_P (arg));
9160
9161                 /* cv-quals from the template are discarded when
9162                    substituting in a function or reference type.  */
9163                 if (TREE_CODE (arg) == FUNCTION_TYPE
9164                     || TREE_CODE (arg) == METHOD_TYPE
9165                     || TREE_CODE (arg) == REFERENCE_TYPE)
9166                   quals = cp_type_quals (arg);
9167                 else
9168                   quals = cp_type_quals (arg) | cp_type_quals (t);
9169                   
9170                 return cp_build_qualified_type_real
9171                   (arg, quals, complain | tf_ignore_bad_quals);
9172               }
9173             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9174               {
9175                 /* We are processing a type constructed from a
9176                    template template parameter.  */
9177                 tree argvec = tsubst (TYPE_TI_ARGS (t),
9178                                       args, complain, in_decl);
9179                 if (argvec == error_mark_node)
9180                   return error_mark_node;
9181
9182                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
9183                    are resolving nested-types in the signature of a
9184                    member function templates.  Otherwise ARG is a
9185                    TEMPLATE_DECL and is the real template to be
9186                    instantiated.  */
9187                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
9188                   arg = TYPE_NAME (arg);
9189
9190                 r = lookup_template_class (arg,
9191                                            argvec, in_decl,
9192                                            DECL_CONTEXT (arg),
9193                                             /*entering_scope=*/0,
9194                                            complain);
9195                 return cp_build_qualified_type_real
9196                   (r, TYPE_QUALS (t), complain);
9197               }
9198             else
9199               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
9200               return arg;
9201           }
9202
9203         if (level == 1)
9204           /* This can happen during the attempted tsubst'ing in
9205              unify.  This means that we don't yet have any information
9206              about the template parameter in question.  */
9207           return t;
9208
9209         /* If we get here, we must have been looking at a parm for a
9210            more deeply nested template.  Make a new version of this
9211            template parameter, but with a lower level.  */
9212         switch (TREE_CODE (t))
9213           {
9214           case TEMPLATE_TYPE_PARM:
9215           case TEMPLATE_TEMPLATE_PARM:
9216           case BOUND_TEMPLATE_TEMPLATE_PARM:
9217             if (cp_type_quals (t))
9218               {
9219                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
9220                 r = cp_build_qualified_type_real
9221                   (r, cp_type_quals (t),
9222                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
9223                                ? tf_ignore_bad_quals : 0));
9224               }
9225             else
9226               {
9227                 r = copy_type (t);
9228                 TEMPLATE_TYPE_PARM_INDEX (r)
9229                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
9230                                                 r, levels, args, complain);
9231                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
9232                 TYPE_MAIN_VARIANT (r) = r;
9233                 TYPE_POINTER_TO (r) = NULL_TREE;
9234                 TYPE_REFERENCE_TO (r) = NULL_TREE;
9235
9236                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
9237                   /* We have reduced the level of the template
9238                      template parameter, but not the levels of its
9239                      template parameters, so canonical_type_parameter
9240                      will not be able to find the canonical template
9241                      template parameter for this level. Thus, we
9242                      require structural equality checking to compare
9243                      TEMPLATE_TEMPLATE_PARMs. */
9244                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9245                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
9246                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9247                 else
9248                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
9249
9250                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9251                   {
9252                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
9253                                           complain, in_decl);
9254                     if (argvec == error_mark_node)
9255                       return error_mark_node;
9256
9257                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
9258                       = tree_cons (TYPE_TI_TEMPLATE (t), argvec, NULL_TREE);
9259                   }
9260               }
9261             break;
9262
9263           case TEMPLATE_PARM_INDEX:
9264             r = reduce_template_parm_level (t, type, levels, args, complain);
9265             break;
9266
9267           default:
9268             gcc_unreachable ();
9269           }
9270
9271         return r;
9272       }
9273
9274     case TREE_LIST:
9275       {
9276         tree purpose, value, chain;
9277
9278         if (t == void_list_node)
9279           return t;
9280
9281         purpose = TREE_PURPOSE (t);
9282         if (purpose)
9283           {
9284             purpose = tsubst (purpose, args, complain, in_decl);
9285             if (purpose == error_mark_node)
9286               return error_mark_node;
9287           }
9288         value = TREE_VALUE (t);
9289         if (value)
9290           {
9291             value = tsubst (value, args, complain, in_decl);
9292             if (value == error_mark_node)
9293               return error_mark_node;
9294           }
9295         chain = TREE_CHAIN (t);
9296         if (chain && chain != void_type_node)
9297           {
9298             chain = tsubst (chain, args, complain, in_decl);
9299             if (chain == error_mark_node)
9300               return error_mark_node;
9301           }
9302         if (purpose == TREE_PURPOSE (t)
9303             && value == TREE_VALUE (t)
9304             && chain == TREE_CHAIN (t))
9305           return t;
9306         return hash_tree_cons (purpose, value, chain);
9307       }
9308
9309     case TREE_BINFO:
9310       /* We should never be tsubsting a binfo.  */
9311       gcc_unreachable ();
9312
9313     case TREE_VEC:
9314       /* A vector of template arguments.  */
9315       gcc_assert (!type);
9316       return tsubst_template_args (t, args, complain, in_decl);
9317
9318     case POINTER_TYPE:
9319     case REFERENCE_TYPE:
9320       {
9321         enum tree_code code;
9322
9323         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
9324           return t;
9325
9326         code = TREE_CODE (t);
9327
9328
9329         /* [temp.deduct]
9330
9331            Type deduction may fail for any of the following
9332            reasons:
9333
9334            -- Attempting to create a pointer to reference type.
9335            -- Attempting to create a reference to a reference type or
9336               a reference to void.
9337
9338           Core issue 106 says that creating a reference to a reference
9339           during instantiation is no longer a cause for failure. We
9340           only enforce this check in strict C++98 mode.  */
9341         if ((TREE_CODE (type) == REFERENCE_TYPE
9342              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
9343             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
9344           {
9345             static location_t last_loc;
9346
9347             /* We keep track of the last time we issued this error
9348                message to avoid spewing a ton of messages during a
9349                single bad template instantiation.  */
9350             if (complain & tf_error
9351                 && last_loc != input_location)
9352               {
9353                 if (TREE_CODE (type) == VOID_TYPE)
9354                   error ("forming reference to void");
9355                 else
9356                   error ("forming %s to reference type %qT",
9357                          (code == POINTER_TYPE) ? "pointer" : "reference",
9358                          type);
9359                 last_loc = input_location;
9360               }
9361
9362             return error_mark_node;
9363           }
9364         else if (code == POINTER_TYPE)
9365           {
9366             r = build_pointer_type (type);
9367             if (TREE_CODE (type) == METHOD_TYPE)
9368               r = build_ptrmemfunc_type (r);
9369           }
9370         else if (TREE_CODE (type) == REFERENCE_TYPE)
9371           /* In C++0x, during template argument substitution, when there is an
9372              attempt to create a reference to a reference type, reference
9373              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
9374
9375              "If a template-argument for a template-parameter T names a type
9376              that is a reference to a type A, an attempt to create the type
9377              'lvalue reference to cv T' creates the type 'lvalue reference to
9378              A,' while an attempt to create the type type rvalue reference to
9379              cv T' creates the type T"
9380           */
9381           r = cp_build_reference_type
9382               (TREE_TYPE (type),
9383                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
9384         else
9385           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
9386         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
9387
9388         if (r != error_mark_node)
9389           /* Will this ever be needed for TYPE_..._TO values?  */
9390           layout_type (r);
9391
9392         return r;
9393       }
9394     case OFFSET_TYPE:
9395       {
9396         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
9397         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
9398           {
9399             /* [temp.deduct]
9400
9401                Type deduction may fail for any of the following
9402                reasons:
9403
9404                -- Attempting to create "pointer to member of T" when T
9405                   is not a class type.  */
9406             if (complain & tf_error)
9407               error ("creating pointer to member of non-class type %qT", r);
9408             return error_mark_node;
9409           }
9410         if (TREE_CODE (type) == REFERENCE_TYPE)
9411           {
9412             if (complain & tf_error)
9413               error ("creating pointer to member reference type %qT", type);
9414             return error_mark_node;
9415           }
9416         if (TREE_CODE (type) == VOID_TYPE)
9417           {
9418             if (complain & tf_error)
9419               error ("creating pointer to member of type void");
9420             return error_mark_node;
9421           }
9422         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
9423         if (TREE_CODE (type) == FUNCTION_TYPE)
9424           {
9425             /* The type of the implicit object parameter gets its
9426                cv-qualifiers from the FUNCTION_TYPE. */
9427             tree method_type;
9428             tree this_type = cp_build_qualified_type (TYPE_MAIN_VARIANT (r),
9429                                                       cp_type_quals (type));
9430             tree memptr;
9431             method_type = build_method_type_directly (this_type,
9432                                                       TREE_TYPE (type),
9433                                                       TYPE_ARG_TYPES (type));
9434             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
9435             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
9436                                                  complain);
9437           }
9438         else
9439           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
9440                                                TYPE_QUALS (t),
9441                                                complain);
9442       }
9443     case FUNCTION_TYPE:
9444     case METHOD_TYPE:
9445       {
9446         tree fntype;
9447         tree specs;
9448         fntype = tsubst_function_type (t, args, complain, in_decl);
9449         if (fntype == error_mark_node)
9450           return error_mark_node;
9451
9452         /* Substitute the exception specification.  */
9453         specs = tsubst_exception_specification (t, args, complain,
9454                                                 in_decl);
9455         if (specs == error_mark_node)
9456           return error_mark_node;
9457         if (specs)
9458           fntype = build_exception_variant (fntype, specs);
9459         return fntype;
9460       }
9461     case ARRAY_TYPE:
9462       {
9463         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
9464         if (domain == error_mark_node)
9465           return error_mark_node;
9466
9467         /* As an optimization, we avoid regenerating the array type if
9468            it will obviously be the same as T.  */
9469         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
9470           return t;
9471
9472         /* These checks should match the ones in grokdeclarator.
9473
9474            [temp.deduct]
9475
9476            The deduction may fail for any of the following reasons:
9477
9478            -- Attempting to create an array with an element type that
9479               is void, a function type, or a reference type, or [DR337]
9480               an abstract class type.  */
9481         if (TREE_CODE (type) == VOID_TYPE
9482             || TREE_CODE (type) == FUNCTION_TYPE
9483             || TREE_CODE (type) == REFERENCE_TYPE)
9484           {
9485             if (complain & tf_error)
9486               error ("creating array of %qT", type);
9487             return error_mark_node;
9488           }
9489         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
9490           {
9491             if (complain & tf_error)
9492               error ("creating array of %qT, which is an abstract class type",
9493                      type);
9494             return error_mark_node;
9495           }
9496
9497         r = build_cplus_array_type (type, domain);
9498
9499         if (TYPE_USER_ALIGN (t))
9500           {
9501             TYPE_ALIGN (r) = TYPE_ALIGN (t);
9502             TYPE_USER_ALIGN (r) = 1;
9503           }
9504
9505         return r;
9506       }
9507
9508     case PLUS_EXPR:
9509     case MINUS_EXPR:
9510       {
9511         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9512         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9513
9514         if (e1 == error_mark_node || e2 == error_mark_node)
9515           return error_mark_node;
9516
9517         return fold_build2 (TREE_CODE (t), TREE_TYPE (t), e1, e2);
9518       }
9519
9520     case NEGATE_EXPR:
9521     case NOP_EXPR:
9522       {
9523         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9524         if (e == error_mark_node)
9525           return error_mark_node;
9526
9527         return fold_build1 (TREE_CODE (t), TREE_TYPE (t), e);
9528       }
9529
9530     case TYPENAME_TYPE:
9531       {
9532         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9533                                      in_decl, /*entering_scope=*/1);
9534         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
9535                               complain, in_decl);
9536
9537         if (ctx == error_mark_node || f == error_mark_node)
9538           return error_mark_node;
9539
9540         if (!MAYBE_CLASS_TYPE_P (ctx))
9541           {
9542             if (complain & tf_error)
9543               error ("%qT is not a class, struct, or union type", ctx);
9544             return error_mark_node;
9545           }
9546         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
9547           {
9548             /* Normally, make_typename_type does not require that the CTX
9549                have complete type in order to allow things like:
9550
9551                  template <class T> struct S { typename S<T>::X Y; };
9552
9553                But, such constructs have already been resolved by this
9554                point, so here CTX really should have complete type, unless
9555                it's a partial instantiation.  */
9556             ctx = complete_type (ctx);
9557             if (!COMPLETE_TYPE_P (ctx))
9558               {
9559                 if (complain & tf_error)
9560                   cxx_incomplete_type_error (NULL_TREE, ctx);
9561                 return error_mark_node;
9562               }
9563           }
9564
9565         f = make_typename_type (ctx, f, typename_type,
9566                                 (complain & tf_error) | tf_keep_type_decl);
9567         if (f == error_mark_node)
9568           return f;
9569         if (TREE_CODE (f) == TYPE_DECL)
9570           {
9571             complain |= tf_ignore_bad_quals;
9572             f = TREE_TYPE (f);
9573           }
9574
9575         if (TREE_CODE (f) != TYPENAME_TYPE)
9576           {
9577             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
9578               error ("%qT resolves to %qT, which is not an enumeration type",
9579                      t, f);
9580             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
9581               error ("%qT resolves to %qT, which is is not a class type",
9582                      t, f);
9583           }
9584
9585         return cp_build_qualified_type_real
9586           (f, cp_type_quals (f) | cp_type_quals (t), complain);
9587       }
9588
9589     case UNBOUND_CLASS_TEMPLATE:
9590       {
9591         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9592                                      in_decl, /*entering_scope=*/1);
9593         tree name = TYPE_IDENTIFIER (t);
9594         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
9595
9596         if (ctx == error_mark_node || name == error_mark_node)
9597           return error_mark_node;
9598
9599         if (parm_list)
9600           parm_list = tsubst_template_parms (parm_list, args, complain);
9601         return make_unbound_class_template (ctx, name, parm_list, complain);
9602       }
9603
9604     case INDIRECT_REF:
9605     case ADDR_EXPR:
9606     case CALL_EXPR:
9607       gcc_unreachable ();
9608
9609     case ARRAY_REF:
9610       {
9611         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9612         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
9613                                /*integral_constant_expression_p=*/false);
9614         if (e1 == error_mark_node || e2 == error_mark_node)
9615           return error_mark_node;
9616
9617         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
9618       }
9619
9620     case SCOPE_REF:
9621       {
9622         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9623         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9624         if (e1 == error_mark_node || e2 == error_mark_node)
9625           return error_mark_node;
9626
9627         return build_qualified_name (/*type=*/NULL_TREE,
9628                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
9629       }
9630
9631     case TYPEOF_TYPE:
9632       {
9633         tree type;
9634
9635         type = finish_typeof (tsubst_expr 
9636                               (TYPEOF_TYPE_EXPR (t), args,
9637                                complain, in_decl,
9638                                /*integral_constant_expression_p=*/false));
9639         return cp_build_qualified_type_real (type,
9640                                              cp_type_quals (t)
9641                                              | cp_type_quals (type),
9642                                              complain);
9643       }
9644
9645     case DECLTYPE_TYPE:
9646       {
9647         tree type;
9648
9649         ++skip_evaluation;
9650
9651         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
9652                             complain, in_decl,
9653                             /*integral_constant_expression_p=*/false);
9654
9655         --skip_evaluation;
9656
9657         type =
9658           finish_decltype_type (type,
9659                                 DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
9660         return cp_build_qualified_type_real (type,
9661                                              cp_type_quals (t)
9662                                              | cp_type_quals (type),
9663                                              complain);
9664       }
9665
9666     case TYPE_ARGUMENT_PACK:
9667     case NONTYPE_ARGUMENT_PACK:
9668       {
9669         tree r = make_node (TREE_CODE (t));
9670         tree packed_out = 
9671           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
9672                                 args,
9673                                 complain,
9674                                 in_decl);
9675         SET_ARGUMENT_PACK_ARGS (r, packed_out);
9676
9677         /* For template nontype argument packs, also substitute into
9678            the type.  */
9679         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
9680           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
9681
9682         return r;
9683       }
9684       break;
9685
9686     default:
9687       sorry ("use of %qs in template",
9688              tree_code_name [(int) TREE_CODE (t)]);
9689       return error_mark_node;
9690     }
9691 }
9692
9693 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
9694    type of the expression on the left-hand side of the "." or "->"
9695    operator.  */
9696
9697 static tree
9698 tsubst_baselink (tree baselink, tree object_type,
9699                  tree args, tsubst_flags_t complain, tree in_decl)
9700 {
9701     tree name;
9702     tree qualifying_scope;
9703     tree fns;
9704     tree optype;
9705     tree template_args = 0;
9706     bool template_id_p = false;
9707
9708     /* A baselink indicates a function from a base class.  Both the
9709        BASELINK_ACCESS_BINFO and the base class referenced may
9710        indicate bases of the template class, rather than the
9711        instantiated class.  In addition, lookups that were not
9712        ambiguous before may be ambiguous now.  Therefore, we perform
9713        the lookup again.  */
9714     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
9715     qualifying_scope = tsubst (qualifying_scope, args,
9716                                complain, in_decl);
9717     fns = BASELINK_FUNCTIONS (baselink);
9718     optype = BASELINK_OPTYPE (baselink);
9719     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
9720       {
9721         template_id_p = true;
9722         template_args = TREE_OPERAND (fns, 1);
9723         fns = TREE_OPERAND (fns, 0);
9724         if (template_args)
9725           template_args = tsubst_template_args (template_args, args,
9726                                                 complain, in_decl);
9727       }
9728     name = DECL_NAME (get_first_fn (fns));
9729     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
9730
9731     /* If lookup found a single function, mark it as used at this
9732        point.  (If it lookup found multiple functions the one selected
9733        later by overload resolution will be marked as used at that
9734        point.)  */
9735     if (BASELINK_P (baselink))
9736       fns = BASELINK_FUNCTIONS (baselink);
9737     if (!template_id_p && !really_overloaded_fn (fns))
9738       mark_used (OVL_CURRENT (fns));
9739
9740     /* Add back the template arguments, if present.  */
9741     if (BASELINK_P (baselink) && template_id_p)
9742       BASELINK_FUNCTIONS (baselink)
9743         = build_nt (TEMPLATE_ID_EXPR,
9744                     BASELINK_FUNCTIONS (baselink),
9745                     template_args);
9746     /* Update the conversion operator type.  */
9747     BASELINK_OPTYPE (baselink) 
9748       = tsubst (optype, args, complain, in_decl);
9749
9750     if (!object_type)
9751       object_type = current_class_type;
9752     return adjust_result_of_qualified_name_lookup (baselink,
9753                                                    qualifying_scope,
9754                                                    object_type);
9755 }
9756
9757 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
9758    true if the qualified-id will be a postfix-expression in-and-of
9759    itself; false if more of the postfix-expression follows the
9760    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
9761    of "&".  */
9762
9763 static tree
9764 tsubst_qualified_id (tree qualified_id, tree args,
9765                      tsubst_flags_t complain, tree in_decl,
9766                      bool done, bool address_p)
9767 {
9768   tree expr;
9769   tree scope;
9770   tree name;
9771   bool is_template;
9772   tree template_args;
9773
9774   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
9775
9776   /* Figure out what name to look up.  */
9777   name = TREE_OPERAND (qualified_id, 1);
9778   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
9779     {
9780       is_template = true;
9781       template_args = TREE_OPERAND (name, 1);
9782       if (template_args)
9783         template_args = tsubst_template_args (template_args, args,
9784                                               complain, in_decl);
9785       name = TREE_OPERAND (name, 0);
9786     }
9787   else
9788     {
9789       is_template = false;
9790       template_args = NULL_TREE;
9791     }
9792
9793   /* Substitute into the qualifying scope.  When there are no ARGS, we
9794      are just trying to simplify a non-dependent expression.  In that
9795      case the qualifying scope may be dependent, and, in any case,
9796      substituting will not help.  */
9797   scope = TREE_OPERAND (qualified_id, 0);
9798   if (args)
9799     {
9800       scope = tsubst (scope, args, complain, in_decl);
9801       expr = tsubst_copy (name, args, complain, in_decl);
9802     }
9803   else
9804     expr = name;
9805
9806   if (dependent_type_p (scope))
9807     return build_qualified_name (/*type=*/NULL_TREE,
9808                                  scope, expr,
9809                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
9810
9811   if (!BASELINK_P (name) && !DECL_P (expr))
9812     {
9813       if (TREE_CODE (expr) == BIT_NOT_EXPR)
9814         /* If this were actually a destructor call, it would have been
9815            parsed as such by the parser.  */
9816         expr = error_mark_node;
9817       else
9818         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
9819       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
9820                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
9821         {
9822           if (complain & tf_error)
9823             {
9824               error ("dependent-name %qE is parsed as a non-type, but "
9825                      "instantiation yields a type", qualified_id);
9826               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
9827             }
9828           return error_mark_node;
9829         }
9830     }
9831
9832   if (DECL_P (expr))
9833     {
9834       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
9835                                            scope);
9836       /* Remember that there was a reference to this entity.  */
9837       mark_used (expr);
9838     }
9839
9840   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
9841     {
9842       if (complain & tf_error)
9843         qualified_name_lookup_error (scope,
9844                                      TREE_OPERAND (qualified_id, 1),
9845                                      expr, input_location);
9846       return error_mark_node;
9847     }
9848
9849   if (is_template)
9850     expr = lookup_template_function (expr, template_args);
9851
9852   if (expr == error_mark_node && complain & tf_error)
9853     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
9854                                  expr, input_location);
9855   else if (TYPE_P (scope))
9856     {
9857       expr = (adjust_result_of_qualified_name_lookup
9858               (expr, scope, current_class_type));
9859       expr = (finish_qualified_id_expr
9860               (scope, expr, done, address_p,
9861                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
9862                /*template_arg_p=*/false));
9863     }
9864
9865   /* Expressions do not generally have reference type.  */
9866   if (TREE_CODE (expr) != SCOPE_REF
9867       /* However, if we're about to form a pointer-to-member, we just
9868          want the referenced member referenced.  */
9869       && TREE_CODE (expr) != OFFSET_REF)
9870     expr = convert_from_reference (expr);
9871
9872   return expr;
9873 }
9874
9875 /* Like tsubst, but deals with expressions.  This function just replaces
9876    template parms; to finish processing the resultant expression, use
9877    tsubst_expr.  */
9878
9879 static tree
9880 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9881 {
9882   enum tree_code code;
9883   tree r;
9884
9885   if (t == NULL_TREE || t == error_mark_node)
9886     return t;
9887
9888   code = TREE_CODE (t);
9889
9890   switch (code)
9891     {
9892     case PARM_DECL:
9893       r = retrieve_local_specialization (t);
9894
9895       if (r == NULL)
9896         {
9897           /* This can happen for a parameter name used later in a function
9898              declaration (such as in a late-specified return type).
9899              Replace it with an arbitrary expression with the same type
9900              (*(T*)0).  This should only occur in an unevaluated context
9901              (i.e. decltype).  */
9902           gcc_assert (skip_evaluation);
9903           r = non_reference (TREE_TYPE (t));
9904           r = tsubst (r, args, complain, in_decl);
9905           r = build_pointer_type (r);
9906           r = build_c_cast (r, null_node);
9907           return cp_build_indirect_ref (r, NULL, tf_warning_or_error);
9908         }
9909       
9910       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
9911         r = ARGUMENT_PACK_SELECT_ARG (r);
9912       mark_used (r);
9913       return r;
9914
9915     case CONST_DECL:
9916       {
9917         tree enum_type;
9918         tree v;
9919
9920         if (DECL_TEMPLATE_PARM_P (t))
9921           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
9922         /* There is no need to substitute into namespace-scope
9923            enumerators.  */
9924         if (DECL_NAMESPACE_SCOPE_P (t))
9925           return t;
9926         /* If ARGS is NULL, then T is known to be non-dependent.  */
9927         if (args == NULL_TREE)
9928           return integral_constant_value (t);
9929
9930         /* Unfortunately, we cannot just call lookup_name here.
9931            Consider:
9932
9933              template <int I> int f() {
9934              enum E { a = I };
9935              struct S { void g() { E e = a; } };
9936              };
9937
9938            When we instantiate f<7>::S::g(), say, lookup_name is not
9939            clever enough to find f<7>::a.  */
9940         enum_type
9941           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
9942                               /*entering_scope=*/0);
9943
9944         for (v = TYPE_VALUES (enum_type);
9945              v != NULL_TREE;
9946              v = TREE_CHAIN (v))
9947           if (TREE_PURPOSE (v) == DECL_NAME (t))
9948             return TREE_VALUE (v);
9949
9950           /* We didn't find the name.  That should never happen; if
9951              name-lookup found it during preliminary parsing, we
9952              should find it again here during instantiation.  */
9953         gcc_unreachable ();
9954       }
9955       return t;
9956
9957     case FIELD_DECL:
9958       if (DECL_CONTEXT (t))
9959         {
9960           tree ctx;
9961
9962           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
9963                                   /*entering_scope=*/1);
9964           if (ctx != DECL_CONTEXT (t))
9965             {
9966               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
9967               if (!r)
9968                 {
9969                   if (complain & tf_error)
9970                     error ("using invalid field %qD", t);
9971                   return error_mark_node;
9972                 }
9973               return r;
9974             }
9975         }
9976
9977       return t;
9978
9979     case VAR_DECL:
9980     case FUNCTION_DECL:
9981       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
9982           || local_variable_p (t))
9983         t = tsubst (t, args, complain, in_decl);
9984       mark_used (t);
9985       return t;
9986
9987     case BASELINK:
9988       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
9989
9990     case TEMPLATE_DECL:
9991       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9992         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
9993                        args, complain, in_decl);
9994       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
9995         return tsubst (t, args, complain, in_decl);
9996       else if (DECL_CLASS_SCOPE_P (t)
9997                && uses_template_parms (DECL_CONTEXT (t)))
9998         {
9999           /* Template template argument like the following example need
10000              special treatment:
10001
10002                template <template <class> class TT> struct C {};
10003                template <class T> struct D {
10004                  template <class U> struct E {};
10005                  C<E> c;                                // #1
10006                };
10007                D<int> d;                                // #2
10008
10009              We are processing the template argument `E' in #1 for
10010              the template instantiation #2.  Originally, `E' is a
10011              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
10012              have to substitute this with one having context `D<int>'.  */
10013
10014           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
10015           return lookup_field (context, DECL_NAME(t), 0, false);
10016         }
10017       else
10018         /* Ordinary template template argument.  */
10019         return t;
10020
10021     case CAST_EXPR:
10022     case REINTERPRET_CAST_EXPR:
10023     case CONST_CAST_EXPR:
10024     case STATIC_CAST_EXPR:
10025     case DYNAMIC_CAST_EXPR:
10026     case NOP_EXPR:
10027       return build1
10028         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10029          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10030
10031     case SIZEOF_EXPR:
10032       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10033         {
10034           /* We only want to compute the number of arguments.  */
10035           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
10036                                                 complain, in_decl);
10037           int len = 0;
10038
10039           if (TREE_CODE (expanded) == TREE_VEC)
10040             len = TREE_VEC_LENGTH (expanded);
10041
10042           if (expanded == error_mark_node)
10043             return error_mark_node;
10044           else if (PACK_EXPANSION_P (expanded)
10045                    || (TREE_CODE (expanded) == TREE_VEC
10046                        && len > 0
10047                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
10048             {
10049               if (TREE_CODE (expanded) == TREE_VEC)
10050                 expanded = TREE_VEC_ELT (expanded, len - 1);
10051
10052               if (TYPE_P (expanded))
10053                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
10054                                                    complain & tf_error);
10055               else
10056                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
10057                                                    complain & tf_error);
10058             }
10059           else
10060             return build_int_cst (size_type_node, len);
10061         }
10062       /* Fall through */
10063
10064     case INDIRECT_REF:
10065     case NEGATE_EXPR:
10066     case TRUTH_NOT_EXPR:
10067     case BIT_NOT_EXPR:
10068     case ADDR_EXPR:
10069     case UNARY_PLUS_EXPR:      /* Unary + */
10070     case ALIGNOF_EXPR:
10071     case ARROW_EXPR:
10072     case THROW_EXPR:
10073     case TYPEID_EXPR:
10074     case REALPART_EXPR:
10075     case IMAGPART_EXPR:
10076       return build1
10077         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10078          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10079
10080     case COMPONENT_REF:
10081       {
10082         tree object;
10083         tree name;
10084
10085         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
10086         name = TREE_OPERAND (t, 1);
10087         if (TREE_CODE (name) == BIT_NOT_EXPR)
10088           {
10089             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10090                                 complain, in_decl);
10091             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10092           }
10093         else if (TREE_CODE (name) == SCOPE_REF
10094                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
10095           {
10096             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
10097                                      complain, in_decl);
10098             name = TREE_OPERAND (name, 1);
10099             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10100                                 complain, in_decl);
10101             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10102             name = build_qualified_name (/*type=*/NULL_TREE,
10103                                          base, name,
10104                                          /*template_p=*/false);
10105           }
10106         else if (TREE_CODE (name) == BASELINK)
10107           name = tsubst_baselink (name,
10108                                   non_reference (TREE_TYPE (object)),
10109                                   args, complain,
10110                                   in_decl);
10111         else
10112           name = tsubst_copy (name, args, complain, in_decl);
10113         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
10114       }
10115
10116     case PLUS_EXPR:
10117     case MINUS_EXPR:
10118     case MULT_EXPR:
10119     case TRUNC_DIV_EXPR:
10120     case CEIL_DIV_EXPR:
10121     case FLOOR_DIV_EXPR:
10122     case ROUND_DIV_EXPR:
10123     case EXACT_DIV_EXPR:
10124     case BIT_AND_EXPR:
10125     case BIT_IOR_EXPR:
10126     case BIT_XOR_EXPR:
10127     case TRUNC_MOD_EXPR:
10128     case FLOOR_MOD_EXPR:
10129     case TRUTH_ANDIF_EXPR:
10130     case TRUTH_ORIF_EXPR:
10131     case TRUTH_AND_EXPR:
10132     case TRUTH_OR_EXPR:
10133     case RSHIFT_EXPR:
10134     case LSHIFT_EXPR:
10135     case RROTATE_EXPR:
10136     case LROTATE_EXPR:
10137     case EQ_EXPR:
10138     case NE_EXPR:
10139     case MAX_EXPR:
10140     case MIN_EXPR:
10141     case LE_EXPR:
10142     case GE_EXPR:
10143     case LT_EXPR:
10144     case GT_EXPR:
10145     case COMPOUND_EXPR:
10146     case DOTSTAR_EXPR:
10147     case MEMBER_REF:
10148     case PREDECREMENT_EXPR:
10149     case PREINCREMENT_EXPR:
10150     case POSTDECREMENT_EXPR:
10151     case POSTINCREMENT_EXPR:
10152       return build_nt
10153         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10154          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10155
10156     case SCOPE_REF:
10157       return build_qualified_name (/*type=*/NULL_TREE,
10158                                    tsubst_copy (TREE_OPERAND (t, 0),
10159                                                 args, complain, in_decl),
10160                                    tsubst_copy (TREE_OPERAND (t, 1),
10161                                                 args, complain, in_decl),
10162                                    QUALIFIED_NAME_IS_TEMPLATE (t));
10163
10164     case ARRAY_REF:
10165       return build_nt
10166         (ARRAY_REF,
10167          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10168          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10169          NULL_TREE, NULL_TREE);
10170
10171     case CALL_EXPR:
10172       {
10173         int n = VL_EXP_OPERAND_LENGTH (t);
10174         tree result = build_vl_exp (CALL_EXPR, n);
10175         int i;
10176         for (i = 0; i < n; i++)
10177           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
10178                                              complain, in_decl);
10179         return result;
10180       }
10181
10182     case COND_EXPR:
10183     case MODOP_EXPR:
10184     case PSEUDO_DTOR_EXPR:
10185       {
10186         r = build_nt
10187           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10188            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10189            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10190         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
10191         return r;
10192       }
10193
10194     case NEW_EXPR:
10195       {
10196         r = build_nt
10197         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10198          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10199          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10200         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
10201         return r;
10202       }
10203
10204     case DELETE_EXPR:
10205       {
10206         r = build_nt
10207         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10208          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10209         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
10210         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
10211         return r;
10212       }
10213
10214     case TEMPLATE_ID_EXPR:
10215       {
10216         /* Substituted template arguments */
10217         tree fn = TREE_OPERAND (t, 0);
10218         tree targs = TREE_OPERAND (t, 1);
10219
10220         fn = tsubst_copy (fn, args, complain, in_decl);
10221         if (targs)
10222           targs = tsubst_template_args (targs, args, complain, in_decl);
10223
10224         return lookup_template_function (fn, targs);
10225       }
10226
10227     case TREE_LIST:
10228       {
10229         tree purpose, value, chain;
10230
10231         if (t == void_list_node)
10232           return t;
10233
10234         purpose = TREE_PURPOSE (t);
10235         if (purpose)
10236           purpose = tsubst_copy (purpose, args, complain, in_decl);
10237         value = TREE_VALUE (t);
10238         if (value)
10239           value = tsubst_copy (value, args, complain, in_decl);
10240         chain = TREE_CHAIN (t);
10241         if (chain && chain != void_type_node)
10242           chain = tsubst_copy (chain, args, complain, in_decl);
10243         if (purpose == TREE_PURPOSE (t)
10244             && value == TREE_VALUE (t)
10245             && chain == TREE_CHAIN (t))
10246           return t;
10247         return tree_cons (purpose, value, chain);
10248       }
10249
10250     case RECORD_TYPE:
10251     case UNION_TYPE:
10252     case ENUMERAL_TYPE:
10253     case INTEGER_TYPE:
10254     case TEMPLATE_TYPE_PARM:
10255     case TEMPLATE_TEMPLATE_PARM:
10256     case BOUND_TEMPLATE_TEMPLATE_PARM:
10257     case TEMPLATE_PARM_INDEX:
10258     case POINTER_TYPE:
10259     case REFERENCE_TYPE:
10260     case OFFSET_TYPE:
10261     case FUNCTION_TYPE:
10262     case METHOD_TYPE:
10263     case ARRAY_TYPE:
10264     case TYPENAME_TYPE:
10265     case UNBOUND_CLASS_TEMPLATE:
10266     case TYPEOF_TYPE:
10267     case DECLTYPE_TYPE:
10268     case TYPE_DECL:
10269       return tsubst (t, args, complain, in_decl);
10270
10271     case IDENTIFIER_NODE:
10272       if (IDENTIFIER_TYPENAME_P (t))
10273         {
10274           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10275           return mangle_conv_op_name_for_type (new_type);
10276         }
10277       else
10278         return t;
10279
10280     case CONSTRUCTOR:
10281       /* This is handled by tsubst_copy_and_build.  */
10282       gcc_unreachable ();
10283
10284     case VA_ARG_EXPR:
10285       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
10286                                           in_decl),
10287                              tsubst (TREE_TYPE (t), args, complain, in_decl));
10288
10289     case CLEANUP_POINT_EXPR:
10290       /* We shouldn't have built any of these during initial template
10291          generation.  Instead, they should be built during instantiation
10292          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
10293       gcc_unreachable ();
10294
10295     case OFFSET_REF:
10296       mark_used (TREE_OPERAND (t, 1));
10297       return t;
10298
10299     case EXPR_PACK_EXPANSION:
10300       error ("invalid use of pack expansion expression");
10301       return error_mark_node;
10302
10303     case NONTYPE_ARGUMENT_PACK:
10304       error ("use %<...%> to expand argument pack");
10305       return error_mark_node;
10306
10307     default:
10308       return t;
10309     }
10310 }
10311
10312 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
10313
10314 static tree
10315 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
10316                     tree in_decl)
10317 {
10318   tree new_clauses = NULL, nc, oc;
10319
10320   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
10321     {
10322       nc = copy_node (oc);
10323       OMP_CLAUSE_CHAIN (nc) = new_clauses;
10324       new_clauses = nc;
10325
10326       switch (OMP_CLAUSE_CODE (nc))
10327         {
10328         case OMP_CLAUSE_LASTPRIVATE:
10329           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
10330             {
10331               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
10332               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
10333                            in_decl, /*integral_constant_expression_p=*/false);
10334               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
10335                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
10336             }
10337           /* FALLTHRU */
10338         case OMP_CLAUSE_PRIVATE:
10339         case OMP_CLAUSE_SHARED:
10340         case OMP_CLAUSE_FIRSTPRIVATE:
10341         case OMP_CLAUSE_REDUCTION:
10342         case OMP_CLAUSE_COPYIN:
10343         case OMP_CLAUSE_COPYPRIVATE:
10344         case OMP_CLAUSE_IF:
10345         case OMP_CLAUSE_NUM_THREADS:
10346         case OMP_CLAUSE_SCHEDULE:
10347         case OMP_CLAUSE_COLLAPSE:
10348           OMP_CLAUSE_OPERAND (nc, 0)
10349             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
10350                            in_decl, /*integral_constant_expression_p=*/false);
10351           break;
10352         case OMP_CLAUSE_NOWAIT:
10353         case OMP_CLAUSE_ORDERED:
10354         case OMP_CLAUSE_DEFAULT:
10355         case OMP_CLAUSE_UNTIED:
10356           break;
10357         default:
10358           gcc_unreachable ();
10359         }
10360     }
10361
10362   return finish_omp_clauses (nreverse (new_clauses));
10363 }
10364
10365 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
10366
10367 static tree
10368 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
10369                           tree in_decl)
10370 {
10371 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
10372
10373   tree purpose, value, chain;
10374
10375   if (t == NULL)
10376     return t;
10377
10378   if (TREE_CODE (t) != TREE_LIST)
10379     return tsubst_copy_and_build (t, args, complain, in_decl,
10380                                   /*function_p=*/false,
10381                                   /*integral_constant_expression_p=*/false);
10382
10383   if (t == void_list_node)
10384     return t;
10385
10386   purpose = TREE_PURPOSE (t);
10387   if (purpose)
10388     purpose = RECUR (purpose);
10389   value = TREE_VALUE (t);
10390   if (value)
10391     value = RECUR (value);
10392   chain = TREE_CHAIN (t);
10393   if (chain && chain != void_type_node)
10394     chain = RECUR (chain);
10395   return tree_cons (purpose, value, chain);
10396 #undef RECUR
10397 }
10398
10399 /* Substitute one OMP_FOR iterator.  */
10400
10401 static void
10402 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
10403                          tree condv, tree incrv, tree *clauses,
10404                          tree args, tsubst_flags_t complain, tree in_decl,
10405                          bool integral_constant_expression_p)
10406 {
10407 #define RECUR(NODE)                             \
10408   tsubst_expr ((NODE), args, complain, in_decl, \
10409                integral_constant_expression_p)
10410   tree decl, init, cond, incr, auto_node;
10411
10412   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
10413   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
10414   decl = RECUR (TREE_OPERAND (init, 0));
10415   init = TREE_OPERAND (init, 1);
10416   auto_node = type_uses_auto (TREE_TYPE (decl));
10417   if (auto_node && init)
10418     {
10419       tree init_expr = init;
10420       if (TREE_CODE (init_expr) == DECL_EXPR)
10421         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
10422       init_expr = RECUR (init_expr);
10423       TREE_TYPE (decl)
10424         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
10425     }
10426   gcc_assert (!type_dependent_expression_p (decl));
10427
10428   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
10429     {
10430       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
10431       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
10432       if (TREE_CODE (incr) == MODIFY_EXPR)
10433         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
10434                                     RECUR (TREE_OPERAND (incr, 1)),
10435                                     complain);
10436       else
10437         incr = RECUR (incr);
10438       TREE_VEC_ELT (declv, i) = decl;
10439       TREE_VEC_ELT (initv, i) = init;
10440       TREE_VEC_ELT (condv, i) = cond;
10441       TREE_VEC_ELT (incrv, i) = incr;
10442       return;
10443     }
10444
10445   if (init && TREE_CODE (init) != DECL_EXPR)
10446     {
10447       tree c;
10448       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
10449         {
10450           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
10451                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
10452               && OMP_CLAUSE_DECL (c) == decl)
10453             break;
10454           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
10455                    && OMP_CLAUSE_DECL (c) == decl)
10456             error ("iteration variable %qD should not be firstprivate", decl);
10457           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
10458                    && OMP_CLAUSE_DECL (c) == decl)
10459             error ("iteration variable %qD should not be reduction", decl);
10460         }
10461       if (c == NULL)
10462         {
10463           c = build_omp_clause (OMP_CLAUSE_PRIVATE);
10464           OMP_CLAUSE_DECL (c) = decl;
10465           c = finish_omp_clauses (c);
10466           if (c)
10467             {
10468               OMP_CLAUSE_CHAIN (c) = *clauses;
10469               *clauses = c;
10470             }
10471         }
10472     }
10473   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
10474   if (COMPARISON_CLASS_P (cond))
10475     cond = build2 (TREE_CODE (cond), boolean_type_node,
10476                    RECUR (TREE_OPERAND (cond, 0)),
10477                    RECUR (TREE_OPERAND (cond, 1)));
10478   else
10479     cond = RECUR (cond);
10480   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
10481   switch (TREE_CODE (incr))
10482     {
10483     case PREINCREMENT_EXPR:
10484     case PREDECREMENT_EXPR:
10485     case POSTINCREMENT_EXPR:
10486     case POSTDECREMENT_EXPR:
10487       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
10488                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
10489       break;
10490     case MODIFY_EXPR:
10491       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
10492           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
10493         {
10494           tree rhs = TREE_OPERAND (incr, 1);
10495           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
10496                          RECUR (TREE_OPERAND (incr, 0)),
10497                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
10498                                  RECUR (TREE_OPERAND (rhs, 0)),
10499                                  RECUR (TREE_OPERAND (rhs, 1))));
10500         }
10501       else
10502         incr = RECUR (incr);
10503       break;
10504     case MODOP_EXPR:
10505       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
10506           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
10507         {
10508           tree lhs = RECUR (TREE_OPERAND (incr, 0));
10509           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
10510                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
10511                                  TREE_TYPE (decl), lhs,
10512                                  RECUR (TREE_OPERAND (incr, 2))));
10513         }
10514       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
10515                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
10516                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
10517         {
10518           tree rhs = TREE_OPERAND (incr, 2);
10519           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
10520                          RECUR (TREE_OPERAND (incr, 0)),
10521                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
10522                                  RECUR (TREE_OPERAND (rhs, 0)),
10523                                  RECUR (TREE_OPERAND (rhs, 1))));
10524         }
10525       else
10526         incr = RECUR (incr);
10527       break;
10528     default:
10529       incr = RECUR (incr);
10530       break;
10531     }
10532
10533   TREE_VEC_ELT (declv, i) = decl;
10534   TREE_VEC_ELT (initv, i) = init;
10535   TREE_VEC_ELT (condv, i) = cond;
10536   TREE_VEC_ELT (incrv, i) = incr;
10537 #undef RECUR
10538 }
10539
10540 /* Like tsubst_copy for expressions, etc. but also does semantic
10541    processing.  */
10542
10543 static tree
10544 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
10545              bool integral_constant_expression_p)
10546 {
10547 #define RECUR(NODE)                             \
10548   tsubst_expr ((NODE), args, complain, in_decl, \
10549                integral_constant_expression_p)
10550
10551   tree stmt, tmp;
10552
10553   if (t == NULL_TREE || t == error_mark_node)
10554     return t;
10555
10556   if (EXPR_HAS_LOCATION (t))
10557     input_location = EXPR_LOCATION (t);
10558   if (STATEMENT_CODE_P (TREE_CODE (t)))
10559     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
10560
10561   switch (TREE_CODE (t))
10562     {
10563     case STATEMENT_LIST:
10564       {
10565         tree_stmt_iterator i;
10566         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
10567           RECUR (tsi_stmt (i));
10568         break;
10569       }
10570
10571     case CTOR_INITIALIZER:
10572       finish_mem_initializers (tsubst_initializer_list
10573                                (TREE_OPERAND (t, 0), args));
10574       break;
10575
10576     case RETURN_EXPR:
10577       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
10578       break;
10579
10580     case EXPR_STMT:
10581       tmp = RECUR (EXPR_STMT_EXPR (t));
10582       if (EXPR_STMT_STMT_EXPR_RESULT (t))
10583         finish_stmt_expr_expr (tmp, cur_stmt_expr);
10584       else
10585         finish_expr_stmt (tmp);
10586       break;
10587
10588     case USING_STMT:
10589       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
10590       break;
10591
10592     case DECL_EXPR:
10593       {
10594         tree decl;
10595         tree init;
10596
10597         decl = DECL_EXPR_DECL (t);
10598         if (TREE_CODE (decl) == LABEL_DECL)
10599           finish_label_decl (DECL_NAME (decl));
10600         else if (TREE_CODE (decl) == USING_DECL)
10601           {
10602             tree scope = USING_DECL_SCOPE (decl);
10603             tree name = DECL_NAME (decl);
10604             tree decl;
10605
10606             scope = RECUR (scope);
10607             decl = lookup_qualified_name (scope, name,
10608                                           /*is_type_p=*/false,
10609                                           /*complain=*/false);
10610             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
10611               qualified_name_lookup_error (scope, name, decl, input_location);
10612             else
10613               do_local_using_decl (decl, scope, name);
10614           }
10615         else
10616           {
10617             init = DECL_INITIAL (decl);
10618             decl = tsubst (decl, args, complain, in_decl);
10619             if (decl != error_mark_node)
10620               {
10621                 /* By marking the declaration as instantiated, we avoid
10622                    trying to instantiate it.  Since instantiate_decl can't
10623                    handle local variables, and since we've already done
10624                    all that needs to be done, that's the right thing to
10625                    do.  */
10626                 if (TREE_CODE (decl) == VAR_DECL)
10627                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10628                 if (TREE_CODE (decl) == VAR_DECL
10629                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
10630                   /* Anonymous aggregates are a special case.  */
10631                   finish_anon_union (decl);
10632                 else
10633                   {
10634                     maybe_push_decl (decl);
10635                     if (TREE_CODE (decl) == VAR_DECL
10636                         && DECL_PRETTY_FUNCTION_P (decl))
10637                       {
10638                         /* For __PRETTY_FUNCTION__ we have to adjust the
10639                            initializer.  */
10640                         const char *const name
10641                           = cxx_printable_name (current_function_decl, 2);
10642                         init = cp_fname_init (name, &TREE_TYPE (decl));
10643                       }
10644                     else
10645                       {
10646                         tree t = RECUR (init);
10647
10648                         if (init && !t)
10649                           /* If we had an initializer but it
10650                              instantiated to nothing,
10651                              value-initialize the object.  This will
10652                              only occur when the initializer was a
10653                              pack expansion where the parameter packs
10654                              used in that expansion were of length
10655                              zero.  */
10656                           init = build_value_init (TREE_TYPE (decl));
10657                         else
10658                           init = t;
10659                       }
10660
10661                     finish_decl (decl, init, NULL_TREE);
10662                   }
10663               }
10664           }
10665
10666         /* A DECL_EXPR can also be used as an expression, in the condition
10667            clause of an if/for/while construct.  */
10668         return decl;
10669       }
10670
10671     case FOR_STMT:
10672       stmt = begin_for_stmt ();
10673                           RECUR (FOR_INIT_STMT (t));
10674       finish_for_init_stmt (stmt);
10675       tmp = RECUR (FOR_COND (t));
10676       finish_for_cond (tmp, stmt);
10677       tmp = RECUR (FOR_EXPR (t));
10678       finish_for_expr (tmp, stmt);
10679       RECUR (FOR_BODY (t));
10680       finish_for_stmt (stmt);
10681       break;
10682
10683     case WHILE_STMT:
10684       stmt = begin_while_stmt ();
10685       tmp = RECUR (WHILE_COND (t));
10686       finish_while_stmt_cond (tmp, stmt);
10687       RECUR (WHILE_BODY (t));
10688       finish_while_stmt (stmt);
10689       break;
10690
10691     case DO_STMT:
10692       stmt = begin_do_stmt ();
10693       RECUR (DO_BODY (t));
10694       finish_do_body (stmt);
10695       tmp = RECUR (DO_COND (t));
10696       finish_do_stmt (tmp, stmt);
10697       break;
10698
10699     case IF_STMT:
10700       stmt = begin_if_stmt ();
10701       tmp = RECUR (IF_COND (t));
10702       finish_if_stmt_cond (tmp, stmt);
10703       RECUR (THEN_CLAUSE (t));
10704       finish_then_clause (stmt);
10705
10706       if (ELSE_CLAUSE (t))
10707         {
10708           begin_else_clause (stmt);
10709           RECUR (ELSE_CLAUSE (t));
10710           finish_else_clause (stmt);
10711         }
10712
10713       finish_if_stmt (stmt);
10714       break;
10715
10716     case BIND_EXPR:
10717       if (BIND_EXPR_BODY_BLOCK (t))
10718         stmt = begin_function_body ();
10719       else
10720         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
10721                                     ? BCS_TRY_BLOCK : 0);
10722
10723       RECUR (BIND_EXPR_BODY (t));
10724
10725       if (BIND_EXPR_BODY_BLOCK (t))
10726         finish_function_body (stmt);
10727       else
10728         finish_compound_stmt (stmt);
10729       break;
10730
10731     case BREAK_STMT:
10732       finish_break_stmt ();
10733       break;
10734
10735     case CONTINUE_STMT:
10736       finish_continue_stmt ();
10737       break;
10738
10739     case SWITCH_STMT:
10740       stmt = begin_switch_stmt ();
10741       tmp = RECUR (SWITCH_STMT_COND (t));
10742       finish_switch_cond (tmp, stmt);
10743       RECUR (SWITCH_STMT_BODY (t));
10744       finish_switch_stmt (stmt);
10745       break;
10746
10747     case CASE_LABEL_EXPR:
10748       finish_case_label (RECUR (CASE_LOW (t)),
10749                          RECUR (CASE_HIGH (t)));
10750       break;
10751
10752     case LABEL_EXPR:
10753       finish_label_stmt (DECL_NAME (LABEL_EXPR_LABEL (t)));
10754       break;
10755
10756     case GOTO_EXPR:
10757       tmp = GOTO_DESTINATION (t);
10758       if (TREE_CODE (tmp) != LABEL_DECL)
10759         /* Computed goto's must be tsubst'd into.  On the other hand,
10760            non-computed gotos must not be; the identifier in question
10761            will have no binding.  */
10762         tmp = RECUR (tmp);
10763       else
10764         tmp = DECL_NAME (tmp);
10765       finish_goto_stmt (tmp);
10766       break;
10767
10768     case ASM_EXPR:
10769       tmp = finish_asm_stmt
10770         (ASM_VOLATILE_P (t),
10771          RECUR (ASM_STRING (t)),
10772          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
10773          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
10774          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl));
10775       {
10776         tree asm_expr = tmp;
10777         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
10778           asm_expr = TREE_OPERAND (asm_expr, 0);
10779         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
10780       }
10781       break;
10782
10783     case TRY_BLOCK:
10784       if (CLEANUP_P (t))
10785         {
10786           stmt = begin_try_block ();
10787           RECUR (TRY_STMTS (t));
10788           finish_cleanup_try_block (stmt);
10789           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
10790         }
10791       else
10792         {
10793           tree compound_stmt = NULL_TREE;
10794
10795           if (FN_TRY_BLOCK_P (t))
10796             stmt = begin_function_try_block (&compound_stmt);
10797           else
10798             stmt = begin_try_block ();
10799
10800           RECUR (TRY_STMTS (t));
10801
10802           if (FN_TRY_BLOCK_P (t))
10803             finish_function_try_block (stmt);
10804           else
10805             finish_try_block (stmt);
10806
10807           RECUR (TRY_HANDLERS (t));
10808           if (FN_TRY_BLOCK_P (t))
10809             finish_function_handler_sequence (stmt, compound_stmt);
10810           else
10811             finish_handler_sequence (stmt);
10812         }
10813       break;
10814
10815     case HANDLER:
10816       {
10817         tree decl = HANDLER_PARMS (t);
10818
10819         if (decl)
10820           {
10821             decl = tsubst (decl, args, complain, in_decl);
10822             /* Prevent instantiate_decl from trying to instantiate
10823                this variable.  We've already done all that needs to be
10824                done.  */
10825             if (decl != error_mark_node)
10826               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10827           }
10828         stmt = begin_handler ();
10829         finish_handler_parms (decl, stmt);
10830         RECUR (HANDLER_BODY (t));
10831         finish_handler (stmt);
10832       }
10833       break;
10834
10835     case TAG_DEFN:
10836       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
10837       break;
10838
10839     case STATIC_ASSERT:
10840       {
10841         tree condition = 
10842           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
10843                        args,
10844                        complain, in_decl,
10845                        /*integral_constant_expression_p=*/true);
10846         finish_static_assert (condition,
10847                               STATIC_ASSERT_MESSAGE (t),
10848                               STATIC_ASSERT_SOURCE_LOCATION (t),
10849                               /*member_p=*/false);
10850       }
10851       break;
10852
10853     case OMP_PARALLEL:
10854       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
10855                                 args, complain, in_decl);
10856       stmt = begin_omp_parallel ();
10857       RECUR (OMP_PARALLEL_BODY (t));
10858       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
10859         = OMP_PARALLEL_COMBINED (t);
10860       break;
10861
10862     case OMP_TASK:
10863       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
10864                                 args, complain, in_decl);
10865       stmt = begin_omp_task ();
10866       RECUR (OMP_TASK_BODY (t));
10867       finish_omp_task (tmp, stmt);
10868       break;
10869
10870     case OMP_FOR:
10871       {
10872         tree clauses, body, pre_body;
10873         tree declv, initv, condv, incrv;
10874         int i;
10875
10876         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
10877                                       args, complain, in_decl);
10878         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
10879         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
10880         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
10881         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
10882
10883         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
10884           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
10885                                    &clauses, args, complain, in_decl,
10886                                    integral_constant_expression_p);
10887
10888         stmt = begin_omp_structured_block ();
10889
10890         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
10891           if (TREE_VEC_ELT (initv, i) == NULL
10892               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
10893             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
10894           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
10895             {
10896               tree init = RECUR (TREE_VEC_ELT (initv, i));
10897               gcc_assert (init == TREE_VEC_ELT (declv, i));
10898               TREE_VEC_ELT (initv, i) = NULL_TREE;
10899             }
10900           else
10901             {
10902               tree decl_expr = TREE_VEC_ELT (initv, i);
10903               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
10904               gcc_assert (init != NULL);
10905               TREE_VEC_ELT (initv, i) = RECUR (init);
10906               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
10907               RECUR (decl_expr);
10908               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
10909             }
10910
10911         pre_body = push_stmt_list ();
10912         RECUR (OMP_FOR_PRE_BODY (t));
10913         pre_body = pop_stmt_list (pre_body);
10914
10915         body = push_stmt_list ();
10916         RECUR (OMP_FOR_BODY (t));
10917         body = pop_stmt_list (body);
10918
10919         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
10920                             body, pre_body, clauses);
10921
10922         add_stmt (finish_omp_structured_block (stmt));
10923       }
10924       break;
10925
10926     case OMP_SECTIONS:
10927     case OMP_SINGLE:
10928       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
10929       stmt = push_stmt_list ();
10930       RECUR (OMP_BODY (t));
10931       stmt = pop_stmt_list (stmt);
10932
10933       t = copy_node (t);
10934       OMP_BODY (t) = stmt;
10935       OMP_CLAUSES (t) = tmp;
10936       add_stmt (t);
10937       break;
10938
10939     case OMP_SECTION:
10940     case OMP_CRITICAL:
10941     case OMP_MASTER:
10942     case OMP_ORDERED:
10943       stmt = push_stmt_list ();
10944       RECUR (OMP_BODY (t));
10945       stmt = pop_stmt_list (stmt);
10946
10947       t = copy_node (t);
10948       OMP_BODY (t) = stmt;
10949       add_stmt (t);
10950       break;
10951
10952     case OMP_ATOMIC:
10953       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
10954       {
10955         tree op1 = TREE_OPERAND (t, 1);
10956         tree lhs = RECUR (TREE_OPERAND (op1, 0));
10957         tree rhs = RECUR (TREE_OPERAND (op1, 1));
10958         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
10959       }
10960       break;
10961
10962     case EXPR_PACK_EXPANSION:
10963       error ("invalid use of pack expansion expression");
10964       return error_mark_node;
10965
10966     case NONTYPE_ARGUMENT_PACK:
10967       error ("use %<...%> to expand argument pack");
10968       return error_mark_node;
10969
10970     default:
10971       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
10972
10973       return tsubst_copy_and_build (t, args, complain, in_decl,
10974                                     /*function_p=*/false,
10975                                     integral_constant_expression_p);
10976     }
10977
10978   return NULL_TREE;
10979 #undef RECUR
10980 }
10981
10982 /* T is a postfix-expression that is not being used in a function
10983    call.  Return the substituted version of T.  */
10984
10985 static tree
10986 tsubst_non_call_postfix_expression (tree t, tree args,
10987                                     tsubst_flags_t complain,
10988                                     tree in_decl)
10989 {
10990   if (TREE_CODE (t) == SCOPE_REF)
10991     t = tsubst_qualified_id (t, args, complain, in_decl,
10992                              /*done=*/false, /*address_p=*/false);
10993   else
10994     t = tsubst_copy_and_build (t, args, complain, in_decl,
10995                                /*function_p=*/false,
10996                                /*integral_constant_expression_p=*/false);
10997
10998   return t;
10999 }
11000
11001 /* Like tsubst but deals with expressions and performs semantic
11002    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
11003
11004 tree
11005 tsubst_copy_and_build (tree t,
11006                        tree args,
11007                        tsubst_flags_t complain,
11008                        tree in_decl,
11009                        bool function_p,
11010                        bool integral_constant_expression_p)
11011 {
11012 #define RECUR(NODE)                                             \
11013   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
11014                          /*function_p=*/false,                  \
11015                          integral_constant_expression_p)
11016
11017   tree op1;
11018
11019   if (t == NULL_TREE || t == error_mark_node)
11020     return t;
11021
11022   switch (TREE_CODE (t))
11023     {
11024     case USING_DECL:
11025       t = DECL_NAME (t);
11026       /* Fall through.  */
11027     case IDENTIFIER_NODE:
11028       {
11029         tree decl;
11030         cp_id_kind idk;
11031         bool non_integral_constant_expression_p;
11032         const char *error_msg;
11033
11034         if (IDENTIFIER_TYPENAME_P (t))
11035           {
11036             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11037             t = mangle_conv_op_name_for_type (new_type);
11038           }
11039
11040         /* Look up the name.  */
11041         decl = lookup_name (t);
11042
11043         /* By convention, expressions use ERROR_MARK_NODE to indicate
11044            failure, not NULL_TREE.  */
11045         if (decl == NULL_TREE)
11046           decl = error_mark_node;
11047
11048         decl = finish_id_expression (t, decl, NULL_TREE,
11049                                      &idk,
11050                                      integral_constant_expression_p,
11051                                      /*allow_non_integral_constant_expression_p=*/false,
11052                                      &non_integral_constant_expression_p,
11053                                      /*template_p=*/false,
11054                                      /*done=*/true,
11055                                      /*address_p=*/false,
11056                                      /*template_arg_p=*/false,
11057                                      &error_msg,
11058                                      input_location);
11059         if (error_msg)
11060           error (error_msg);
11061         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
11062           decl = unqualified_name_lookup_error (decl);
11063         return decl;
11064       }
11065
11066     case TEMPLATE_ID_EXPR:
11067       {
11068         tree object;
11069         tree templ = RECUR (TREE_OPERAND (t, 0));
11070         tree targs = TREE_OPERAND (t, 1);
11071
11072         if (targs)
11073           targs = tsubst_template_args (targs, args, complain, in_decl);
11074
11075         if (TREE_CODE (templ) == COMPONENT_REF)
11076           {
11077             object = TREE_OPERAND (templ, 0);
11078             templ = TREE_OPERAND (templ, 1);
11079           }
11080         else
11081           object = NULL_TREE;
11082         templ = lookup_template_function (templ, targs);
11083
11084         if (object)
11085           return build3 (COMPONENT_REF, TREE_TYPE (templ),
11086                          object, templ, NULL_TREE);
11087         else
11088           return baselink_for_fns (templ);
11089       }
11090
11091     case INDIRECT_REF:
11092       {
11093         tree r = RECUR (TREE_OPERAND (t, 0));
11094
11095         if (REFERENCE_REF_P (t))
11096           {
11097             /* A type conversion to reference type will be enclosed in
11098                such an indirect ref, but the substitution of the cast
11099                will have also added such an indirect ref.  */
11100             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
11101               r = convert_from_reference (r);
11102           }
11103         else
11104           r = build_x_indirect_ref (r, "unary *", complain);
11105         return r;
11106       }
11107
11108     case NOP_EXPR:
11109       return build_nop
11110         (tsubst (TREE_TYPE (t), args, complain, in_decl),
11111          RECUR (TREE_OPERAND (t, 0)));
11112
11113     case CAST_EXPR:
11114     case REINTERPRET_CAST_EXPR:
11115     case CONST_CAST_EXPR:
11116     case DYNAMIC_CAST_EXPR:
11117     case STATIC_CAST_EXPR:
11118       {
11119         tree type;
11120         tree op;
11121
11122         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11123         if (integral_constant_expression_p
11124             && !cast_valid_in_integral_constant_expression_p (type))
11125           {
11126             if (complain & tf_error)
11127               error ("a cast to a type other than an integral or "
11128                      "enumeration type cannot appear in a constant-expression");
11129             return error_mark_node; 
11130           }
11131
11132         op = RECUR (TREE_OPERAND (t, 0));
11133
11134         switch (TREE_CODE (t))
11135           {
11136           case CAST_EXPR:
11137             return build_functional_cast (type, op, complain);
11138           case REINTERPRET_CAST_EXPR:
11139             return build_reinterpret_cast (type, op, complain);
11140           case CONST_CAST_EXPR:
11141             return build_const_cast (type, op, complain);
11142           case DYNAMIC_CAST_EXPR:
11143             return build_dynamic_cast (type, op, complain);
11144           case STATIC_CAST_EXPR:
11145             return build_static_cast (type, op, complain);
11146           default:
11147             gcc_unreachable ();
11148           }
11149       }
11150
11151     case POSTDECREMENT_EXPR:
11152     case POSTINCREMENT_EXPR:
11153       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11154                                                 args, complain, in_decl);
11155       return build_x_unary_op (TREE_CODE (t), op1, complain);
11156
11157     case PREDECREMENT_EXPR:
11158     case PREINCREMENT_EXPR:
11159     case NEGATE_EXPR:
11160     case BIT_NOT_EXPR:
11161     case ABS_EXPR:
11162     case TRUTH_NOT_EXPR:
11163     case UNARY_PLUS_EXPR:  /* Unary + */
11164     case REALPART_EXPR:
11165     case IMAGPART_EXPR:
11166       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
11167                                complain);
11168
11169     case ADDR_EXPR:
11170       op1 = TREE_OPERAND (t, 0);
11171       if (TREE_CODE (op1) == SCOPE_REF)
11172         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
11173                                    /*done=*/true, /*address_p=*/true);
11174       else
11175         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
11176                                                   in_decl);
11177       if (TREE_CODE (op1) == LABEL_DECL)
11178         return finish_label_address_expr (DECL_NAME (op1),
11179                                           EXPR_LOCATION (op1));
11180       return build_x_unary_op (ADDR_EXPR, op1, complain);
11181
11182     case PLUS_EXPR:
11183     case MINUS_EXPR:
11184     case MULT_EXPR:
11185     case TRUNC_DIV_EXPR:
11186     case CEIL_DIV_EXPR:
11187     case FLOOR_DIV_EXPR:
11188     case ROUND_DIV_EXPR:
11189     case EXACT_DIV_EXPR:
11190     case BIT_AND_EXPR:
11191     case BIT_IOR_EXPR:
11192     case BIT_XOR_EXPR:
11193     case TRUNC_MOD_EXPR:
11194     case FLOOR_MOD_EXPR:
11195     case TRUTH_ANDIF_EXPR:
11196     case TRUTH_ORIF_EXPR:
11197     case TRUTH_AND_EXPR:
11198     case TRUTH_OR_EXPR:
11199     case RSHIFT_EXPR:
11200     case LSHIFT_EXPR:
11201     case RROTATE_EXPR:
11202     case LROTATE_EXPR:
11203     case EQ_EXPR:
11204     case NE_EXPR:
11205     case MAX_EXPR:
11206     case MIN_EXPR:
11207     case LE_EXPR:
11208     case GE_EXPR:
11209     case LT_EXPR:
11210     case GT_EXPR:
11211     case MEMBER_REF:
11212     case DOTSTAR_EXPR:
11213       return build_x_binary_op
11214         (TREE_CODE (t),
11215          RECUR (TREE_OPERAND (t, 0)),
11216          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
11217           ? ERROR_MARK
11218           : TREE_CODE (TREE_OPERAND (t, 0))),
11219          RECUR (TREE_OPERAND (t, 1)),
11220          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
11221           ? ERROR_MARK
11222           : TREE_CODE (TREE_OPERAND (t, 1))),
11223          /*overloaded_p=*/NULL,
11224          complain);
11225
11226     case SCOPE_REF:
11227       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
11228                                   /*address_p=*/false);
11229     case ARRAY_REF:
11230       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11231                                                 args, complain, in_decl);
11232       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
11233
11234     case SIZEOF_EXPR:
11235       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11236         return tsubst_copy (t, args, complain, in_decl);
11237       /* Fall through */
11238       
11239     case ALIGNOF_EXPR:
11240       op1 = TREE_OPERAND (t, 0);
11241       if (!args)
11242         {
11243           /* When there are no ARGS, we are trying to evaluate a
11244              non-dependent expression from the parser.  Trying to do
11245              the substitutions may not work.  */
11246           if (!TYPE_P (op1))
11247             op1 = TREE_TYPE (op1);
11248         }
11249       else
11250         {
11251           ++skip_evaluation;
11252           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
11253                                        /*function_p=*/false,
11254                                        /*integral_constant_expression_p=*/false);
11255           --skip_evaluation;
11256         }
11257       if (TYPE_P (op1))
11258         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
11259                                            complain & tf_error);
11260       else
11261         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
11262                                            complain & tf_error);
11263
11264     case MODOP_EXPR:
11265       {
11266         tree r = build_x_modify_expr
11267           (RECUR (TREE_OPERAND (t, 0)),
11268            TREE_CODE (TREE_OPERAND (t, 1)),
11269            RECUR (TREE_OPERAND (t, 2)),
11270            complain);
11271         /* TREE_NO_WARNING must be set if either the expression was
11272            parenthesized or it uses an operator such as >>= rather
11273            than plain assignment.  In the former case, it was already
11274            set and must be copied.  In the latter case,
11275            build_x_modify_expr sets it and it must not be reset
11276            here.  */
11277         if (TREE_NO_WARNING (t))
11278           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11279         return r;
11280       }
11281
11282     case ARROW_EXPR:
11283       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11284                                                 args, complain, in_decl);
11285       /* Remember that there was a reference to this entity.  */
11286       if (DECL_P (op1))
11287         mark_used (op1);
11288       return build_x_arrow (op1);
11289
11290     case NEW_EXPR:
11291       {
11292         tree init = RECUR (TREE_OPERAND (t, 3));
11293
11294         if (TREE_OPERAND (t, 3) && !init)
11295           /* If there was an initializer in the original tree, but
11296              it instantiated to an empty list, then we should pass on
11297              VOID_ZERO_NODE to tell build_new that it was an empty
11298              initializer () rather than no initializer.  This can only
11299              happen when the initializer is a pack expansion whose
11300              parameter packs are of length zero.  */
11301           init = void_zero_node;
11302
11303         return build_new
11304           (RECUR (TREE_OPERAND (t, 0)),
11305            RECUR (TREE_OPERAND (t, 1)),
11306            RECUR (TREE_OPERAND (t, 2)),
11307            init,
11308            NEW_EXPR_USE_GLOBAL (t),
11309            complain);
11310       }
11311
11312     case DELETE_EXPR:
11313      return delete_sanity
11314        (RECUR (TREE_OPERAND (t, 0)),
11315         RECUR (TREE_OPERAND (t, 1)),
11316         DELETE_EXPR_USE_VEC (t),
11317         DELETE_EXPR_USE_GLOBAL (t));
11318
11319     case COMPOUND_EXPR:
11320       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
11321                                     RECUR (TREE_OPERAND (t, 1)),
11322                                     complain);
11323
11324     case CALL_EXPR:
11325       {
11326         tree function;
11327         tree call_args;
11328         bool qualified_p;
11329         bool koenig_p;
11330
11331         function = CALL_EXPR_FN (t);
11332         /* When we parsed the expression,  we determined whether or
11333            not Koenig lookup should be performed.  */
11334         koenig_p = KOENIG_LOOKUP_P (t);
11335         if (TREE_CODE (function) == SCOPE_REF)
11336           {
11337             qualified_p = true;
11338             function = tsubst_qualified_id (function, args, complain, in_decl,
11339                                             /*done=*/false,
11340                                             /*address_p=*/false);
11341           }
11342         else
11343           {
11344             if (TREE_CODE (function) == COMPONENT_REF)
11345               {
11346                 tree op = TREE_OPERAND (function, 1);
11347
11348                 qualified_p = (TREE_CODE (op) == SCOPE_REF
11349                                || (BASELINK_P (op)
11350                                    && BASELINK_QUALIFIED_P (op)));
11351               }
11352             else
11353               qualified_p = false;
11354
11355             function = tsubst_copy_and_build (function, args, complain,
11356                                               in_decl,
11357                                               !qualified_p,
11358                                               integral_constant_expression_p);
11359
11360             if (BASELINK_P (function))
11361               qualified_p = true;
11362           }
11363
11364         /* FIXME:  Rewrite this so as not to construct an arglist.  */
11365         call_args = RECUR (CALL_EXPR_ARGS (t));
11366
11367         /* We do not perform argument-dependent lookup if normal
11368            lookup finds a non-function, in accordance with the
11369            expected resolution of DR 218.  */
11370         if (koenig_p
11371             && ((is_overloaded_fn (function)
11372                  /* If lookup found a member function, the Koenig lookup is
11373                     not appropriate, even if an unqualified-name was used
11374                     to denote the function.  */
11375                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
11376                 || TREE_CODE (function) == IDENTIFIER_NODE))
11377           function = perform_koenig_lookup (function, call_args);
11378
11379         if (TREE_CODE (function) == IDENTIFIER_NODE)
11380           {
11381             unqualified_name_lookup_error (function);
11382             return error_mark_node;
11383           }
11384
11385         /* Remember that there was a reference to this entity.  */
11386         if (DECL_P (function))
11387           mark_used (function);
11388
11389         if (TREE_CODE (function) == OFFSET_REF)
11390           return build_offset_ref_call_from_tree (function, call_args);
11391         if (TREE_CODE (function) == COMPONENT_REF)
11392           {
11393             if (!BASELINK_P (TREE_OPERAND (function, 1)))
11394               return finish_call_expr (function, call_args,
11395                                        /*disallow_virtual=*/false,
11396                                        /*koenig_p=*/false,
11397                                        complain);
11398             else
11399               return (build_new_method_call
11400                       (TREE_OPERAND (function, 0),
11401                        TREE_OPERAND (function, 1),
11402                        call_args, NULL_TREE,
11403                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
11404                        /*fn_p=*/NULL,
11405                        complain));
11406           }
11407         /* Pass true for koenig_p so that build_new_function_call will
11408            allow hidden friends found by arg-dependent lookup at template
11409            parsing time.  */
11410         return finish_call_expr (function, call_args,
11411                                  /*disallow_virtual=*/qualified_p,
11412                                  /*koenig_p*/true,
11413                                  complain);
11414       }
11415
11416     case COND_EXPR:
11417       return build_x_conditional_expr
11418         (RECUR (TREE_OPERAND (t, 0)),
11419          RECUR (TREE_OPERAND (t, 1)),
11420          RECUR (TREE_OPERAND (t, 2)),
11421          complain);
11422
11423     case PSEUDO_DTOR_EXPR:
11424       return finish_pseudo_destructor_expr
11425         (RECUR (TREE_OPERAND (t, 0)),
11426          RECUR (TREE_OPERAND (t, 1)),
11427          RECUR (TREE_OPERAND (t, 2)));
11428
11429     case TREE_LIST:
11430       {
11431         tree purpose, value, chain;
11432
11433         if (t == void_list_node)
11434           return t;
11435
11436         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
11437             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
11438           {
11439             /* We have pack expansions, so expand those and
11440                create a new list out of it.  */
11441             tree purposevec = NULL_TREE;
11442             tree valuevec = NULL_TREE;
11443             tree chain;
11444             int i, len = -1;
11445
11446             /* Expand the argument expressions.  */
11447             if (TREE_PURPOSE (t))
11448               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
11449                                                  complain, in_decl);
11450             if (TREE_VALUE (t))
11451               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
11452                                                complain, in_decl);
11453
11454             /* Build the rest of the list.  */
11455             chain = TREE_CHAIN (t);
11456             if (chain && chain != void_type_node)
11457               chain = RECUR (chain);
11458
11459             /* Determine the number of arguments.  */
11460             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
11461               {
11462                 len = TREE_VEC_LENGTH (purposevec);
11463                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
11464               }
11465             else if (TREE_CODE (valuevec) == TREE_VEC)
11466               len = TREE_VEC_LENGTH (valuevec);
11467             else
11468               {
11469                 /* Since we only performed a partial substitution into
11470                    the argument pack, we only return a single list
11471                    node.  */
11472                 if (purposevec == TREE_PURPOSE (t)
11473                     && valuevec == TREE_VALUE (t)
11474                     && chain == TREE_CHAIN (t))
11475                   return t;
11476
11477                 return tree_cons (purposevec, valuevec, chain);
11478               }
11479             
11480             /* Convert the argument vectors into a TREE_LIST */
11481             i = len;
11482             while (i > 0)
11483               {
11484                 /* Grab the Ith values.  */
11485                 i--;
11486                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
11487                                      : NULL_TREE;
11488                 value 
11489                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
11490                              : NULL_TREE;
11491
11492                 /* Build the list (backwards).  */
11493                 chain = tree_cons (purpose, value, chain);
11494               }
11495
11496             return chain;
11497           }
11498
11499         purpose = TREE_PURPOSE (t);
11500         if (purpose)
11501           purpose = RECUR (purpose);
11502         value = TREE_VALUE (t);
11503         if (value)
11504           value = RECUR (value);
11505         chain = TREE_CHAIN (t);
11506         if (chain && chain != void_type_node)
11507           chain = RECUR (chain);
11508         if (purpose == TREE_PURPOSE (t)
11509             && value == TREE_VALUE (t)
11510             && chain == TREE_CHAIN (t))
11511           return t;
11512         return tree_cons (purpose, value, chain);
11513       }
11514
11515     case COMPONENT_REF:
11516       {
11517         tree object;
11518         tree object_type;
11519         tree member;
11520
11521         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11522                                                      args, complain, in_decl);
11523         /* Remember that there was a reference to this entity.  */
11524         if (DECL_P (object))
11525           mark_used (object);
11526         object_type = TREE_TYPE (object);
11527
11528         member = TREE_OPERAND (t, 1);
11529         if (BASELINK_P (member))
11530           member = tsubst_baselink (member,
11531                                     non_reference (TREE_TYPE (object)),
11532                                     args, complain, in_decl);
11533         else
11534           member = tsubst_copy (member, args, complain, in_decl);
11535         if (member == error_mark_node)
11536           return error_mark_node;
11537
11538         if (object_type && !CLASS_TYPE_P (object_type))
11539           {
11540             if (SCALAR_TYPE_P (object_type))
11541               {
11542                 tree s = NULL_TREE;
11543                 tree dtor = member;
11544
11545                 if (TREE_CODE (dtor) == SCOPE_REF)
11546                   {
11547                     s = TREE_OPERAND (dtor, 0);
11548                     dtor = TREE_OPERAND (dtor, 1);
11549                   }
11550                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
11551                   {
11552                     dtor = TREE_OPERAND (dtor, 0);
11553                     if (TYPE_P (dtor))
11554                       return finish_pseudo_destructor_expr (object, s, dtor);
11555                   }
11556               }
11557           }
11558         else if (TREE_CODE (member) == SCOPE_REF
11559                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
11560           {
11561             tree tmpl;
11562             tree args;
11563
11564             /* Lookup the template functions now that we know what the
11565                scope is.  */
11566             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
11567             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
11568             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
11569                                             /*is_type_p=*/false,
11570                                             /*complain=*/false);
11571             if (BASELINK_P (member))
11572               {
11573                 BASELINK_FUNCTIONS (member)
11574                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
11575                               args);
11576                 member = (adjust_result_of_qualified_name_lookup
11577                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
11578                            object_type));
11579               }
11580             else
11581               {
11582                 qualified_name_lookup_error (object_type, tmpl, member,
11583                                              input_location);
11584                 return error_mark_node;
11585               }
11586           }
11587         else if (TREE_CODE (member) == SCOPE_REF
11588                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
11589                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
11590           {
11591             if (complain & tf_error)
11592               {
11593                 if (TYPE_P (TREE_OPERAND (member, 0)))
11594                   error ("%qT is not a class or namespace",
11595                          TREE_OPERAND (member, 0));
11596                 else
11597                   error ("%qD is not a class or namespace",
11598                          TREE_OPERAND (member, 0));
11599               }
11600             return error_mark_node;
11601           }
11602         else if (TREE_CODE (member) == FIELD_DECL)
11603           return finish_non_static_data_member (member, object, NULL_TREE);
11604
11605         return finish_class_member_access_expr (object, member,
11606                                                 /*template_p=*/false,
11607                                                 complain);
11608       }
11609
11610     case THROW_EXPR:
11611       return build_throw
11612         (RECUR (TREE_OPERAND (t, 0)));
11613
11614     case CONSTRUCTOR:
11615       {
11616         VEC(constructor_elt,gc) *n;
11617         constructor_elt *ce;
11618         unsigned HOST_WIDE_INT idx;
11619         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11620         bool process_index_p;
11621         int newlen;
11622         bool need_copy_p = false;
11623         tree r;
11624
11625         if (type == error_mark_node)
11626           return error_mark_node;
11627
11628         /* digest_init will do the wrong thing if we let it.  */
11629         if (type && TYPE_PTRMEMFUNC_P (type))
11630           return t;
11631
11632         /* We do not want to process the index of aggregate
11633            initializers as they are identifier nodes which will be
11634            looked up by digest_init.  */
11635         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
11636
11637         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
11638         newlen = VEC_length (constructor_elt, n);
11639         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
11640           {
11641             if (ce->index && process_index_p)
11642               ce->index = RECUR (ce->index);
11643
11644             if (PACK_EXPANSION_P (ce->value))
11645               {
11646                 /* Substitute into the pack expansion.  */
11647                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
11648                                                   in_decl);
11649
11650                 if (ce->value == error_mark_node)
11651                   ;
11652                 else if (TREE_VEC_LENGTH (ce->value) == 1)
11653                   /* Just move the argument into place.  */
11654                   ce->value = TREE_VEC_ELT (ce->value, 0);
11655                 else
11656                   {
11657                     /* Update the length of the final CONSTRUCTOR
11658                        arguments vector, and note that we will need to
11659                        copy.*/
11660                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
11661                     need_copy_p = true;
11662                   }
11663               }
11664             else
11665               ce->value = RECUR (ce->value);
11666           }
11667
11668         if (need_copy_p)
11669           {
11670             VEC(constructor_elt,gc) *old_n = n;
11671
11672             n = VEC_alloc (constructor_elt, gc, newlen);
11673             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
11674                  idx++)
11675               {
11676                 if (TREE_CODE (ce->value) == TREE_VEC)
11677                   {
11678                     int i, len = TREE_VEC_LENGTH (ce->value);
11679                     for (i = 0; i < len; ++i)
11680                       CONSTRUCTOR_APPEND_ELT (n, 0,
11681                                               TREE_VEC_ELT (ce->value, i));
11682                   }
11683                 else
11684                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
11685               }
11686           }
11687
11688         r = build_constructor (init_list_type_node, n);
11689         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
11690
11691         if (TREE_HAS_CONSTRUCTOR (t))
11692           return finish_compound_literal (type, r);
11693
11694         return r;
11695       }
11696
11697     case TYPEID_EXPR:
11698       {
11699         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
11700         if (TYPE_P (operand_0))
11701           return get_typeid (operand_0);
11702         return build_typeid (operand_0);
11703       }
11704
11705     case VAR_DECL:
11706       if (!args)
11707         return t;
11708       /* Fall through */
11709
11710     case PARM_DECL:
11711       {
11712         tree r = tsubst_copy (t, args, complain, in_decl);
11713
11714         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
11715           /* If the original type was a reference, we'll be wrapped in
11716              the appropriate INDIRECT_REF.  */
11717           r = convert_from_reference (r);
11718         return r;
11719       }
11720
11721     case VA_ARG_EXPR:
11722       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
11723                              tsubst_copy (TREE_TYPE (t), args, complain,
11724                                           in_decl));
11725
11726     case OFFSETOF_EXPR:
11727       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
11728
11729     case TRAIT_EXPR:
11730       {
11731         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
11732                                   complain, in_decl);
11733
11734         tree type2 = TRAIT_EXPR_TYPE2 (t);
11735         if (type2)
11736           type2 = tsubst_copy (type2, args, complain, in_decl);
11737         
11738         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
11739       }
11740
11741     case STMT_EXPR:
11742       {
11743         tree old_stmt_expr = cur_stmt_expr;
11744         tree stmt_expr = begin_stmt_expr ();
11745
11746         cur_stmt_expr = stmt_expr;
11747         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
11748                      integral_constant_expression_p);
11749         stmt_expr = finish_stmt_expr (stmt_expr, false);
11750         cur_stmt_expr = old_stmt_expr;
11751
11752         return stmt_expr;
11753       }
11754
11755     case CONST_DECL:
11756       t = tsubst_copy (t, args, complain, in_decl);
11757       /* As in finish_id_expression, we resolve enumeration constants
11758          to their underlying values.  */
11759       if (TREE_CODE (t) == CONST_DECL)
11760         {
11761           used_types_insert (TREE_TYPE (t));
11762           return DECL_INITIAL (t);
11763         }
11764       return t;
11765
11766     default:
11767       /* Handle Objective-C++ constructs, if appropriate.  */
11768       {
11769         tree subst
11770           = objcp_tsubst_copy_and_build (t, args, complain,
11771                                          in_decl, /*function_p=*/false);
11772         if (subst)
11773           return subst;
11774       }
11775       return tsubst_copy (t, args, complain, in_decl);
11776     }
11777
11778 #undef RECUR
11779 }
11780
11781 /* Verify that the instantiated ARGS are valid. For type arguments,
11782    make sure that the type's linkage is ok. For non-type arguments,
11783    make sure they are constants if they are integral or enumerations.
11784    Emit an error under control of COMPLAIN, and return TRUE on error.  */
11785
11786 static bool
11787 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
11788 {
11789   if (ARGUMENT_PACK_P (t))
11790     {
11791       tree vec = ARGUMENT_PACK_ARGS (t);
11792       int len = TREE_VEC_LENGTH (vec);
11793       bool result = false;
11794       int i;
11795
11796       for (i = 0; i < len; ++i)
11797         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
11798           result = true;
11799       return result;
11800     }
11801   else if (TYPE_P (t))
11802     {
11803       /* [basic.link]: A name with no linkage (notably, the name
11804          of a class or enumeration declared in a local scope)
11805          shall not be used to declare an entity with linkage.
11806          This implies that names with no linkage cannot be used as
11807          template arguments.  */
11808       tree nt = no_linkage_check (t, /*relaxed_p=*/false);
11809
11810       if (nt)
11811         {
11812           /* DR 488 makes use of a type with no linkage cause
11813              type deduction to fail.  */
11814           if (complain & tf_error)
11815             {
11816               if (TYPE_ANONYMOUS_P (nt))
11817                 error ("%qT is/uses anonymous type", t);
11818               else
11819                 error ("template argument for %qD uses local type %qT",
11820                        tmpl, t);
11821             }
11822           return true;
11823         }
11824       /* In order to avoid all sorts of complications, we do not
11825          allow variably-modified types as template arguments.  */
11826       else if (variably_modified_type_p (t, NULL_TREE))
11827         {
11828           if (complain & tf_error)
11829             error ("%qT is a variably modified type", t);
11830           return true;
11831         }
11832     }
11833   /* A non-type argument of integral or enumerated type must be a
11834      constant.  */
11835   else if (TREE_TYPE (t)
11836            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
11837            && !TREE_CONSTANT (t))
11838     {
11839       if (complain & tf_error)
11840         error ("integral expression %qE is not constant", t);
11841       return true;
11842     }
11843   return false;
11844 }
11845
11846 static bool
11847 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
11848 {
11849   int ix, len = DECL_NTPARMS (tmpl);
11850   bool result = false;
11851
11852   for (ix = 0; ix != len; ix++)
11853     {
11854       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
11855         result = true;
11856     }
11857   if (result && (complain & tf_error))
11858     error ("  trying to instantiate %qD", tmpl);
11859   return result;
11860 }
11861
11862 /* Instantiate the indicated variable or function template TMPL with
11863    the template arguments in TARG_PTR.  */
11864
11865 tree
11866 instantiate_template (tree tmpl, tree targ_ptr, tsubst_flags_t complain)
11867 {
11868   tree fndecl;
11869   tree gen_tmpl;
11870   tree spec;
11871   HOST_WIDE_INT saved_processing_template_decl;
11872
11873   if (tmpl == error_mark_node)
11874     return error_mark_node;
11875
11876   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
11877
11878   /* If this function is a clone, handle it specially.  */
11879   if (DECL_CLONED_FUNCTION_P (tmpl))
11880     {
11881       tree spec;
11882       tree clone;
11883
11884       spec = instantiate_template (DECL_CLONED_FUNCTION (tmpl), targ_ptr,
11885                                    complain);
11886       if (spec == error_mark_node)
11887         return error_mark_node;
11888
11889       /* Look for the clone.  */
11890       FOR_EACH_CLONE (clone, spec)
11891         if (DECL_NAME (clone) == DECL_NAME (tmpl))
11892           return clone;
11893       /* We should always have found the clone by now.  */
11894       gcc_unreachable ();
11895       return NULL_TREE;
11896     }
11897
11898   /* Check to see if we already have this specialization.  */
11899   spec = retrieve_specialization (tmpl, targ_ptr,
11900                                   /*class_specializations_p=*/false);
11901   if (spec != NULL_TREE)
11902     return spec;
11903
11904   gen_tmpl = most_general_template (tmpl);
11905   if (tmpl != gen_tmpl)
11906     {
11907       /* The TMPL is a partial instantiation.  To get a full set of
11908          arguments we must add the arguments used to perform the
11909          partial instantiation.  */
11910       targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
11911                                               targ_ptr);
11912
11913       /* Check to see if we already have this specialization.  */
11914       spec = retrieve_specialization (gen_tmpl, targ_ptr,
11915                                       /*class_specializations_p=*/false);
11916       if (spec != NULL_TREE)
11917         return spec;
11918     }
11919
11920   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
11921                                complain))
11922     return error_mark_node;
11923
11924   /* We are building a FUNCTION_DECL, during which the access of its
11925      parameters and return types have to be checked.  However this
11926      FUNCTION_DECL which is the desired context for access checking
11927      is not built yet.  We solve this chicken-and-egg problem by
11928      deferring all checks until we have the FUNCTION_DECL.  */
11929   push_deferring_access_checks (dk_deferred);
11930
11931   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
11932      (because, for example, we have encountered a non-dependent
11933      function call in the body of a template function and must now
11934      determine which of several overloaded functions will be called),
11935      within the instantiation itself we are not processing a
11936      template.  */  
11937   saved_processing_template_decl = processing_template_decl;
11938   processing_template_decl = 0;
11939   /* Substitute template parameters to obtain the specialization.  */
11940   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
11941                    targ_ptr, complain, gen_tmpl);
11942   processing_template_decl = saved_processing_template_decl;
11943   if (fndecl == error_mark_node)
11944     return error_mark_node;
11945
11946   /* Now we know the specialization, compute access previously
11947      deferred.  */
11948   push_access_scope (fndecl);
11949   perform_deferred_access_checks ();
11950   pop_access_scope (fndecl);
11951   pop_deferring_access_checks ();
11952
11953   /* The DECL_TI_TEMPLATE should always be the immediate parent
11954      template, not the most general template.  */
11955   DECL_TI_TEMPLATE (fndecl) = tmpl;
11956
11957   /* If we've just instantiated the main entry point for a function,
11958      instantiate all the alternate entry points as well.  We do this
11959      by cloning the instantiation of the main entry point, not by
11960      instantiating the template clones.  */
11961   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
11962     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
11963
11964   return fndecl;
11965 }
11966
11967 /* The FN is a TEMPLATE_DECL for a function.  The ARGS are the
11968    arguments that are being used when calling it.  TARGS is a vector
11969    into which the deduced template arguments are placed.
11970
11971    Return zero for success, 2 for an incomplete match that doesn't resolve
11972    all the types, and 1 for complete failure.  An error message will be
11973    printed only for an incomplete match.
11974
11975    If FN is a conversion operator, or we are trying to produce a specific
11976    specialization, RETURN_TYPE is the return type desired.
11977
11978    The EXPLICIT_TARGS are explicit template arguments provided via a
11979    template-id.
11980
11981    The parameter STRICT is one of:
11982
11983    DEDUCE_CALL:
11984      We are deducing arguments for a function call, as in
11985      [temp.deduct.call].
11986
11987    DEDUCE_CONV:
11988      We are deducing arguments for a conversion function, as in
11989      [temp.deduct.conv].
11990
11991    DEDUCE_EXACT:
11992      We are deducing arguments when doing an explicit instantiation
11993      as in [temp.explicit], when determining an explicit specialization
11994      as in [temp.expl.spec], or when taking the address of a function
11995      template, as in [temp.deduct.funcaddr].  */
11996
11997 int
11998 fn_type_unification (tree fn,
11999                      tree explicit_targs,
12000                      tree targs,
12001                      tree args,
12002                      tree return_type,
12003                      unification_kind_t strict,
12004                      int flags)
12005 {
12006   tree parms;
12007   tree fntype;
12008   int result;
12009   bool incomplete_argument_packs_p = false;
12010
12011   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
12012
12013   fntype = TREE_TYPE (fn);
12014   if (explicit_targs)
12015     {
12016       /* [temp.deduct]
12017
12018          The specified template arguments must match the template
12019          parameters in kind (i.e., type, nontype, template), and there
12020          must not be more arguments than there are parameters;
12021          otherwise type deduction fails.
12022
12023          Nontype arguments must match the types of the corresponding
12024          nontype template parameters, or must be convertible to the
12025          types of the corresponding nontype parameters as specified in
12026          _temp.arg.nontype_, otherwise type deduction fails.
12027
12028          All references in the function type of the function template
12029          to the corresponding template parameters are replaced by the
12030          specified template argument values.  If a substitution in a
12031          template parameter or in the function type of the function
12032          template results in an invalid type, type deduction fails.  */
12033       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
12034       int i, len = TREE_VEC_LENGTH (tparms);
12035       tree converted_args;
12036       bool incomplete = false;
12037
12038       if (explicit_targs == error_mark_node)
12039         return 1;
12040
12041       converted_args
12042         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
12043                                   /*require_all_args=*/false,
12044                                   /*use_default_args=*/false));
12045       if (converted_args == error_mark_node)
12046         return 1;
12047
12048       /* Substitute the explicit args into the function type.  This is
12049          necessary so that, for instance, explicitly declared function
12050          arguments can match null pointed constants.  If we were given
12051          an incomplete set of explicit args, we must not do semantic
12052          processing during substitution as we could create partial
12053          instantiations.  */
12054       for (i = 0; i < len; i++)
12055         {
12056           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12057           bool parameter_pack = false;
12058
12059           /* Dig out the actual parm.  */
12060           if (TREE_CODE (parm) == TYPE_DECL
12061               || TREE_CODE (parm) == TEMPLATE_DECL)
12062             {
12063               parm = TREE_TYPE (parm);
12064               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
12065             }
12066           else if (TREE_CODE (parm) == PARM_DECL)
12067             {
12068               parm = DECL_INITIAL (parm);
12069               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
12070             }
12071
12072           if (parameter_pack)
12073             {
12074               int level, idx;
12075               tree targ;
12076               template_parm_level_and_index (parm, &level, &idx);
12077
12078               /* Mark the argument pack as "incomplete". We could
12079                  still deduce more arguments during unification.  */
12080               targ = TMPL_ARG (converted_args, level, idx);
12081               if (targ)
12082                 {
12083                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
12084                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
12085                     = ARGUMENT_PACK_ARGS (targ);
12086                 }
12087
12088               /* We have some incomplete argument packs.  */
12089               incomplete_argument_packs_p = true;
12090             }
12091         }
12092
12093       if (incomplete_argument_packs_p)
12094         /* Any substitution is guaranteed to be incomplete if there
12095            are incomplete argument packs, because we can still deduce
12096            more arguments.  */
12097         incomplete = 1;
12098       else
12099         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
12100
12101       processing_template_decl += incomplete;
12102       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
12103       processing_template_decl -= incomplete;
12104
12105       if (fntype == error_mark_node)
12106         return 1;
12107
12108       /* Place the explicitly specified arguments in TARGS.  */
12109       for (i = NUM_TMPL_ARGS (converted_args); i--;)
12110         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
12111     }
12112
12113   /* Never do unification on the 'this' parameter.  */
12114   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
12115
12116   if (return_type)
12117     {
12118       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
12119       args = tree_cons (NULL_TREE, return_type, args);
12120     }
12121
12122   /* We allow incomplete unification without an error message here
12123      because the standard doesn't seem to explicitly prohibit it.  Our
12124      callers must be ready to deal with unification failures in any
12125      event.  */
12126   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
12127                                   targs, parms, args, /*subr=*/0,
12128                                   strict, flags);
12129
12130   if (result == 0 && incomplete_argument_packs_p)
12131     {
12132       int i, len = NUM_TMPL_ARGS (targs);
12133
12134       /* Clear the "incomplete" flags on all argument packs.  */
12135       for (i = 0; i < len; i++)
12136         {
12137           tree arg = TREE_VEC_ELT (targs, i);
12138           if (ARGUMENT_PACK_P (arg))
12139             {
12140               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
12141               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
12142             }
12143         }
12144     }
12145
12146   /* Now that we have bindings for all of the template arguments,
12147      ensure that the arguments deduced for the template template
12148      parameters have compatible template parameter lists.  We cannot
12149      check this property before we have deduced all template
12150      arguments, because the template parameter types of a template
12151      template parameter might depend on prior template parameters
12152      deduced after the template template parameter.  The following
12153      ill-formed example illustrates this issue:
12154
12155        template<typename T, template<T> class C> void f(C<5>, T);
12156
12157        template<int N> struct X {};
12158
12159        void g() {
12160          f(X<5>(), 5l); // error: template argument deduction fails
12161        }
12162
12163      The template parameter list of 'C' depends on the template type
12164      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
12165      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
12166      time that we deduce 'C'.  */
12167   if (result == 0
12168       && !template_template_parm_bindings_ok_p 
12169            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
12170     return 1;
12171
12172   if (result == 0)
12173     /* All is well so far.  Now, check:
12174
12175        [temp.deduct]
12176
12177        When all template arguments have been deduced, all uses of
12178        template parameters in nondeduced contexts are replaced with
12179        the corresponding deduced argument values.  If the
12180        substitution results in an invalid type, as described above,
12181        type deduction fails.  */
12182     if (tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE)
12183         == error_mark_node)
12184       return 1;
12185
12186   return result;
12187 }
12188
12189 /* Adjust types before performing type deduction, as described in
12190    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
12191    sections are symmetric.  PARM is the type of a function parameter
12192    or the return type of the conversion function.  ARG is the type of
12193    the argument passed to the call, or the type of the value
12194    initialized with the result of the conversion function.
12195    ARG_EXPR is the original argument expression, which may be null.  */
12196
12197 static int
12198 maybe_adjust_types_for_deduction (unification_kind_t strict,
12199                                   tree* parm,
12200                                   tree* arg,
12201                                   tree arg_expr)
12202 {
12203   int result = 0;
12204
12205   switch (strict)
12206     {
12207     case DEDUCE_CALL:
12208       break;
12209
12210     case DEDUCE_CONV:
12211       {
12212         /* Swap PARM and ARG throughout the remainder of this
12213            function; the handling is precisely symmetric since PARM
12214            will initialize ARG rather than vice versa.  */
12215         tree* temp = parm;
12216         parm = arg;
12217         arg = temp;
12218         break;
12219       }
12220
12221     case DEDUCE_EXACT:
12222       /* There is nothing to do in this case.  */
12223       return 0;
12224
12225     default:
12226       gcc_unreachable ();
12227     }
12228
12229   if (TREE_CODE (*parm) != REFERENCE_TYPE)
12230     {
12231       /* [temp.deduct.call]
12232
12233          If P is not a reference type:
12234
12235          --If A is an array type, the pointer type produced by the
12236          array-to-pointer standard conversion (_conv.array_) is
12237          used in place of A for type deduction; otherwise,
12238
12239          --If A is a function type, the pointer type produced by
12240          the function-to-pointer standard conversion
12241          (_conv.func_) is used in place of A for type deduction;
12242          otherwise,
12243
12244          --If A is a cv-qualified type, the top level
12245          cv-qualifiers of A's type are ignored for type
12246          deduction.  */
12247       if (TREE_CODE (*arg) == ARRAY_TYPE)
12248         *arg = build_pointer_type (TREE_TYPE (*arg));
12249       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
12250         *arg = build_pointer_type (*arg);
12251       else
12252         *arg = TYPE_MAIN_VARIANT (*arg);
12253     }
12254
12255   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
12256      of the form T&&, where T is a template parameter, and the argument
12257      is an lvalue, T is deduced as A& */
12258   if (TREE_CODE (*parm) == REFERENCE_TYPE
12259       && TYPE_REF_IS_RVALUE (*parm)
12260       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
12261       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
12262       && arg_expr && real_lvalue_p (arg_expr))
12263     *arg = build_reference_type (*arg);
12264
12265   /* [temp.deduct.call]
12266
12267      If P is a cv-qualified type, the top level cv-qualifiers
12268      of P's type are ignored for type deduction.  If P is a
12269      reference type, the type referred to by P is used for
12270      type deduction.  */
12271   *parm = TYPE_MAIN_VARIANT (*parm);
12272   if (TREE_CODE (*parm) == REFERENCE_TYPE)
12273     {
12274       *parm = TREE_TYPE (*parm);
12275       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
12276     }
12277
12278   /* DR 322. For conversion deduction, remove a reference type on parm
12279      too (which has been swapped into ARG).  */
12280   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
12281     *arg = TREE_TYPE (*arg);
12282
12283   return result;
12284 }
12285
12286 /* Most parms like fn_type_unification.
12287
12288    If SUBR is 1, we're being called recursively (to unify the
12289    arguments of a function or method parameter of a function
12290    template). */
12291
12292 static int
12293 type_unification_real (tree tparms,
12294                        tree targs,
12295                        tree xparms,
12296                        tree xargs,
12297                        int subr,
12298                        unification_kind_t strict,
12299                        int flags)
12300 {
12301   tree parm, arg, arg_expr;
12302   int i;
12303   int ntparms = TREE_VEC_LENGTH (tparms);
12304   int sub_strict;
12305   int saw_undeduced = 0;
12306   tree parms, args;
12307
12308   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
12309   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
12310   gcc_assert (!xargs || TREE_CODE (xargs) == TREE_LIST);
12311   gcc_assert (ntparms > 0);
12312
12313   switch (strict)
12314     {
12315     case DEDUCE_CALL:
12316       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
12317                     | UNIFY_ALLOW_DERIVED);
12318       break;
12319
12320     case DEDUCE_CONV:
12321       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
12322       break;
12323
12324     case DEDUCE_EXACT:
12325       sub_strict = UNIFY_ALLOW_NONE;
12326       break;
12327
12328     default:
12329       gcc_unreachable ();
12330     }
12331
12332  again:
12333   parms = xparms;
12334   args = xargs;
12335
12336   while (parms && parms != void_list_node
12337          && args && args != void_list_node)
12338     {
12339       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12340         break;
12341
12342       parm = TREE_VALUE (parms);
12343       parms = TREE_CHAIN (parms);
12344       arg = TREE_VALUE (args);
12345       args = TREE_CHAIN (args);
12346       arg_expr = NULL;
12347
12348       if (arg == error_mark_node)
12349         return 1;
12350       if (arg == unknown_type_node)
12351         /* We can't deduce anything from this, but we might get all the
12352            template args from other function args.  */
12353         continue;
12354
12355       /* Conversions will be performed on a function argument that
12356          corresponds with a function parameter that contains only
12357          non-deducible template parameters and explicitly specified
12358          template parameters.  */
12359       if (!uses_template_parms (parm))
12360         {
12361           tree type;
12362
12363           if (!TYPE_P (arg))
12364             type = TREE_TYPE (arg);
12365           else
12366             type = arg;
12367
12368           if (same_type_p (parm, type))
12369             continue;
12370           if (strict != DEDUCE_EXACT
12371               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
12372                                   flags))
12373             continue;
12374
12375           return 1;
12376         }
12377
12378       if (!TYPE_P (arg))
12379         {
12380           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
12381           if (type_unknown_p (arg))
12382             {
12383               /* [temp.deduct.type] 
12384
12385                  A template-argument can be deduced from a pointer to
12386                  function or pointer to member function argument if
12387                  the set of overloaded functions does not contain
12388                  function templates and at most one of a set of
12389                  overloaded functions provides a unique match.  */
12390               if (resolve_overloaded_unification
12391                   (tparms, targs, parm, arg, strict, sub_strict))
12392                 continue;
12393
12394               return 1;
12395             }
12396           arg_expr = arg;
12397           arg = unlowered_expr_type (arg);
12398           if (arg == error_mark_node)
12399             return 1;
12400         }
12401
12402       {
12403         int arg_strict = sub_strict;
12404
12405         if (!subr)
12406           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
12407                                                           arg_expr);
12408
12409         if (arg == init_list_type_node && arg_expr)
12410           arg = arg_expr;
12411         if (unify (tparms, targs, parm, arg, arg_strict))
12412           return 1;
12413       }
12414     }
12415
12416
12417   if (parms 
12418       && parms != void_list_node
12419       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12420     {
12421       /* Unify the remaining arguments with the pack expansion type.  */
12422       tree argvec;
12423       tree parmvec = make_tree_vec (1);
12424       int len = 0;
12425       tree t;
12426
12427       /* Count the number of arguments that remain.  */
12428       for (t = args; t && t != void_list_node; t = TREE_CHAIN (t))
12429         len++;
12430         
12431       /* Allocate a TREE_VEC and copy in all of the arguments */ 
12432       argvec = make_tree_vec (len);
12433       for (i = 0; args && args != void_list_node; args = TREE_CHAIN (args))
12434         {
12435           TREE_VEC_ELT (argvec, i) = TREE_VALUE (args);
12436           ++i;
12437         }
12438
12439       /* Copy the parameter into parmvec.  */
12440       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
12441       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
12442                                 /*call_args_p=*/true, /*subr=*/subr))
12443         return 1;
12444
12445       /* Advance to the end of the list of parameters.  */
12446       parms = TREE_CHAIN (parms);
12447     }
12448
12449   /* Fail if we've reached the end of the parm list, and more args
12450      are present, and the parm list isn't variadic.  */
12451   if (args && args != void_list_node && parms == void_list_node)
12452     return 1;
12453   /* Fail if parms are left and they don't have default values.  */
12454   if (parms && parms != void_list_node
12455       && TREE_PURPOSE (parms) == NULL_TREE)
12456     return 1;
12457
12458   if (!subr)
12459     for (i = 0; i < ntparms; i++)
12460       if (!TREE_VEC_ELT (targs, i))
12461         {
12462           tree tparm;
12463
12464           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
12465             continue;
12466
12467           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12468
12469           /* If this is an undeduced nontype parameter that depends on
12470              a type parameter, try another pass; its type may have been
12471              deduced from a later argument than the one from which
12472              this parameter can be deduced.  */
12473           if (TREE_CODE (tparm) == PARM_DECL
12474               && uses_template_parms (TREE_TYPE (tparm))
12475               && !saw_undeduced++)
12476             goto again;
12477
12478           /* Core issue #226 (C++0x) [temp.deduct]:
12479
12480                If a template argument has not been deduced, its
12481                default template argument, if any, is used. 
12482
12483              When we are in C++98 mode, TREE_PURPOSE will either
12484              be NULL_TREE or ERROR_MARK_NODE, so we do not need
12485              to explicitly check cxx_dialect here.  */
12486           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
12487             {
12488               tree arg = tsubst (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)), 
12489                                  targs, tf_none, NULL_TREE);
12490               if (arg == error_mark_node)
12491                 return 1;
12492               else
12493                 {
12494                   TREE_VEC_ELT (targs, i) = arg;
12495                   continue;
12496                 }
12497             }
12498
12499           /* If the type parameter is a parameter pack, then it will
12500              be deduced to an empty parameter pack.  */
12501           if (template_parameter_pack_p (tparm))
12502             {
12503               tree arg;
12504
12505               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
12506                 {
12507                   arg = make_node (NONTYPE_ARGUMENT_PACK);
12508                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
12509                   TREE_CONSTANT (arg) = 1;
12510                 }
12511               else
12512                 arg = make_node (TYPE_ARGUMENT_PACK);
12513
12514               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
12515
12516               TREE_VEC_ELT (targs, i) = arg;
12517               continue;
12518             }
12519
12520           return 2;
12521         }
12522
12523   return 0;
12524 }
12525
12526 /* Subroutine of type_unification_real.  Args are like the variables
12527    at the call site.  ARG is an overloaded function (or template-id);
12528    we try deducing template args from each of the overloads, and if
12529    only one succeeds, we go with that.  Modifies TARGS and returns
12530    true on success.  */
12531
12532 static bool
12533 resolve_overloaded_unification (tree tparms,
12534                                 tree targs,
12535                                 tree parm,
12536                                 tree arg,
12537                                 unification_kind_t strict,
12538                                 int sub_strict)
12539 {
12540   tree tempargs = copy_node (targs);
12541   int good = 0;
12542   bool addr_p;
12543
12544   if (TREE_CODE (arg) == ADDR_EXPR)
12545     {
12546       arg = TREE_OPERAND (arg, 0);
12547       addr_p = true;
12548     }
12549   else
12550     addr_p = false;
12551
12552   if (TREE_CODE (arg) == COMPONENT_REF)
12553     /* Handle `&x' where `x' is some static or non-static member
12554        function name.  */
12555     arg = TREE_OPERAND (arg, 1);
12556
12557   if (TREE_CODE (arg) == OFFSET_REF)
12558     arg = TREE_OPERAND (arg, 1);
12559
12560   /* Strip baselink information.  */
12561   if (BASELINK_P (arg))
12562     arg = BASELINK_FUNCTIONS (arg);
12563
12564   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
12565     {
12566       /* If we got some explicit template args, we need to plug them into
12567          the affected templates before we try to unify, in case the
12568          explicit args will completely resolve the templates in question.  */
12569
12570       tree expl_subargs = TREE_OPERAND (arg, 1);
12571       arg = TREE_OPERAND (arg, 0);
12572
12573       for (; arg; arg = OVL_NEXT (arg))
12574         {
12575           tree fn = OVL_CURRENT (arg);
12576           tree subargs, elem;
12577
12578           if (TREE_CODE (fn) != TEMPLATE_DECL)
12579             continue;
12580
12581           ++processing_template_decl;
12582           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
12583                                   expl_subargs, /*check_ret=*/false);
12584           if (subargs)
12585             {
12586               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
12587               good += try_one_overload (tparms, targs, tempargs, parm,
12588                                         elem, strict, sub_strict, addr_p);
12589             }
12590           --processing_template_decl;
12591         }
12592     }
12593   else if (TREE_CODE (arg) != OVERLOAD
12594            && TREE_CODE (arg) != FUNCTION_DECL)
12595     /* If ARG is, for example, "(0, &f)" then its type will be unknown
12596        -- but the deduction does not succeed because the expression is
12597        not just the function on its own.  */
12598     return false;
12599   else
12600     for (; arg; arg = OVL_NEXT (arg))
12601       good += try_one_overload (tparms, targs, tempargs, parm,
12602                                 TREE_TYPE (OVL_CURRENT (arg)),
12603                                 strict, sub_strict, addr_p);
12604
12605   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12606      to function or pointer to member function argument if the set of
12607      overloaded functions does not contain function templates and at most
12608      one of a set of overloaded functions provides a unique match.
12609
12610      So if we found multiple possibilities, we return success but don't
12611      deduce anything.  */
12612
12613   if (good == 1)
12614     {
12615       int i = TREE_VEC_LENGTH (targs);
12616       for (; i--; )
12617         if (TREE_VEC_ELT (tempargs, i))
12618           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
12619     }
12620   if (good)
12621     return true;
12622
12623   return false;
12624 }
12625
12626 /* Subroutine of resolve_overloaded_unification; does deduction for a single
12627    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
12628    different overloads deduce different arguments for a given parm.
12629    ADDR_P is true if the expression for which deduction is being
12630    performed was of the form "& fn" rather than simply "fn".
12631
12632    Returns 1 on success.  */
12633
12634 static int
12635 try_one_overload (tree tparms,
12636                   tree orig_targs,
12637                   tree targs,
12638                   tree parm,
12639                   tree arg,
12640                   unification_kind_t strict,
12641                   int sub_strict,
12642                   bool addr_p)
12643 {
12644   int nargs;
12645   tree tempargs;
12646   int i;
12647
12648   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12649      to function or pointer to member function argument if the set of
12650      overloaded functions does not contain function templates and at most
12651      one of a set of overloaded functions provides a unique match.
12652
12653      So if this is a template, just return success.  */
12654
12655   if (uses_template_parms (arg))
12656     return 1;
12657
12658   if (TREE_CODE (arg) == METHOD_TYPE)
12659     arg = build_ptrmemfunc_type (build_pointer_type (arg));
12660   else if (addr_p)
12661     arg = build_pointer_type (arg);
12662
12663   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
12664
12665   /* We don't copy orig_targs for this because if we have already deduced
12666      some template args from previous args, unify would complain when we
12667      try to deduce a template parameter for the same argument, even though
12668      there isn't really a conflict.  */
12669   nargs = TREE_VEC_LENGTH (targs);
12670   tempargs = make_tree_vec (nargs);
12671
12672   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
12673     return 0;
12674
12675   /* First make sure we didn't deduce anything that conflicts with
12676      explicitly specified args.  */
12677   for (i = nargs; i--; )
12678     {
12679       tree elt = TREE_VEC_ELT (tempargs, i);
12680       tree oldelt = TREE_VEC_ELT (orig_targs, i);
12681
12682       if (!elt)
12683         /*NOP*/;
12684       else if (uses_template_parms (elt))
12685         /* Since we're unifying against ourselves, we will fill in
12686            template args used in the function parm list with our own
12687            template parms.  Discard them.  */
12688         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
12689       else if (oldelt && !template_args_equal (oldelt, elt))
12690         return 0;
12691     }
12692
12693   for (i = nargs; i--; )
12694     {
12695       tree elt = TREE_VEC_ELT (tempargs, i);
12696
12697       if (elt)
12698         TREE_VEC_ELT (targs, i) = elt;
12699     }
12700
12701   return 1;
12702 }
12703
12704 /* PARM is a template class (perhaps with unbound template
12705    parameters).  ARG is a fully instantiated type.  If ARG can be
12706    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
12707    TARGS are as for unify.  */
12708
12709 static tree
12710 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
12711 {
12712   tree copy_of_targs;
12713
12714   if (!CLASSTYPE_TEMPLATE_INFO (arg)
12715       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
12716           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
12717     return NULL_TREE;
12718
12719   /* We need to make a new template argument vector for the call to
12720      unify.  If we used TARGS, we'd clutter it up with the result of
12721      the attempted unification, even if this class didn't work out.
12722      We also don't want to commit ourselves to all the unifications
12723      we've already done, since unification is supposed to be done on
12724      an argument-by-argument basis.  In other words, consider the
12725      following pathological case:
12726
12727        template <int I, int J, int K>
12728        struct S {};
12729
12730        template <int I, int J>
12731        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
12732
12733        template <int I, int J, int K>
12734        void f(S<I, J, K>, S<I, I, I>);
12735
12736        void g() {
12737          S<0, 0, 0> s0;
12738          S<0, 1, 2> s2;
12739
12740          f(s0, s2);
12741        }
12742
12743      Now, by the time we consider the unification involving `s2', we
12744      already know that we must have `f<0, 0, 0>'.  But, even though
12745      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
12746      because there are two ways to unify base classes of S<0, 1, 2>
12747      with S<I, I, I>.  If we kept the already deduced knowledge, we
12748      would reject the possibility I=1.  */
12749   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
12750
12751   /* If unification failed, we're done.  */
12752   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
12753              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
12754     return NULL_TREE;
12755
12756   return arg;
12757 }
12758
12759 /* Given a template type PARM and a class type ARG, find the unique
12760    base type in ARG that is an instance of PARM.  We do not examine
12761    ARG itself; only its base-classes.  If there is not exactly one
12762    appropriate base class, return NULL_TREE.  PARM may be the type of
12763    a partial specialization, as well as a plain template type.  Used
12764    by unify.  */
12765
12766 static tree
12767 get_template_base (tree tparms, tree targs, tree parm, tree arg)
12768 {
12769   tree rval = NULL_TREE;
12770   tree binfo;
12771
12772   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
12773
12774   binfo = TYPE_BINFO (complete_type (arg));
12775   if (!binfo)
12776     /* The type could not be completed.  */
12777     return NULL_TREE;
12778
12779   /* Walk in inheritance graph order.  The search order is not
12780      important, and this avoids multiple walks of virtual bases.  */
12781   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
12782     {
12783       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
12784
12785       if (r)
12786         {
12787           /* If there is more than one satisfactory baseclass, then:
12788
12789                [temp.deduct.call]
12790
12791               If they yield more than one possible deduced A, the type
12792               deduction fails.
12793
12794              applies.  */
12795           if (rval && !same_type_p (r, rval))
12796             return NULL_TREE;
12797
12798           rval = r;
12799         }
12800     }
12801
12802   return rval;
12803 }
12804
12805 /* Returns the level of DECL, which declares a template parameter.  */
12806
12807 static int
12808 template_decl_level (tree decl)
12809 {
12810   switch (TREE_CODE (decl))
12811     {
12812     case TYPE_DECL:
12813     case TEMPLATE_DECL:
12814       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
12815
12816     case PARM_DECL:
12817       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
12818
12819     default:
12820       gcc_unreachable ();
12821     }
12822   return 0;
12823 }
12824
12825 /* Decide whether ARG can be unified with PARM, considering only the
12826    cv-qualifiers of each type, given STRICT as documented for unify.
12827    Returns nonzero iff the unification is OK on that basis.  */
12828
12829 static int
12830 check_cv_quals_for_unify (int strict, tree arg, tree parm)
12831 {
12832   int arg_quals = cp_type_quals (arg);
12833   int parm_quals = cp_type_quals (parm);
12834
12835   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
12836       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
12837     {
12838       /*  Although a CVR qualifier is ignored when being applied to a
12839           substituted template parameter ([8.3.2]/1 for example), that
12840           does not apply during deduction [14.8.2.4]/1, (even though
12841           that is not explicitly mentioned, [14.8.2.4]/9 indicates
12842           this).  Except when we're allowing additional CV qualifiers
12843           at the outer level [14.8.2.1]/3,1st bullet.  */
12844       if ((TREE_CODE (arg) == REFERENCE_TYPE
12845            || TREE_CODE (arg) == FUNCTION_TYPE
12846            || TREE_CODE (arg) == METHOD_TYPE)
12847           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
12848         return 0;
12849
12850       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
12851           && (parm_quals & TYPE_QUAL_RESTRICT))
12852         return 0;
12853     }
12854
12855   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
12856       && (arg_quals & parm_quals) != parm_quals)
12857     return 0;
12858
12859   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
12860       && (parm_quals & arg_quals) != arg_quals)
12861     return 0;
12862
12863   return 1;
12864 }
12865
12866 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
12867 void 
12868 template_parm_level_and_index (tree parm, int* level, int* index)
12869 {
12870   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
12871       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
12872       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
12873     {
12874       *index = TEMPLATE_TYPE_IDX (parm);
12875       *level = TEMPLATE_TYPE_LEVEL (parm);
12876     }
12877   else
12878     {
12879       *index = TEMPLATE_PARM_IDX (parm);
12880       *level = TEMPLATE_PARM_LEVEL (parm);
12881     }
12882 }
12883
12884 /* Unifies the remaining arguments in PACKED_ARGS with the pack
12885    expansion at the end of PACKED_PARMS. Returns 0 if the type
12886    deduction succeeds, 1 otherwise. STRICT is the same as in
12887    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
12888    call argument list. We'll need to adjust the arguments to make them
12889    types. SUBR tells us if this is from a recursive call to
12890    type_unification_real.  */
12891 int
12892 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
12893                       tree packed_args, int strict, bool call_args_p,
12894                       bool subr)
12895 {
12896   tree parm 
12897     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
12898   tree pattern = PACK_EXPANSION_PATTERN (parm);
12899   tree pack, packs = NULL_TREE;
12900   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
12901   int len = TREE_VEC_LENGTH (packed_args);
12902
12903   /* Determine the parameter packs we will be deducing from the
12904      pattern, and record their current deductions.  */
12905   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
12906        pack; pack = TREE_CHAIN (pack))
12907     {
12908       tree parm_pack = TREE_VALUE (pack);
12909       int idx, level;
12910
12911       /* Determine the index and level of this parameter pack.  */
12912       template_parm_level_and_index (parm_pack, &level, &idx);
12913
12914       /* Keep track of the parameter packs and their corresponding
12915          argument packs.  */
12916       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
12917       TREE_TYPE (packs) = make_tree_vec (len - start);
12918     }
12919   
12920   /* Loop through all of the arguments that have not yet been
12921      unified and unify each with the pattern.  */
12922   for (i = start; i < len; i++)
12923     {
12924       tree parm = pattern;
12925
12926       /* For each parameter pack, clear out the deduced value so that
12927          we can deduce it again.  */
12928       for (pack = packs; pack; pack = TREE_CHAIN (pack))
12929         {
12930           int idx, level;
12931           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12932
12933           TMPL_ARG (targs, level, idx) = NULL_TREE;
12934         }
12935
12936       /* Unify the pattern with the current argument.  */
12937       {
12938         tree arg = TREE_VEC_ELT (packed_args, i);
12939         tree arg_expr = NULL_TREE;
12940         int arg_strict = strict;
12941         bool skip_arg_p = false;
12942
12943         if (call_args_p)
12944           {
12945             int sub_strict;
12946
12947             /* This mirrors what we do in type_unification_real.  */
12948             switch (strict)
12949               {
12950               case DEDUCE_CALL:
12951                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
12952                               | UNIFY_ALLOW_MORE_CV_QUAL
12953                               | UNIFY_ALLOW_DERIVED);
12954                 break;
12955                 
12956               case DEDUCE_CONV:
12957                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
12958                 break;
12959                 
12960               case DEDUCE_EXACT:
12961                 sub_strict = UNIFY_ALLOW_NONE;
12962                 break;
12963                 
12964               default:
12965                 gcc_unreachable ();
12966               }
12967
12968             if (!TYPE_P (arg))
12969               {
12970                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
12971                 if (type_unknown_p (arg))
12972                   {
12973                     /* [temp.deduct.type] A template-argument can be
12974                        deduced from a pointer to function or pointer
12975                        to member function argument if the set of
12976                        overloaded functions does not contain function
12977                        templates and at most one of a set of
12978                        overloaded functions provides a unique
12979                        match.  */
12980
12981                     if (resolve_overloaded_unification
12982                         (tparms, targs, parm, arg, strict, sub_strict)
12983                         != 0)
12984                       return 1;
12985                     skip_arg_p = true;
12986                   }
12987
12988                 if (!skip_arg_p)
12989                   {
12990                     arg_expr = arg;
12991                     arg = unlowered_expr_type (arg);
12992                     if (arg == error_mark_node)
12993                       return 1;
12994                   }
12995               }
12996       
12997             arg_strict = sub_strict;
12998
12999             if (!subr)
13000               arg_strict |= 
13001                 maybe_adjust_types_for_deduction (strict, &parm, &arg, 
13002                                                   arg_expr);
13003           }
13004
13005         if (!skip_arg_p)
13006           {
13007             if (unify (tparms, targs, parm, arg, arg_strict))
13008               return 1;
13009           }
13010       }
13011
13012       /* For each parameter pack, collect the deduced value.  */
13013       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13014         {
13015           int idx, level;
13016           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13017
13018           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
13019             TMPL_ARG (targs, level, idx);
13020         }
13021     }
13022
13023   /* Verify that the results of unification with the parameter packs
13024      produce results consistent with what we've seen before, and make
13025      the deduced argument packs available.  */
13026   for (pack = packs; pack; pack = TREE_CHAIN (pack))
13027     {
13028       tree old_pack = TREE_VALUE (pack);
13029       tree new_args = TREE_TYPE (pack);
13030       int i, len = TREE_VEC_LENGTH (new_args);
13031       bool nondeduced_p = false;
13032
13033       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
13034          actually deduce anything.  */
13035       for (i = 0; i < len && !nondeduced_p; ++i)
13036         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
13037           nondeduced_p = true;
13038       if (nondeduced_p)
13039         continue;
13040
13041       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
13042         {
13043           /* Prepend the explicit arguments onto NEW_ARGS.  */
13044           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13045           tree old_args = new_args;
13046           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
13047           int len = explicit_len + TREE_VEC_LENGTH (old_args);
13048
13049           /* Copy the explicit arguments.  */
13050           new_args = make_tree_vec (len);
13051           for (i = 0; i < explicit_len; i++)
13052             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
13053
13054           /* Copy the deduced arguments.  */
13055           for (; i < len; i++)
13056             TREE_VEC_ELT (new_args, i) =
13057               TREE_VEC_ELT (old_args, i - explicit_len);
13058         }
13059
13060       if (!old_pack)
13061         {
13062           tree result;
13063           int idx, level;
13064           
13065           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13066
13067           /* Build the deduced *_ARGUMENT_PACK.  */
13068           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
13069             {
13070               result = make_node (NONTYPE_ARGUMENT_PACK);
13071               TREE_TYPE (result) = 
13072                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
13073               TREE_CONSTANT (result) = 1;
13074             }
13075           else
13076             result = make_node (TYPE_ARGUMENT_PACK);
13077
13078           SET_ARGUMENT_PACK_ARGS (result, new_args);
13079
13080           /* Note the deduced argument packs for this parameter
13081              pack.  */
13082           TMPL_ARG (targs, level, idx) = result;
13083         }
13084       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
13085                && (ARGUMENT_PACK_ARGS (old_pack) 
13086                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
13087         {
13088           /* We only had the explicitly-provided arguments before, but
13089              now we have a complete set of arguments.  */
13090           int idx, level;
13091           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13092           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13093
13094           /* Keep the original deduced argument pack.  */
13095           TMPL_ARG (targs, level, idx) = old_pack;
13096
13097           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
13098           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
13099           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
13100         }
13101       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
13102                                     new_args))
13103         /* Inconsistent unification of this parameter pack.  */
13104         return 1;
13105       else
13106         {
13107           int idx, level;
13108           
13109           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13110
13111           /* Keep the original deduced argument pack.  */
13112           TMPL_ARG (targs, level, idx) = old_pack;
13113         }
13114     }
13115
13116   return 0;
13117 }
13118
13119 /* Deduce the value of template parameters.  TPARMS is the (innermost)
13120    set of template parameters to a template.  TARGS is the bindings
13121    for those template parameters, as determined thus far; TARGS may
13122    include template arguments for outer levels of template parameters
13123    as well.  PARM is a parameter to a template function, or a
13124    subcomponent of that parameter; ARG is the corresponding argument.
13125    This function attempts to match PARM with ARG in a manner
13126    consistent with the existing assignments in TARGS.  If more values
13127    are deduced, then TARGS is updated.
13128
13129    Returns 0 if the type deduction succeeds, 1 otherwise.  The
13130    parameter STRICT is a bitwise or of the following flags:
13131
13132      UNIFY_ALLOW_NONE:
13133        Require an exact match between PARM and ARG.
13134      UNIFY_ALLOW_MORE_CV_QUAL:
13135        Allow the deduced ARG to be more cv-qualified (by qualification
13136        conversion) than ARG.
13137      UNIFY_ALLOW_LESS_CV_QUAL:
13138        Allow the deduced ARG to be less cv-qualified than ARG.
13139      UNIFY_ALLOW_DERIVED:
13140        Allow the deduced ARG to be a template base class of ARG,
13141        or a pointer to a template base class of the type pointed to by
13142        ARG.
13143      UNIFY_ALLOW_INTEGER:
13144        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
13145        case for more information.
13146      UNIFY_ALLOW_OUTER_LEVEL:
13147        This is the outermost level of a deduction. Used to determine validity
13148        of qualification conversions. A valid qualification conversion must
13149        have const qualified pointers leading up to the inner type which
13150        requires additional CV quals, except at the outer level, where const
13151        is not required [conv.qual]. It would be normal to set this flag in
13152        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
13153      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
13154        This is the outermost level of a deduction, and PARM can be more CV
13155        qualified at this point.
13156      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
13157        This is the outermost level of a deduction, and PARM can be less CV
13158        qualified at this point.  */
13159
13160 static int
13161 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
13162 {
13163   int idx;
13164   tree targ;
13165   tree tparm;
13166   int strict_in = strict;
13167
13168   /* I don't think this will do the right thing with respect to types.
13169      But the only case I've seen it in so far has been array bounds, where
13170      signedness is the only information lost, and I think that will be
13171      okay.  */
13172   while (TREE_CODE (parm) == NOP_EXPR)
13173     parm = TREE_OPERAND (parm, 0);
13174
13175   if (arg == error_mark_node)
13176     return 1;
13177   if (arg == unknown_type_node
13178       || arg == init_list_type_node)
13179     /* We can't deduce anything from this, but we might get all the
13180        template args from other function args.  */
13181     return 0;
13182
13183   /* If PARM uses template parameters, then we can't bail out here,
13184      even if ARG == PARM, since we won't record unifications for the
13185      template parameters.  We might need them if we're trying to
13186      figure out which of two things is more specialized.  */
13187   if (arg == parm && !uses_template_parms (parm))
13188     return 0;
13189
13190   /* Handle init lists early, so the rest of the function can assume
13191      we're dealing with a type. */
13192   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
13193     {
13194       tree elt, elttype;
13195       unsigned i;
13196
13197       if (!is_std_init_list (parm))
13198         /* We can only deduce from an initializer list argument if the
13199            parameter is std::initializer_list; otherwise this is a
13200            non-deduced context. */
13201         return 0;
13202
13203       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
13204
13205       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
13206         {
13207           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
13208             elt = TREE_TYPE (elt);
13209           if (unify (tparms, targs, elttype, elt, UNIFY_ALLOW_NONE))
13210             return 1;
13211         }
13212       return 0;
13213     }
13214
13215   /* Immediately reject some pairs that won't unify because of
13216      cv-qualification mismatches.  */
13217   if (TREE_CODE (arg) == TREE_CODE (parm)
13218       && TYPE_P (arg)
13219       /* It is the elements of the array which hold the cv quals of an array
13220          type, and the elements might be template type parms. We'll check
13221          when we recurse.  */
13222       && TREE_CODE (arg) != ARRAY_TYPE
13223       /* We check the cv-qualifiers when unifying with template type
13224          parameters below.  We want to allow ARG `const T' to unify with
13225          PARM `T' for example, when computing which of two templates
13226          is more specialized, for example.  */
13227       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
13228       && !check_cv_quals_for_unify (strict_in, arg, parm))
13229     return 1;
13230
13231   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
13232       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
13233     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
13234   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
13235   strict &= ~UNIFY_ALLOW_DERIVED;
13236   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13237   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
13238
13239   switch (TREE_CODE (parm))
13240     {
13241     case TYPENAME_TYPE:
13242     case SCOPE_REF:
13243     case UNBOUND_CLASS_TEMPLATE:
13244       /* In a type which contains a nested-name-specifier, template
13245          argument values cannot be deduced for template parameters used
13246          within the nested-name-specifier.  */
13247       return 0;
13248
13249     case TEMPLATE_TYPE_PARM:
13250     case TEMPLATE_TEMPLATE_PARM:
13251     case BOUND_TEMPLATE_TEMPLATE_PARM:
13252       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
13253       if (tparm == error_mark_node)
13254         return 1;
13255
13256       if (TEMPLATE_TYPE_LEVEL (parm)
13257           != template_decl_level (tparm))
13258         /* The PARM is not one we're trying to unify.  Just check
13259            to see if it matches ARG.  */
13260         return (TREE_CODE (arg) == TREE_CODE (parm)
13261                 && same_type_p (parm, arg)) ? 0 : 1;
13262       idx = TEMPLATE_TYPE_IDX (parm);
13263       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13264       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
13265
13266       /* Check for mixed types and values.  */
13267       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13268            && TREE_CODE (tparm) != TYPE_DECL)
13269           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13270               && TREE_CODE (tparm) != TEMPLATE_DECL))
13271         return 1;
13272
13273       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13274         {
13275           /* ARG must be constructed from a template class or a template
13276              template parameter.  */
13277           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
13278               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
13279             return 1;
13280
13281           {
13282             tree parmvec = TYPE_TI_ARGS (parm);
13283             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
13284             tree parm_parms 
13285               = DECL_INNERMOST_TEMPLATE_PARMS
13286                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
13287             int i, len;
13288             int parm_variadic_p = 0;
13289
13290             /* The resolution to DR150 makes clear that default
13291                arguments for an N-argument may not be used to bind T
13292                to a template template parameter with fewer than N
13293                parameters.  It is not safe to permit the binding of
13294                default arguments as an extension, as that may change
13295                the meaning of a conforming program.  Consider:
13296
13297                   struct Dense { static const unsigned int dim = 1; };
13298
13299                   template <template <typename> class View,
13300                             typename Block>
13301                   void operator+(float, View<Block> const&);
13302
13303                   template <typename Block,
13304                             unsigned int Dim = Block::dim>
13305                   struct Lvalue_proxy { operator float() const; };
13306
13307                   void
13308                   test_1d (void) {
13309                     Lvalue_proxy<Dense> p;
13310                     float b;
13311                     b + p;
13312                   }
13313
13314               Here, if Lvalue_proxy is permitted to bind to View, then
13315               the global operator+ will be used; if they are not, the
13316               Lvalue_proxy will be converted to float.  */
13317             if (coerce_template_parms (parm_parms,
13318                                        argvec,
13319                                        TYPE_TI_TEMPLATE (parm),
13320                                        tf_none,
13321                                        /*require_all_args=*/true,
13322                                        /*use_default_args=*/false)
13323                 == error_mark_node)
13324               return 1;
13325
13326             /* Deduce arguments T, i from TT<T> or TT<i>.
13327                We check each element of PARMVEC and ARGVEC individually
13328                rather than the whole TREE_VEC since they can have
13329                different number of elements.  */
13330
13331             parmvec = expand_template_argument_pack (parmvec);
13332             argvec = expand_template_argument_pack (argvec);
13333
13334             len = TREE_VEC_LENGTH (parmvec);
13335
13336             /* Check if the parameters end in a pack, making them
13337                variadic.  */
13338             if (len > 0
13339                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
13340               parm_variadic_p = 1;
13341             
13342             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
13343               return 1;
13344
13345              for (i = 0; i < len - parm_variadic_p; ++i)
13346               {
13347                 if (unify (tparms, targs,
13348                            TREE_VEC_ELT (parmvec, i),
13349                            TREE_VEC_ELT (argvec, i),
13350                            UNIFY_ALLOW_NONE))
13351                   return 1;
13352               }
13353
13354             if (parm_variadic_p
13355                 && unify_pack_expansion (tparms, targs,
13356                                          parmvec, argvec,
13357                                          UNIFY_ALLOW_NONE,
13358                                          /*call_args_p=*/false,
13359                                          /*subr=*/false))
13360               return 1;
13361           }
13362           arg = TYPE_TI_TEMPLATE (arg);
13363
13364           /* Fall through to deduce template name.  */
13365         }
13366
13367       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13368           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13369         {
13370           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
13371
13372           /* Simple cases: Value already set, does match or doesn't.  */
13373           if (targ != NULL_TREE && template_args_equal (targ, arg))
13374             return 0;
13375           else if (targ)
13376             return 1;
13377         }
13378       else
13379         {
13380           /* If PARM is `const T' and ARG is only `int', we don't have
13381              a match unless we are allowing additional qualification.
13382              If ARG is `const int' and PARM is just `T' that's OK;
13383              that binds `const int' to `T'.  */
13384           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
13385                                          arg, parm))
13386             return 1;
13387
13388           /* Consider the case where ARG is `const volatile int' and
13389              PARM is `const T'.  Then, T should be `volatile int'.  */
13390           arg = cp_build_qualified_type_real
13391             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
13392           if (arg == error_mark_node)
13393             return 1;
13394
13395           /* Simple cases: Value already set, does match or doesn't.  */
13396           if (targ != NULL_TREE && same_type_p (targ, arg))
13397             return 0;
13398           else if (targ)
13399             return 1;
13400
13401           /* Make sure that ARG is not a variable-sized array.  (Note
13402              that were talking about variable-sized arrays (like
13403              `int[n]'), rather than arrays of unknown size (like
13404              `int[]').)  We'll get very confused by such a type since
13405              the bound of the array will not be computable in an
13406              instantiation.  Besides, such types are not allowed in
13407              ISO C++, so we can do as we please here.  */
13408           if (variably_modified_type_p (arg, NULL_TREE))
13409             return 1;
13410         }
13411
13412       /* If ARG is a parameter pack or an expansion, we cannot unify
13413          against it unless PARM is also a parameter pack.  */
13414       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13415           && !template_parameter_pack_p (parm))
13416         return 1;
13417
13418       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13419       return 0;
13420
13421     case TEMPLATE_PARM_INDEX:
13422       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
13423       if (tparm == error_mark_node)
13424         return 1;
13425
13426       if (TEMPLATE_PARM_LEVEL (parm)
13427           != template_decl_level (tparm))
13428         /* The PARM is not one we're trying to unify.  Just check
13429            to see if it matches ARG.  */
13430         return !(TREE_CODE (arg) == TREE_CODE (parm)
13431                  && cp_tree_equal (parm, arg));
13432
13433       idx = TEMPLATE_PARM_IDX (parm);
13434       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13435
13436       if (targ)
13437         return !cp_tree_equal (targ, arg);
13438
13439       /* [temp.deduct.type] If, in the declaration of a function template
13440          with a non-type template-parameter, the non-type
13441          template-parameter is used in an expression in the function
13442          parameter-list and, if the corresponding template-argument is
13443          deduced, the template-argument type shall match the type of the
13444          template-parameter exactly, except that a template-argument
13445          deduced from an array bound may be of any integral type.
13446          The non-type parameter might use already deduced type parameters.  */
13447       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
13448       if (!TREE_TYPE (arg))
13449         /* Template-parameter dependent expression.  Just accept it for now.
13450            It will later be processed in convert_template_argument.  */
13451         ;
13452       else if (same_type_p (TREE_TYPE (arg), tparm))
13453         /* OK */;
13454       else if ((strict & UNIFY_ALLOW_INTEGER)
13455                && (TREE_CODE (tparm) == INTEGER_TYPE
13456                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
13457         /* Convert the ARG to the type of PARM; the deduced non-type
13458            template argument must exactly match the types of the
13459            corresponding parameter.  */
13460         arg = fold (build_nop (tparm, arg));
13461       else if (uses_template_parms (tparm))
13462         /* We haven't deduced the type of this parameter yet.  Try again
13463            later.  */
13464         return 0;
13465       else
13466         return 1;
13467
13468       /* If ARG is a parameter pack or an expansion, we cannot unify
13469          against it unless PARM is also a parameter pack.  */
13470       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13471           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
13472         return 1;
13473
13474       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13475       return 0;
13476
13477     case PTRMEM_CST:
13478      {
13479         /* A pointer-to-member constant can be unified only with
13480          another constant.  */
13481       if (TREE_CODE (arg) != PTRMEM_CST)
13482         return 1;
13483
13484       /* Just unify the class member. It would be useless (and possibly
13485          wrong, depending on the strict flags) to unify also
13486          PTRMEM_CST_CLASS, because we want to be sure that both parm and
13487          arg refer to the same variable, even if through different
13488          classes. For instance:
13489
13490          struct A { int x; };
13491          struct B : A { };
13492
13493          Unification of &A::x and &B::x must succeed.  */
13494       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
13495                     PTRMEM_CST_MEMBER (arg), strict);
13496      }
13497
13498     case POINTER_TYPE:
13499       {
13500         if (TREE_CODE (arg) != POINTER_TYPE)
13501           return 1;
13502
13503         /* [temp.deduct.call]
13504
13505            A can be another pointer or pointer to member type that can
13506            be converted to the deduced A via a qualification
13507            conversion (_conv.qual_).
13508
13509            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
13510            This will allow for additional cv-qualification of the
13511            pointed-to types if appropriate.  */
13512
13513         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
13514           /* The derived-to-base conversion only persists through one
13515              level of pointers.  */
13516           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
13517
13518         return unify (tparms, targs, TREE_TYPE (parm),
13519                       TREE_TYPE (arg), strict);
13520       }
13521
13522     case REFERENCE_TYPE:
13523       if (TREE_CODE (arg) != REFERENCE_TYPE)
13524         return 1;
13525       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13526                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
13527
13528     case ARRAY_TYPE:
13529       if (TREE_CODE (arg) != ARRAY_TYPE)
13530         return 1;
13531       if ((TYPE_DOMAIN (parm) == NULL_TREE)
13532           != (TYPE_DOMAIN (arg) == NULL_TREE))
13533         return 1;
13534       if (TYPE_DOMAIN (parm) != NULL_TREE)
13535         {
13536           tree parm_max;
13537           tree arg_max;
13538           bool parm_cst;
13539           bool arg_cst;
13540
13541           /* Our representation of array types uses "N - 1" as the
13542              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
13543              not an integer constant.  We cannot unify arbitrarily
13544              complex expressions, so we eliminate the MINUS_EXPRs
13545              here.  */
13546           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
13547           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
13548           if (!parm_cst)
13549             {
13550               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
13551               parm_max = TREE_OPERAND (parm_max, 0);
13552             }
13553           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
13554           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
13555           if (!arg_cst)
13556             {
13557               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
13558                  trying to unify the type of a variable with the type
13559                  of a template parameter.  For example:
13560
13561                    template <unsigned int N>
13562                    void f (char (&) [N]);
13563                    int g(); 
13564                    void h(int i) {
13565                      char a[g(i)];
13566                      f(a); 
13567                    }
13568
13569                 Here, the type of the ARG will be "int [g(i)]", and
13570                 may be a SAVE_EXPR, etc.  */
13571               if (TREE_CODE (arg_max) != MINUS_EXPR)
13572                 return 1;
13573               arg_max = TREE_OPERAND (arg_max, 0);
13574             }
13575
13576           /* If only one of the bounds used a MINUS_EXPR, compensate
13577              by adding one to the other bound.  */
13578           if (parm_cst && !arg_cst)
13579             parm_max = fold_build2 (PLUS_EXPR,
13580                                     integer_type_node,
13581                                     parm_max,
13582                                     integer_one_node);
13583           else if (arg_cst && !parm_cst)
13584             arg_max = fold_build2 (PLUS_EXPR,
13585                                    integer_type_node,
13586                                    arg_max,
13587                                    integer_one_node);
13588
13589           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
13590             return 1;
13591         }
13592       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13593                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
13594
13595     case REAL_TYPE:
13596     case COMPLEX_TYPE:
13597     case VECTOR_TYPE:
13598     case INTEGER_TYPE:
13599     case BOOLEAN_TYPE:
13600     case ENUMERAL_TYPE:
13601     case VOID_TYPE:
13602       if (TREE_CODE (arg) != TREE_CODE (parm))
13603         return 1;
13604
13605       /* We have already checked cv-qualification at the top of the
13606          function.  */
13607       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
13608         return 1;
13609
13610       /* As far as unification is concerned, this wins.  Later checks
13611          will invalidate it if necessary.  */
13612       return 0;
13613
13614       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
13615       /* Type INTEGER_CST can come from ordinary constant template args.  */
13616     case INTEGER_CST:
13617       while (TREE_CODE (arg) == NOP_EXPR)
13618         arg = TREE_OPERAND (arg, 0);
13619
13620       if (TREE_CODE (arg) != INTEGER_CST)
13621         return 1;
13622       return !tree_int_cst_equal (parm, arg);
13623
13624     case TREE_VEC:
13625       {
13626         int i;
13627         if (TREE_CODE (arg) != TREE_VEC)
13628           return 1;
13629         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
13630           return 1;
13631         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
13632           if (unify (tparms, targs,
13633                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
13634                      UNIFY_ALLOW_NONE))
13635             return 1;
13636         return 0;
13637       }
13638
13639     case RECORD_TYPE:
13640     case UNION_TYPE:
13641       if (TREE_CODE (arg) != TREE_CODE (parm))
13642         return 1;
13643
13644       if (TYPE_PTRMEMFUNC_P (parm))
13645         {
13646           if (!TYPE_PTRMEMFUNC_P (arg))
13647             return 1;
13648
13649           return unify (tparms, targs,
13650                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
13651                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
13652                         strict);
13653         }
13654
13655       if (CLASSTYPE_TEMPLATE_INFO (parm))
13656         {
13657           tree t = NULL_TREE;
13658
13659           if (strict_in & UNIFY_ALLOW_DERIVED)
13660             {
13661               /* First, we try to unify the PARM and ARG directly.  */
13662               t = try_class_unification (tparms, targs,
13663                                          parm, arg);
13664
13665               if (!t)
13666                 {
13667                   /* Fallback to the special case allowed in
13668                      [temp.deduct.call]:
13669
13670                        If P is a class, and P has the form
13671                        template-id, then A can be a derived class of
13672                        the deduced A.  Likewise, if P is a pointer to
13673                        a class of the form template-id, A can be a
13674                        pointer to a derived class pointed to by the
13675                        deduced A.  */
13676                   t = get_template_base (tparms, targs, parm, arg);
13677
13678                   if (!t)
13679                     return 1;
13680                 }
13681             }
13682           else if (CLASSTYPE_TEMPLATE_INFO (arg)
13683                    && (CLASSTYPE_TI_TEMPLATE (parm)
13684                        == CLASSTYPE_TI_TEMPLATE (arg)))
13685             /* Perhaps PARM is something like S<U> and ARG is S<int>.
13686                Then, we should unify `int' and `U'.  */
13687             t = arg;
13688           else
13689             /* There's no chance of unification succeeding.  */
13690             return 1;
13691
13692           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
13693                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
13694         }
13695       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
13696         return 1;
13697       return 0;
13698
13699     case METHOD_TYPE:
13700     case FUNCTION_TYPE:
13701       if (TREE_CODE (arg) != TREE_CODE (parm))
13702         return 1;
13703
13704       /* CV qualifications for methods can never be deduced, they must
13705          match exactly.  We need to check them explicitly here,
13706          because type_unification_real treats them as any other
13707          cv-qualified parameter.  */
13708       if (TREE_CODE (parm) == METHOD_TYPE
13709           && (!check_cv_quals_for_unify
13710               (UNIFY_ALLOW_NONE,
13711                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
13712                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
13713         return 1;
13714
13715       if (unify (tparms, targs, TREE_TYPE (parm),
13716                  TREE_TYPE (arg), UNIFY_ALLOW_NONE))
13717         return 1;
13718       return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
13719                                     TYPE_ARG_TYPES (arg), 1, DEDUCE_EXACT,
13720                                     LOOKUP_NORMAL);
13721
13722     case OFFSET_TYPE:
13723       /* Unify a pointer to member with a pointer to member function, which
13724          deduces the type of the member as a function type. */
13725       if (TYPE_PTRMEMFUNC_P (arg))
13726         {
13727           tree method_type;
13728           tree fntype;
13729           cp_cv_quals cv_quals;
13730
13731           /* Check top-level cv qualifiers */
13732           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
13733             return 1;
13734
13735           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
13736                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
13737             return 1;
13738
13739           /* Determine the type of the function we are unifying against. */
13740           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
13741           fntype =
13742             build_function_type (TREE_TYPE (method_type),
13743                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
13744
13745           /* Extract the cv-qualifiers of the member function from the
13746              implicit object parameter and place them on the function
13747              type to be restored later. */
13748           cv_quals =
13749             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
13750           fntype = build_qualified_type (fntype, cv_quals);
13751           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
13752         }
13753
13754       if (TREE_CODE (arg) != OFFSET_TYPE)
13755         return 1;
13756       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
13757                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
13758         return 1;
13759       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13760                     strict);
13761
13762     case CONST_DECL:
13763       if (DECL_TEMPLATE_PARM_P (parm))
13764         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
13765       if (arg != integral_constant_value (parm))
13766         return 1;
13767       return 0;
13768
13769     case FIELD_DECL:
13770     case TEMPLATE_DECL:
13771       /* Matched cases are handled by the ARG == PARM test above.  */
13772       return 1;
13773
13774     case TYPE_ARGUMENT_PACK:
13775     case NONTYPE_ARGUMENT_PACK:
13776       {
13777         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
13778         tree packed_args = ARGUMENT_PACK_ARGS (arg);
13779         int i, len = TREE_VEC_LENGTH (packed_parms);
13780         int argslen = TREE_VEC_LENGTH (packed_args);
13781         int parm_variadic_p = 0;
13782
13783         for (i = 0; i < len; ++i)
13784           {
13785             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
13786               {
13787                 if (i == len - 1)
13788                   /* We can unify against something with a trailing
13789                      parameter pack.  */
13790                   parm_variadic_p = 1;
13791                 else
13792                   /* Since there is something following the pack
13793                      expansion, we cannot unify this template argument
13794                      list.  */
13795                   return 0;
13796               }
13797           }
13798           
13799
13800         /* If we don't have enough arguments to satisfy the parameters
13801            (not counting the pack expression at the end), or we have
13802            too many arguments for a parameter list that doesn't end in
13803            a pack expression, we can't unify.  */
13804         if (argslen < (len - parm_variadic_p)
13805             || (argslen > len && !parm_variadic_p))
13806           return 1;
13807
13808         /* Unify all of the parameters that precede the (optional)
13809            pack expression.  */
13810         for (i = 0; i < len - parm_variadic_p; ++i)
13811           {
13812             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
13813                        TREE_VEC_ELT (packed_args, i), strict))
13814               return 1;
13815           }
13816
13817         if (parm_variadic_p)
13818           return unify_pack_expansion (tparms, targs, 
13819                                        packed_parms, packed_args,
13820                                        strict, /*call_args_p=*/false,
13821                                        /*subr=*/false);
13822         return 0;
13823       }
13824
13825       break;
13826
13827     case TYPEOF_TYPE:
13828     case DECLTYPE_TYPE:
13829       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
13830          nodes.  */
13831       return 0;
13832
13833     case ERROR_MARK:
13834       /* Unification fails if we hit an error node.  */
13835       return 1;
13836
13837     default:
13838       gcc_assert (EXPR_P (parm));
13839
13840       /* We must be looking at an expression.  This can happen with
13841          something like:
13842
13843            template <int I>
13844            void foo(S<I>, S<I + 2>);
13845
13846          This is a "nondeduced context":
13847
13848            [deduct.type]
13849
13850            The nondeduced contexts are:
13851
13852            --A type that is a template-id in which one or more of
13853              the template-arguments is an expression that references
13854              a template-parameter.
13855
13856          In these cases, we assume deduction succeeded, but don't
13857          actually infer any unifications.  */
13858
13859       if (!uses_template_parms (parm)
13860           && !template_args_equal (parm, arg))
13861         return 1;
13862       else
13863         return 0;
13864     }
13865 }
13866 \f
13867 /* Note that DECL can be defined in this translation unit, if
13868    required.  */
13869
13870 static void
13871 mark_definable (tree decl)
13872 {
13873   tree clone;
13874   DECL_NOT_REALLY_EXTERN (decl) = 1;
13875   FOR_EACH_CLONE (clone, decl)
13876     DECL_NOT_REALLY_EXTERN (clone) = 1;
13877 }
13878
13879 /* Called if RESULT is explicitly instantiated, or is a member of an
13880    explicitly instantiated class.  */
13881
13882 void
13883 mark_decl_instantiated (tree result, int extern_p)
13884 {
13885   SET_DECL_EXPLICIT_INSTANTIATION (result);
13886
13887   /* If this entity has already been written out, it's too late to
13888      make any modifications.  */
13889   if (TREE_ASM_WRITTEN (result))
13890     return;
13891
13892   if (TREE_CODE (result) != FUNCTION_DECL)
13893     /* The TREE_PUBLIC flag for function declarations will have been
13894        set correctly by tsubst.  */
13895     TREE_PUBLIC (result) = 1;
13896
13897   /* This might have been set by an earlier implicit instantiation.  */
13898   DECL_COMDAT (result) = 0;
13899
13900   if (extern_p)
13901     DECL_NOT_REALLY_EXTERN (result) = 0;
13902   else
13903     {
13904       mark_definable (result);
13905       /* Always make artificials weak.  */
13906       if (DECL_ARTIFICIAL (result) && flag_weak)
13907         comdat_linkage (result);
13908       /* For WIN32 we also want to put explicit instantiations in
13909          linkonce sections.  */
13910       else if (TREE_PUBLIC (result))
13911         maybe_make_one_only (result);
13912     }
13913
13914   /* If EXTERN_P, then this function will not be emitted -- unless
13915      followed by an explicit instantiation, at which point its linkage
13916      will be adjusted.  If !EXTERN_P, then this function will be
13917      emitted here.  In neither circumstance do we want
13918      import_export_decl to adjust the linkage.  */
13919   DECL_INTERFACE_KNOWN (result) = 1;
13920 }
13921
13922 /* Given two function templates PAT1 and PAT2, return:
13923
13924    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
13925    -1 if PAT2 is more specialized than PAT1.
13926    0 if neither is more specialized.
13927
13928    LEN indicates the number of parameters we should consider
13929    (defaulted parameters should not be considered).
13930
13931    The 1998 std underspecified function template partial ordering, and
13932    DR214 addresses the issue.  We take pairs of arguments, one from
13933    each of the templates, and deduce them against each other.  One of
13934    the templates will be more specialized if all the *other*
13935    template's arguments deduce against its arguments and at least one
13936    of its arguments *does* *not* deduce against the other template's
13937    corresponding argument.  Deduction is done as for class templates.
13938    The arguments used in deduction have reference and top level cv
13939    qualifiers removed.  Iff both arguments were originally reference
13940    types *and* deduction succeeds in both directions, the template
13941    with the more cv-qualified argument wins for that pairing (if
13942    neither is more cv-qualified, they both are equal).  Unlike regular
13943    deduction, after all the arguments have been deduced in this way,
13944    we do *not* verify the deduced template argument values can be
13945    substituted into non-deduced contexts, nor do we have to verify
13946    that all template arguments have been deduced.  */
13947
13948 int
13949 more_specialized_fn (tree pat1, tree pat2, int len)
13950 {
13951   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
13952   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
13953   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
13954   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
13955   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
13956   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
13957   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
13958   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
13959   int better1 = 0;
13960   int better2 = 0;
13961
13962   /* Remove the this parameter from non-static member functions.  If
13963      one is a non-static member function and the other is not a static
13964      member function, remove the first parameter from that function
13965      also.  This situation occurs for operator functions where we
13966      locate both a member function (with this pointer) and non-member
13967      operator (with explicit first operand).  */
13968   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
13969     {
13970       len--; /* LEN is the number of significant arguments for DECL1 */
13971       args1 = TREE_CHAIN (args1);
13972       if (!DECL_STATIC_FUNCTION_P (decl2))
13973         args2 = TREE_CHAIN (args2);
13974     }
13975   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
13976     {
13977       args2 = TREE_CHAIN (args2);
13978       if (!DECL_STATIC_FUNCTION_P (decl1))
13979         {
13980           len--;
13981           args1 = TREE_CHAIN (args1);
13982         }
13983     }
13984
13985   /* If only one is a conversion operator, they are unordered.  */
13986   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
13987     return 0;
13988
13989   /* Consider the return type for a conversion function */
13990   if (DECL_CONV_FN_P (decl1))
13991     {
13992       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
13993       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
13994       len++;
13995     }
13996
13997   processing_template_decl++;
13998
13999   while (len--
14000          /* Stop when an ellipsis is seen.  */
14001          && args1 != NULL_TREE && args2 != NULL_TREE)
14002     {
14003       tree arg1 = TREE_VALUE (args1);
14004       tree arg2 = TREE_VALUE (args2);
14005       int deduce1, deduce2;
14006       int quals1 = -1;
14007       int quals2 = -1;
14008
14009       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
14010           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14011         {
14012           /* When both arguments are pack expansions, we need only
14013              unify the patterns themselves.  */
14014           arg1 = PACK_EXPANSION_PATTERN (arg1);
14015           arg2 = PACK_EXPANSION_PATTERN (arg2);
14016
14017           /* This is the last comparison we need to do.  */
14018           len = 0;
14019         }
14020
14021       if (TREE_CODE (arg1) == REFERENCE_TYPE)
14022         {
14023           arg1 = TREE_TYPE (arg1);
14024           quals1 = cp_type_quals (arg1);
14025         }
14026
14027       if (TREE_CODE (arg2) == REFERENCE_TYPE)
14028         {
14029           arg2 = TREE_TYPE (arg2);
14030           quals2 = cp_type_quals (arg2);
14031         }
14032
14033       if ((quals1 < 0) != (quals2 < 0))
14034         {
14035           /* Only of the args is a reference, see if we should apply
14036              array/function pointer decay to it.  This is not part of
14037              DR214, but is, IMHO, consistent with the deduction rules
14038              for the function call itself, and with our earlier
14039              implementation of the underspecified partial ordering
14040              rules.  (nathan).  */
14041           if (quals1 >= 0)
14042             {
14043               switch (TREE_CODE (arg1))
14044                 {
14045                 case ARRAY_TYPE:
14046                   arg1 = TREE_TYPE (arg1);
14047                   /* FALLTHROUGH. */
14048                 case FUNCTION_TYPE:
14049                   arg1 = build_pointer_type (arg1);
14050                   break;
14051
14052                 default:
14053                   break;
14054                 }
14055             }
14056           else
14057             {
14058               switch (TREE_CODE (arg2))
14059                 {
14060                 case ARRAY_TYPE:
14061                   arg2 = TREE_TYPE (arg2);
14062                   /* FALLTHROUGH. */
14063                 case FUNCTION_TYPE:
14064                   arg2 = build_pointer_type (arg2);
14065                   break;
14066
14067                 default:
14068                   break;
14069                 }
14070             }
14071         }
14072
14073       arg1 = TYPE_MAIN_VARIANT (arg1);
14074       arg2 = TYPE_MAIN_VARIANT (arg2);
14075
14076       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
14077         {
14078           int i, len2 = list_length (args2);
14079           tree parmvec = make_tree_vec (1);
14080           tree argvec = make_tree_vec (len2);
14081           tree ta = args2;
14082
14083           /* Setup the parameter vector, which contains only ARG1.  */
14084           TREE_VEC_ELT (parmvec, 0) = arg1;
14085
14086           /* Setup the argument vector, which contains the remaining
14087              arguments.  */
14088           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
14089             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
14090
14091           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
14092                                            argvec, UNIFY_ALLOW_NONE, 
14093                                            /*call_args_p=*/false, 
14094                                            /*subr=*/0);
14095
14096           /* We cannot deduce in the other direction, because ARG1 is
14097              a pack expansion but ARG2 is not.  */
14098           deduce2 = 0;
14099         }
14100       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14101         {
14102           int i, len1 = list_length (args1);
14103           tree parmvec = make_tree_vec (1);
14104           tree argvec = make_tree_vec (len1);
14105           tree ta = args1;
14106
14107           /* Setup the parameter vector, which contains only ARG1.  */
14108           TREE_VEC_ELT (parmvec, 0) = arg2;
14109
14110           /* Setup the argument vector, which contains the remaining
14111              arguments.  */
14112           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
14113             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
14114
14115           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
14116                                            argvec, UNIFY_ALLOW_NONE, 
14117                                            /*call_args_p=*/false, 
14118                                            /*subr=*/0);
14119
14120           /* We cannot deduce in the other direction, because ARG2 is
14121              a pack expansion but ARG1 is not.*/
14122           deduce1 = 0;
14123         }
14124
14125       else
14126         {
14127           /* The normal case, where neither argument is a pack
14128              expansion.  */
14129           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
14130           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
14131         }
14132
14133       if (!deduce1)
14134         better2 = -1;
14135       if (!deduce2)
14136         better1 = -1;
14137       if (better1 < 0 && better2 < 0)
14138         /* We've failed to deduce something in either direction.
14139            These must be unordered.  */
14140         break;
14141
14142       if (deduce1 && deduce2 && quals1 >= 0 && quals2 >= 0)
14143         {
14144           /* Deduces in both directions, see if quals can
14145              disambiguate.  Pretend the worse one failed to deduce. */
14146           if ((quals1 & quals2) == quals2)
14147             deduce1 = 0;
14148           if ((quals1 & quals2) == quals1)
14149             deduce2 = 0;
14150         }
14151       if (deduce1 && !deduce2 && !better2)
14152         better2 = 1;
14153       if (deduce2 && !deduce1 && !better1)
14154         better1 = 1;
14155
14156       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
14157           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14158         /* We have already processed all of the arguments in our
14159            handing of the pack expansion type.  */
14160         len = 0;
14161
14162       args1 = TREE_CHAIN (args1);
14163       args2 = TREE_CHAIN (args2);
14164     }
14165
14166   processing_template_decl--;
14167
14168   /* All things being equal, if the next argument is a pack expansion
14169      for one function but not for the other, prefer the
14170      non-variadic function.  */
14171   if ((better1 > 0) - (better2 > 0) == 0
14172       && args1 && TREE_VALUE (args1)
14173       && args2 && TREE_VALUE (args2))
14174     {
14175       if (TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION)
14176         return TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION ? 0 : -1;
14177       else if (TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION)
14178         return 1;
14179     }
14180
14181   return (better1 > 0) - (better2 > 0);
14182 }
14183
14184 /* Determine which of two partial specializations is more specialized.
14185
14186    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
14187    to the first partial specialization.  The TREE_VALUE is the
14188    innermost set of template parameters for the partial
14189    specialization.  PAT2 is similar, but for the second template.
14190
14191    Return 1 if the first partial specialization is more specialized;
14192    -1 if the second is more specialized; 0 if neither is more
14193    specialized.
14194
14195    See [temp.class.order] for information about determining which of
14196    two templates is more specialized.  */
14197
14198 static int
14199 more_specialized_class (tree pat1, tree pat2)
14200 {
14201   tree targs;
14202   tree tmpl1, tmpl2;
14203   int winner = 0;
14204   bool any_deductions = false;
14205
14206   tmpl1 = TREE_TYPE (pat1);
14207   tmpl2 = TREE_TYPE (pat2);
14208
14209   /* Just like what happens for functions, if we are ordering between
14210      different class template specializations, we may encounter dependent
14211      types in the arguments, and we need our dependency check functions
14212      to behave correctly.  */
14213   ++processing_template_decl;
14214   targs = get_class_bindings (TREE_VALUE (pat1),
14215                               CLASSTYPE_TI_ARGS (tmpl1),
14216                               CLASSTYPE_TI_ARGS (tmpl2));
14217   if (targs)
14218     {
14219       --winner;
14220       any_deductions = true;
14221     }
14222
14223   targs = get_class_bindings (TREE_VALUE (pat2),
14224                               CLASSTYPE_TI_ARGS (tmpl2),
14225                               CLASSTYPE_TI_ARGS (tmpl1));
14226   if (targs)
14227     {
14228       ++winner;
14229       any_deductions = true;
14230     }
14231   --processing_template_decl;
14232
14233   /* In the case of a tie where at least one of the class templates
14234      has a parameter pack at the end, the template with the most
14235      non-packed parameters wins.  */
14236   if (winner == 0
14237       && any_deductions
14238       && (template_args_variadic_p (TREE_PURPOSE (pat1))
14239           || template_args_variadic_p (TREE_PURPOSE (pat2))))
14240     {
14241       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
14242       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
14243       int len1 = TREE_VEC_LENGTH (args1);
14244       int len2 = TREE_VEC_LENGTH (args2);
14245
14246       /* We don't count the pack expansion at the end.  */
14247       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
14248         --len1;
14249       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
14250         --len2;
14251
14252       if (len1 > len2)
14253         return 1;
14254       else if (len1 < len2)
14255         return -1;
14256     }
14257
14258   return winner;
14259 }
14260
14261 /* Return the template arguments that will produce the function signature
14262    DECL from the function template FN, with the explicit template
14263    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
14264    also match.  Return NULL_TREE if no satisfactory arguments could be
14265    found.  */
14266
14267 static tree
14268 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
14269 {
14270   int ntparms = DECL_NTPARMS (fn);
14271   tree targs = make_tree_vec (ntparms);
14272   tree decl_type;
14273   tree decl_arg_types;
14274
14275   /* Substitute the explicit template arguments into the type of DECL.
14276      The call to fn_type_unification will handle substitution into the
14277      FN.  */
14278   decl_type = TREE_TYPE (decl);
14279   if (explicit_args && uses_template_parms (decl_type))
14280     {
14281       tree tmpl;
14282       tree converted_args;
14283
14284       if (DECL_TEMPLATE_INFO (decl))
14285         tmpl = DECL_TI_TEMPLATE (decl);
14286       else
14287         /* We can get here for some invalid specializations.  */
14288         return NULL_TREE;
14289
14290       converted_args
14291         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
14292                                  explicit_args, NULL_TREE,
14293                                  tf_none,
14294                                  /*require_all_args=*/false,
14295                                  /*use_default_args=*/false);
14296       if (converted_args == error_mark_node)
14297         return NULL_TREE;
14298
14299       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
14300       if (decl_type == error_mark_node)
14301         return NULL_TREE;
14302     }
14303
14304   /* Never do unification on the 'this' parameter.  */
14305   decl_arg_types = skip_artificial_parms_for (decl, 
14306                                               TYPE_ARG_TYPES (decl_type));
14307
14308   if (fn_type_unification (fn, explicit_args, targs,
14309                            decl_arg_types,
14310                            (check_rettype || DECL_CONV_FN_P (fn)
14311                             ? TREE_TYPE (decl_type) : NULL_TREE),
14312                            DEDUCE_EXACT, LOOKUP_NORMAL))
14313     return NULL_TREE;
14314
14315   return targs;
14316 }
14317
14318 /* Return the innermost template arguments that, when applied to a
14319    template specialization whose innermost template parameters are
14320    TPARMS, and whose specialization arguments are PARMS, yield the
14321    ARGS.
14322
14323    For example, suppose we have:
14324
14325      template <class T, class U> struct S {};
14326      template <class T> struct S<T*, int> {};
14327
14328    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
14329    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
14330    int}.  The resulting vector will be {double}, indicating that `T'
14331    is bound to `double'.  */
14332
14333 static tree
14334 get_class_bindings (tree tparms, tree spec_args, tree args)
14335 {
14336   int i, ntparms = TREE_VEC_LENGTH (tparms);
14337   tree deduced_args;
14338   tree innermost_deduced_args;
14339
14340   innermost_deduced_args = make_tree_vec (ntparms);
14341   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
14342     {
14343       deduced_args = copy_node (args);
14344       SET_TMPL_ARGS_LEVEL (deduced_args,
14345                            TMPL_ARGS_DEPTH (deduced_args),
14346                            innermost_deduced_args);
14347     }
14348   else
14349     deduced_args = innermost_deduced_args;
14350
14351   if (unify (tparms, deduced_args,
14352              INNERMOST_TEMPLATE_ARGS (spec_args),
14353              INNERMOST_TEMPLATE_ARGS (args),
14354              UNIFY_ALLOW_NONE))
14355     return NULL_TREE;
14356
14357   for (i =  0; i < ntparms; ++i)
14358     if (! TREE_VEC_ELT (innermost_deduced_args, i))
14359       return NULL_TREE;
14360
14361   /* Verify that nondeduced template arguments agree with the type
14362      obtained from argument deduction.
14363
14364      For example:
14365
14366        struct A { typedef int X; };
14367        template <class T, class U> struct C {};
14368        template <class T> struct C<T, typename T::X> {};
14369
14370      Then with the instantiation `C<A, int>', we can deduce that
14371      `T' is `A' but unify () does not check whether `typename T::X'
14372      is `int'.  */
14373   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
14374   if (spec_args == error_mark_node
14375       /* We only need to check the innermost arguments; the other
14376          arguments will always agree.  */
14377       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
14378                               INNERMOST_TEMPLATE_ARGS (args)))
14379     return NULL_TREE;
14380
14381   /* Now that we have bindings for all of the template arguments,
14382      ensure that the arguments deduced for the template template
14383      parameters have compatible template parameter lists.  See the use
14384      of template_template_parm_bindings_ok_p in fn_type_unification
14385      for more information.  */
14386   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
14387     return NULL_TREE;
14388
14389   return deduced_args;
14390 }
14391
14392 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
14393    Return the TREE_LIST node with the most specialized template, if
14394    any.  If there is no most specialized template, the error_mark_node
14395    is returned.
14396
14397    Note that this function does not look at, or modify, the
14398    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
14399    returned is one of the elements of INSTANTIATIONS, callers may
14400    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
14401    and retrieve it from the value returned.  */
14402
14403 tree
14404 most_specialized_instantiation (tree templates)
14405 {
14406   tree fn, champ;
14407
14408   ++processing_template_decl;
14409
14410   champ = templates;
14411   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
14412     {
14413       int fate = 0;
14414
14415       if (get_bindings (TREE_VALUE (champ),
14416                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14417                         NULL_TREE, /*check_ret=*/false))
14418         fate--;
14419
14420       if (get_bindings (TREE_VALUE (fn),
14421                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14422                         NULL_TREE, /*check_ret=*/false))
14423         fate++;
14424
14425       if (fate == -1)
14426         champ = fn;
14427       else if (!fate)
14428         {
14429           /* Equally specialized, move to next function.  If there
14430              is no next function, nothing's most specialized.  */
14431           fn = TREE_CHAIN (fn);
14432           champ = fn;
14433           if (!fn)
14434             break;
14435         }
14436     }
14437
14438   if (champ)
14439     /* Now verify that champ is better than everything earlier in the
14440        instantiation list.  */
14441     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
14442       if (get_bindings (TREE_VALUE (champ),
14443                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14444                         NULL_TREE, /*check_ret=*/false)
14445           || !get_bindings (TREE_VALUE (fn),
14446                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14447                             NULL_TREE, /*check_ret=*/false))
14448         {
14449           champ = NULL_TREE;
14450           break;
14451         }
14452
14453   processing_template_decl--;
14454
14455   if (!champ)
14456     return error_mark_node;
14457
14458   return champ;
14459 }
14460
14461 /* If DECL is a specialization of some template, return the most
14462    general such template.  Otherwise, returns NULL_TREE.
14463
14464    For example, given:
14465
14466      template <class T> struct S { template <class U> void f(U); };
14467
14468    if TMPL is `template <class U> void S<int>::f(U)' this will return
14469    the full template.  This function will not trace past partial
14470    specializations, however.  For example, given in addition:
14471
14472      template <class T> struct S<T*> { template <class U> void f(U); };
14473
14474    if TMPL is `template <class U> void S<int*>::f(U)' this will return
14475    `template <class T> template <class U> S<T*>::f(U)'.  */
14476
14477 tree
14478 most_general_template (tree decl)
14479 {
14480   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
14481      an immediate specialization.  */
14482   if (TREE_CODE (decl) == FUNCTION_DECL)
14483     {
14484       if (DECL_TEMPLATE_INFO (decl)) {
14485         decl = DECL_TI_TEMPLATE (decl);
14486
14487         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
14488            template friend.  */
14489         if (TREE_CODE (decl) != TEMPLATE_DECL)
14490           return NULL_TREE;
14491       } else
14492         return NULL_TREE;
14493     }
14494
14495   /* Look for more and more general templates.  */
14496   while (DECL_TEMPLATE_INFO (decl))
14497     {
14498       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
14499          (See cp-tree.h for details.)  */
14500       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
14501         break;
14502
14503       if (CLASS_TYPE_P (TREE_TYPE (decl))
14504           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
14505         break;
14506
14507       /* Stop if we run into an explicitly specialized class template.  */
14508       if (!DECL_NAMESPACE_SCOPE_P (decl)
14509           && DECL_CONTEXT (decl)
14510           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
14511         break;
14512
14513       decl = DECL_TI_TEMPLATE (decl);
14514     }
14515
14516   return decl;
14517 }
14518
14519 /* Return the most specialized of the class template partial
14520    specializations of TMPL which can produce TYPE, a specialization of
14521    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
14522    a _TYPE node corresponding to the partial specialization, while the
14523    TREE_PURPOSE is the set of template arguments that must be
14524    substituted into the TREE_TYPE in order to generate TYPE.
14525
14526    If the choice of partial specialization is ambiguous, a diagnostic
14527    is issued, and the error_mark_node is returned.  If there are no
14528    partial specializations of TMPL matching TYPE, then NULL_TREE is
14529    returned.  */
14530
14531 static tree
14532 most_specialized_class (tree type, tree tmpl)
14533 {
14534   tree list = NULL_TREE;
14535   tree t;
14536   tree champ;
14537   int fate;
14538   bool ambiguous_p;
14539   tree args;
14540   tree outer_args = NULL_TREE;
14541
14542   tmpl = most_general_template (tmpl);
14543   args = CLASSTYPE_TI_ARGS (type);
14544
14545   /* For determining which partial specialization to use, only the
14546      innermost args are interesting.  */
14547   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
14548     {
14549       outer_args = strip_innermost_template_args (args, 1);
14550       args = INNERMOST_TEMPLATE_ARGS (args);
14551     }
14552
14553   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
14554     {
14555       tree partial_spec_args;
14556       tree spec_args;
14557       tree parms = TREE_VALUE (t);
14558
14559       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
14560       if (outer_args)
14561         {
14562           int i;
14563
14564           ++processing_template_decl;
14565
14566           /* Discard the outer levels of args, and then substitute in the
14567              template args from the enclosing class.  */
14568           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
14569           partial_spec_args = tsubst_template_args
14570             (partial_spec_args, outer_args, tf_none, NULL_TREE);
14571
14572           /* PARMS already refers to just the innermost parms, but the
14573              template parms in partial_spec_args had their levels lowered
14574              by tsubst, so we need to do the same for the parm list.  We
14575              can't just tsubst the TREE_VEC itself, as tsubst wants to
14576              treat a TREE_VEC as an argument vector.  */
14577           parms = copy_node (parms);
14578           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
14579             TREE_VEC_ELT (parms, i) =
14580               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
14581
14582           --processing_template_decl;
14583         }
14584       spec_args = get_class_bindings (parms,
14585                                       partial_spec_args,
14586                                       args);
14587       if (spec_args)
14588         {
14589           if (outer_args)
14590             spec_args = add_to_template_args (outer_args, spec_args);
14591           list = tree_cons (spec_args, TREE_VALUE (t), list);
14592           TREE_TYPE (list) = TREE_TYPE (t);
14593         }
14594     }
14595
14596   if (! list)
14597     return NULL_TREE;
14598
14599   ambiguous_p = false;
14600   t = list;
14601   champ = t;
14602   t = TREE_CHAIN (t);
14603   for (; t; t = TREE_CHAIN (t))
14604     {
14605       fate = more_specialized_class (champ, t);
14606       if (fate == 1)
14607         ;
14608       else
14609         {
14610           if (fate == 0)
14611             {
14612               t = TREE_CHAIN (t);
14613               if (! t)
14614                 {
14615                   ambiguous_p = true;
14616                   break;
14617                 }
14618             }
14619           champ = t;
14620         }
14621     }
14622
14623   if (!ambiguous_p)
14624     for (t = list; t && t != champ; t = TREE_CHAIN (t))
14625       {
14626         fate = more_specialized_class (champ, t);
14627         if (fate != 1)
14628           {
14629             ambiguous_p = true;
14630             break;
14631           }
14632       }
14633
14634   if (ambiguous_p)
14635     {
14636       const char *str = "candidates are:";
14637       error ("ambiguous class template instantiation for %q#T", type);
14638       for (t = list; t; t = TREE_CHAIN (t))
14639         {
14640           error ("%s %+#T", str, TREE_TYPE (t));
14641           str = "               ";
14642         }
14643       return error_mark_node;
14644     }
14645
14646   return champ;
14647 }
14648
14649 /* Explicitly instantiate DECL.  */
14650
14651 void
14652 do_decl_instantiation (tree decl, tree storage)
14653 {
14654   tree result = NULL_TREE;
14655   int extern_p = 0;
14656
14657   if (!decl || decl == error_mark_node)
14658     /* An error occurred, for which grokdeclarator has already issued
14659        an appropriate message.  */
14660     return;
14661   else if (! DECL_LANG_SPECIFIC (decl))
14662     {
14663       error ("explicit instantiation of non-template %q#D", decl);
14664       return;
14665     }
14666   else if (TREE_CODE (decl) == VAR_DECL)
14667     {
14668       /* There is an asymmetry here in the way VAR_DECLs and
14669          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
14670          the latter, the DECL we get back will be marked as a
14671          template instantiation, and the appropriate
14672          DECL_TEMPLATE_INFO will be set up.  This does not happen for
14673          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
14674          should handle VAR_DECLs as it currently handles
14675          FUNCTION_DECLs.  */
14676       if (!DECL_CLASS_SCOPE_P (decl))
14677         {
14678           error ("%qD is not a static data member of a class template", decl);
14679           return;
14680         }
14681       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
14682       if (!result || TREE_CODE (result) != VAR_DECL)
14683         {
14684           error ("no matching template for %qD found", decl);
14685           return;
14686         }
14687       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
14688         {
14689           error ("type %qT for explicit instantiation %qD does not match "
14690                  "declared type %qT", TREE_TYPE (result), decl,
14691                  TREE_TYPE (decl));
14692           return;
14693         }
14694     }
14695   else if (TREE_CODE (decl) != FUNCTION_DECL)
14696     {
14697       error ("explicit instantiation of %q#D", decl);
14698       return;
14699     }
14700   else
14701     result = decl;
14702
14703   /* Check for various error cases.  Note that if the explicit
14704      instantiation is valid the RESULT will currently be marked as an
14705      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
14706      until we get here.  */
14707
14708   if (DECL_TEMPLATE_SPECIALIZATION (result))
14709     {
14710       /* DR 259 [temp.spec].
14711
14712          Both an explicit instantiation and a declaration of an explicit
14713          specialization shall not appear in a program unless the explicit
14714          instantiation follows a declaration of the explicit specialization.
14715
14716          For a given set of template parameters, if an explicit
14717          instantiation of a template appears after a declaration of an
14718          explicit specialization for that template, the explicit
14719          instantiation has no effect.  */
14720       return;
14721     }
14722   else if (DECL_EXPLICIT_INSTANTIATION (result))
14723     {
14724       /* [temp.spec]
14725
14726          No program shall explicitly instantiate any template more
14727          than once.
14728
14729          We check DECL_NOT_REALLY_EXTERN so as not to complain when
14730          the first instantiation was `extern' and the second is not,
14731          and EXTERN_P for the opposite case.  */
14732       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
14733         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
14734       /* If an "extern" explicit instantiation follows an ordinary
14735          explicit instantiation, the template is instantiated.  */
14736       if (extern_p)
14737         return;
14738     }
14739   else if (!DECL_IMPLICIT_INSTANTIATION (result))
14740     {
14741       error ("no matching template for %qD found", result);
14742       return;
14743     }
14744   else if (!DECL_TEMPLATE_INFO (result))
14745     {
14746       permerror (input_location, "explicit instantiation of non-template %q#D", result);
14747       return;
14748     }
14749
14750   if (storage == NULL_TREE)
14751     ;
14752   else if (storage == ridpointers[(int) RID_EXTERN])
14753     {
14754       if (!in_system_header && (cxx_dialect == cxx98))
14755         pedwarn (input_location, OPT_pedantic, 
14756                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
14757                  "instantiations");
14758       extern_p = 1;
14759     }
14760   else
14761     error ("storage class %qD applied to template instantiation", storage);
14762
14763   check_explicit_instantiation_namespace (result);
14764   mark_decl_instantiated (result, extern_p);
14765   if (! extern_p)
14766     instantiate_decl (result, /*defer_ok=*/1,
14767                       /*expl_inst_class_mem_p=*/false);
14768 }
14769
14770 static void
14771 mark_class_instantiated (tree t, int extern_p)
14772 {
14773   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
14774   SET_CLASSTYPE_INTERFACE_KNOWN (t);
14775   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
14776   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
14777   if (! extern_p)
14778     {
14779       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
14780       rest_of_type_compilation (t, 1);
14781     }
14782 }
14783
14784 /* Called from do_type_instantiation through binding_table_foreach to
14785    do recursive instantiation for the type bound in ENTRY.  */
14786 static void
14787 bt_instantiate_type_proc (binding_entry entry, void *data)
14788 {
14789   tree storage = *(tree *) data;
14790
14791   if (MAYBE_CLASS_TYPE_P (entry->type)
14792       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
14793     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
14794 }
14795
14796 /* Called from do_type_instantiation to instantiate a member
14797    (a member function or a static member variable) of an
14798    explicitly instantiated class template.  */
14799 static void
14800 instantiate_class_member (tree decl, int extern_p)
14801 {
14802   mark_decl_instantiated (decl, extern_p);
14803   if (! extern_p)
14804     instantiate_decl (decl, /*defer_ok=*/1,
14805                       /*expl_inst_class_mem_p=*/true);
14806 }
14807
14808 /* Perform an explicit instantiation of template class T.  STORAGE, if
14809    non-null, is the RID for extern, inline or static.  COMPLAIN is
14810    nonzero if this is called from the parser, zero if called recursively,
14811    since the standard is unclear (as detailed below).  */
14812
14813 void
14814 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
14815 {
14816   int extern_p = 0;
14817   int nomem_p = 0;
14818   int static_p = 0;
14819   int previous_instantiation_extern_p = 0;
14820
14821   if (TREE_CODE (t) == TYPE_DECL)
14822     t = TREE_TYPE (t);
14823
14824   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
14825     {
14826       error ("explicit instantiation of non-template type %qT", t);
14827       return;
14828     }
14829
14830   complete_type (t);
14831
14832   if (!COMPLETE_TYPE_P (t))
14833     {
14834       if (complain & tf_error)
14835         error ("explicit instantiation of %q#T before definition of template",
14836                t);
14837       return;
14838     }
14839
14840   if (storage != NULL_TREE)
14841     {
14842       if (!in_system_header)
14843         {
14844           if (storage == ridpointers[(int) RID_EXTERN])
14845             {
14846               if (cxx_dialect == cxx98)
14847                 pedwarn (input_location, OPT_pedantic, 
14848                          "ISO C++ 1998 forbids the use of %<extern%> on "
14849                          "explicit instantiations");
14850             }
14851           else
14852             pedwarn (input_location, OPT_pedantic, 
14853                      "ISO C++ forbids the use of %qE"
14854                      " on explicit instantiations", storage);
14855         }
14856
14857       if (storage == ridpointers[(int) RID_INLINE])
14858         nomem_p = 1;
14859       else if (storage == ridpointers[(int) RID_EXTERN])
14860         extern_p = 1;
14861       else if (storage == ridpointers[(int) RID_STATIC])
14862         static_p = 1;
14863       else
14864         {
14865           error ("storage class %qD applied to template instantiation",
14866                  storage);
14867           extern_p = 0;
14868         }
14869     }
14870
14871   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
14872     {
14873       /* DR 259 [temp.spec].
14874
14875          Both an explicit instantiation and a declaration of an explicit
14876          specialization shall not appear in a program unless the explicit
14877          instantiation follows a declaration of the explicit specialization.
14878
14879          For a given set of template parameters, if an explicit
14880          instantiation of a template appears after a declaration of an
14881          explicit specialization for that template, the explicit
14882          instantiation has no effect.  */
14883       return;
14884     }
14885   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
14886     {
14887       /* [temp.spec]
14888
14889          No program shall explicitly instantiate any template more
14890          than once.
14891
14892          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
14893          instantiation was `extern'.  If EXTERN_P then the second is.
14894          These cases are OK.  */
14895       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
14896
14897       if (!previous_instantiation_extern_p && !extern_p
14898           && (complain & tf_error))
14899         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
14900
14901       /* If we've already instantiated the template, just return now.  */
14902       if (!CLASSTYPE_INTERFACE_ONLY (t))
14903         return;
14904     }
14905
14906   check_explicit_instantiation_namespace (TYPE_NAME (t));
14907   mark_class_instantiated (t, extern_p);
14908
14909   if (nomem_p)
14910     return;
14911
14912   {
14913     tree tmp;
14914
14915     /* In contrast to implicit instantiation, where only the
14916        declarations, and not the definitions, of members are
14917        instantiated, we have here:
14918
14919          [temp.explicit]
14920
14921          The explicit instantiation of a class template specialization
14922          implies the instantiation of all of its members not
14923          previously explicitly specialized in the translation unit
14924          containing the explicit instantiation.
14925
14926        Of course, we can't instantiate member template classes, since
14927        we don't have any arguments for them.  Note that the standard
14928        is unclear on whether the instantiation of the members are
14929        *explicit* instantiations or not.  However, the most natural
14930        interpretation is that it should be an explicit instantiation.  */
14931
14932     if (! static_p)
14933       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
14934         if (TREE_CODE (tmp) == FUNCTION_DECL
14935             && DECL_TEMPLATE_INSTANTIATION (tmp))
14936           instantiate_class_member (tmp, extern_p);
14937
14938     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
14939       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
14940         instantiate_class_member (tmp, extern_p);
14941
14942     if (CLASSTYPE_NESTED_UTDS (t))
14943       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
14944                              bt_instantiate_type_proc, &storage);
14945   }
14946 }
14947
14948 /* Given a function DECL, which is a specialization of TMPL, modify
14949    DECL to be a re-instantiation of TMPL with the same template
14950    arguments.  TMPL should be the template into which tsubst'ing
14951    should occur for DECL, not the most general template.
14952
14953    One reason for doing this is a scenario like this:
14954
14955      template <class T>
14956      void f(const T&, int i);
14957
14958      void g() { f(3, 7); }
14959
14960      template <class T>
14961      void f(const T& t, const int i) { }
14962
14963    Note that when the template is first instantiated, with
14964    instantiate_template, the resulting DECL will have no name for the
14965    first parameter, and the wrong type for the second.  So, when we go
14966    to instantiate the DECL, we regenerate it.  */
14967
14968 static void
14969 regenerate_decl_from_template (tree decl, tree tmpl)
14970 {
14971   /* The arguments used to instantiate DECL, from the most general
14972      template.  */
14973   tree args;
14974   tree code_pattern;
14975
14976   args = DECL_TI_ARGS (decl);
14977   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
14978
14979   /* Make sure that we can see identifiers, and compute access
14980      correctly.  */
14981   push_access_scope (decl);
14982
14983   if (TREE_CODE (decl) == FUNCTION_DECL)
14984     {
14985       tree decl_parm;
14986       tree pattern_parm;
14987       tree specs;
14988       int args_depth;
14989       int parms_depth;
14990
14991       args_depth = TMPL_ARGS_DEPTH (args);
14992       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
14993       if (args_depth > parms_depth)
14994         args = get_innermost_template_args (args, parms_depth);
14995
14996       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
14997                                               args, tf_error, NULL_TREE);
14998       if (specs)
14999         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
15000                                                     specs);
15001
15002       /* Merge parameter declarations.  */
15003       decl_parm = skip_artificial_parms_for (decl,
15004                                              DECL_ARGUMENTS (decl));
15005       pattern_parm
15006         = skip_artificial_parms_for (code_pattern,
15007                                      DECL_ARGUMENTS (code_pattern));
15008       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
15009         {
15010           tree parm_type;
15011           tree attributes;
15012           
15013           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
15014             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
15015           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
15016                               NULL_TREE);
15017           parm_type = type_decays_to (parm_type);
15018           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
15019             TREE_TYPE (decl_parm) = parm_type;
15020           attributes = DECL_ATTRIBUTES (pattern_parm);
15021           if (DECL_ATTRIBUTES (decl_parm) != attributes)
15022             {
15023               DECL_ATTRIBUTES (decl_parm) = attributes;
15024               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
15025             }
15026           decl_parm = TREE_CHAIN (decl_parm);
15027           pattern_parm = TREE_CHAIN (pattern_parm);
15028         }
15029       /* Merge any parameters that match with the function parameter
15030          pack.  */
15031       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
15032         {
15033           int i, len;
15034           tree expanded_types;
15035           /* Expand the TYPE_PACK_EXPANSION that provides the types for
15036              the parameters in this function parameter pack.  */
15037           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
15038                                                  args, tf_error, NULL_TREE);
15039           len = TREE_VEC_LENGTH (expanded_types);
15040           for (i = 0; i < len; i++)
15041             {
15042               tree parm_type;
15043               tree attributes;
15044           
15045               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
15046                 /* Rename the parameter to include the index.  */
15047                 DECL_NAME (decl_parm) = 
15048                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
15049               parm_type = TREE_VEC_ELT (expanded_types, i);
15050               parm_type = type_decays_to (parm_type);
15051               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
15052                 TREE_TYPE (decl_parm) = parm_type;
15053               attributes = DECL_ATTRIBUTES (pattern_parm);
15054               if (DECL_ATTRIBUTES (decl_parm) != attributes)
15055                 {
15056                   DECL_ATTRIBUTES (decl_parm) = attributes;
15057                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
15058                 }
15059               decl_parm = TREE_CHAIN (decl_parm);
15060             }
15061         }
15062       /* Merge additional specifiers from the CODE_PATTERN.  */
15063       if (DECL_DECLARED_INLINE_P (code_pattern)
15064           && !DECL_DECLARED_INLINE_P (decl))
15065         DECL_DECLARED_INLINE_P (decl) = 1;
15066     }
15067   else if (TREE_CODE (decl) == VAR_DECL)
15068     DECL_INITIAL (decl) =
15069       tsubst_expr (DECL_INITIAL (code_pattern), args,
15070                    tf_error, DECL_TI_TEMPLATE (decl),
15071                    /*integral_constant_expression_p=*/false);
15072   else
15073     gcc_unreachable ();
15074
15075   pop_access_scope (decl);
15076 }
15077
15078 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
15079    substituted to get DECL.  */
15080
15081 tree
15082 template_for_substitution (tree decl)
15083 {
15084   tree tmpl = DECL_TI_TEMPLATE (decl);
15085
15086   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
15087      for the instantiation.  This is not always the most general
15088      template.  Consider, for example:
15089
15090         template <class T>
15091         struct S { template <class U> void f();
15092                    template <> void f<int>(); };
15093
15094      and an instantiation of S<double>::f<int>.  We want TD to be the
15095      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
15096   while (/* An instantiation cannot have a definition, so we need a
15097             more general template.  */
15098          DECL_TEMPLATE_INSTANTIATION (tmpl)
15099            /* We must also deal with friend templates.  Given:
15100
15101                 template <class T> struct S {
15102                   template <class U> friend void f() {};
15103                 };
15104
15105               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
15106               so far as the language is concerned, but that's still
15107               where we get the pattern for the instantiation from.  On
15108               other hand, if the definition comes outside the class, say:
15109
15110                 template <class T> struct S {
15111                   template <class U> friend void f();
15112                 };
15113                 template <class U> friend void f() {}
15114
15115               we don't need to look any further.  That's what the check for
15116               DECL_INITIAL is for.  */
15117           || (TREE_CODE (decl) == FUNCTION_DECL
15118               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
15119               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
15120     {
15121       /* The present template, TD, should not be a definition.  If it
15122          were a definition, we should be using it!  Note that we
15123          cannot restructure the loop to just keep going until we find
15124          a template with a definition, since that might go too far if
15125          a specialization was declared, but not defined.  */
15126       gcc_assert (TREE_CODE (decl) != VAR_DECL
15127                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
15128
15129       /* Fetch the more general template.  */
15130       tmpl = DECL_TI_TEMPLATE (tmpl);
15131     }
15132
15133   return tmpl;
15134 }
15135
15136 /* Produce the definition of D, a _DECL generated from a template.  If
15137    DEFER_OK is nonzero, then we don't have to actually do the
15138    instantiation now; we just have to do it sometime.  Normally it is
15139    an error if this is an explicit instantiation but D is undefined.
15140    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
15141    explicitly instantiated class template.  */
15142
15143 tree
15144 instantiate_decl (tree d, int defer_ok,
15145                   bool expl_inst_class_mem_p)
15146 {
15147   tree tmpl = DECL_TI_TEMPLATE (d);
15148   tree gen_args;
15149   tree args;
15150   tree td;
15151   tree code_pattern;
15152   tree spec;
15153   tree gen_tmpl;
15154   bool pattern_defined;
15155   int need_push;
15156   location_t saved_loc = input_location;
15157   bool external_p;
15158
15159   /* This function should only be used to instantiate templates for
15160      functions and static member variables.  */
15161   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
15162               || TREE_CODE (d) == VAR_DECL);
15163
15164   /* Variables are never deferred; if instantiation is required, they
15165      are instantiated right away.  That allows for better code in the
15166      case that an expression refers to the value of the variable --
15167      if the variable has a constant value the referring expression can
15168      take advantage of that fact.  */
15169   if (TREE_CODE (d) == VAR_DECL)
15170     defer_ok = 0;
15171
15172   /* Don't instantiate cloned functions.  Instead, instantiate the
15173      functions they cloned.  */
15174   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
15175     d = DECL_CLONED_FUNCTION (d);
15176
15177   if (DECL_TEMPLATE_INSTANTIATED (d))
15178     /* D has already been instantiated.  It might seem reasonable to
15179        check whether or not D is an explicit instantiation, and, if so,
15180        stop here.  But when an explicit instantiation is deferred
15181        until the end of the compilation, DECL_EXPLICIT_INSTANTIATION
15182        is set, even though we still need to do the instantiation.  */
15183     return d;
15184
15185   /* If we already have a specialization of this declaration, then
15186      there's no reason to instantiate it.  Note that
15187      retrieve_specialization gives us both instantiations and
15188      specializations, so we must explicitly check
15189      DECL_TEMPLATE_SPECIALIZATION.  */
15190   gen_tmpl = most_general_template (tmpl);
15191   gen_args = DECL_TI_ARGS (d);
15192   spec = retrieve_specialization (gen_tmpl, gen_args,
15193                                   /*class_specializations_p=*/false);
15194   if (spec != NULL_TREE && DECL_TEMPLATE_SPECIALIZATION (spec))
15195     return spec;
15196
15197   /* This needs to happen before any tsubsting.  */
15198   if (! push_tinst_level (d))
15199     return d;
15200
15201   timevar_push (TV_PARSE);
15202
15203   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
15204      for the instantiation.  */
15205   td = template_for_substitution (d);
15206   code_pattern = DECL_TEMPLATE_RESULT (td);
15207
15208   /* We should never be trying to instantiate a member of a class
15209      template or partial specialization.  */
15210   gcc_assert (d != code_pattern);
15211
15212   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
15213       || DECL_TEMPLATE_SPECIALIZATION (td))
15214     /* In the case of a friend template whose definition is provided
15215        outside the class, we may have too many arguments.  Drop the
15216        ones we don't need.  The same is true for specializations.  */
15217     args = get_innermost_template_args
15218       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
15219   else
15220     args = gen_args;
15221
15222   if (TREE_CODE (d) == FUNCTION_DECL)
15223     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
15224   else
15225     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
15226
15227   /* We may be in the middle of deferred access check.  Disable it now.  */
15228   push_deferring_access_checks (dk_no_deferred);
15229
15230   /* Unless an explicit instantiation directive has already determined
15231      the linkage of D, remember that a definition is available for
15232      this entity.  */
15233   if (pattern_defined
15234       && !DECL_INTERFACE_KNOWN (d)
15235       && !DECL_NOT_REALLY_EXTERN (d))
15236     mark_definable (d);
15237
15238   input_location = DECL_SOURCE_LOCATION (d);
15239
15240   /* If D is a member of an explicitly instantiated class template,
15241      and no definition is available, treat it like an implicit
15242      instantiation.  */
15243   if (!pattern_defined && expl_inst_class_mem_p
15244       && DECL_EXPLICIT_INSTANTIATION (d))
15245     {
15246       DECL_NOT_REALLY_EXTERN (d) = 0;
15247       DECL_INTERFACE_KNOWN (d) = 0;
15248       SET_DECL_IMPLICIT_INSTANTIATION (d);
15249     }
15250
15251   if (!defer_ok)
15252     {
15253       /* Recheck the substitutions to obtain any warning messages
15254          about ignoring cv qualifiers.  */
15255       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
15256       tree type = TREE_TYPE (gen);
15257
15258       /* Make sure that we can see identifiers, and compute access
15259          correctly.  D is already the target FUNCTION_DECL with the
15260          right context.  */
15261       push_access_scope (d);
15262
15263       if (TREE_CODE (gen) == FUNCTION_DECL)
15264         {
15265           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
15266           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
15267                                           d);
15268           /* Don't simply tsubst the function type, as that will give
15269              duplicate warnings about poor parameter qualifications.
15270              The function arguments are the same as the decl_arguments
15271              without the top level cv qualifiers.  */
15272           type = TREE_TYPE (type);
15273         }
15274       tsubst (type, gen_args, tf_warning_or_error, d);
15275
15276       pop_access_scope (d);
15277     }
15278
15279   /* Check to see whether we know that this template will be
15280      instantiated in some other file, as with "extern template"
15281      extension.  */
15282   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
15283   /* In general, we do not instantiate such templates...  */
15284   if (external_p
15285       /* ... but we instantiate inline functions so that we can inline
15286          them and ... */
15287       && ! (TREE_CODE (d) == FUNCTION_DECL
15288             && possibly_inlined_p (d))
15289       /* ... we instantiate static data members whose values are
15290          needed in integral constant expressions.  */
15291       && ! (TREE_CODE (d) == VAR_DECL
15292             && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (d)))
15293     goto out;
15294   /* Defer all other templates, unless we have been explicitly
15295      forbidden from doing so.  */
15296   if (/* If there is no definition, we cannot instantiate the
15297          template.  */
15298       ! pattern_defined
15299       /* If it's OK to postpone instantiation, do so.  */
15300       || defer_ok
15301       /* If this is a static data member that will be defined
15302          elsewhere, we don't want to instantiate the entire data
15303          member, but we do want to instantiate the initializer so that
15304          we can substitute that elsewhere.  */
15305       || (external_p && TREE_CODE (d) == VAR_DECL))
15306     {
15307       /* The definition of the static data member is now required so
15308          we must substitute the initializer.  */
15309       if (TREE_CODE (d) == VAR_DECL
15310           && !DECL_INITIAL (d)
15311           && DECL_INITIAL (code_pattern))
15312         {
15313           tree ns;
15314           tree init;
15315
15316           ns = decl_namespace_context (d);
15317           push_nested_namespace (ns);
15318           push_nested_class (DECL_CONTEXT (d));
15319           init = tsubst_expr (DECL_INITIAL (code_pattern),
15320                               args,
15321                               tf_warning_or_error, NULL_TREE,
15322                               /*integral_constant_expression_p=*/false);
15323           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
15324                           /*asmspec_tree=*/NULL_TREE,
15325                           LOOKUP_ONLYCONVERTING);
15326           pop_nested_class ();
15327           pop_nested_namespace (ns);
15328         }
15329
15330       /* We restore the source position here because it's used by
15331          add_pending_template.  */
15332       input_location = saved_loc;
15333
15334       if (at_eof && !pattern_defined
15335           && DECL_EXPLICIT_INSTANTIATION (d)
15336           && DECL_NOT_REALLY_EXTERN (d))
15337         /* [temp.explicit]
15338
15339            The definition of a non-exported function template, a
15340            non-exported member function template, or a non-exported
15341            member function or static data member of a class template
15342            shall be present in every translation unit in which it is
15343            explicitly instantiated.  */
15344         permerror (input_location,  "explicit instantiation of %qD "
15345                    "but no definition available", d);
15346
15347       /* ??? Historically, we have instantiated inline functions, even
15348          when marked as "extern template".  */
15349       if (!(external_p && TREE_CODE (d) == VAR_DECL))
15350         add_pending_template (d);
15351       goto out;
15352     }
15353   /* Tell the repository that D is available in this translation unit
15354      -- and see if it is supposed to be instantiated here.  */
15355   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
15356     {
15357       /* In a PCH file, despite the fact that the repository hasn't
15358          requested instantiation in the PCH it is still possible that
15359          an instantiation will be required in a file that includes the
15360          PCH.  */
15361       if (pch_file)
15362         add_pending_template (d);
15363       /* Instantiate inline functions so that the inliner can do its
15364          job, even though we'll not be emitting a copy of this
15365          function.  */
15366       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
15367         goto out;
15368     }
15369
15370   need_push = !cfun || !global_bindings_p ();
15371   if (need_push)
15372     push_to_top_level ();
15373
15374   /* Mark D as instantiated so that recursive calls to
15375      instantiate_decl do not try to instantiate it again.  */
15376   DECL_TEMPLATE_INSTANTIATED (d) = 1;
15377
15378   /* Regenerate the declaration in case the template has been modified
15379      by a subsequent redeclaration.  */
15380   regenerate_decl_from_template (d, td);
15381
15382   /* We already set the file and line above.  Reset them now in case
15383      they changed as a result of calling regenerate_decl_from_template.  */
15384   input_location = DECL_SOURCE_LOCATION (d);
15385
15386   if (TREE_CODE (d) == VAR_DECL)
15387     {
15388       tree init;
15389
15390       /* Clear out DECL_RTL; whatever was there before may not be right
15391          since we've reset the type of the declaration.  */
15392       SET_DECL_RTL (d, NULL_RTX);
15393       DECL_IN_AGGR_P (d) = 0;
15394
15395       /* The initializer is placed in DECL_INITIAL by
15396          regenerate_decl_from_template.  Pull it out so that
15397          finish_decl can process it.  */
15398       init = DECL_INITIAL (d);
15399       DECL_INITIAL (d) = NULL_TREE;
15400       DECL_INITIALIZED_P (d) = 0;
15401
15402       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
15403          initializer.  That function will defer actual emission until
15404          we have a chance to determine linkage.  */
15405       DECL_EXTERNAL (d) = 0;
15406
15407       /* Enter the scope of D so that access-checking works correctly.  */
15408       push_nested_class (DECL_CONTEXT (d));
15409       finish_decl (d, init, NULL_TREE);
15410       pop_nested_class ();
15411     }
15412   else if (TREE_CODE (d) == FUNCTION_DECL)
15413     {
15414       htab_t saved_local_specializations;
15415       tree subst_decl;
15416       tree tmpl_parm;
15417       tree spec_parm;
15418
15419       /* Save away the current list, in case we are instantiating one
15420          template from within the body of another.  */
15421       saved_local_specializations = local_specializations;
15422
15423       /* Set up the list of local specializations.  */
15424       local_specializations = htab_create (37,
15425                                            hash_local_specialization,
15426                                            eq_local_specializations,
15427                                            NULL);
15428
15429       /* Set up context.  */
15430       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
15431
15432       /* Create substitution entries for the parameters.  */
15433       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
15434       tmpl_parm = DECL_ARGUMENTS (subst_decl);
15435       spec_parm = DECL_ARGUMENTS (d);
15436       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
15437         {
15438           register_local_specialization (spec_parm, tmpl_parm);
15439           spec_parm = skip_artificial_parms_for (d, spec_parm);
15440           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
15441         }
15442       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15443         {
15444           register_local_specialization (spec_parm, tmpl_parm);
15445           tmpl_parm = TREE_CHAIN (tmpl_parm);
15446           spec_parm = TREE_CHAIN (spec_parm);
15447         }
15448       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15449         {
15450           /* Collect all of the extra "packed" parameters into an
15451              argument pack.  */
15452           tree parmvec;
15453           tree parmtypevec;
15454           tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
15455           tree argtypepack = make_node (TYPE_ARGUMENT_PACK);
15456           int i, len = 0;
15457           tree t;
15458           
15459           /* Count how many parameters remain.  */
15460           for (t = spec_parm; t; t = TREE_CHAIN (t))
15461             len++;
15462
15463           /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
15464           parmvec = make_tree_vec (len);
15465           parmtypevec = make_tree_vec (len);
15466           for(i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
15467             {
15468               TREE_VEC_ELT (parmvec, i) = spec_parm;
15469               TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
15470             }
15471
15472           /* Build the argument packs.  */
15473           SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
15474           SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
15475           TREE_TYPE (argpack) = argtypepack;
15476           
15477           /* Register the (value) argument pack as a specialization of
15478              TMPL_PARM, then move on.  */
15479           register_local_specialization (argpack, tmpl_parm);
15480           tmpl_parm = TREE_CHAIN (tmpl_parm);
15481         }
15482       gcc_assert (!spec_parm);
15483
15484       /* Substitute into the body of the function.  */
15485       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
15486                    tf_warning_or_error, tmpl,
15487                    /*integral_constant_expression_p=*/false);
15488
15489       /* Set the current input_location to the end of the function
15490          so that finish_function knows where we are.  */
15491       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
15492
15493       /* We don't need the local specializations any more.  */
15494       htab_delete (local_specializations);
15495       local_specializations = saved_local_specializations;
15496
15497       /* Finish the function.  */
15498       d = finish_function (0);
15499       expand_or_defer_fn (d);
15500     }
15501
15502   /* We're not deferring instantiation any more.  */
15503   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
15504
15505   if (need_push)
15506     pop_from_top_level ();
15507
15508 out:
15509   input_location = saved_loc;
15510   pop_deferring_access_checks ();
15511   pop_tinst_level ();
15512
15513   timevar_pop (TV_PARSE);
15514
15515   return d;
15516 }
15517
15518 /* Run through the list of templates that we wish we could
15519    instantiate, and instantiate any we can.  RETRIES is the
15520    number of times we retry pending template instantiation.  */
15521
15522 void
15523 instantiate_pending_templates (int retries)
15524 {
15525   int reconsider;
15526   location_t saved_loc = input_location;
15527
15528   /* Instantiating templates may trigger vtable generation.  This in turn
15529      may require further template instantiations.  We place a limit here
15530      to avoid infinite loop.  */
15531   if (pending_templates && retries >= max_tinst_depth)
15532     {
15533       tree decl = pending_templates->tinst->decl;
15534
15535       error ("template instantiation depth exceeds maximum of %d"
15536              " instantiating %q+D, possibly from virtual table generation"
15537              " (use -ftemplate-depth-NN to increase the maximum)",
15538              max_tinst_depth, decl);
15539       if (TREE_CODE (decl) == FUNCTION_DECL)
15540         /* Pretend that we defined it.  */
15541         DECL_INITIAL (decl) = error_mark_node;
15542       return;
15543     }
15544
15545   do
15546     {
15547       struct pending_template **t = &pending_templates;
15548       struct pending_template *last = NULL;
15549       reconsider = 0;
15550       while (*t)
15551         {
15552           tree instantiation = reopen_tinst_level ((*t)->tinst);
15553           bool complete = false;
15554
15555           if (TYPE_P (instantiation))
15556             {
15557               tree fn;
15558
15559               if (!COMPLETE_TYPE_P (instantiation))
15560                 {
15561                   instantiate_class_template (instantiation);
15562                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
15563                     for (fn = TYPE_METHODS (instantiation);
15564                          fn;
15565                          fn = TREE_CHAIN (fn))
15566                       if (! DECL_ARTIFICIAL (fn))
15567                         instantiate_decl (fn,
15568                                           /*defer_ok=*/0,
15569                                           /*expl_inst_class_mem_p=*/false);
15570                   if (COMPLETE_TYPE_P (instantiation))
15571                     reconsider = 1;
15572                 }
15573
15574               complete = COMPLETE_TYPE_P (instantiation);
15575             }
15576           else
15577             {
15578               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
15579                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
15580                 {
15581                   instantiation
15582                     = instantiate_decl (instantiation,
15583                                         /*defer_ok=*/0,
15584                                         /*expl_inst_class_mem_p=*/false);
15585                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
15586                     reconsider = 1;
15587                 }
15588
15589               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
15590                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
15591             }
15592
15593           if (complete)
15594             /* If INSTANTIATION has been instantiated, then we don't
15595                need to consider it again in the future.  */
15596             *t = (*t)->next;
15597           else
15598             {
15599               last = *t;
15600               t = &(*t)->next;
15601             }
15602           tinst_depth = 0;
15603           current_tinst_level = NULL;
15604         }
15605       last_pending_template = last;
15606     }
15607   while (reconsider);
15608
15609   input_location = saved_loc;
15610 }
15611
15612 /* Substitute ARGVEC into T, which is a list of initializers for
15613    either base class or a non-static data member.  The TREE_PURPOSEs
15614    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
15615    instantiate_decl.  */
15616
15617 static tree
15618 tsubst_initializer_list (tree t, tree argvec)
15619 {
15620   tree inits = NULL_TREE;
15621
15622   for (; t; t = TREE_CHAIN (t))
15623     {
15624       tree decl;
15625       tree init;
15626       tree expanded_bases = NULL_TREE;
15627       tree expanded_arguments = NULL_TREE;
15628       int i, len = 1;
15629
15630       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
15631         {
15632           tree expr;
15633           tree arg;
15634
15635           /* Expand the base class expansion type into separate base
15636              classes.  */
15637           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
15638                                                  tf_warning_or_error,
15639                                                  NULL_TREE);
15640           if (expanded_bases == error_mark_node)
15641             continue;
15642           
15643           /* We'll be building separate TREE_LISTs of arguments for
15644              each base.  */
15645           len = TREE_VEC_LENGTH (expanded_bases);
15646           expanded_arguments = make_tree_vec (len);
15647           for (i = 0; i < len; i++)
15648             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
15649
15650           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
15651              expand each argument in the TREE_VALUE of t.  */
15652           expr = make_node (EXPR_PACK_EXPANSION);
15653           PACK_EXPANSION_PARAMETER_PACKS (expr) =
15654             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
15655
15656           if (TREE_VALUE (t) == void_type_node)
15657             /* VOID_TYPE_NODE is used to indicate
15658                value-initialization.  */
15659             {
15660               for (i = 0; i < len; i++)
15661                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
15662             }
15663           else
15664             {
15665               /* Substitute parameter packs into each argument in the
15666                  TREE_LIST.  */
15667               in_base_initializer = 1;
15668               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
15669                 {
15670                   tree expanded_exprs;
15671
15672                   /* Expand the argument.  */
15673                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
15674                   expanded_exprs 
15675                     = tsubst_pack_expansion (expr, argvec,
15676                                              tf_warning_or_error,
15677                                              NULL_TREE);
15678                   if (expanded_exprs == error_mark_node)
15679                     continue;
15680
15681                   /* Prepend each of the expanded expressions to the
15682                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
15683                   for (i = 0; i < len; i++)
15684                     {
15685                       TREE_VEC_ELT (expanded_arguments, i) = 
15686                         tree_cons (NULL_TREE, 
15687                                    TREE_VEC_ELT (expanded_exprs, i),
15688                                    TREE_VEC_ELT (expanded_arguments, i));
15689                     }
15690                 }
15691               in_base_initializer = 0;
15692
15693               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
15694                  since we built them backwards.  */
15695               for (i = 0; i < len; i++)
15696                 {
15697                   TREE_VEC_ELT (expanded_arguments, i) = 
15698                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
15699                 }
15700             }
15701         }
15702
15703       for (i = 0; i < len; ++i)
15704         {
15705           if (expanded_bases)
15706             {
15707               decl = TREE_VEC_ELT (expanded_bases, i);
15708               decl = expand_member_init (decl);
15709               init = TREE_VEC_ELT (expanded_arguments, i);
15710             }
15711           else
15712             {
15713               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
15714                                   tf_warning_or_error, NULL_TREE);
15715
15716               decl = expand_member_init (decl);
15717               if (decl && !DECL_P (decl))
15718                 in_base_initializer = 1;
15719
15720               init = tsubst_expr (TREE_VALUE (t), argvec, 
15721                                   tf_warning_or_error, NULL_TREE,
15722                                   /*integral_constant_expression_p=*/false);
15723               in_base_initializer = 0;
15724             }
15725
15726           if (decl)
15727             {
15728               init = build_tree_list (decl, init);
15729               TREE_CHAIN (init) = inits;
15730               inits = init;
15731             }
15732         }
15733     }
15734   return inits;
15735 }
15736
15737 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
15738
15739 static void
15740 set_current_access_from_decl (tree decl)
15741 {
15742   if (TREE_PRIVATE (decl))
15743     current_access_specifier = access_private_node;
15744   else if (TREE_PROTECTED (decl))
15745     current_access_specifier = access_protected_node;
15746   else
15747     current_access_specifier = access_public_node;
15748 }
15749
15750 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
15751    is the instantiation (which should have been created with
15752    start_enum) and ARGS are the template arguments to use.  */
15753
15754 static void
15755 tsubst_enum (tree tag, tree newtag, tree args)
15756 {
15757   tree e;
15758
15759   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
15760     {
15761       tree value;
15762       tree decl;
15763
15764       decl = TREE_VALUE (e);
15765       /* Note that in a template enum, the TREE_VALUE is the
15766          CONST_DECL, not the corresponding INTEGER_CST.  */
15767       value = tsubst_expr (DECL_INITIAL (decl),
15768                            args, tf_warning_or_error, NULL_TREE,
15769                            /*integral_constant_expression_p=*/true);
15770
15771       /* Give this enumeration constant the correct access.  */
15772       set_current_access_from_decl (decl);
15773
15774       /* Actually build the enumerator itself.  */
15775       build_enumerator (DECL_NAME (decl), value, newtag);
15776     }
15777
15778   finish_enum (newtag);
15779   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
15780     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
15781 }
15782
15783 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
15784    its type -- but without substituting the innermost set of template
15785    arguments.  So, innermost set of template parameters will appear in
15786    the type.  */
15787
15788 tree
15789 get_mostly_instantiated_function_type (tree decl)
15790 {
15791   tree fn_type;
15792   tree tmpl;
15793   tree targs;
15794   tree tparms;
15795   int parm_depth;
15796
15797   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15798   targs = DECL_TI_ARGS (decl);
15799   tparms = DECL_TEMPLATE_PARMS (tmpl);
15800   parm_depth = TMPL_PARMS_DEPTH (tparms);
15801
15802   /* There should be as many levels of arguments as there are levels
15803      of parameters.  */
15804   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
15805
15806   fn_type = TREE_TYPE (tmpl);
15807
15808   if (parm_depth == 1)
15809     /* No substitution is necessary.  */
15810     ;
15811   else
15812     {
15813       int i, save_access_control;
15814       tree partial_args;
15815
15816       /* Replace the innermost level of the TARGS with NULL_TREEs to
15817          let tsubst know not to substitute for those parameters.  */
15818       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
15819       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
15820         SET_TMPL_ARGS_LEVEL (partial_args, i,
15821                              TMPL_ARGS_LEVEL (targs, i));
15822       SET_TMPL_ARGS_LEVEL (partial_args,
15823                            TMPL_ARGS_DEPTH (targs),
15824                            make_tree_vec (DECL_NTPARMS (tmpl)));
15825
15826       /* Disable access control as this function is used only during
15827          name-mangling.  */
15828       save_access_control = flag_access_control;
15829       flag_access_control = 0;
15830
15831       ++processing_template_decl;
15832       /* Now, do the (partial) substitution to figure out the
15833          appropriate function type.  */
15834       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
15835       --processing_template_decl;
15836
15837       /* Substitute into the template parameters to obtain the real
15838          innermost set of parameters.  This step is important if the
15839          innermost set of template parameters contains value
15840          parameters whose types depend on outer template parameters.  */
15841       TREE_VEC_LENGTH (partial_args)--;
15842       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
15843
15844       flag_access_control = save_access_control;
15845     }
15846
15847   return fn_type;
15848 }
15849
15850 /* Return truthvalue if we're processing a template different from
15851    the last one involved in diagnostics.  */
15852 int
15853 problematic_instantiation_changed (void)
15854 {
15855   return last_template_error_tick != tinst_level_tick;
15856 }
15857
15858 /* Remember current template involved in diagnostics.  */
15859 void
15860 record_last_problematic_instantiation (void)
15861 {
15862   last_template_error_tick = tinst_level_tick;
15863 }
15864
15865 struct tinst_level *
15866 current_instantiation (void)
15867 {
15868   return current_tinst_level;
15869 }
15870
15871 /* [temp.param] Check that template non-type parm TYPE is of an allowable
15872    type. Return zero for ok, nonzero for disallowed. Issue error and
15873    warning messages under control of COMPLAIN.  */
15874
15875 static int
15876 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
15877 {
15878   if (INTEGRAL_TYPE_P (type))
15879     return 0;
15880   else if (POINTER_TYPE_P (type))
15881     return 0;
15882   else if (TYPE_PTR_TO_MEMBER_P (type))
15883     return 0;
15884   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
15885     return 0;
15886   else if (TREE_CODE (type) == TYPENAME_TYPE)
15887     return 0;
15888
15889   if (complain & tf_error)
15890     error ("%q#T is not a valid type for a template constant parameter", type);
15891   return 1;
15892 }
15893
15894 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
15895    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
15896
15897 static bool
15898 dependent_type_p_r (tree type)
15899 {
15900   tree scope;
15901
15902   /* [temp.dep.type]
15903
15904      A type is dependent if it is:
15905
15906      -- a template parameter. Template template parameters are types
15907         for us (since TYPE_P holds true for them) so we handle
15908         them here.  */
15909   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
15910       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
15911     return true;
15912   /* -- a qualified-id with a nested-name-specifier which contains a
15913         class-name that names a dependent type or whose unqualified-id
15914         names a dependent type.  */
15915   if (TREE_CODE (type) == TYPENAME_TYPE)
15916     return true;
15917   /* -- a cv-qualified type where the cv-unqualified type is
15918         dependent.  */
15919   type = TYPE_MAIN_VARIANT (type);
15920   /* -- a compound type constructed from any dependent type.  */
15921   if (TYPE_PTR_TO_MEMBER_P (type))
15922     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
15923             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
15924                                            (type)));
15925   else if (TREE_CODE (type) == POINTER_TYPE
15926            || TREE_CODE (type) == REFERENCE_TYPE)
15927     return dependent_type_p (TREE_TYPE (type));
15928   else if (TREE_CODE (type) == FUNCTION_TYPE
15929            || TREE_CODE (type) == METHOD_TYPE)
15930     {
15931       tree arg_type;
15932
15933       if (dependent_type_p (TREE_TYPE (type)))
15934         return true;
15935       for (arg_type = TYPE_ARG_TYPES (type);
15936            arg_type;
15937            arg_type = TREE_CHAIN (arg_type))
15938         if (dependent_type_p (TREE_VALUE (arg_type)))
15939           return true;
15940       return false;
15941     }
15942   /* -- an array type constructed from any dependent type or whose
15943         size is specified by a constant expression that is
15944         value-dependent.  */
15945   if (TREE_CODE (type) == ARRAY_TYPE)
15946     {
15947       if (TYPE_DOMAIN (type)
15948           && dependent_type_p (TYPE_DOMAIN (type)))
15949         return true;
15950       return dependent_type_p (TREE_TYPE (type));
15951     }
15952   else if (TREE_CODE (type) == INTEGER_TYPE
15953            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
15954     {
15955       /* If this is the TYPE_DOMAIN of an array type, consider it
15956          dependent.  */
15957       return (value_dependent_expression_p (TYPE_MAX_VALUE (type))
15958               || type_dependent_expression_p (TYPE_MAX_VALUE (type)));
15959     }
15960
15961   /* -- a template-id in which either the template name is a template
15962      parameter ...  */
15963   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
15964     return true;
15965   /* ... or any of the template arguments is a dependent type or
15966         an expression that is type-dependent or value-dependent.  */
15967   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
15968            && (any_dependent_template_arguments_p
15969                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
15970     return true;
15971
15972   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
15973      argument of the `typeof' expression is not type-dependent, then
15974      it should already been have resolved.  */
15975   if (TREE_CODE (type) == TYPEOF_TYPE
15976       || TREE_CODE (type) == DECLTYPE_TYPE)
15977     return true;
15978
15979   /* A template argument pack is dependent if any of its packed
15980      arguments are.  */
15981   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
15982     {
15983       tree args = ARGUMENT_PACK_ARGS (type);
15984       int i, len = TREE_VEC_LENGTH (args);
15985       for (i = 0; i < len; ++i)
15986         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
15987           return true;
15988     }
15989
15990   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
15991      be template parameters.  */
15992   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
15993     return true;
15994
15995   /* The standard does not specifically mention types that are local
15996      to template functions or local classes, but they should be
15997      considered dependent too.  For example:
15998
15999        template <int I> void f() {
16000          enum E { a = I };
16001          S<sizeof (E)> s;
16002        }
16003
16004      The size of `E' cannot be known until the value of `I' has been
16005      determined.  Therefore, `E' must be considered dependent.  */
16006   scope = TYPE_CONTEXT (type);
16007   if (scope && TYPE_P (scope))
16008     return dependent_type_p (scope);
16009   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
16010     return type_dependent_expression_p (scope);
16011
16012   /* Other types are non-dependent.  */
16013   return false;
16014 }
16015
16016 /* Returns TRUE if TYPE is dependent, in the sense of
16017    [temp.dep.type].  */
16018
16019 bool
16020 dependent_type_p (tree type)
16021 {
16022   /* If there are no template parameters in scope, then there can't be
16023      any dependent types.  */
16024   if (!processing_template_decl)
16025     {
16026       /* If we are not processing a template, then nobody should be
16027          providing us with a dependent type.  */
16028       gcc_assert (type);
16029       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
16030       return false;
16031     }
16032
16033   /* If the type is NULL, we have not computed a type for the entity
16034      in question; in that case, the type is dependent.  */
16035   if (!type)
16036     return true;
16037
16038   /* Erroneous types can be considered non-dependent.  */
16039   if (type == error_mark_node)
16040     return false;
16041
16042   /* If we have not already computed the appropriate value for TYPE,
16043      do so now.  */
16044   if (!TYPE_DEPENDENT_P_VALID (type))
16045     {
16046       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
16047       TYPE_DEPENDENT_P_VALID (type) = 1;
16048     }
16049
16050   return TYPE_DEPENDENT_P (type);
16051 }
16052
16053 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
16054
16055 static bool
16056 dependent_scope_ref_p (tree expression, bool criterion (tree))
16057 {
16058   tree scope;
16059   tree name;
16060
16061   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
16062
16063   if (!TYPE_P (TREE_OPERAND (expression, 0)))
16064     return true;
16065
16066   scope = TREE_OPERAND (expression, 0);
16067   name = TREE_OPERAND (expression, 1);
16068
16069   /* [temp.dep.expr]
16070
16071      An id-expression is type-dependent if it contains a
16072      nested-name-specifier that contains a class-name that names a
16073      dependent type.  */
16074   /* The suggested resolution to Core Issue 2 implies that if the
16075      qualifying type is the current class, then we must peek
16076      inside it.  */
16077   if (DECL_P (name)
16078       && currently_open_class (scope)
16079       && !criterion (name))
16080     return false;
16081   if (dependent_type_p (scope))
16082     return true;
16083
16084   return false;
16085 }
16086
16087 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
16088    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
16089    expression.  */
16090
16091 bool
16092 value_dependent_expression_p (tree expression)
16093 {
16094   if (!processing_template_decl)
16095     return false;
16096
16097   /* A name declared with a dependent type.  */
16098   if (DECL_P (expression) && type_dependent_expression_p (expression))
16099     return true;
16100
16101   switch (TREE_CODE (expression))
16102     {
16103     case IDENTIFIER_NODE:
16104       /* A name that has not been looked up -- must be dependent.  */
16105       return true;
16106
16107     case TEMPLATE_PARM_INDEX:
16108       /* A non-type template parm.  */
16109       return true;
16110
16111     case CONST_DECL:
16112       /* A non-type template parm.  */
16113       if (DECL_TEMPLATE_PARM_P (expression))
16114         return true;
16115       return value_dependent_expression_p (DECL_INITIAL (expression));
16116
16117     case VAR_DECL:
16118        /* A constant with integral or enumeration type and is initialized
16119           with an expression that is value-dependent.  */
16120       if (DECL_INITIAL (expression)
16121           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
16122           && value_dependent_expression_p (DECL_INITIAL (expression)))
16123         return true;
16124       return false;
16125
16126     case DYNAMIC_CAST_EXPR:
16127     case STATIC_CAST_EXPR:
16128     case CONST_CAST_EXPR:
16129     case REINTERPRET_CAST_EXPR:
16130     case CAST_EXPR:
16131       /* These expressions are value-dependent if the type to which
16132          the cast occurs is dependent or the expression being casted
16133          is value-dependent.  */
16134       {
16135         tree type = TREE_TYPE (expression);
16136
16137         if (dependent_type_p (type))
16138           return true;
16139
16140         /* A functional cast has a list of operands.  */
16141         expression = TREE_OPERAND (expression, 0);
16142         if (!expression)
16143           {
16144             /* If there are no operands, it must be an expression such
16145                as "int()". This should not happen for aggregate types
16146                because it would form non-constant expressions.  */
16147             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
16148
16149             return false;
16150           }
16151
16152         if (TREE_CODE (expression) == TREE_LIST)
16153           return any_value_dependent_elements_p (expression);
16154
16155         return value_dependent_expression_p (expression);
16156       }
16157
16158     case SIZEOF_EXPR:
16159     case ALIGNOF_EXPR:
16160       /* A `sizeof' expression is value-dependent if the operand is
16161          type-dependent or is a pack expansion.  */
16162       expression = TREE_OPERAND (expression, 0);
16163       if (PACK_EXPANSION_P (expression))
16164         return true;
16165       else if (TYPE_P (expression))
16166         return dependent_type_p (expression);
16167       return type_dependent_expression_p (expression);
16168
16169     case SCOPE_REF:
16170       return dependent_scope_ref_p (expression, value_dependent_expression_p);
16171
16172     case COMPONENT_REF:
16173       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
16174               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
16175
16176     case CALL_EXPR:
16177       /* A CALL_EXPR may appear in a constant expression if it is a
16178          call to a builtin function, e.g., __builtin_constant_p.  All
16179          such calls are value-dependent.  */
16180       return true;
16181
16182     case NONTYPE_ARGUMENT_PACK:
16183       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
16184          is value-dependent.  */
16185       {
16186         tree values = ARGUMENT_PACK_ARGS (expression);
16187         int i, len = TREE_VEC_LENGTH (values);
16188         
16189         for (i = 0; i < len; ++i)
16190           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
16191             return true;
16192         
16193         return false;
16194       }
16195
16196     case TRAIT_EXPR:
16197       {
16198         tree type2 = TRAIT_EXPR_TYPE2 (expression);
16199         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
16200                 || (type2 ? dependent_type_p (type2) : false));
16201       }
16202
16203     case MODOP_EXPR:
16204       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
16205               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
16206
16207     default:
16208       /* A constant expression is value-dependent if any subexpression is
16209          value-dependent.  */
16210       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
16211         {
16212         case tcc_reference:
16213         case tcc_unary:
16214           return (value_dependent_expression_p
16215                   (TREE_OPERAND (expression, 0)));
16216
16217         case tcc_comparison:
16218         case tcc_binary:
16219           return ((value_dependent_expression_p
16220                    (TREE_OPERAND (expression, 0)))
16221                   || (value_dependent_expression_p
16222                       (TREE_OPERAND (expression, 1))));
16223
16224         case tcc_expression:
16225         case tcc_vl_exp:
16226           {
16227             int i;
16228             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
16229               /* In some cases, some of the operands may be missing.
16230                  (For example, in the case of PREDECREMENT_EXPR, the
16231                  amount to increment by may be missing.)  That doesn't
16232                  make the expression dependent.  */
16233               if (TREE_OPERAND (expression, i)
16234                   && (value_dependent_expression_p
16235                       (TREE_OPERAND (expression, i))))
16236                 return true;
16237             return false;
16238           }
16239
16240         default:
16241           break;
16242         }
16243     }
16244
16245   /* The expression is not value-dependent.  */
16246   return false;
16247 }
16248
16249 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
16250    [temp.dep.expr].  */
16251
16252 bool
16253 type_dependent_expression_p (tree expression)
16254 {
16255   if (!processing_template_decl)
16256     return false;
16257
16258   if (expression == error_mark_node)
16259     return false;
16260
16261   /* An unresolved name is always dependent.  */
16262   if (TREE_CODE (expression) == IDENTIFIER_NODE
16263       || TREE_CODE (expression) == USING_DECL)
16264     return true;
16265
16266   /* Some expression forms are never type-dependent.  */
16267   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
16268       || TREE_CODE (expression) == SIZEOF_EXPR
16269       || TREE_CODE (expression) == ALIGNOF_EXPR
16270       || TREE_CODE (expression) == TRAIT_EXPR
16271       || TREE_CODE (expression) == TYPEID_EXPR
16272       || TREE_CODE (expression) == DELETE_EXPR
16273       || TREE_CODE (expression) == VEC_DELETE_EXPR
16274       || TREE_CODE (expression) == THROW_EXPR)
16275     return false;
16276
16277   /* The types of these expressions depends only on the type to which
16278      the cast occurs.  */
16279   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
16280       || TREE_CODE (expression) == STATIC_CAST_EXPR
16281       || TREE_CODE (expression) == CONST_CAST_EXPR
16282       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
16283       || TREE_CODE (expression) == CAST_EXPR)
16284     return dependent_type_p (TREE_TYPE (expression));
16285
16286   /* The types of these expressions depends only on the type created
16287      by the expression.  */
16288   if (TREE_CODE (expression) == NEW_EXPR
16289       || TREE_CODE (expression) == VEC_NEW_EXPR)
16290     {
16291       /* For NEW_EXPR tree nodes created inside a template, either
16292          the object type itself or a TREE_LIST may appear as the
16293          operand 1.  */
16294       tree type = TREE_OPERAND (expression, 1);
16295       if (TREE_CODE (type) == TREE_LIST)
16296         /* This is an array type.  We need to check array dimensions
16297            as well.  */
16298         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
16299                || value_dependent_expression_p
16300                     (TREE_OPERAND (TREE_VALUE (type), 1));
16301       else
16302         return dependent_type_p (type);
16303     }
16304
16305   if (TREE_CODE (expression) == SCOPE_REF
16306       && dependent_scope_ref_p (expression,
16307                                 type_dependent_expression_p))
16308     return true;
16309
16310   if (TREE_CODE (expression) == FUNCTION_DECL
16311       && DECL_LANG_SPECIFIC (expression)
16312       && DECL_TEMPLATE_INFO (expression)
16313       && (any_dependent_template_arguments_p
16314           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
16315     return true;
16316
16317   if (TREE_CODE (expression) == TEMPLATE_DECL
16318       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
16319     return false;
16320
16321   if (TREE_CODE (expression) == STMT_EXPR)
16322     expression = stmt_expr_value_expr (expression);
16323
16324   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
16325     {
16326       tree elt;
16327       unsigned i;
16328
16329       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
16330         {
16331           if (type_dependent_expression_p (elt))
16332             return true;
16333         }
16334       return false;
16335     }
16336
16337   if (TREE_TYPE (expression) == unknown_type_node)
16338     {
16339       if (TREE_CODE (expression) == ADDR_EXPR)
16340         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
16341       if (TREE_CODE (expression) == COMPONENT_REF
16342           || TREE_CODE (expression) == OFFSET_REF)
16343         {
16344           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
16345             return true;
16346           expression = TREE_OPERAND (expression, 1);
16347           if (TREE_CODE (expression) == IDENTIFIER_NODE)
16348             return false;
16349         }
16350       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
16351       if (TREE_CODE (expression) == SCOPE_REF)
16352         return false;
16353
16354       if (TREE_CODE (expression) == BASELINK)
16355         expression = BASELINK_FUNCTIONS (expression);
16356
16357       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
16358         {
16359           if (any_dependent_template_arguments_p
16360               (TREE_OPERAND (expression, 1)))
16361             return true;
16362           expression = TREE_OPERAND (expression, 0);
16363         }
16364       gcc_assert (TREE_CODE (expression) == OVERLOAD
16365                   || TREE_CODE (expression) == FUNCTION_DECL);
16366
16367       while (expression)
16368         {
16369           if (type_dependent_expression_p (OVL_CURRENT (expression)))
16370             return true;
16371           expression = OVL_NEXT (expression);
16372         }
16373       return false;
16374     }
16375
16376   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
16377
16378   return (dependent_type_p (TREE_TYPE (expression)));
16379 }
16380
16381 /* Returns TRUE if ARGS (a TREE_LIST of arguments to a function call)
16382    contains a type-dependent expression.  */
16383
16384 bool
16385 any_type_dependent_arguments_p (const_tree args)
16386 {
16387   while (args)
16388     {
16389       tree arg = TREE_VALUE (args);
16390
16391       if (type_dependent_expression_p (arg))
16392         return true;
16393       args = TREE_CHAIN (args);
16394     }
16395   return false;
16396 }
16397
16398 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
16399    expressions) contains any value-dependent expressions.  */
16400
16401 bool
16402 any_value_dependent_elements_p (const_tree list)
16403 {
16404   for (; list; list = TREE_CHAIN (list))
16405     if (value_dependent_expression_p (TREE_VALUE (list)))
16406       return true;
16407
16408   return false;
16409 }
16410
16411 /* Returns TRUE if the ARG (a template argument) is dependent.  */
16412
16413 bool
16414 dependent_template_arg_p (tree arg)
16415 {
16416   if (!processing_template_decl)
16417     return false;
16418
16419   if (TREE_CODE (arg) == TEMPLATE_DECL
16420       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16421     return dependent_template_p (arg);
16422   else if (ARGUMENT_PACK_P (arg))
16423     {
16424       tree args = ARGUMENT_PACK_ARGS (arg);
16425       int i, len = TREE_VEC_LENGTH (args);
16426       for (i = 0; i < len; ++i)
16427         {
16428           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
16429             return true;
16430         }
16431
16432       return false;
16433     }
16434   else if (TYPE_P (arg))
16435     return dependent_type_p (arg);
16436   else
16437     return (type_dependent_expression_p (arg)
16438             || value_dependent_expression_p (arg));
16439 }
16440
16441 /* Returns true if ARGS (a collection of template arguments) contains
16442    any types that require structural equality testing.  */
16443
16444 bool
16445 any_template_arguments_need_structural_equality_p (tree args)
16446 {
16447   int i;
16448   int j;
16449
16450   if (!args)
16451     return false;
16452   if (args == error_mark_node)
16453     return true;
16454
16455   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
16456     {
16457       tree level = TMPL_ARGS_LEVEL (args, i + 1);
16458       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
16459         {
16460           tree arg = TREE_VEC_ELT (level, j);
16461           tree packed_args = NULL_TREE;
16462           int k, len = 1;
16463
16464           if (ARGUMENT_PACK_P (arg))
16465             {
16466               /* Look inside the argument pack.  */
16467               packed_args = ARGUMENT_PACK_ARGS (arg);
16468               len = TREE_VEC_LENGTH (packed_args);
16469             }
16470
16471           for (k = 0; k < len; ++k)
16472             {
16473               if (packed_args)
16474                 arg = TREE_VEC_ELT (packed_args, k);
16475
16476               if (error_operand_p (arg))
16477                 return true;
16478               else if (TREE_CODE (arg) == TEMPLATE_DECL
16479                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16480                 continue;
16481               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
16482                 return true;
16483               else if (!TYPE_P (arg) && TREE_TYPE (arg)
16484                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
16485                 return true;
16486             }
16487         }
16488     }
16489
16490   return false;
16491 }
16492
16493 /* Returns true if ARGS (a collection of template arguments) contains
16494    any dependent arguments.  */
16495
16496 bool
16497 any_dependent_template_arguments_p (const_tree args)
16498 {
16499   int i;
16500   int j;
16501
16502   if (!args)
16503     return false;
16504   if (args == error_mark_node)
16505     return true;
16506
16507   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
16508     {
16509       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
16510       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
16511         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
16512           return true;
16513     }
16514
16515   return false;
16516 }
16517
16518 /* Returns TRUE if the template TMPL is dependent.  */
16519
16520 bool
16521 dependent_template_p (tree tmpl)
16522 {
16523   if (TREE_CODE (tmpl) == OVERLOAD)
16524     {
16525       while (tmpl)
16526         {
16527           if (dependent_template_p (OVL_FUNCTION (tmpl)))
16528             return true;
16529           tmpl = OVL_CHAIN (tmpl);
16530         }
16531       return false;
16532     }
16533
16534   /* Template template parameters are dependent.  */
16535   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
16536       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
16537     return true;
16538   /* So are names that have not been looked up.  */
16539   if (TREE_CODE (tmpl) == SCOPE_REF
16540       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
16541     return true;
16542   /* So are member templates of dependent classes.  */
16543   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
16544     return dependent_type_p (DECL_CONTEXT (tmpl));
16545   return false;
16546 }
16547
16548 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
16549
16550 bool
16551 dependent_template_id_p (tree tmpl, tree args)
16552 {
16553   return (dependent_template_p (tmpl)
16554           || any_dependent_template_arguments_p (args));
16555 }
16556
16557 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
16558    is dependent.  */
16559
16560 bool
16561 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
16562 {
16563   int i;
16564
16565   if (!processing_template_decl)
16566     return false;
16567
16568   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
16569     {
16570       tree decl = TREE_VEC_ELT (declv, i);
16571       tree init = TREE_VEC_ELT (initv, i);
16572       tree cond = TREE_VEC_ELT (condv, i);
16573       tree incr = TREE_VEC_ELT (incrv, i);
16574
16575       if (type_dependent_expression_p (decl))
16576         return true;
16577
16578       if (init && type_dependent_expression_p (init))
16579         return true;
16580
16581       if (type_dependent_expression_p (cond))
16582         return true;
16583
16584       if (COMPARISON_CLASS_P (cond)
16585           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
16586               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
16587         return true;
16588
16589       if (TREE_CODE (incr) == MODOP_EXPR)
16590         {
16591           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
16592               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
16593             return true;
16594         }
16595       else if (type_dependent_expression_p (incr))
16596         return true;
16597       else if (TREE_CODE (incr) == MODIFY_EXPR)
16598         {
16599           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
16600             return true;
16601           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
16602             {
16603               tree t = TREE_OPERAND (incr, 1);
16604               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
16605                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
16606                 return true;
16607             }
16608         }
16609     }
16610
16611   return false;
16612 }
16613
16614 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
16615    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
16616    no such TYPE can be found.  Note that this function peers inside
16617    uninstantiated templates and therefore should be used only in
16618    extremely limited situations.  ONLY_CURRENT_P restricts this
16619    peering to the currently open classes hierarchy (which is required
16620    when comparing types).  */
16621
16622 tree
16623 resolve_typename_type (tree type, bool only_current_p)
16624 {
16625   tree scope;
16626   tree name;
16627   tree decl;
16628   int quals;
16629   tree pushed_scope;
16630   tree result;
16631
16632   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
16633
16634   scope = TYPE_CONTEXT (type);
16635   name = TYPE_IDENTIFIER (type);
16636
16637   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
16638      it first before we can figure out what NAME refers to.  */
16639   if (TREE_CODE (scope) == TYPENAME_TYPE)
16640     scope = resolve_typename_type (scope, only_current_p);
16641   /* If we don't know what SCOPE refers to, then we cannot resolve the
16642      TYPENAME_TYPE.  */
16643   if (TREE_CODE (scope) == TYPENAME_TYPE)
16644     return type;
16645   /* If the SCOPE is a template type parameter, we have no way of
16646      resolving the name.  */
16647   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
16648     return type;
16649   /* If the SCOPE is not the current instantiation, there's no reason
16650      to look inside it.  */
16651   if (only_current_p && !currently_open_class (scope))
16652     return type;
16653   /* If SCOPE isn't the template itself, it will not have a valid
16654      TYPE_FIELDS list.  */
16655   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
16656     /* scope is either the template itself or a compatible instantiation
16657        like X<T>, so look up the name in the original template.  */
16658     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
16659   else
16660     /* scope is a partial instantiation, so we can't do the lookup or we
16661        will lose the template arguments.  */
16662     return type;
16663   /* Enter the SCOPE so that name lookup will be resolved as if we
16664      were in the class definition.  In particular, SCOPE will no
16665      longer be considered a dependent type.  */
16666   pushed_scope = push_scope (scope);
16667   /* Look up the declaration.  */
16668   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
16669
16670   result = NULL_TREE;
16671   
16672   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
16673      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
16674   if (!decl)
16675     /*nop*/;
16676   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
16677            && TREE_CODE (decl) == TYPE_DECL)
16678     {
16679       result = TREE_TYPE (decl);
16680       if (result == error_mark_node)
16681         result = NULL_TREE;
16682     }
16683   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
16684            && DECL_CLASS_TEMPLATE_P (decl))
16685     {
16686       tree tmpl;
16687       tree args;
16688       /* Obtain the template and the arguments.  */
16689       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
16690       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
16691       /* Instantiate the template.  */
16692       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
16693                                       /*entering_scope=*/0,
16694                                       tf_error | tf_user);
16695       if (result == error_mark_node)
16696         result = NULL_TREE;
16697     }
16698   
16699   /* Leave the SCOPE.  */
16700   if (pushed_scope)
16701     pop_scope (pushed_scope);
16702
16703   /* If we failed to resolve it, return the original typename.  */
16704   if (!result)
16705     return type;
16706   
16707   /* If lookup found a typename type, resolve that too.  */
16708   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
16709     {
16710       /* Ill-formed programs can cause infinite recursion here, so we
16711          must catch that.  */
16712       TYPENAME_IS_RESOLVING_P (type) = 1;
16713       result = resolve_typename_type (result, only_current_p);
16714       TYPENAME_IS_RESOLVING_P (type) = 0;
16715     }
16716   
16717   /* Qualify the resulting type.  */
16718   quals = cp_type_quals (type);
16719   if (quals)
16720     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
16721
16722   return result;
16723 }
16724
16725 /* EXPR is an expression which is not type-dependent.  Return a proxy
16726    for EXPR that can be used to compute the types of larger
16727    expressions containing EXPR.  */
16728
16729 tree
16730 build_non_dependent_expr (tree expr)
16731 {
16732   tree inner_expr;
16733
16734   /* Preserve null pointer constants so that the type of things like
16735      "p == 0" where "p" is a pointer can be determined.  */
16736   if (null_ptr_cst_p (expr))
16737     return expr;
16738   /* Preserve OVERLOADs; the functions must be available to resolve
16739      types.  */
16740   inner_expr = expr;
16741   if (TREE_CODE (inner_expr) == STMT_EXPR)
16742     inner_expr = stmt_expr_value_expr (inner_expr);
16743   if (TREE_CODE (inner_expr) == ADDR_EXPR)
16744     inner_expr = TREE_OPERAND (inner_expr, 0);
16745   if (TREE_CODE (inner_expr) == COMPONENT_REF)
16746     inner_expr = TREE_OPERAND (inner_expr, 1);
16747   if (is_overloaded_fn (inner_expr)
16748       || TREE_CODE (inner_expr) == OFFSET_REF)
16749     return expr;
16750   /* There is no need to return a proxy for a variable.  */
16751   if (TREE_CODE (expr) == VAR_DECL)
16752     return expr;
16753   /* Preserve string constants; conversions from string constants to
16754      "char *" are allowed, even though normally a "const char *"
16755      cannot be used to initialize a "char *".  */
16756   if (TREE_CODE (expr) == STRING_CST)
16757     return expr;
16758   /* Preserve arithmetic constants, as an optimization -- there is no
16759      reason to create a new node.  */
16760   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
16761     return expr;
16762   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
16763      There is at least one place where we want to know that a
16764      particular expression is a throw-expression: when checking a ?:
16765      expression, there are special rules if the second or third
16766      argument is a throw-expression.  */
16767   if (TREE_CODE (expr) == THROW_EXPR)
16768     return expr;
16769
16770   if (TREE_CODE (expr) == COND_EXPR)
16771     return build3 (COND_EXPR,
16772                    TREE_TYPE (expr),
16773                    TREE_OPERAND (expr, 0),
16774                    (TREE_OPERAND (expr, 1)
16775                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
16776                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
16777                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
16778   if (TREE_CODE (expr) == COMPOUND_EXPR
16779       && !COMPOUND_EXPR_OVERLOADED (expr))
16780     return build2 (COMPOUND_EXPR,
16781                    TREE_TYPE (expr),
16782                    TREE_OPERAND (expr, 0),
16783                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
16784
16785   /* If the type is unknown, it can't really be non-dependent */
16786   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
16787
16788   /* Otherwise, build a NON_DEPENDENT_EXPR.
16789
16790      REFERENCE_TYPEs are not stripped for expressions in templates
16791      because doing so would play havoc with mangling.  Consider, for
16792      example:
16793
16794        template <typename T> void f<T& g>() { g(); }
16795
16796      In the body of "f", the expression for "g" will have
16797      REFERENCE_TYPE, even though the standard says that it should
16798      not.  The reason is that we must preserve the syntactic form of
16799      the expression so that mangling (say) "f<g>" inside the body of
16800      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
16801      stripped here.  */
16802   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
16803 }
16804
16805 /* ARGS is a TREE_LIST of expressions as arguments to a function call.
16806    Return a new TREE_LIST with the various arguments replaced with
16807    equivalent non-dependent expressions.  */
16808
16809 tree
16810 build_non_dependent_args (tree args)
16811 {
16812   tree a;
16813   tree new_args;
16814
16815   new_args = NULL_TREE;
16816   for (a = args; a; a = TREE_CHAIN (a))
16817     new_args = tree_cons (NULL_TREE,
16818                           build_non_dependent_expr (TREE_VALUE (a)),
16819                           new_args);
16820   return nreverse (new_args);
16821 }
16822
16823 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
16824    with a level one deeper than the actual template parms.  */
16825
16826 tree
16827 make_auto (void)
16828 {
16829   tree au;
16830
16831   /* ??? Is it worth caching this for multiple autos at the same level?  */
16832   au = cxx_make_type (TEMPLATE_TYPE_PARM);
16833   TYPE_NAME (au) = build_decl (TYPE_DECL, get_identifier ("auto"), au);
16834   TYPE_STUB_DECL (au) = TYPE_NAME (au);
16835   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
16836     (0, processing_template_decl + 1, processing_template_decl + 1,
16837      TYPE_NAME (au), NULL_TREE);
16838   TYPE_CANONICAL (au) = canonical_type_parameter (au);
16839   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
16840   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
16841
16842   return au;
16843 }
16844
16845 /* Replace auto in TYPE with std::initializer_list<auto>.  */
16846
16847 static tree
16848 listify_autos (tree type, tree auto_node)
16849 {
16850   tree std_init_list = namespace_binding
16851     (get_identifier ("initializer_list"), std_node);
16852   tree argvec;
16853   tree init_auto;
16854   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
16855     {    
16856       error ("deducing auto from brace-enclosed initializer list requires "
16857              "#include <initializer_list>");
16858       return error_mark_node;
16859     }
16860   argvec = make_tree_vec (1);
16861   TREE_VEC_ELT (argvec, 0) = auto_node;
16862   init_auto = lookup_template_class (std_init_list, argvec, NULL_TREE,
16863                                      NULL_TREE, 0, tf_warning_or_error);
16864
16865   TREE_VEC_ELT (argvec, 0) = init_auto;
16866   if (processing_template_decl)
16867     argvec = add_to_template_args (current_template_args (), argvec);
16868   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
16869 }
16870
16871 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
16872    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
16873
16874 tree
16875 do_auto_deduction (tree type, tree init, tree auto_node)
16876 {
16877   tree parms, args, tparms, targs;
16878   int val;
16879
16880   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
16881      with either a new invented type template parameter U or, if the
16882      initializer is a braced-init-list (8.5.4), with
16883      std::initializer_list<U>.  */
16884   if (BRACE_ENCLOSED_INITIALIZER_P (init))
16885     type = listify_autos (type, auto_node);
16886
16887   parms = build_tree_list (NULL_TREE, type);
16888   args = build_tree_list (NULL_TREE, init);
16889   tparms = make_tree_vec (1);
16890   targs = make_tree_vec (1);
16891   TREE_VEC_ELT (tparms, 0)
16892     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
16893   val = type_unification_real (tparms, targs, parms, args, 0,
16894                                DEDUCE_CALL, LOOKUP_NORMAL);
16895   if (val > 0)
16896     {
16897       error ("unable to deduce %qT from %qE", type, init);
16898       return error_mark_node;
16899     }
16900
16901   if (processing_template_decl)
16902     targs = add_to_template_args (current_template_args (), targs);
16903   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
16904 }
16905
16906 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
16907    result.  */
16908
16909 tree
16910 splice_late_return_type (tree type, tree late_return_type)
16911 {
16912   tree argvec;
16913
16914   if (late_return_type == NULL_TREE)
16915     return type;
16916   argvec = make_tree_vec (1);
16917   TREE_VEC_ELT (argvec, 0) = late_return_type;
16918   if (processing_template_decl)
16919     argvec = add_to_template_args (current_template_args (), argvec);
16920   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
16921 }
16922
16923 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
16924
16925 bool
16926 is_auto (const_tree type)
16927 {
16928   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
16929       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
16930     return true;
16931   else
16932     return false;
16933 }
16934
16935 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
16936    appear as a type-specifier for the declaration in question, we don't
16937    have to look through the whole type.  */
16938
16939 tree
16940 type_uses_auto (tree type)
16941 {
16942   enum tree_code code;
16943   if (is_auto (type))
16944     return type;
16945
16946   code = TREE_CODE (type);
16947
16948   if (code == POINTER_TYPE || code == REFERENCE_TYPE
16949       || code == OFFSET_TYPE || code == FUNCTION_TYPE
16950       || code == METHOD_TYPE || code == ARRAY_TYPE)
16951     return type_uses_auto (TREE_TYPE (type));
16952
16953   if (TYPE_PTRMEMFUNC_P (type))
16954     return type_uses_auto (TREE_TYPE (TREE_TYPE
16955                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
16956
16957   return NULL_TREE;
16958 }
16959
16960 #include "gt-cp-pt.h"