OSDN Git Service

2010-12-09 Martin Jambor <mjambor@suse.cz>
[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, 2010
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 "tree.h"
34 #include "intl.h"
35 #include "pointer-set.h"
36 #include "flags.h"
37 #include "cp-tree.h"
38 #include "c-family/c-common.h"
39 #include "c-family/c-objc.h"
40 #include "cp-objcp-common.h"
41 #include "tree-inline.h"
42 #include "decl.h"
43 #include "output.h"
44 #include "toplev.h"
45 #include "timevar.h"
46 #include "tree-iterator.h"
47 #include "vecprim.h"
48
49 /* The type of functions taking a tree, and some additional data, and
50    returning an int.  */
51 typedef int (*tree_fn_t) (tree, void*);
52
53 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
54    instantiations have been deferred, either because their definitions
55    were not yet available, or because we were putting off doing the work.  */
56 struct GTY (()) pending_template {
57   struct pending_template *next;
58   struct tinst_level *tinst;
59 };
60
61 static GTY(()) struct pending_template *pending_templates;
62 static GTY(()) struct pending_template *last_pending_template;
63
64 int processing_template_parmlist;
65 static int template_header_count;
66
67 static GTY(()) tree saved_trees;
68 static VEC(int,heap) *inline_parm_levels;
69
70 static GTY(()) struct tinst_level *current_tinst_level;
71
72 static GTY(()) tree saved_access_scope;
73
74 /* Live only within one (recursive) call to tsubst_expr.  We use
75    this to pass the statement expression node from the STMT_EXPR
76    to the EXPR_STMT that is its result.  */
77 static tree cur_stmt_expr;
78
79 /* A map from local variable declarations in the body of the template
80    presently being instantiated to the corresponding instantiated
81    local variables.  */
82 static htab_t local_specializations;
83
84 typedef struct GTY(()) spec_entry
85 {
86   tree tmpl;
87   tree args;
88   tree spec;
89 } spec_entry;
90
91 static GTY ((param_is (spec_entry)))
92   htab_t decl_specializations;
93
94 static GTY ((param_is (spec_entry)))
95   htab_t type_specializations;
96
97 /* Contains canonical template parameter types. The vector is indexed by
98    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
99    TREE_LIST, whose TREE_VALUEs contain the canonical template
100    parameters of various types and levels.  */
101 static GTY(()) VEC(tree,gc) *canonical_template_parms;
102
103 #define UNIFY_ALLOW_NONE 0
104 #define UNIFY_ALLOW_MORE_CV_QUAL 1
105 #define UNIFY_ALLOW_LESS_CV_QUAL 2
106 #define UNIFY_ALLOW_DERIVED 4
107 #define UNIFY_ALLOW_INTEGER 8
108 #define UNIFY_ALLOW_OUTER_LEVEL 16
109 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
110 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
111
112 static void push_access_scope (tree);
113 static void pop_access_scope (tree);
114 static bool resolve_overloaded_unification (tree, tree, tree, tree,
115                                             unification_kind_t, int);
116 static int try_one_overload (tree, tree, tree, tree, tree,
117                              unification_kind_t, int, bool);
118 static int unify (tree, tree, tree, tree, int);
119 static void add_pending_template (tree);
120 static tree reopen_tinst_level (struct tinst_level *);
121 static tree tsubst_initializer_list (tree, tree);
122 static tree get_class_bindings (tree, tree, tree);
123 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
124                                    bool, bool);
125 static void tsubst_enum (tree, tree, tree);
126 static tree add_to_template_args (tree, tree);
127 static tree add_outermost_template_args (tree, tree);
128 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
129 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
130                                              tree);
131 static int type_unification_real (tree, tree, tree, const tree *,
132                                   unsigned int, int, unification_kind_t, int);
133 static void note_template_header (int);
134 static tree convert_nontype_argument_function (tree, tree);
135 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
136 static tree convert_template_argument (tree, tree, tree,
137                                        tsubst_flags_t, int, tree);
138 static int for_each_template_parm (tree, tree_fn_t, void*,
139                                    struct pointer_set_t*, bool);
140 static tree expand_template_argument_pack (tree);
141 static tree build_template_parm_index (int, int, int, int, tree, tree);
142 static bool inline_needs_template_parms (tree);
143 static void push_inline_template_parms_recursive (tree, int);
144 static tree retrieve_local_specialization (tree);
145 static void register_local_specialization (tree, tree);
146 static hashval_t hash_specialization (const void *p);
147 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
148 static int mark_template_parm (tree, void *);
149 static int template_parm_this_level_p (tree, void *);
150 static tree tsubst_friend_function (tree, tree);
151 static tree tsubst_friend_class (tree, tree);
152 static int can_complete_type_without_circularity (tree);
153 static tree get_bindings (tree, tree, tree, bool);
154 static int template_decl_level (tree);
155 static int check_cv_quals_for_unify (int, tree, tree);
156 static void template_parm_level_and_index (tree, int*, int*);
157 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
158 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
159 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
160 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
161 static void regenerate_decl_from_template (tree, tree);
162 static tree most_specialized_class (tree, tree, tsubst_flags_t);
163 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
164 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
165 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
166 static bool check_specialization_scope (void);
167 static tree process_partial_specialization (tree);
168 static void set_current_access_from_decl (tree);
169 static tree get_template_base (tree, tree, tree, tree);
170 static tree try_class_unification (tree, tree, tree, tree);
171 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
172                                            tree, tree);
173 static bool template_template_parm_bindings_ok_p (tree, tree);
174 static int template_args_equal (tree, tree);
175 static void tsubst_default_arguments (tree);
176 static tree for_each_template_parm_r (tree *, int *, void *);
177 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
178 static void copy_default_args_to_explicit_spec (tree);
179 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
180 static int eq_local_specializations (const void *, const void *);
181 static bool dependent_template_arg_p (tree);
182 static bool any_template_arguments_need_structural_equality_p (tree);
183 static bool dependent_type_p_r (tree);
184 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
185 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
186 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
187 static tree tsubst_decl (tree, tree, tsubst_flags_t);
188 static void perform_typedefs_access_check (tree tmpl, tree targs);
189 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
190                                                         location_t);
191 static tree listify (tree);
192 static tree listify_autos (tree, tree);
193 static tree template_parm_to_arg (tree t);
194 static tree current_template_args (void);
195 static tree fixup_template_type_parm_type (tree, int);
196 static tree fixup_template_parm_index (tree, tree, int);
197 static void fixup_template_parms (void);
198 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
199
200 /* Make the current scope suitable for access checking when we are
201    processing T.  T can be FUNCTION_DECL for instantiated function
202    template, or VAR_DECL for static member variable (need by
203    instantiate_decl).  */
204
205 static void
206 push_access_scope (tree t)
207 {
208   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
209               || TREE_CODE (t) == VAR_DECL);
210
211   if (DECL_FRIEND_CONTEXT (t))
212     push_nested_class (DECL_FRIEND_CONTEXT (t));
213   else if (DECL_CLASS_SCOPE_P (t))
214     push_nested_class (DECL_CONTEXT (t));
215   else
216     push_to_top_level ();
217
218   if (TREE_CODE (t) == FUNCTION_DECL)
219     {
220       saved_access_scope = tree_cons
221         (NULL_TREE, current_function_decl, saved_access_scope);
222       current_function_decl = t;
223     }
224 }
225
226 /* Restore the scope set up by push_access_scope.  T is the node we
227    are processing.  */
228
229 static void
230 pop_access_scope (tree t)
231 {
232   if (TREE_CODE (t) == FUNCTION_DECL)
233     {
234       current_function_decl = TREE_VALUE (saved_access_scope);
235       saved_access_scope = TREE_CHAIN (saved_access_scope);
236     }
237
238   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
239     pop_nested_class ();
240   else
241     pop_from_top_level ();
242 }
243
244 /* Do any processing required when DECL (a member template
245    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
246    to DECL, unless it is a specialization, in which case the DECL
247    itself is returned.  */
248
249 tree
250 finish_member_template_decl (tree decl)
251 {
252   if (decl == error_mark_node)
253     return error_mark_node;
254
255   gcc_assert (DECL_P (decl));
256
257   if (TREE_CODE (decl) == TYPE_DECL)
258     {
259       tree type;
260
261       type = TREE_TYPE (decl);
262       if (type == error_mark_node)
263         return error_mark_node;
264       if (MAYBE_CLASS_TYPE_P (type)
265           && CLASSTYPE_TEMPLATE_INFO (type)
266           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
267         {
268           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
269           check_member_template (tmpl);
270           return tmpl;
271         }
272       return NULL_TREE;
273     }
274   else if (TREE_CODE (decl) == FIELD_DECL)
275     error ("data member %qD cannot be a member template", decl);
276   else if (DECL_TEMPLATE_INFO (decl))
277     {
278       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
279         {
280           check_member_template (DECL_TI_TEMPLATE (decl));
281           return DECL_TI_TEMPLATE (decl);
282         }
283       else
284         return decl;
285     }
286   else
287     error ("invalid member template declaration %qD", decl);
288
289   return error_mark_node;
290 }
291
292 /* Create a template info node.  */
293
294 tree
295 build_template_info (tree template_decl, tree template_args)
296 {
297   tree result = make_node (TEMPLATE_INFO);
298   TI_TEMPLATE (result) = template_decl;
299   TI_ARGS (result) = template_args;
300   return result;
301 }
302
303 /* Return the template info node corresponding to T, whatever T is.  */
304
305 tree
306 get_template_info (const_tree t)
307 {
308   tree tinfo = NULL_TREE;
309
310   if (!t || t == error_mark_node)
311     return NULL;
312
313   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
314     tinfo = DECL_TEMPLATE_INFO (t);
315
316   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
317     t = TREE_TYPE (t);
318
319   if (TAGGED_TYPE_P (t))
320     tinfo = TYPE_TEMPLATE_INFO (t);
321   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
322     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
323
324   return tinfo;
325 }
326
327 /* Returns the template nesting level of the indicated class TYPE.
328
329    For example, in:
330      template <class T>
331      struct A
332      {
333        template <class U>
334        struct B {};
335      };
336
337    A<T>::B<U> has depth two, while A<T> has depth one.
338    Both A<T>::B<int> and A<int>::B<U> have depth one, if
339    they are instantiations, not specializations.
340
341    This function is guaranteed to return 0 if passed NULL_TREE so
342    that, for example, `template_class_depth (current_class_type)' is
343    always safe.  */
344
345 int
346 template_class_depth (tree type)
347 {
348   int depth;
349
350   for (depth = 0;
351        type && TREE_CODE (type) != NAMESPACE_DECL;
352        type = (TREE_CODE (type) == FUNCTION_DECL)
353          ? CP_DECL_CONTEXT (type) : CP_TYPE_CONTEXT (type))
354     {
355       tree tinfo = get_template_info (type);
356
357       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
358           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
359         ++depth;
360     }
361
362   return depth;
363 }
364
365 /* Subroutine of maybe_begin_member_template_processing.
366    Returns true if processing DECL needs us to push template parms.  */
367
368 static bool
369 inline_needs_template_parms (tree decl)
370 {
371   if (! DECL_TEMPLATE_INFO (decl))
372     return false;
373
374   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
375           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
376 }
377
378 /* Subroutine of maybe_begin_member_template_processing.
379    Push the template parms in PARMS, starting from LEVELS steps into the
380    chain, and ending at the beginning, since template parms are listed
381    innermost first.  */
382
383 static void
384 push_inline_template_parms_recursive (tree parmlist, int levels)
385 {
386   tree parms = TREE_VALUE (parmlist);
387   int i;
388
389   if (levels > 1)
390     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
391
392   ++processing_template_decl;
393   current_template_parms
394     = tree_cons (size_int (processing_template_decl),
395                  parms, current_template_parms);
396   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
397
398   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
399                NULL);
400   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
401     {
402       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
403
404       if (parm == error_mark_node)
405         continue;
406
407       gcc_assert (DECL_P (parm));
408
409       switch (TREE_CODE (parm))
410         {
411         case TYPE_DECL:
412         case TEMPLATE_DECL:
413           pushdecl (parm);
414           break;
415
416         case PARM_DECL:
417           {
418             /* Make a CONST_DECL as is done in process_template_parm.
419                It is ugly that we recreate this here; the original
420                version built in process_template_parm is no longer
421                available.  */
422             tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
423                                     CONST_DECL, DECL_NAME (parm),
424                                     TREE_TYPE (parm));
425             DECL_ARTIFICIAL (decl) = 1;
426             TREE_CONSTANT (decl) = 1;
427             TREE_READONLY (decl) = 1;
428             DECL_INITIAL (decl) = DECL_INITIAL (parm);
429             SET_DECL_TEMPLATE_PARM_P (decl);
430             pushdecl (decl);
431           }
432           break;
433
434         default:
435           gcc_unreachable ();
436         }
437     }
438 }
439
440 /* Restore the template parameter context for a member template or
441    a friend template defined in a class definition.  */
442
443 void
444 maybe_begin_member_template_processing (tree decl)
445 {
446   tree parms;
447   int levels = 0;
448
449   if (inline_needs_template_parms (decl))
450     {
451       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
452       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
453
454       if (DECL_TEMPLATE_SPECIALIZATION (decl))
455         {
456           --levels;
457           parms = TREE_CHAIN (parms);
458         }
459
460       push_inline_template_parms_recursive (parms, levels);
461     }
462
463   /* Remember how many levels of template parameters we pushed so that
464      we can pop them later.  */
465   VEC_safe_push (int, heap, inline_parm_levels, levels);
466 }
467
468 /* Undo the effects of maybe_begin_member_template_processing.  */
469
470 void
471 maybe_end_member_template_processing (void)
472 {
473   int i;
474   int last;
475
476   if (VEC_length (int, inline_parm_levels) == 0)
477     return;
478
479   last = VEC_pop (int, inline_parm_levels);
480   for (i = 0; i < last; ++i)
481     {
482       --processing_template_decl;
483       current_template_parms = TREE_CHAIN (current_template_parms);
484       poplevel (0, 0, 0);
485     }
486 }
487
488 /* Return a new template argument vector which contains all of ARGS,
489    but has as its innermost set of arguments the EXTRA_ARGS.  */
490
491 static tree
492 add_to_template_args (tree args, tree extra_args)
493 {
494   tree new_args;
495   int extra_depth;
496   int i;
497   int j;
498
499   if (args == NULL_TREE || extra_args == error_mark_node)
500     return extra_args;
501
502   extra_depth = TMPL_ARGS_DEPTH (extra_args);
503   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
504
505   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
506     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
507
508   for (j = 1; j <= extra_depth; ++j, ++i)
509     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
510
511   return new_args;
512 }
513
514 /* Like add_to_template_args, but only the outermost ARGS are added to
515    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
516    (EXTRA_ARGS) levels are added.  This function is used to combine
517    the template arguments from a partial instantiation with the
518    template arguments used to attain the full instantiation from the
519    partial instantiation.  */
520
521 static tree
522 add_outermost_template_args (tree args, tree extra_args)
523 {
524   tree new_args;
525
526   /* If there are more levels of EXTRA_ARGS than there are ARGS,
527      something very fishy is going on.  */
528   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
529
530   /* If *all* the new arguments will be the EXTRA_ARGS, just return
531      them.  */
532   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
533     return extra_args;
534
535   /* For the moment, we make ARGS look like it contains fewer levels.  */
536   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
537
538   new_args = add_to_template_args (args, extra_args);
539
540   /* Now, we restore ARGS to its full dimensions.  */
541   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
542
543   return new_args;
544 }
545
546 /* Return the N levels of innermost template arguments from the ARGS.  */
547
548 tree
549 get_innermost_template_args (tree args, int n)
550 {
551   tree new_args;
552   int extra_levels;
553   int i;
554
555   gcc_assert (n >= 0);
556
557   /* If N is 1, just return the innermost set of template arguments.  */
558   if (n == 1)
559     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
560
561   /* If we're not removing anything, just return the arguments we were
562      given.  */
563   extra_levels = TMPL_ARGS_DEPTH (args) - n;
564   gcc_assert (extra_levels >= 0);
565   if (extra_levels == 0)
566     return args;
567
568   /* Make a new set of arguments, not containing the outer arguments.  */
569   new_args = make_tree_vec (n);
570   for (i = 1; i <= n; ++i)
571     SET_TMPL_ARGS_LEVEL (new_args, i,
572                          TMPL_ARGS_LEVEL (args, i + extra_levels));
573
574   return new_args;
575 }
576
577 /* The inverse of get_innermost_template_args: Return all but the innermost
578    EXTRA_LEVELS levels of template arguments from the ARGS.  */
579
580 static tree
581 strip_innermost_template_args (tree args, int extra_levels)
582 {
583   tree new_args;
584   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
585   int i;
586
587   gcc_assert (n >= 0);
588
589   /* If N is 1, just return the outermost set of template arguments.  */
590   if (n == 1)
591     return TMPL_ARGS_LEVEL (args, 1);
592
593   /* If we're not removing anything, just return the arguments we were
594      given.  */
595   gcc_assert (extra_levels >= 0);
596   if (extra_levels == 0)
597     return args;
598
599   /* Make a new set of arguments, not containing the inner arguments.  */
600   new_args = make_tree_vec (n);
601   for (i = 1; i <= n; ++i)
602     SET_TMPL_ARGS_LEVEL (new_args, i,
603                          TMPL_ARGS_LEVEL (args, i));
604
605   return new_args;
606 }
607
608 /* We've got a template header coming up; push to a new level for storing
609    the parms.  */
610
611 void
612 begin_template_parm_list (void)
613 {
614   /* We use a non-tag-transparent scope here, which causes pushtag to
615      put tags in this scope, rather than in the enclosing class or
616      namespace scope.  This is the right thing, since we want
617      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
618      global template class, push_template_decl handles putting the
619      TEMPLATE_DECL into top-level scope.  For a nested template class,
620      e.g.:
621
622        template <class T> struct S1 {
623          template <class T> struct S2 {};
624        };
625
626      pushtag contains special code to call pushdecl_with_scope on the
627      TEMPLATE_DECL for S2.  */
628   begin_scope (sk_template_parms, NULL);
629   ++processing_template_decl;
630   ++processing_template_parmlist;
631   note_template_header (0);
632 }
633
634 /* This routine is called when a specialization is declared.  If it is
635    invalid to declare a specialization here, an error is reported and
636    false is returned, otherwise this routine will return true.  */
637
638 static bool
639 check_specialization_scope (void)
640 {
641   tree scope = current_scope ();
642
643   /* [temp.expl.spec]
644
645      An explicit specialization shall be declared in the namespace of
646      which the template is a member, or, for member templates, in the
647      namespace of which the enclosing class or enclosing class
648      template is a member.  An explicit specialization of a member
649      function, member class or static data member of a class template
650      shall be declared in the namespace of which the class template
651      is a member.  */
652   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
653     {
654       error ("explicit specialization in non-namespace scope %qD", scope);
655       return false;
656     }
657
658   /* [temp.expl.spec]
659
660      In an explicit specialization declaration for a member of a class
661      template or a member template that appears in namespace scope,
662      the member template and some of its enclosing class templates may
663      remain unspecialized, except that the declaration shall not
664      explicitly specialize a class member template if its enclosing
665      class templates are not explicitly specialized as well.  */
666   if (current_template_parms)
667     {
668       error ("enclosing class templates are not explicitly specialized");
669       return false;
670     }
671
672   return true;
673 }
674
675 /* We've just seen template <>.  */
676
677 bool
678 begin_specialization (void)
679 {
680   begin_scope (sk_template_spec, NULL);
681   note_template_header (1);
682   return check_specialization_scope ();
683 }
684
685 /* Called at then end of processing a declaration preceded by
686    template<>.  */
687
688 void
689 end_specialization (void)
690 {
691   finish_scope ();
692   reset_specialization ();
693 }
694
695 /* Any template <>'s that we have seen thus far are not referring to a
696    function specialization.  */
697
698 void
699 reset_specialization (void)
700 {
701   processing_specialization = 0;
702   template_header_count = 0;
703 }
704
705 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
706    it was of the form template <>.  */
707
708 static void
709 note_template_header (int specialization)
710 {
711   processing_specialization = specialization;
712   template_header_count++;
713 }
714
715 /* We're beginning an explicit instantiation.  */
716
717 void
718 begin_explicit_instantiation (void)
719 {
720   gcc_assert (!processing_explicit_instantiation);
721   processing_explicit_instantiation = true;
722 }
723
724
725 void
726 end_explicit_instantiation (void)
727 {
728   gcc_assert (processing_explicit_instantiation);
729   processing_explicit_instantiation = false;
730 }
731
732 /* An explicit specialization or partial specialization TMPL is being
733    declared.  Check that the namespace in which the specialization is
734    occurring is permissible.  Returns false iff it is invalid to
735    specialize TMPL in the current namespace.  */
736
737 static bool
738 check_specialization_namespace (tree tmpl)
739 {
740   tree tpl_ns = decl_namespace_context (tmpl);
741
742   /* [tmpl.expl.spec]
743
744      An explicit specialization shall be declared in the namespace of
745      which the template is a member, or, for member templates, in the
746      namespace of which the enclosing class or enclosing class
747      template is a member.  An explicit specialization of a member
748      function, member class or static data member of a class template
749      shall be declared in the namespace of which the class template is
750      a member.  */
751   if (current_scope() != DECL_CONTEXT (tmpl)
752       && !at_namespace_scope_p ())
753     {
754       error ("specialization of %qD must appear at namespace scope", tmpl);
755       return false;
756     }
757   if (is_associated_namespace (current_namespace, tpl_ns))
758     /* Same or super-using namespace.  */
759     return true;
760   else
761     {
762       permerror (input_location, "specialization of %qD in different namespace", tmpl);
763       permerror (input_location, "  from definition of %q+#D", tmpl);
764       return false;
765     }
766 }
767
768 /* SPEC is an explicit instantiation.  Check that it is valid to
769    perform this explicit instantiation in the current namespace.  */
770
771 static void
772 check_explicit_instantiation_namespace (tree spec)
773 {
774   tree ns;
775
776   /* DR 275: An explicit instantiation shall appear in an enclosing
777      namespace of its template.  */
778   ns = decl_namespace_context (spec);
779   if (!is_ancestor (current_namespace, ns))
780     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
781                "(which does not enclose namespace %qD)",
782                spec, current_namespace, ns);
783 }
784
785 /* The TYPE is being declared.  If it is a template type, that means it
786    is a partial specialization.  Do appropriate error-checking.  */
787
788 tree
789 maybe_process_partial_specialization (tree type)
790 {
791   tree context;
792
793   if (type == error_mark_node)
794     return error_mark_node;
795
796   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
797     {
798       error ("name of class shadows template template parameter %qD",
799              TYPE_NAME (type));
800       return error_mark_node;
801     }
802
803   context = TYPE_CONTEXT (type);
804
805   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
806     {
807       /* This is for ordinary explicit specialization and partial
808          specialization of a template class such as:
809
810            template <> class C<int>;
811
812          or:
813
814            template <class T> class C<T*>;
815
816          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
817
818       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
819           && !COMPLETE_TYPE_P (type))
820         {
821           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
822           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
823           if (processing_template_decl)
824             {
825               if (push_template_decl (TYPE_MAIN_DECL (type))
826                   == error_mark_node)
827                 return error_mark_node;
828             }
829         }
830       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
831         error ("specialization of %qT after instantiation", type);
832     }
833   else if (CLASS_TYPE_P (type)
834            && !CLASSTYPE_USE_TEMPLATE (type)
835            && CLASSTYPE_TEMPLATE_INFO (type)
836            && context && CLASS_TYPE_P (context)
837            && CLASSTYPE_TEMPLATE_INFO (context))
838     {
839       /* This is for an explicit specialization of member class
840          template according to [temp.expl.spec/18]:
841
842            template <> template <class U> class C<int>::D;
843
844          The context `C<int>' must be an implicit instantiation.
845          Otherwise this is just a member class template declared
846          earlier like:
847
848            template <> class C<int> { template <class U> class D; };
849            template <> template <class U> class C<int>::D;
850
851          In the first case, `C<int>::D' is a specialization of `C<T>::D'
852          while in the second case, `C<int>::D' is a primary template
853          and `C<T>::D' may not exist.  */
854
855       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
856           && !COMPLETE_TYPE_P (type))
857         {
858           tree t;
859           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
860
861           if (current_namespace
862               != decl_namespace_context (tmpl))
863             {
864               permerror (input_location, "specializing %q#T in different namespace", type);
865               permerror (input_location, "  from definition of %q+#D", tmpl);
866             }
867
868           /* Check for invalid specialization after instantiation:
869
870                template <> template <> class C<int>::D<int>;
871                template <> template <class U> class C<int>::D;  */
872
873           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
874                t; t = TREE_CHAIN (t))
875             {
876               tree inst = TREE_VALUE (t);
877               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst))
878                 {
879                   /* We already have a full specialization of this partial
880                      instantiation.  Reassign it to the new member
881                      specialization template.  */
882                   spec_entry elt;
883                   spec_entry **slot;
884
885                   elt.tmpl = most_general_template (tmpl);
886                   elt.args = CLASSTYPE_TI_ARGS (inst);
887                   elt.spec = inst;
888
889                   htab_remove_elt (type_specializations, &elt);
890
891                   elt.tmpl = tmpl;
892                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
893
894                   slot = (spec_entry **)
895                     htab_find_slot (type_specializations, &elt, INSERT);
896                   *slot = ggc_alloc_spec_entry ();
897                   **slot = elt;
898                 }
899               else if (COMPLETE_OR_OPEN_TYPE_P (inst))
900                 /* But if we've had an implicit instantiation, that's a
901                    problem ([temp.expl.spec]/6).  */
902                 error ("specialization %qT after instantiation %qT",
903                        type, inst);
904             }
905
906           /* Mark TYPE as a specialization.  And as a result, we only
907              have one level of template argument for the innermost
908              class template.  */
909           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
910           CLASSTYPE_TI_ARGS (type)
911             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
912         }
913     }
914   else if (processing_specialization)
915     {
916        /* Someday C++0x may allow for enum template specialization.  */
917       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
918           && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
919         pedwarn (input_location, OPT_pedantic, "template specialization "
920                  "of %qD not allowed by ISO C++", type);
921       else
922         {
923           error ("explicit specialization of non-template %qT", type);
924           return error_mark_node;
925         }
926     }
927
928   return type;
929 }
930
931 /* Returns nonzero if we can optimize the retrieval of specializations
932    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
933    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
934
935 static inline bool
936 optimize_specialization_lookup_p (tree tmpl)
937 {
938   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
939           && DECL_CLASS_SCOPE_P (tmpl)
940           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
941              parameter.  */
942           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
943           /* The optimized lookup depends on the fact that the
944              template arguments for the member function template apply
945              purely to the containing class, which is not true if the
946              containing class is an explicit or partial
947              specialization.  */
948           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
949           && !DECL_MEMBER_TEMPLATE_P (tmpl)
950           && !DECL_CONV_FN_P (tmpl)
951           /* It is possible to have a template that is not a member
952              template and is not a member of a template class:
953
954              template <typename T>
955              struct S { friend A::f(); };
956
957              Here, the friend function is a template, but the context does
958              not have template information.  The optimized lookup relies
959              on having ARGS be the template arguments for both the class
960              and the function template.  */
961           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
962 }
963
964 /* Retrieve the specialization (in the sense of [temp.spec] - a
965    specialization is either an instantiation or an explicit
966    specialization) of TMPL for the given template ARGS.  If there is
967    no such specialization, return NULL_TREE.  The ARGS are a vector of
968    arguments, or a vector of vectors of arguments, in the case of
969    templates with more than one level of parameters.
970
971    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
972    then we search for a partial specialization matching ARGS.  This
973    parameter is ignored if TMPL is not a class template.  */
974
975 static tree
976 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
977 {
978   if (args == error_mark_node)
979     return NULL_TREE;
980
981   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
982
983   /* There should be as many levels of arguments as there are
984      levels of parameters.  */
985   gcc_assert (TMPL_ARGS_DEPTH (args)
986               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
987
988   if (optimize_specialization_lookup_p (tmpl))
989     {
990       tree class_template;
991       tree class_specialization;
992       VEC(tree,gc) *methods;
993       tree fns;
994       int idx;
995
996       /* The template arguments actually apply to the containing
997          class.  Find the class specialization with those
998          arguments.  */
999       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1000       class_specialization
1001         = retrieve_specialization (class_template, args, 0);
1002       if (!class_specialization)
1003         return NULL_TREE;
1004       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
1005          for the specialization.  */
1006       idx = class_method_index_for_fn (class_specialization, tmpl);
1007       if (idx == -1)
1008         return NULL_TREE;
1009       /* Iterate through the methods with the indicated name, looking
1010          for the one that has an instance of TMPL.  */
1011       methods = CLASSTYPE_METHOD_VEC (class_specialization);
1012       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
1013         {
1014           tree fn = OVL_CURRENT (fns);
1015           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1016               /* using-declarations can add base methods to the method vec,
1017                  and we don't want those here.  */
1018               && DECL_CONTEXT (fn) == class_specialization)
1019             return fn;
1020         }
1021       return NULL_TREE;
1022     }
1023   else
1024     {
1025       spec_entry *found;
1026       spec_entry elt;
1027       htab_t specializations;
1028
1029       elt.tmpl = tmpl;
1030       elt.args = args;
1031       elt.spec = NULL_TREE;
1032
1033       if (DECL_CLASS_TEMPLATE_P (tmpl))
1034         specializations = type_specializations;
1035       else
1036         specializations = decl_specializations;
1037
1038       if (hash == 0)
1039         hash = hash_specialization (&elt);
1040       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1041       if (found)
1042         return found->spec;
1043     }
1044
1045   return NULL_TREE;
1046 }
1047
1048 /* Like retrieve_specialization, but for local declarations.  */
1049
1050 static tree
1051 retrieve_local_specialization (tree tmpl)
1052 {
1053   tree spec;
1054
1055   if (local_specializations == NULL)
1056     return NULL_TREE;
1057
1058   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1059                                      htab_hash_pointer (tmpl));
1060   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1061 }
1062
1063 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1064
1065 int
1066 is_specialization_of (tree decl, tree tmpl)
1067 {
1068   tree t;
1069
1070   if (TREE_CODE (decl) == FUNCTION_DECL)
1071     {
1072       for (t = decl;
1073            t != NULL_TREE;
1074            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1075         if (t == tmpl)
1076           return 1;
1077     }
1078   else
1079     {
1080       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1081
1082       for (t = TREE_TYPE (decl);
1083            t != NULL_TREE;
1084            t = CLASSTYPE_USE_TEMPLATE (t)
1085              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1086         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1087           return 1;
1088     }
1089
1090   return 0;
1091 }
1092
1093 /* Returns nonzero iff DECL is a specialization of friend declaration
1094    FRIEND_DECL according to [temp.friend].  */
1095
1096 bool
1097 is_specialization_of_friend (tree decl, tree friend_decl)
1098 {
1099   bool need_template = true;
1100   int template_depth;
1101
1102   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1103               || TREE_CODE (decl) == TYPE_DECL);
1104
1105   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1106      of a template class, we want to check if DECL is a specialization
1107      if this.  */
1108   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1109       && DECL_TEMPLATE_INFO (friend_decl)
1110       && !DECL_USE_TEMPLATE (friend_decl))
1111     {
1112       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1113       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1114       need_template = false;
1115     }
1116   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1117            && !PRIMARY_TEMPLATE_P (friend_decl))
1118     need_template = false;
1119
1120   /* There is nothing to do if this is not a template friend.  */
1121   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1122     return false;
1123
1124   if (is_specialization_of (decl, friend_decl))
1125     return true;
1126
1127   /* [temp.friend/6]
1128      A member of a class template may be declared to be a friend of a
1129      non-template class.  In this case, the corresponding member of
1130      every specialization of the class template is a friend of the
1131      class granting friendship.
1132
1133      For example, given a template friend declaration
1134
1135        template <class T> friend void A<T>::f();
1136
1137      the member function below is considered a friend
1138
1139        template <> struct A<int> {
1140          void f();
1141        };
1142
1143      For this type of template friend, TEMPLATE_DEPTH below will be
1144      nonzero.  To determine if DECL is a friend of FRIEND, we first
1145      check if the enclosing class is a specialization of another.  */
1146
1147   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1148   if (template_depth
1149       && DECL_CLASS_SCOPE_P (decl)
1150       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1151                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1152     {
1153       /* Next, we check the members themselves.  In order to handle
1154          a few tricky cases, such as when FRIEND_DECL's are
1155
1156            template <class T> friend void A<T>::g(T t);
1157            template <class T> template <T t> friend void A<T>::h();
1158
1159          and DECL's are
1160
1161            void A<int>::g(int);
1162            template <int> void A<int>::h();
1163
1164          we need to figure out ARGS, the template arguments from
1165          the context of DECL.  This is required for template substitution
1166          of `T' in the function parameter of `g' and template parameter
1167          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1168
1169       tree context = DECL_CONTEXT (decl);
1170       tree args = NULL_TREE;
1171       int current_depth = 0;
1172
1173       while (current_depth < template_depth)
1174         {
1175           if (CLASSTYPE_TEMPLATE_INFO (context))
1176             {
1177               if (current_depth == 0)
1178                 args = TYPE_TI_ARGS (context);
1179               else
1180                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1181               current_depth++;
1182             }
1183           context = TYPE_CONTEXT (context);
1184         }
1185
1186       if (TREE_CODE (decl) == FUNCTION_DECL)
1187         {
1188           bool is_template;
1189           tree friend_type;
1190           tree decl_type;
1191           tree friend_args_type;
1192           tree decl_args_type;
1193
1194           /* Make sure that both DECL and FRIEND_DECL are templates or
1195              non-templates.  */
1196           is_template = DECL_TEMPLATE_INFO (decl)
1197                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1198           if (need_template ^ is_template)
1199             return false;
1200           else if (is_template)
1201             {
1202               /* If both are templates, check template parameter list.  */
1203               tree friend_parms
1204                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1205                                          args, tf_none);
1206               if (!comp_template_parms
1207                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1208                       friend_parms))
1209                 return false;
1210
1211               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1212             }
1213           else
1214             decl_type = TREE_TYPE (decl);
1215
1216           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1217                                               tf_none, NULL_TREE);
1218           if (friend_type == error_mark_node)
1219             return false;
1220
1221           /* Check if return types match.  */
1222           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1223             return false;
1224
1225           /* Check if function parameter types match, ignoring the
1226              `this' parameter.  */
1227           friend_args_type = TYPE_ARG_TYPES (friend_type);
1228           decl_args_type = TYPE_ARG_TYPES (decl_type);
1229           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1230             friend_args_type = TREE_CHAIN (friend_args_type);
1231           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1232             decl_args_type = TREE_CHAIN (decl_args_type);
1233
1234           return compparms (decl_args_type, friend_args_type);
1235         }
1236       else
1237         {
1238           /* DECL is a TYPE_DECL */
1239           bool is_template;
1240           tree decl_type = TREE_TYPE (decl);
1241
1242           /* Make sure that both DECL and FRIEND_DECL are templates or
1243              non-templates.  */
1244           is_template
1245             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1246               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1247
1248           if (need_template ^ is_template)
1249             return false;
1250           else if (is_template)
1251             {
1252               tree friend_parms;
1253               /* If both are templates, check the name of the two
1254                  TEMPLATE_DECL's first because is_friend didn't.  */
1255               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1256                   != DECL_NAME (friend_decl))
1257                 return false;
1258
1259               /* Now check template parameter list.  */
1260               friend_parms
1261                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1262                                          args, tf_none);
1263               return comp_template_parms
1264                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1265                  friend_parms);
1266             }
1267           else
1268             return (DECL_NAME (decl)
1269                     == DECL_NAME (friend_decl));
1270         }
1271     }
1272   return false;
1273 }
1274
1275 /* Register the specialization SPEC as a specialization of TMPL with
1276    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1277    is actually just a friend declaration.  Returns SPEC, or an
1278    equivalent prior declaration, if available.  */
1279
1280 static tree
1281 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1282                          hashval_t hash)
1283 {
1284   tree fn;
1285   spec_entry **slot = NULL;
1286   spec_entry elt;
1287
1288   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1289
1290   if (TREE_CODE (spec) == FUNCTION_DECL
1291       && uses_template_parms (DECL_TI_ARGS (spec)))
1292     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1293        register it; we want the corresponding TEMPLATE_DECL instead.
1294        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1295        the more obvious `uses_template_parms (spec)' to avoid problems
1296        with default function arguments.  In particular, given
1297        something like this:
1298
1299           template <class T> void f(T t1, T t = T())
1300
1301        the default argument expression is not substituted for in an
1302        instantiation unless and until it is actually needed.  */
1303     return spec;
1304
1305   if (optimize_specialization_lookup_p (tmpl))
1306     /* We don't put these specializations in the hash table, but we might
1307        want to give an error about a mismatch.  */
1308     fn = retrieve_specialization (tmpl, args, 0);
1309   else
1310     {
1311       elt.tmpl = tmpl;
1312       elt.args = args;
1313       elt.spec = spec;
1314
1315       if (hash == 0)
1316         hash = hash_specialization (&elt);
1317
1318       slot = (spec_entry **)
1319         htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1320       if (*slot)
1321         fn = (*slot)->spec;
1322       else
1323         fn = NULL_TREE;
1324     }
1325
1326   /* We can sometimes try to re-register a specialization that we've
1327      already got.  In particular, regenerate_decl_from_template calls
1328      duplicate_decls which will update the specialization list.  But,
1329      we'll still get called again here anyhow.  It's more convenient
1330      to simply allow this than to try to prevent it.  */
1331   if (fn == spec)
1332     return spec;
1333   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1334     {
1335       if (DECL_TEMPLATE_INSTANTIATION (fn))
1336         {
1337           if (DECL_ODR_USED (fn)
1338               || DECL_EXPLICIT_INSTANTIATION (fn))
1339             {
1340               error ("specialization of %qD after instantiation",
1341                      fn);
1342               return error_mark_node;
1343             }
1344           else
1345             {
1346               tree clone;
1347               /* This situation should occur only if the first
1348                  specialization is an implicit instantiation, the
1349                  second is an explicit specialization, and the
1350                  implicit instantiation has not yet been used.  That
1351                  situation can occur if we have implicitly
1352                  instantiated a member function and then specialized
1353                  it later.
1354
1355                  We can also wind up here if a friend declaration that
1356                  looked like an instantiation turns out to be a
1357                  specialization:
1358
1359                    template <class T> void foo(T);
1360                    class S { friend void foo<>(int) };
1361                    template <> void foo(int);
1362
1363                  We transform the existing DECL in place so that any
1364                  pointers to it become pointers to the updated
1365                  declaration.
1366
1367                  If there was a definition for the template, but not
1368                  for the specialization, we want this to look as if
1369                  there were no definition, and vice versa.  */
1370               DECL_INITIAL (fn) = NULL_TREE;
1371               duplicate_decls (spec, fn, is_friend);
1372               /* The call to duplicate_decls will have applied
1373                  [temp.expl.spec]:
1374
1375                    An explicit specialization of a function template
1376                    is inline only if it is explicitly declared to be,
1377                    and independently of whether its function template
1378                    is.
1379
1380                 to the primary function; now copy the inline bits to
1381                 the various clones.  */
1382               FOR_EACH_CLONE (clone, fn)
1383                 {
1384                   DECL_DECLARED_INLINE_P (clone)
1385                     = DECL_DECLARED_INLINE_P (fn);
1386                   DECL_SOURCE_LOCATION (clone)
1387                     = DECL_SOURCE_LOCATION (fn);
1388                 }
1389               check_specialization_namespace (fn);
1390
1391               return fn;
1392             }
1393         }
1394       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1395         {
1396           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1397             /* Dup decl failed, but this is a new definition. Set the
1398                line number so any errors match this new
1399                definition.  */
1400             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1401
1402           return fn;
1403         }
1404     }
1405   else if (fn)
1406     return duplicate_decls (spec, fn, is_friend);
1407
1408   /* A specialization must be declared in the same namespace as the
1409      template it is specializing.  */
1410   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1411       && !check_specialization_namespace (tmpl))
1412     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1413
1414   if (!optimize_specialization_lookup_p (tmpl))
1415     {
1416       gcc_assert (tmpl && args && spec);
1417       *slot = ggc_alloc_spec_entry ();
1418       **slot = elt;
1419       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1420           && PRIMARY_TEMPLATE_P (tmpl)
1421           && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1422         /* TMPL is a forward declaration of a template function; keep a list
1423            of all specializations in case we need to reassign them to a friend
1424            template later in tsubst_friend_function.  */
1425         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1426           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1427     }
1428
1429   return spec;
1430 }
1431
1432 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1433    TMPL and ARGS members, ignores SPEC.  */
1434
1435 static int
1436 eq_specializations (const void *p1, const void *p2)
1437 {
1438   const spec_entry *e1 = (const spec_entry *)p1;
1439   const spec_entry *e2 = (const spec_entry *)p2;
1440
1441   return (e1->tmpl == e2->tmpl
1442           && comp_template_args (e1->args, e2->args));
1443 }
1444
1445 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1446
1447 static hashval_t
1448 hash_tmpl_and_args (tree tmpl, tree args)
1449 {
1450   hashval_t val = DECL_UID (tmpl);
1451   return iterative_hash_template_arg (args, val);
1452 }
1453
1454 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1455    ignoring SPEC.  */
1456
1457 static hashval_t
1458 hash_specialization (const void *p)
1459 {
1460   const spec_entry *e = (const spec_entry *)p;
1461   return hash_tmpl_and_args (e->tmpl, e->args);
1462 }
1463
1464 /* Recursively calculate a hash value for a template argument ARG, for use
1465    in the hash tables of template specializations.  */
1466
1467 hashval_t
1468 iterative_hash_template_arg (tree arg, hashval_t val)
1469 {
1470   unsigned HOST_WIDE_INT i;
1471   enum tree_code code;
1472   char tclass;
1473
1474   if (arg == NULL_TREE)
1475     return iterative_hash_object (arg, val);
1476
1477   if (!TYPE_P (arg))
1478     STRIP_NOPS (arg);
1479
1480   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1481     /* We can get one of these when re-hashing a previous entry in the middle
1482        of substituting into a pack expansion.  Just look through it.  */
1483     arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1484
1485   code = TREE_CODE (arg);
1486   tclass = TREE_CODE_CLASS (code);
1487
1488   val = iterative_hash_object (code, val);
1489
1490   switch (code)
1491     {
1492     case ERROR_MARK:
1493       return val;
1494
1495     case IDENTIFIER_NODE:
1496       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1497
1498     case TREE_VEC:
1499       {
1500         int i, len = TREE_VEC_LENGTH (arg);
1501         for (i = 0; i < len; ++i)
1502           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1503         return val;
1504       }
1505
1506     case TYPE_PACK_EXPANSION:
1507     case EXPR_PACK_EXPANSION:
1508       return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1509
1510     case TYPE_ARGUMENT_PACK:
1511     case NONTYPE_ARGUMENT_PACK:
1512       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1513
1514     case TREE_LIST:
1515       for (; arg; arg = TREE_CHAIN (arg))
1516         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1517       return val;
1518
1519     case OVERLOAD:
1520       for (; arg; arg = OVL_CHAIN (arg))
1521         val = iterative_hash_template_arg (OVL_FUNCTION (arg), val);
1522       return val;
1523
1524     case CONSTRUCTOR:
1525       {
1526         tree field, value;
1527         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1528           {
1529             val = iterative_hash_template_arg (field, val);
1530             val = iterative_hash_template_arg (value, val);
1531           }
1532         return val;
1533       }
1534
1535     case PARM_DECL:
1536       if (!DECL_ARTIFICIAL (arg))
1537         val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1538       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1539
1540     case TARGET_EXPR:
1541       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1542
1543     case PTRMEM_CST:
1544       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1545       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1546
1547     case TEMPLATE_PARM_INDEX:
1548       val = iterative_hash_template_arg
1549         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1550       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1551       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1552
1553     case TRAIT_EXPR:
1554       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1555       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1556       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1557
1558     case BASELINK:
1559       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1560                                          val);
1561       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1562                                           val);
1563
1564     case MODOP_EXPR:
1565       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1566       code = TREE_CODE (TREE_OPERAND (arg, 1));
1567       val = iterative_hash_object (code, val);
1568       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1569
1570     case ARRAY_TYPE:
1571       /* layout_type sets structural equality for arrays of
1572          incomplete type, so we can't rely on the canonical type
1573          for hashing.  */
1574       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1575       return iterative_hash_template_arg (TYPE_DOMAIN (arg), val);
1576
1577     case LAMBDA_EXPR:
1578       /* A lambda can't appear in a template arg, but don't crash on
1579          erroneous input.  */
1580       gcc_assert (seen_error ());
1581       return val;
1582
1583     case CAST_EXPR:
1584     case STATIC_CAST_EXPR:
1585     case REINTERPRET_CAST_EXPR:
1586     case CONST_CAST_EXPR:
1587     case DYNAMIC_CAST_EXPR:
1588     case NEW_EXPR:
1589       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1590       /* Now hash operands as usual.  */
1591       break;
1592
1593     default:
1594       break;
1595     }
1596
1597   switch (tclass)
1598     {
1599     case tcc_type:
1600       if (TYPE_CANONICAL (arg))
1601         return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1602                                       val);
1603       else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1604         return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1605       /* Otherwise just compare the types during lookup.  */
1606       return val;
1607
1608     case tcc_declaration:
1609     case tcc_constant:
1610       return iterative_hash_expr (arg, val);
1611
1612     default:
1613       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1614       {
1615         unsigned n = TREE_OPERAND_LENGTH (arg);
1616         for (i = 0; i < n; ++i)
1617           val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1618         return val;
1619       }
1620     }
1621   gcc_unreachable ();
1622   return 0;
1623 }
1624
1625 /* Unregister the specialization SPEC as a specialization of TMPL.
1626    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1627    if the SPEC was listed as a specialization of TMPL.
1628
1629    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1630
1631 bool
1632 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1633 {
1634   spec_entry **slot;
1635   spec_entry elt;
1636
1637   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1638   elt.args = TI_ARGS (tinfo);
1639   elt.spec = NULL_TREE;
1640
1641   slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1642   if (*slot)
1643     {
1644       gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1645       gcc_assert (new_spec != NULL_TREE);
1646       (*slot)->spec = new_spec;
1647       return 1;
1648     }
1649
1650   return 0;
1651 }
1652
1653 /* Compare an entry in the local specializations hash table P1 (which
1654    is really a pointer to a TREE_LIST) with P2 (which is really a
1655    DECL).  */
1656
1657 static int
1658 eq_local_specializations (const void *p1, const void *p2)
1659 {
1660   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1661 }
1662
1663 /* Hash P1, an entry in the local specializations table.  */
1664
1665 static hashval_t
1666 hash_local_specialization (const void* p1)
1667 {
1668   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1669 }
1670
1671 /* Like register_specialization, but for local declarations.  We are
1672    registering SPEC, an instantiation of TMPL.  */
1673
1674 static void
1675 register_local_specialization (tree spec, tree tmpl)
1676 {
1677   void **slot;
1678
1679   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1680                                    htab_hash_pointer (tmpl), INSERT);
1681   *slot = build_tree_list (spec, tmpl);
1682 }
1683
1684 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1685    specialized class.  */
1686
1687 bool
1688 explicit_class_specialization_p (tree type)
1689 {
1690   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1691     return false;
1692   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1693 }
1694
1695 /* Print the list of functions at FNS, going through all the overloads
1696    for each element of the list.  Alternatively, FNS can not be a
1697    TREE_LIST, in which case it will be printed together with all the
1698    overloads.
1699
1700    MORE and *STR should respectively be FALSE and NULL when the function
1701    is called from the outside.  They are used internally on recursive
1702    calls.  print_candidates manages the two parameters and leaves NULL
1703    in *STR when it ends.  */
1704
1705 static void
1706 print_candidates_1 (tree fns, bool more, const char **str)
1707 {
1708   tree fn, fn2;
1709   char *spaces = NULL;
1710
1711   for (fn = fns; fn; fn = OVL_NEXT (fn))
1712     if (TREE_CODE (fn) == TREE_LIST)
1713       {
1714         gcc_assert (!OVL_NEXT (fn) && !is_overloaded_fn (fn));
1715         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1716           print_candidates_1 (TREE_VALUE (fn2),
1717                               TREE_CHAIN (fn2) || more, str);
1718       }
1719     else
1720       {
1721         if (!*str)
1722           {
1723             /* Pick the prefix string.  */
1724             if (!more && !OVL_NEXT (fns))
1725               {
1726                 error ("candidate is: %+#D", OVL_CURRENT (fn));
1727                 continue;
1728               }
1729
1730             *str = _("candidates are:");
1731             spaces = get_spaces (*str);
1732           }
1733         error ("%s %+#D", *str, OVL_CURRENT (fn));
1734         *str = spaces ? spaces : *str;
1735       }
1736
1737   if (!more)
1738     {
1739       free (spaces);
1740       *str = NULL;
1741     }
1742 }
1743
1744 /* Print the list of candidate FNS in an error message.  */
1745
1746 void
1747 print_candidates (tree fns)
1748 {
1749   const char *str = NULL;
1750   print_candidates_1 (fns, false, &str);
1751   gcc_assert (str == NULL);
1752 }
1753
1754 /* Returns the template (one of the functions given by TEMPLATE_ID)
1755    which can be specialized to match the indicated DECL with the
1756    explicit template args given in TEMPLATE_ID.  The DECL may be
1757    NULL_TREE if none is available.  In that case, the functions in
1758    TEMPLATE_ID are non-members.
1759
1760    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1761    specialization of a member template.
1762
1763    The TEMPLATE_COUNT is the number of references to qualifying
1764    template classes that appeared in the name of the function. See
1765    check_explicit_specialization for a more accurate description.
1766
1767    TSK indicates what kind of template declaration (if any) is being
1768    declared.  TSK_TEMPLATE indicates that the declaration given by
1769    DECL, though a FUNCTION_DECL, has template parameters, and is
1770    therefore a template function.
1771
1772    The template args (those explicitly specified and those deduced)
1773    are output in a newly created vector *TARGS_OUT.
1774
1775    If it is impossible to determine the result, an error message is
1776    issued.  The error_mark_node is returned to indicate failure.  */
1777
1778 static tree
1779 determine_specialization (tree template_id,
1780                           tree decl,
1781                           tree* targs_out,
1782                           int need_member_template,
1783                           int template_count,
1784                           tmpl_spec_kind tsk)
1785 {
1786   tree fns;
1787   tree targs;
1788   tree explicit_targs;
1789   tree candidates = NULL_TREE;
1790   /* A TREE_LIST of templates of which DECL may be a specialization.
1791      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1792      corresponding TREE_PURPOSE is the set of template arguments that,
1793      when used to instantiate the template, would produce a function
1794      with the signature of DECL.  */
1795   tree templates = NULL_TREE;
1796   int header_count;
1797   struct cp_binding_level *b;
1798
1799   *targs_out = NULL_TREE;
1800
1801   if (template_id == error_mark_node || decl == error_mark_node)
1802     return error_mark_node;
1803
1804   fns = TREE_OPERAND (template_id, 0);
1805   explicit_targs = TREE_OPERAND (template_id, 1);
1806
1807   if (fns == error_mark_node)
1808     return error_mark_node;
1809
1810   /* Check for baselinks.  */
1811   if (BASELINK_P (fns))
1812     fns = BASELINK_FUNCTIONS (fns);
1813
1814   if (!is_overloaded_fn (fns))
1815     {
1816       error ("%qD is not a function template", fns);
1817       return error_mark_node;
1818     }
1819
1820   /* Count the number of template headers specified for this
1821      specialization.  */
1822   header_count = 0;
1823   for (b = current_binding_level;
1824        b->kind == sk_template_parms;
1825        b = b->level_chain)
1826     ++header_count;
1827
1828   for (; fns; fns = OVL_NEXT (fns))
1829     {
1830       tree fn = OVL_CURRENT (fns);
1831
1832       if (TREE_CODE (fn) == TEMPLATE_DECL)
1833         {
1834           tree decl_arg_types;
1835           tree fn_arg_types;
1836
1837           /* In case of explicit specialization, we need to check if
1838              the number of template headers appearing in the specialization
1839              is correct. This is usually done in check_explicit_specialization,
1840              but the check done there cannot be exhaustive when specializing
1841              member functions. Consider the following code:
1842
1843              template <> void A<int>::f(int);
1844              template <> template <> void A<int>::f(int);
1845
1846              Assuming that A<int> is not itself an explicit specialization
1847              already, the first line specializes "f" which is a non-template
1848              member function, whilst the second line specializes "f" which
1849              is a template member function. So both lines are syntactically
1850              correct, and check_explicit_specialization does not reject
1851              them.
1852
1853              Here, we can do better, as we are matching the specialization
1854              against the declarations. We count the number of template
1855              headers, and we check if they match TEMPLATE_COUNT + 1
1856              (TEMPLATE_COUNT is the number of qualifying template classes,
1857              plus there must be another header for the member template
1858              itself).
1859
1860              Notice that if header_count is zero, this is not a
1861              specialization but rather a template instantiation, so there
1862              is no check we can perform here.  */
1863           if (header_count && header_count != template_count + 1)
1864             continue;
1865
1866           /* Check that the number of template arguments at the
1867              innermost level for DECL is the same as for FN.  */
1868           if (current_binding_level->kind == sk_template_parms
1869               && !current_binding_level->explicit_spec_p
1870               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1871                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1872                                       (current_template_parms))))
1873             continue;
1874
1875           /* DECL might be a specialization of FN.  */
1876           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1877           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1878
1879           /* For a non-static member function, we need to make sure
1880              that the const qualification is the same.  Since
1881              get_bindings does not try to merge the "this" parameter,
1882              we must do the comparison explicitly.  */
1883           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1884               && !same_type_p (TREE_VALUE (fn_arg_types),
1885                                TREE_VALUE (decl_arg_types)))
1886             continue;
1887
1888           /* Skip the "this" parameter and, for constructors of
1889              classes with virtual bases, the VTT parameter.  A
1890              full specialization of a constructor will have a VTT
1891              parameter, but a template never will.  */ 
1892           decl_arg_types 
1893             = skip_artificial_parms_for (decl, decl_arg_types);
1894           fn_arg_types 
1895             = skip_artificial_parms_for (fn, fn_arg_types);
1896
1897           /* Check that the number of function parameters matches.
1898              For example,
1899                template <class T> void f(int i = 0);
1900                template <> void f<int>();
1901              The specialization f<int> is invalid but is not caught
1902              by get_bindings below.  */
1903           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1904             continue;
1905
1906           /* Function templates cannot be specializations; there are
1907              no partial specializations of functions.  Therefore, if
1908              the type of DECL does not match FN, there is no
1909              match.  */
1910           if (tsk == tsk_template)
1911             {
1912               if (compparms (fn_arg_types, decl_arg_types))
1913                 candidates = tree_cons (NULL_TREE, fn, candidates);
1914               continue;
1915             }
1916
1917           /* See whether this function might be a specialization of this
1918              template.  */
1919           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1920
1921           if (!targs)
1922             /* We cannot deduce template arguments that when used to
1923                specialize TMPL will produce DECL.  */
1924             continue;
1925
1926           /* Save this template, and the arguments deduced.  */
1927           templates = tree_cons (targs, fn, templates);
1928         }
1929       else if (need_member_template)
1930         /* FN is an ordinary member function, and we need a
1931            specialization of a member template.  */
1932         ;
1933       else if (TREE_CODE (fn) != FUNCTION_DECL)
1934         /* We can get IDENTIFIER_NODEs here in certain erroneous
1935            cases.  */
1936         ;
1937       else if (!DECL_FUNCTION_MEMBER_P (fn))
1938         /* This is just an ordinary non-member function.  Nothing can
1939            be a specialization of that.  */
1940         ;
1941       else if (DECL_ARTIFICIAL (fn))
1942         /* Cannot specialize functions that are created implicitly.  */
1943         ;
1944       else
1945         {
1946           tree decl_arg_types;
1947
1948           /* This is an ordinary member function.  However, since
1949              we're here, we can assume it's enclosing class is a
1950              template class.  For example,
1951
1952                template <typename T> struct S { void f(); };
1953                template <> void S<int>::f() {}
1954
1955              Here, S<int>::f is a non-template, but S<int> is a
1956              template class.  If FN has the same type as DECL, we
1957              might be in business.  */
1958
1959           if (!DECL_TEMPLATE_INFO (fn))
1960             /* Its enclosing class is an explicit specialization
1961                of a template class.  This is not a candidate.  */
1962             continue;
1963
1964           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1965                             TREE_TYPE (TREE_TYPE (fn))))
1966             /* The return types differ.  */
1967             continue;
1968
1969           /* Adjust the type of DECL in case FN is a static member.  */
1970           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1971           if (DECL_STATIC_FUNCTION_P (fn)
1972               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1973             decl_arg_types = TREE_CHAIN (decl_arg_types);
1974
1975           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1976                          decl_arg_types))
1977             /* They match!  */
1978             candidates = tree_cons (NULL_TREE, fn, candidates);
1979         }
1980     }
1981
1982   if (templates && TREE_CHAIN (templates))
1983     {
1984       /* We have:
1985
1986            [temp.expl.spec]
1987
1988            It is possible for a specialization with a given function
1989            signature to be instantiated from more than one function
1990            template.  In such cases, explicit specification of the
1991            template arguments must be used to uniquely identify the
1992            function template specialization being specialized.
1993
1994          Note that here, there's no suggestion that we're supposed to
1995          determine which of the candidate templates is most
1996          specialized.  However, we, also have:
1997
1998            [temp.func.order]
1999
2000            Partial ordering of overloaded function template
2001            declarations is used in the following contexts to select
2002            the function template to which a function template
2003            specialization refers:
2004
2005            -- when an explicit specialization refers to a function
2006               template.
2007
2008          So, we do use the partial ordering rules, at least for now.
2009          This extension can only serve to make invalid programs valid,
2010          so it's safe.  And, there is strong anecdotal evidence that
2011          the committee intended the partial ordering rules to apply;
2012          the EDG front end has that behavior, and John Spicer claims
2013          that the committee simply forgot to delete the wording in
2014          [temp.expl.spec].  */
2015       tree tmpl = most_specialized_instantiation (templates);
2016       if (tmpl != error_mark_node)
2017         {
2018           templates = tmpl;
2019           TREE_CHAIN (templates) = NULL_TREE;
2020         }
2021     }
2022
2023   if (templates == NULL_TREE && candidates == NULL_TREE)
2024     {
2025       error ("template-id %qD for %q+D does not match any template "
2026              "declaration", template_id, decl);
2027       if (header_count && header_count != template_count + 1)
2028         inform (input_location, "saw %d %<template<>%>, need %d for "
2029                 "specializing a member function template",
2030                 header_count, template_count + 1);
2031       return error_mark_node;
2032     }
2033   else if ((templates && TREE_CHAIN (templates))
2034            || (candidates && TREE_CHAIN (candidates))
2035            || (templates && candidates))
2036     {
2037       error ("ambiguous template specialization %qD for %q+D",
2038              template_id, decl);
2039       candidates = chainon (candidates, templates);
2040       print_candidates (candidates);
2041       return error_mark_node;
2042     }
2043
2044   /* We have one, and exactly one, match.  */
2045   if (candidates)
2046     {
2047       tree fn = TREE_VALUE (candidates);
2048       *targs_out = copy_node (DECL_TI_ARGS (fn));
2049       /* DECL is a re-declaration or partial instantiation of a template
2050          function.  */
2051       if (TREE_CODE (fn) == TEMPLATE_DECL)
2052         return fn;
2053       /* It was a specialization of an ordinary member function in a
2054          template class.  */
2055       return DECL_TI_TEMPLATE (fn);
2056     }
2057
2058   /* It was a specialization of a template.  */
2059   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2060   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2061     {
2062       *targs_out = copy_node (targs);
2063       SET_TMPL_ARGS_LEVEL (*targs_out,
2064                            TMPL_ARGS_DEPTH (*targs_out),
2065                            TREE_PURPOSE (templates));
2066     }
2067   else
2068     *targs_out = TREE_PURPOSE (templates);
2069   return TREE_VALUE (templates);
2070 }
2071
2072 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2073    but with the default argument values filled in from those in the
2074    TMPL_TYPES.  */
2075
2076 static tree
2077 copy_default_args_to_explicit_spec_1 (tree spec_types,
2078                                       tree tmpl_types)
2079 {
2080   tree new_spec_types;
2081
2082   if (!spec_types)
2083     return NULL_TREE;
2084
2085   if (spec_types == void_list_node)
2086     return void_list_node;
2087
2088   /* Substitute into the rest of the list.  */
2089   new_spec_types =
2090     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2091                                           TREE_CHAIN (tmpl_types));
2092
2093   /* Add the default argument for this parameter.  */
2094   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2095                          TREE_VALUE (spec_types),
2096                          new_spec_types);
2097 }
2098
2099 /* DECL is an explicit specialization.  Replicate default arguments
2100    from the template it specializes.  (That way, code like:
2101
2102      template <class T> void f(T = 3);
2103      template <> void f(double);
2104      void g () { f (); }
2105
2106    works, as required.)  An alternative approach would be to look up
2107    the correct default arguments at the call-site, but this approach
2108    is consistent with how implicit instantiations are handled.  */
2109
2110 static void
2111 copy_default_args_to_explicit_spec (tree decl)
2112 {
2113   tree tmpl;
2114   tree spec_types;
2115   tree tmpl_types;
2116   tree new_spec_types;
2117   tree old_type;
2118   tree new_type;
2119   tree t;
2120   tree object_type = NULL_TREE;
2121   tree in_charge = NULL_TREE;
2122   tree vtt = NULL_TREE;
2123
2124   /* See if there's anything we need to do.  */
2125   tmpl = DECL_TI_TEMPLATE (decl);
2126   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2127   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2128     if (TREE_PURPOSE (t))
2129       break;
2130   if (!t)
2131     return;
2132
2133   old_type = TREE_TYPE (decl);
2134   spec_types = TYPE_ARG_TYPES (old_type);
2135
2136   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2137     {
2138       /* Remove the this pointer, but remember the object's type for
2139          CV quals.  */
2140       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2141       spec_types = TREE_CHAIN (spec_types);
2142       tmpl_types = TREE_CHAIN (tmpl_types);
2143
2144       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2145         {
2146           /* DECL may contain more parameters than TMPL due to the extra
2147              in-charge parameter in constructors and destructors.  */
2148           in_charge = spec_types;
2149           spec_types = TREE_CHAIN (spec_types);
2150         }
2151       if (DECL_HAS_VTT_PARM_P (decl))
2152         {
2153           vtt = spec_types;
2154           spec_types = TREE_CHAIN (spec_types);
2155         }
2156     }
2157
2158   /* Compute the merged default arguments.  */
2159   new_spec_types =
2160     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2161
2162   /* Compute the new FUNCTION_TYPE.  */
2163   if (object_type)
2164     {
2165       if (vtt)
2166         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2167                                          TREE_VALUE (vtt),
2168                                          new_spec_types);
2169
2170       if (in_charge)
2171         /* Put the in-charge parameter back.  */
2172         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2173                                          TREE_VALUE (in_charge),
2174                                          new_spec_types);
2175
2176       new_type = build_method_type_directly (object_type,
2177                                              TREE_TYPE (old_type),
2178                                              new_spec_types);
2179     }
2180   else
2181     new_type = build_function_type (TREE_TYPE (old_type),
2182                                     new_spec_types);
2183   new_type = cp_build_type_attribute_variant (new_type,
2184                                               TYPE_ATTRIBUTES (old_type));
2185   new_type = build_exception_variant (new_type,
2186                                       TYPE_RAISES_EXCEPTIONS (old_type));
2187   TREE_TYPE (decl) = new_type;
2188 }
2189
2190 /* Check to see if the function just declared, as indicated in
2191    DECLARATOR, and in DECL, is a specialization of a function
2192    template.  We may also discover that the declaration is an explicit
2193    instantiation at this point.
2194
2195    Returns DECL, or an equivalent declaration that should be used
2196    instead if all goes well.  Issues an error message if something is
2197    amiss.  Returns error_mark_node if the error is not easily
2198    recoverable.
2199
2200    FLAGS is a bitmask consisting of the following flags:
2201
2202    2: The function has a definition.
2203    4: The function is a friend.
2204
2205    The TEMPLATE_COUNT is the number of references to qualifying
2206    template classes that appeared in the name of the function.  For
2207    example, in
2208
2209      template <class T> struct S { void f(); };
2210      void S<int>::f();
2211
2212    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2213    classes are not counted in the TEMPLATE_COUNT, so that in
2214
2215      template <class T> struct S {};
2216      template <> struct S<int> { void f(); }
2217      template <> void S<int>::f();
2218
2219    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2220    invalid; there should be no template <>.)
2221
2222    If the function is a specialization, it is marked as such via
2223    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2224    is set up correctly, and it is added to the list of specializations
2225    for that template.  */
2226
2227 tree
2228 check_explicit_specialization (tree declarator,
2229                                tree decl,
2230                                int template_count,
2231                                int flags)
2232 {
2233   int have_def = flags & 2;
2234   int is_friend = flags & 4;
2235   int specialization = 0;
2236   int explicit_instantiation = 0;
2237   int member_specialization = 0;
2238   tree ctype = DECL_CLASS_CONTEXT (decl);
2239   tree dname = DECL_NAME (decl);
2240   tmpl_spec_kind tsk;
2241
2242   if (is_friend)
2243     {
2244       if (!processing_specialization)
2245         tsk = tsk_none;
2246       else
2247         tsk = tsk_excessive_parms;
2248     }
2249   else
2250     tsk = current_tmpl_spec_kind (template_count);
2251
2252   switch (tsk)
2253     {
2254     case tsk_none:
2255       if (processing_specialization)
2256         {
2257           specialization = 1;
2258           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2259         }
2260       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2261         {
2262           if (is_friend)
2263             /* This could be something like:
2264
2265                template <class T> void f(T);
2266                class S { friend void f<>(int); }  */
2267             specialization = 1;
2268           else
2269             {
2270               /* This case handles bogus declarations like template <>
2271                  template <class T> void f<int>(); */
2272
2273               error ("template-id %qD in declaration of primary template",
2274                      declarator);
2275               return decl;
2276             }
2277         }
2278       break;
2279
2280     case tsk_invalid_member_spec:
2281       /* The error has already been reported in
2282          check_specialization_scope.  */
2283       return error_mark_node;
2284
2285     case tsk_invalid_expl_inst:
2286       error ("template parameter list used in explicit instantiation");
2287
2288       /* Fall through.  */
2289
2290     case tsk_expl_inst:
2291       if (have_def)
2292         error ("definition provided for explicit instantiation");
2293
2294       explicit_instantiation = 1;
2295       break;
2296
2297     case tsk_excessive_parms:
2298     case tsk_insufficient_parms:
2299       if (tsk == tsk_excessive_parms)
2300         error ("too many template parameter lists in declaration of %qD",
2301                decl);
2302       else if (template_header_count)
2303         error("too few template parameter lists in declaration of %qD", decl);
2304       else
2305         error("explicit specialization of %qD must be introduced by "
2306               "%<template <>%>", decl);
2307
2308       /* Fall through.  */
2309     case tsk_expl_spec:
2310       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2311       if (ctype)
2312         member_specialization = 1;
2313       else
2314         specialization = 1;
2315       break;
2316
2317     case tsk_template:
2318       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2319         {
2320           /* This case handles bogus declarations like template <>
2321              template <class T> void f<int>(); */
2322
2323           if (uses_template_parms (declarator))
2324             error ("function template partial specialization %qD "
2325                    "is not allowed", declarator);
2326           else
2327             error ("template-id %qD in declaration of primary template",
2328                    declarator);
2329           return decl;
2330         }
2331
2332       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2333         /* This is a specialization of a member template, without
2334            specialization the containing class.  Something like:
2335
2336              template <class T> struct S {
2337                template <class U> void f (U);
2338              };
2339              template <> template <class U> void S<int>::f(U) {}
2340
2341            That's a specialization -- but of the entire template.  */
2342         specialization = 1;
2343       break;
2344
2345     default:
2346       gcc_unreachable ();
2347     }
2348
2349   if (specialization || member_specialization)
2350     {
2351       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2352       for (; t; t = TREE_CHAIN (t))
2353         if (TREE_PURPOSE (t))
2354           {
2355             permerror (input_location, 
2356                        "default argument specified in explicit specialization");
2357             break;
2358           }
2359     }
2360
2361   if (specialization || member_specialization || explicit_instantiation)
2362     {
2363       tree tmpl = NULL_TREE;
2364       tree targs = NULL_TREE;
2365
2366       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2367       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2368         {
2369           tree fns;
2370
2371           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2372           if (ctype)
2373             fns = dname;
2374           else
2375             {
2376               /* If there is no class context, the explicit instantiation
2377                  must be at namespace scope.  */
2378               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2379
2380               /* Find the namespace binding, using the declaration
2381                  context.  */
2382               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2383                                            false, true);
2384               if (fns == error_mark_node || !is_overloaded_fn (fns))
2385                 {
2386                   error ("%qD is not a template function", dname);
2387                   fns = error_mark_node;
2388                 }
2389               else
2390                 {
2391                   tree fn = OVL_CURRENT (fns);
2392                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2393                                                 CP_DECL_CONTEXT (fn)))
2394                     error ("%qD is not declared in %qD",
2395                            decl, current_namespace);
2396                 }
2397             }
2398
2399           declarator = lookup_template_function (fns, NULL_TREE);
2400         }
2401
2402       if (declarator == error_mark_node)
2403         return error_mark_node;
2404
2405       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2406         {
2407           if (!explicit_instantiation)
2408             /* A specialization in class scope.  This is invalid,
2409                but the error will already have been flagged by
2410                check_specialization_scope.  */
2411             return error_mark_node;
2412           else
2413             {
2414               /* It's not valid to write an explicit instantiation in
2415                  class scope, e.g.:
2416
2417                    class C { template void f(); }
2418
2419                    This case is caught by the parser.  However, on
2420                    something like:
2421
2422                    template class C { void f(); };
2423
2424                    (which is invalid) we can get here.  The error will be
2425                    issued later.  */
2426               ;
2427             }
2428
2429           return decl;
2430         }
2431       else if (ctype != NULL_TREE
2432                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2433                    IDENTIFIER_NODE))
2434         {
2435           /* Find the list of functions in ctype that have the same
2436              name as the declared function.  */
2437           tree name = TREE_OPERAND (declarator, 0);
2438           tree fns = NULL_TREE;
2439           int idx;
2440
2441           if (constructor_name_p (name, ctype))
2442             {
2443               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2444
2445               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2446                   : !CLASSTYPE_DESTRUCTORS (ctype))
2447                 {
2448                   /* From [temp.expl.spec]:
2449
2450                      If such an explicit specialization for the member
2451                      of a class template names an implicitly-declared
2452                      special member function (clause _special_), the
2453                      program is ill-formed.
2454
2455                      Similar language is found in [temp.explicit].  */
2456                   error ("specialization of implicitly-declared special member function");
2457                   return error_mark_node;
2458                 }
2459
2460               name = is_constructor ? ctor_identifier : dtor_identifier;
2461             }
2462
2463           if (!DECL_CONV_FN_P (decl))
2464             {
2465               idx = lookup_fnfields_1 (ctype, name);
2466               if (idx >= 0)
2467                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2468             }
2469           else
2470             {
2471               VEC(tree,gc) *methods;
2472               tree ovl;
2473
2474               /* For a type-conversion operator, we cannot do a
2475                  name-based lookup.  We might be looking for `operator
2476                  int' which will be a specialization of `operator T'.
2477                  So, we find *all* the conversion operators, and then
2478                  select from them.  */
2479               fns = NULL_TREE;
2480
2481               methods = CLASSTYPE_METHOD_VEC (ctype);
2482               if (methods)
2483                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2484                      VEC_iterate (tree, methods, idx, ovl);
2485                      ++idx)
2486                   {
2487                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2488                       /* There are no more conversion functions.  */
2489                       break;
2490
2491                     /* Glue all these conversion functions together
2492                        with those we already have.  */
2493                     for (; ovl; ovl = OVL_NEXT (ovl))
2494                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2495                   }
2496             }
2497
2498           if (fns == NULL_TREE)
2499             {
2500               error ("no member function %qD declared in %qT", name, ctype);
2501               return error_mark_node;
2502             }
2503           else
2504             TREE_OPERAND (declarator, 0) = fns;
2505         }
2506
2507       /* Figure out what exactly is being specialized at this point.
2508          Note that for an explicit instantiation, even one for a
2509          member function, we cannot tell apriori whether the
2510          instantiation is for a member template, or just a member
2511          function of a template class.  Even if a member template is
2512          being instantiated, the member template arguments may be
2513          elided if they can be deduced from the rest of the
2514          declaration.  */
2515       tmpl = determine_specialization (declarator, decl,
2516                                        &targs,
2517                                        member_specialization,
2518                                        template_count,
2519                                        tsk);
2520
2521       if (!tmpl || tmpl == error_mark_node)
2522         /* We couldn't figure out what this declaration was
2523            specializing.  */
2524         return error_mark_node;
2525       else
2526         {
2527           tree gen_tmpl = most_general_template (tmpl);
2528
2529           if (explicit_instantiation)
2530             {
2531               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2532                  is done by do_decl_instantiation later.  */
2533
2534               int arg_depth = TMPL_ARGS_DEPTH (targs);
2535               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2536
2537               if (arg_depth > parm_depth)
2538                 {
2539                   /* If TMPL is not the most general template (for
2540                      example, if TMPL is a friend template that is
2541                      injected into namespace scope), then there will
2542                      be too many levels of TARGS.  Remove some of them
2543                      here.  */
2544                   int i;
2545                   tree new_targs;
2546
2547                   new_targs = make_tree_vec (parm_depth);
2548                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2549                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2550                       = TREE_VEC_ELT (targs, i);
2551                   targs = new_targs;
2552                 }
2553
2554               return instantiate_template (tmpl, targs, tf_error);
2555             }
2556
2557           /* If we thought that the DECL was a member function, but it
2558              turns out to be specializing a static member function,
2559              make DECL a static member function as well.  */
2560           if (DECL_STATIC_FUNCTION_P (tmpl)
2561               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2562             revert_static_member_fn (decl);
2563
2564           /* If this is a specialization of a member template of a
2565              template class, we want to return the TEMPLATE_DECL, not
2566              the specialization of it.  */
2567           if (tsk == tsk_template)
2568             {
2569               tree result = DECL_TEMPLATE_RESULT (tmpl);
2570               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2571               DECL_INITIAL (result) = NULL_TREE;
2572               if (have_def)
2573                 {
2574                   tree parm;
2575                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2576                   DECL_SOURCE_LOCATION (result)
2577                     = DECL_SOURCE_LOCATION (decl);
2578                   /* We want to use the argument list specified in the
2579                      definition, not in the original declaration.  */
2580                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2581                   for (parm = DECL_ARGUMENTS (result); parm;
2582                        parm = DECL_CHAIN (parm))
2583                     DECL_CONTEXT (parm) = result;
2584                 }
2585               return register_specialization (tmpl, gen_tmpl, targs,
2586                                               is_friend, 0);
2587             }
2588
2589           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2590           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2591
2592           /* Inherit default function arguments from the template
2593              DECL is specializing.  */
2594           copy_default_args_to_explicit_spec (decl);
2595
2596           /* This specialization has the same protection as the
2597              template it specializes.  */
2598           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2599           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2600
2601           /* 7.1.1-1 [dcl.stc]
2602
2603              A storage-class-specifier shall not be specified in an
2604              explicit specialization...
2605
2606              The parser rejects these, so unless action is taken here,
2607              explicit function specializations will always appear with
2608              global linkage.
2609
2610              The action recommended by the C++ CWG in response to C++
2611              defect report 605 is to make the storage class and linkage
2612              of the explicit specialization match the templated function:
2613
2614              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2615            */
2616           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2617             {
2618               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2619               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2620
2621               /* This specialization has the same linkage and visibility as
2622                  the function template it specializes.  */
2623               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2624               if (! TREE_PUBLIC (decl))
2625                 {
2626                   DECL_INTERFACE_KNOWN (decl) = 1;
2627                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2628                 }
2629               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2630               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2631                 {
2632                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2633                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2634                 }
2635             }
2636
2637           /* If DECL is a friend declaration, declared using an
2638              unqualified name, the namespace associated with DECL may
2639              have been set incorrectly.  For example, in:
2640
2641                template <typename T> void f(T);
2642                namespace N {
2643                  struct S { friend void f<int>(int); }
2644                }
2645
2646              we will have set the DECL_CONTEXT for the friend
2647              declaration to N, rather than to the global namespace.  */
2648           if (DECL_NAMESPACE_SCOPE_P (decl))
2649             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2650
2651           if (is_friend && !have_def)
2652             /* This is not really a declaration of a specialization.
2653                It's just the name of an instantiation.  But, it's not
2654                a request for an instantiation, either.  */
2655             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2656           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2657             /* This is indeed a specialization.  In case of constructors
2658                and destructors, we need in-charge and not-in-charge
2659                versions in V3 ABI.  */
2660             clone_function_decl (decl, /*update_method_vec_p=*/0);
2661
2662           /* Register this specialization so that we can find it
2663              again.  */
2664           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2665         }
2666     }
2667
2668   return decl;
2669 }
2670
2671 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2672    parameters.  These are represented in the same format used for
2673    DECL_TEMPLATE_PARMS.  */
2674
2675 int
2676 comp_template_parms (const_tree parms1, const_tree parms2)
2677 {
2678   const_tree p1;
2679   const_tree p2;
2680
2681   if (parms1 == parms2)
2682     return 1;
2683
2684   for (p1 = parms1, p2 = parms2;
2685        p1 != NULL_TREE && p2 != NULL_TREE;
2686        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2687     {
2688       tree t1 = TREE_VALUE (p1);
2689       tree t2 = TREE_VALUE (p2);
2690       int i;
2691
2692       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2693       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2694
2695       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2696         return 0;
2697
2698       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2699         {
2700           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2701           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2702
2703           /* If either of the template parameters are invalid, assume
2704              they match for the sake of error recovery. */
2705           if (parm1 == error_mark_node || parm2 == error_mark_node)
2706             return 1;
2707
2708           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2709             return 0;
2710
2711           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2712               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2713                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2714             continue;
2715           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2716             return 0;
2717         }
2718     }
2719
2720   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2721     /* One set of parameters has more parameters lists than the
2722        other.  */
2723     return 0;
2724
2725   return 1;
2726 }
2727
2728 /* Determine whether PARM is a parameter pack.  */
2729
2730 bool 
2731 template_parameter_pack_p (const_tree parm)
2732 {
2733   /* Determine if we have a non-type template parameter pack.  */
2734   if (TREE_CODE (parm) == PARM_DECL)
2735     return (DECL_TEMPLATE_PARM_P (parm) 
2736             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2737
2738   /* If this is a list of template parameters, we could get a
2739      TYPE_DECL or a TEMPLATE_DECL.  */ 
2740   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2741     parm = TREE_TYPE (parm);
2742
2743   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2744            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2745           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2746 }
2747
2748 /* Determine if T is a function parameter pack.  */
2749
2750 bool
2751 function_parameter_pack_p (const_tree t)
2752 {
2753   if (t && TREE_CODE (t) == PARM_DECL)
2754     return FUNCTION_PARAMETER_PACK_P (t);
2755   return false;
2756 }
2757
2758 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2759    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2760
2761 tree
2762 get_function_template_decl (const_tree primary_func_tmpl_inst)
2763 {
2764   if (! primary_func_tmpl_inst
2765       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2766       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2767     return NULL;
2768
2769   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2770 }
2771
2772 /* Return true iff the function parameter PARAM_DECL was expanded
2773    from the function parameter pack PACK.  */
2774
2775 bool
2776 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2777 {
2778   if (DECL_ARTIFICIAL (param_decl)
2779       || !function_parameter_pack_p (pack))
2780     return false;
2781
2782   /* The parameter pack and its pack arguments have the same
2783      DECL_PARM_INDEX.  */
2784   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2785 }
2786
2787 /* Determine whether ARGS describes a variadic template args list,
2788    i.e., one that is terminated by a template argument pack.  */
2789
2790 static bool 
2791 template_args_variadic_p (tree args)
2792 {
2793   int nargs;
2794   tree last_parm;
2795
2796   if (args == NULL_TREE)
2797     return false;
2798
2799   args = INNERMOST_TEMPLATE_ARGS (args);
2800   nargs = TREE_VEC_LENGTH (args);
2801
2802   if (nargs == 0)
2803     return false;
2804
2805   last_parm = TREE_VEC_ELT (args, nargs - 1);
2806
2807   return ARGUMENT_PACK_P (last_parm);
2808 }
2809
2810 /* Generate a new name for the parameter pack name NAME (an
2811    IDENTIFIER_NODE) that incorporates its */
2812
2813 static tree
2814 make_ith_pack_parameter_name (tree name, int i)
2815 {
2816   /* Munge the name to include the parameter index.  */
2817 #define NUMBUF_LEN 128
2818   char numbuf[NUMBUF_LEN];
2819   char* newname;
2820   int newname_len;
2821
2822   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2823   newname_len = IDENTIFIER_LENGTH (name)
2824                 + strlen (numbuf) + 2;
2825   newname = (char*)alloca (newname_len);
2826   snprintf (newname, newname_len,
2827             "%s#%i", IDENTIFIER_POINTER (name), i);
2828   return get_identifier (newname);
2829 }
2830
2831 /* Return true if T is a primary function
2832    or class template instantiation.  */
2833
2834 bool
2835 primary_template_instantiation_p (const_tree t)
2836 {
2837   if (!t)
2838     return false;
2839
2840   if (TREE_CODE (t) == FUNCTION_DECL)
2841     return DECL_LANG_SPECIFIC (t)
2842            && DECL_TEMPLATE_INSTANTIATION (t)
2843            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2844   else if (CLASS_TYPE_P (t))
2845     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2846            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2847   return false;
2848 }
2849
2850 /* Return true if PARM is a template template parameter.  */
2851
2852 bool
2853 template_template_parameter_p (const_tree parm)
2854 {
2855   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2856 }
2857
2858 /* Return the template parameters of T if T is a
2859    primary template instantiation, NULL otherwise.  */
2860
2861 tree
2862 get_primary_template_innermost_parameters (const_tree t)
2863 {
2864   tree parms = NULL, template_info = NULL;
2865
2866   if ((template_info = get_template_info (t))
2867       && primary_template_instantiation_p (t))
2868     parms = INNERMOST_TEMPLATE_PARMS
2869         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2870
2871   return parms;
2872 }
2873
2874 /* Return the template parameters of the LEVELth level from the full list
2875    of template parameters PARMS.  */
2876
2877 tree
2878 get_template_parms_at_level (tree parms, int level)
2879 {
2880   tree p;
2881   if (!parms
2882       || TREE_CODE (parms) != TREE_LIST
2883       || level > TMPL_PARMS_DEPTH (parms))
2884     return NULL_TREE;
2885
2886   for (p = parms; p; p = TREE_CHAIN (p))
2887     if (TMPL_PARMS_DEPTH (p) == level)
2888       return p;
2889
2890   return NULL_TREE;
2891 }
2892
2893 /* Returns the template arguments of T if T is a template instantiation,
2894    NULL otherwise.  */
2895
2896 tree
2897 get_template_innermost_arguments (const_tree t)
2898 {
2899   tree args = NULL, template_info = NULL;
2900
2901   if ((template_info = get_template_info (t))
2902       && TI_ARGS (template_info))
2903     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2904
2905   return args;
2906 }
2907
2908 /* Return the argument pack elements of T if T is a template argument pack,
2909    NULL otherwise.  */
2910
2911 tree
2912 get_template_argument_pack_elems (const_tree t)
2913 {
2914   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2915       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2916     return NULL;
2917
2918   return ARGUMENT_PACK_ARGS (t);
2919 }
2920
2921 /* Structure used to track the progress of find_parameter_packs_r.  */
2922 struct find_parameter_pack_data 
2923 {
2924   /* TREE_LIST that will contain all of the parameter packs found by
2925      the traversal.  */
2926   tree* parameter_packs;
2927
2928   /* Set of AST nodes that have been visited by the traversal.  */
2929   struct pointer_set_t *visited;
2930 };
2931
2932 /* Identifies all of the argument packs that occur in a template
2933    argument and appends them to the TREE_LIST inside DATA, which is a
2934    find_parameter_pack_data structure. This is a subroutine of
2935    make_pack_expansion and uses_parameter_packs.  */
2936 static tree
2937 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2938 {
2939   tree t = *tp;
2940   struct find_parameter_pack_data* ppd = 
2941     (struct find_parameter_pack_data*)data;
2942   bool parameter_pack_p = false;
2943
2944   /* Identify whether this is a parameter pack or not.  */
2945   switch (TREE_CODE (t))
2946     {
2947     case TEMPLATE_PARM_INDEX:
2948       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2949         parameter_pack_p = true;
2950       break;
2951
2952     case TEMPLATE_TYPE_PARM:
2953     case TEMPLATE_TEMPLATE_PARM:
2954       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2955         parameter_pack_p = true;
2956       break;
2957
2958     case PARM_DECL:
2959       if (FUNCTION_PARAMETER_PACK_P (t))
2960         {
2961           /* We don't want to walk into the type of a PARM_DECL,
2962              because we don't want to see the type parameter pack.  */
2963           *walk_subtrees = 0;
2964           parameter_pack_p = true;
2965         }
2966       break;
2967
2968     default:
2969       /* Not a parameter pack.  */
2970       break;
2971     }
2972
2973   if (parameter_pack_p)
2974     {
2975       /* Add this parameter pack to the list.  */
2976       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2977     }
2978
2979   if (TYPE_P (t))
2980     cp_walk_tree (&TYPE_CONTEXT (t), 
2981                   &find_parameter_packs_r, ppd, ppd->visited);
2982
2983   /* This switch statement will return immediately if we don't find a
2984      parameter pack.  */
2985   switch (TREE_CODE (t)) 
2986     {
2987     case TEMPLATE_PARM_INDEX:
2988       return NULL_TREE;
2989
2990     case BOUND_TEMPLATE_TEMPLATE_PARM:
2991       /* Check the template itself.  */
2992       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2993                     &find_parameter_packs_r, ppd, ppd->visited);
2994       /* Check the template arguments.  */
2995       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2996                     ppd->visited);
2997       *walk_subtrees = 0;
2998       return NULL_TREE;
2999
3000     case TEMPLATE_TYPE_PARM:
3001     case TEMPLATE_TEMPLATE_PARM:
3002       return NULL_TREE;
3003
3004     case PARM_DECL:
3005       return NULL_TREE;
3006
3007     case RECORD_TYPE:
3008       if (TYPE_PTRMEMFUNC_P (t))
3009         return NULL_TREE;
3010       /* Fall through.  */
3011
3012     case UNION_TYPE:
3013     case ENUMERAL_TYPE:
3014       if (TYPE_TEMPLATE_INFO (t))
3015         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
3016                       &find_parameter_packs_r, ppd, ppd->visited);
3017
3018       *walk_subtrees = 0;
3019       return NULL_TREE;
3020
3021     case TEMPLATE_DECL:
3022       cp_walk_tree (&TREE_TYPE (t),
3023                     &find_parameter_packs_r, ppd, ppd->visited);
3024       return NULL_TREE;
3025  
3026     case TYPENAME_TYPE:
3027       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3028                    ppd, ppd->visited);
3029       *walk_subtrees = 0;
3030       return NULL_TREE;
3031       
3032     case TYPE_PACK_EXPANSION:
3033     case EXPR_PACK_EXPANSION:
3034       *walk_subtrees = 0;
3035       return NULL_TREE;
3036
3037     case INTEGER_TYPE:
3038       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
3039                     ppd, ppd->visited);
3040       *walk_subtrees = 0;
3041       return NULL_TREE;
3042
3043     case IDENTIFIER_NODE:
3044       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
3045                     ppd->visited);
3046       *walk_subtrees = 0;
3047       return NULL_TREE;
3048
3049     default:
3050       return NULL_TREE;
3051     }
3052
3053   return NULL_TREE;
3054 }
3055
3056 /* Determines if the expression or type T uses any parameter packs.  */
3057 bool
3058 uses_parameter_packs (tree t)
3059 {
3060   tree parameter_packs = NULL_TREE;
3061   struct find_parameter_pack_data ppd;
3062   ppd.parameter_packs = &parameter_packs;
3063   ppd.visited = pointer_set_create ();
3064   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3065   pointer_set_destroy (ppd.visited);
3066   return parameter_packs != NULL_TREE;
3067 }
3068
3069 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3070    representation a base-class initializer into a parameter pack
3071    expansion. If all goes well, the resulting node will be an
3072    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3073    respectively.  */
3074 tree 
3075 make_pack_expansion (tree arg)
3076 {
3077   tree result;
3078   tree parameter_packs = NULL_TREE;
3079   bool for_types = false;
3080   struct find_parameter_pack_data ppd;
3081
3082   if (!arg || arg == error_mark_node)
3083     return arg;
3084
3085   if (TREE_CODE (arg) == TREE_LIST)
3086     {
3087       /* The only time we will see a TREE_LIST here is for a base
3088          class initializer.  In this case, the TREE_PURPOSE will be a
3089          _TYPE node (representing the base class expansion we're
3090          initializing) and the TREE_VALUE will be a TREE_LIST
3091          containing the initialization arguments. 
3092
3093          The resulting expansion looks somewhat different from most
3094          expansions. Rather than returning just one _EXPANSION, we
3095          return a TREE_LIST whose TREE_PURPOSE is a
3096          TYPE_PACK_EXPANSION containing the bases that will be
3097          initialized.  The TREE_VALUE will be identical to the
3098          original TREE_VALUE, which is a list of arguments that will
3099          be passed to each base.  We do not introduce any new pack
3100          expansion nodes into the TREE_VALUE (although it is possible
3101          that some already exist), because the TREE_PURPOSE and
3102          TREE_VALUE all need to be expanded together with the same
3103          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3104          resulting TREE_PURPOSE will mention the parameter packs in
3105          both the bases and the arguments to the bases.  */
3106       tree purpose;
3107       tree value;
3108       tree parameter_packs = NULL_TREE;
3109
3110       /* Determine which parameter packs will be used by the base
3111          class expansion.  */
3112       ppd.visited = pointer_set_create ();
3113       ppd.parameter_packs = &parameter_packs;
3114       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3115                     &ppd, ppd.visited);
3116
3117       if (parameter_packs == NULL_TREE)
3118         {
3119           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3120           pointer_set_destroy (ppd.visited);
3121           return error_mark_node;
3122         }
3123
3124       if (TREE_VALUE (arg) != void_type_node)
3125         {
3126           /* Collect the sets of parameter packs used in each of the
3127              initialization arguments.  */
3128           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3129             {
3130               /* Determine which parameter packs will be expanded in this
3131                  argument.  */
3132               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3133                             &ppd, ppd.visited);
3134             }
3135         }
3136
3137       pointer_set_destroy (ppd.visited);
3138
3139       /* Create the pack expansion type for the base type.  */
3140       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3141       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3142       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3143
3144       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3145          they will rarely be compared to anything.  */
3146       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3147
3148       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3149     }
3150
3151   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3152     for_types = true;
3153
3154   /* Build the PACK_EXPANSION_* node.  */
3155   result = for_types
3156      ? cxx_make_type (TYPE_PACK_EXPANSION)
3157      : make_node (EXPR_PACK_EXPANSION);
3158   SET_PACK_EXPANSION_PATTERN (result, arg);
3159   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3160     {
3161       /* Propagate type and const-expression information.  */
3162       TREE_TYPE (result) = TREE_TYPE (arg);
3163       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3164     }
3165   else
3166     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3167        they will rarely be compared to anything.  */
3168     SET_TYPE_STRUCTURAL_EQUALITY (result);
3169
3170   /* Determine which parameter packs will be expanded.  */
3171   ppd.parameter_packs = &parameter_packs;
3172   ppd.visited = pointer_set_create ();
3173   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3174   pointer_set_destroy (ppd.visited);
3175
3176   /* Make sure we found some parameter packs.  */
3177   if (parameter_packs == NULL_TREE)
3178     {
3179       if (TYPE_P (arg))
3180         error ("expansion pattern %<%T%> contains no argument packs", arg);
3181       else
3182         error ("expansion pattern %<%E%> contains no argument packs", arg);
3183       return error_mark_node;
3184     }
3185   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3186
3187   return result;
3188 }
3189
3190 /* Checks T for any "bare" parameter packs, which have not yet been
3191    expanded, and issues an error if any are found. This operation can
3192    only be done on full expressions or types (e.g., an expression
3193    statement, "if" condition, etc.), because we could have expressions like:
3194
3195      foo(f(g(h(args)))...)
3196
3197    where "args" is a parameter pack. check_for_bare_parameter_packs
3198    should not be called for the subexpressions args, h(args),
3199    g(h(args)), or f(g(h(args))), because we would produce erroneous
3200    error messages. 
3201
3202    Returns TRUE and emits an error if there were bare parameter packs,
3203    returns FALSE otherwise.  */
3204 bool 
3205 check_for_bare_parameter_packs (tree t)
3206 {
3207   tree parameter_packs = NULL_TREE;
3208   struct find_parameter_pack_data ppd;
3209
3210   if (!processing_template_decl || !t || t == error_mark_node)
3211     return false;
3212
3213   if (TREE_CODE (t) == TYPE_DECL)
3214     t = TREE_TYPE (t);
3215
3216   ppd.parameter_packs = &parameter_packs;
3217   ppd.visited = pointer_set_create ();
3218   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3219   pointer_set_destroy (ppd.visited);
3220
3221   if (parameter_packs) 
3222     {
3223       error ("parameter packs not expanded with %<...%>:");
3224       while (parameter_packs)
3225         {
3226           tree pack = TREE_VALUE (parameter_packs);
3227           tree name = NULL_TREE;
3228
3229           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3230               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3231             name = TYPE_NAME (pack);
3232           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3233             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3234           else
3235             name = DECL_NAME (pack);
3236
3237           if (name)
3238             inform (input_location, "        %qD", name);
3239           else
3240             inform (input_location, "        <anonymous>");
3241
3242           parameter_packs = TREE_CHAIN (parameter_packs);
3243         }
3244
3245       return true;
3246     }
3247
3248   return false;
3249 }
3250
3251 /* Expand any parameter packs that occur in the template arguments in
3252    ARGS.  */
3253 tree
3254 expand_template_argument_pack (tree args)
3255 {
3256   tree result_args = NULL_TREE;
3257   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3258   int num_result_args = -1;
3259   int non_default_args_count = -1;
3260
3261   /* First, determine if we need to expand anything, and the number of
3262      slots we'll need.  */
3263   for (in_arg = 0; in_arg < nargs; ++in_arg)
3264     {
3265       tree arg = TREE_VEC_ELT (args, in_arg);
3266       if (arg == NULL_TREE)
3267         return args;
3268       if (ARGUMENT_PACK_P (arg))
3269         {
3270           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3271           if (num_result_args < 0)
3272             num_result_args = in_arg + num_packed;
3273           else
3274             num_result_args += num_packed;
3275         }
3276       else
3277         {
3278           if (num_result_args >= 0)
3279             num_result_args++;
3280         }
3281     }
3282
3283   /* If no expansion is necessary, we're done.  */
3284   if (num_result_args < 0)
3285     return args;
3286
3287   /* Expand arguments.  */
3288   result_args = make_tree_vec (num_result_args);
3289   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3290     non_default_args_count =
3291       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3292   for (in_arg = 0; in_arg < nargs; ++in_arg)
3293     {
3294       tree arg = TREE_VEC_ELT (args, in_arg);
3295       if (ARGUMENT_PACK_P (arg))
3296         {
3297           tree packed = ARGUMENT_PACK_ARGS (arg);
3298           int i, num_packed = TREE_VEC_LENGTH (packed);
3299           for (i = 0; i < num_packed; ++i, ++out_arg)
3300             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3301           if (non_default_args_count > 0)
3302             non_default_args_count += num_packed;
3303         }
3304       else
3305         {
3306           TREE_VEC_ELT (result_args, out_arg) = arg;
3307           ++out_arg;
3308         }
3309     }
3310   if (non_default_args_count >= 0)
3311     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3312   return result_args;
3313 }
3314
3315 /* Checks if DECL shadows a template parameter.
3316
3317    [temp.local]: A template-parameter shall not be redeclared within its
3318    scope (including nested scopes).
3319
3320    Emits an error and returns TRUE if the DECL shadows a parameter,
3321    returns FALSE otherwise.  */
3322
3323 bool
3324 check_template_shadow (tree decl)
3325 {
3326   tree olddecl;
3327
3328   /* If we're not in a template, we can't possibly shadow a template
3329      parameter.  */
3330   if (!current_template_parms)
3331     return true;
3332
3333   /* Figure out what we're shadowing.  */
3334   if (TREE_CODE (decl) == OVERLOAD)
3335     decl = OVL_CURRENT (decl);
3336   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3337
3338   /* If there's no previous binding for this name, we're not shadowing
3339      anything, let alone a template parameter.  */
3340   if (!olddecl)
3341     return true;
3342
3343   /* If we're not shadowing a template parameter, we're done.  Note
3344      that OLDDECL might be an OVERLOAD (or perhaps even an
3345      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3346      node.  */
3347   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3348     return true;
3349
3350   /* We check for decl != olddecl to avoid bogus errors for using a
3351      name inside a class.  We check TPFI to avoid duplicate errors for
3352      inline member templates.  */
3353   if (decl == olddecl
3354       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3355     return true;
3356
3357   error ("declaration of %q+#D", decl);
3358   error (" shadows template parm %q+#D", olddecl);
3359   return false;
3360 }
3361
3362 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3363    ORIG_LEVEL, DECL, and TYPE.  NUM_SIBLINGS is the total number of
3364    template parameters.  */
3365
3366 static tree
3367 build_template_parm_index (int index,
3368                            int level,
3369                            int orig_level,
3370                            int num_siblings,
3371                            tree decl,
3372                            tree type)
3373 {
3374   tree t = make_node (TEMPLATE_PARM_INDEX);
3375   TEMPLATE_PARM_IDX (t) = index;
3376   TEMPLATE_PARM_LEVEL (t) = level;
3377   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3378   TEMPLATE_PARM_NUM_SIBLINGS (t) = num_siblings;
3379   TEMPLATE_PARM_DECL (t) = decl;
3380   TREE_TYPE (t) = type;
3381   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3382   TREE_READONLY (t) = TREE_READONLY (decl);
3383
3384   return t;
3385 }
3386
3387 /* Find the canonical type parameter for the given template type
3388    parameter.  Returns the canonical type parameter, which may be TYPE
3389    if no such parameter existed.  */
3390
3391 static tree
3392 canonical_type_parameter (tree type)
3393 {
3394   tree list;
3395   int idx = TEMPLATE_TYPE_IDX (type);
3396   if (!canonical_template_parms)
3397     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3398
3399   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3400     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3401
3402   list = VEC_index (tree, canonical_template_parms, idx);
3403   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3404     list = TREE_CHAIN (list);
3405
3406   if (list)
3407     return TREE_VALUE (list);
3408   else
3409     {
3410       VEC_replace(tree, canonical_template_parms, idx,
3411                   tree_cons (NULL_TREE, type, 
3412                              VEC_index (tree, canonical_template_parms, idx)));
3413       return type;
3414     }
3415 }
3416
3417 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3418    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3419    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3420    new one is created.  */
3421
3422 static tree
3423 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3424                             tsubst_flags_t complain)
3425 {
3426   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3427       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3428           != TEMPLATE_PARM_LEVEL (index) - levels)
3429       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3430     {
3431       tree orig_decl = TEMPLATE_PARM_DECL (index);
3432       tree decl, t;
3433
3434       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3435                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3436       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3437       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3438       DECL_ARTIFICIAL (decl) = 1;
3439       SET_DECL_TEMPLATE_PARM_P (decl);
3440
3441       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3442                                      TEMPLATE_PARM_LEVEL (index) - levels,
3443                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3444                                      TEMPLATE_PARM_NUM_SIBLINGS (index),
3445                                      decl, type);
3446       TEMPLATE_PARM_DESCENDANTS (index) = t;
3447       TEMPLATE_PARM_PARAMETER_PACK (t) 
3448         = TEMPLATE_PARM_PARAMETER_PACK (index);
3449
3450         /* Template template parameters need this.  */
3451       if (TREE_CODE (decl) == TEMPLATE_DECL)
3452         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3453           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3454            args, complain);
3455     }
3456
3457   return TEMPLATE_PARM_DESCENDANTS (index);
3458 }
3459
3460 /* Process information from new template parameter PARM and append it
3461    to the LIST being built.  This new parameter is a non-type
3462    parameter iff IS_NON_TYPE is true. This new parameter is a
3463    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
3464    is in PARM_LOC. NUM_TEMPLATE_PARMS is the size of the template
3465    parameter list PARM belongs to. This is used used to create a
3466    proper canonical type for the type of PARM that is to be created,
3467    iff PARM is a type.  If the size is not known, this parameter shall
3468    be set to 0.  */
3469
3470 tree
3471 process_template_parm (tree list, location_t parm_loc, tree parm,
3472                        bool is_non_type, bool is_parameter_pack,
3473                        unsigned num_template_parms)
3474 {
3475   tree decl = 0;
3476   tree defval;
3477   tree err_parm_list;
3478   int idx = 0;
3479
3480   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3481   defval = TREE_PURPOSE (parm);
3482
3483   if (list)
3484     {
3485       tree p = tree_last (list);
3486
3487       if (p && TREE_VALUE (p) != error_mark_node)
3488         {
3489           p = TREE_VALUE (p);
3490           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3491             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3492           else
3493             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3494         }
3495
3496       ++idx;
3497     }
3498   else
3499     idx = 0;
3500
3501   if (is_non_type)
3502     {
3503       parm = TREE_VALUE (parm);
3504
3505       SET_DECL_TEMPLATE_PARM_P (parm);
3506
3507       if (TREE_TYPE (parm) == error_mark_node)
3508         {
3509           err_parm_list = build_tree_list (defval, parm);
3510           TREE_VALUE (err_parm_list) = error_mark_node;
3511            return chainon (list, err_parm_list);
3512         }
3513       else
3514       {
3515         /* [temp.param]
3516
3517            The top-level cv-qualifiers on the template-parameter are
3518            ignored when determining its type.  */
3519         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3520         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3521           {
3522             err_parm_list = build_tree_list (defval, parm);
3523             TREE_VALUE (err_parm_list) = error_mark_node;
3524              return chainon (list, err_parm_list);
3525           }
3526
3527         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3528           {
3529             /* This template parameter is not a parameter pack, but it
3530                should be. Complain about "bare" parameter packs.  */
3531             check_for_bare_parameter_packs (TREE_TYPE (parm));
3532             
3533             /* Recover by calling this a parameter pack.  */
3534             is_parameter_pack = true;
3535           }
3536       }
3537
3538       /* A template parameter is not modifiable.  */
3539       TREE_CONSTANT (parm) = 1;
3540       TREE_READONLY (parm) = 1;
3541       decl = build_decl (parm_loc,
3542                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3543       TREE_CONSTANT (decl) = 1;
3544       TREE_READONLY (decl) = 1;
3545       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3546         = build_template_parm_index (idx, processing_template_decl,
3547                                      processing_template_decl,
3548                                      num_template_parms,
3549                                      decl, TREE_TYPE (parm));
3550
3551       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3552         = is_parameter_pack;
3553     }
3554   else
3555     {
3556       tree t;
3557       parm = TREE_VALUE (TREE_VALUE (parm));
3558
3559       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3560         {
3561           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3562           /* This is for distinguishing between real templates and template
3563              template parameters */
3564           TREE_TYPE (parm) = t;
3565           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3566           decl = parm;
3567         }
3568       else
3569         {
3570           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3571           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3572           decl = build_decl (parm_loc,
3573                              TYPE_DECL, parm, t);
3574         }
3575
3576       TYPE_NAME (t) = decl;
3577       TYPE_STUB_DECL (t) = decl;
3578       parm = decl;
3579       TEMPLATE_TYPE_PARM_INDEX (t)
3580         = build_template_parm_index (idx, processing_template_decl,
3581                                      processing_template_decl,
3582                                      num_template_parms,
3583                                      decl, TREE_TYPE (parm));
3584       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3585       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3586     }
3587   DECL_ARTIFICIAL (decl) = 1;
3588   SET_DECL_TEMPLATE_PARM_P (decl);
3589   pushdecl (decl);
3590   parm = build_tree_list (defval, parm);
3591   return chainon (list, parm);
3592 }
3593
3594 /* The end of a template parameter list has been reached.  Process the
3595    tree list into a parameter vector, converting each parameter into a more
3596    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3597    as PARM_DECLs.  */
3598
3599 tree
3600 end_template_parm_list (tree parms)
3601 {
3602   int nparms;
3603   tree parm, next;
3604   tree saved_parmlist = make_tree_vec (list_length (parms));
3605
3606   current_template_parms
3607     = tree_cons (size_int (processing_template_decl),
3608                  saved_parmlist, current_template_parms);
3609
3610   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3611     {
3612       next = TREE_CHAIN (parm);
3613       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3614       TREE_CHAIN (parm) = NULL_TREE;
3615     }
3616
3617   fixup_template_parms ();
3618
3619   --processing_template_parmlist;
3620
3621   return saved_parmlist;
3622 }
3623
3624 /* Create a new type almost identical to TYPE but which has the
3625    following differences:
3626
3627      1/ T has a new TEMPLATE_PARM_INDEX that carries the new number of
3628      template sibling parameters of T.
3629
3630      2/ T has a new canonical type that matches the new number
3631      of sibling parms.
3632
3633      3/ From now on, T is going to be what lookups referring to the
3634      name of TYPE will return. No lookup should return TYPE anymore.
3635
3636    NUM_PARMS is the new number of sibling parms TYPE belongs to.
3637
3638    This is a subroutine of fixup_template_parms.  */
3639
3640 static tree
3641 fixup_template_type_parm_type (tree type, int num_parms)
3642 {
3643   tree orig_idx = TEMPLATE_TYPE_PARM_INDEX (type), idx;
3644   tree t;
3645   /* This is the decl which name is inserted into the symbol table for
3646      the template parm type. So whenever we lookup the type name, this
3647      is the DECL we get.  */
3648   tree decl;
3649
3650   /* Do not fix up the type twice.  */
3651   if (orig_idx && TEMPLATE_PARM_NUM_SIBLINGS (orig_idx) != 0)
3652     return type;
3653
3654   t = copy_type (type);
3655   decl = TYPE_NAME (t);
3656
3657   TYPE_MAIN_VARIANT (t) = t;
3658   TYPE_NEXT_VARIANT (t)= NULL_TREE;
3659   TYPE_POINTER_TO (t) = 0;
3660   TYPE_REFERENCE_TO (t) = 0;
3661
3662   idx = build_template_parm_index (TEMPLATE_PARM_IDX (orig_idx),
3663                                    TEMPLATE_PARM_LEVEL (orig_idx),
3664                                    TEMPLATE_PARM_ORIG_LEVEL (orig_idx),
3665                                    num_parms,
3666                                    decl, t);
3667   TEMPLATE_PARM_DESCENDANTS (idx) = TEMPLATE_PARM_DESCENDANTS (orig_idx);
3668   TEMPLATE_PARM_PARAMETER_PACK (idx) = TEMPLATE_PARM_PARAMETER_PACK (orig_idx);
3669   TEMPLATE_TYPE_PARM_INDEX (t) = idx;
3670
3671   TYPE_STUB_DECL (t) = decl;
3672   TEMPLATE_TYPE_DECL (t) = decl;
3673   if (TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
3674     TREE_TYPE (DECL_TEMPLATE_RESULT  (decl)) = t;
3675
3676   /* Update the type associated to the type name stored in the symbol
3677      table. Now, whenever the type name is looked up, the resulting
3678      type is properly fixed up.  */
3679   TREE_TYPE (decl) = t;
3680
3681   TYPE_CANONICAL (t) = canonical_type_parameter (t);
3682
3683   return t;
3684 }
3685
3686 /* Create and return a new TEMPLATE_PARM_INDEX that is almost
3687    identical to I, but that is fixed up as to:
3688
3689    1/ carry the number of sibling parms (NUM_PARMS) of the template
3690    parm represented by I.
3691
3692    2/ replace all references to template parm types declared before I
3693    (in the same template parm list as I) by references to template
3694    parm types contained in ARGS. ARGS should contain the list of
3695    template parms that have been fixed up so far, in a form suitable
3696    to be passed to tsubst.
3697
3698    This is a subroutine of fixup_template_parms.  */
3699
3700 static tree
3701 fixup_template_parm_index (tree i, tree args, int num_parms)
3702 {
3703   tree index, decl, type;
3704
3705   if (i == NULL_TREE
3706       || TREE_CODE (i) != TEMPLATE_PARM_INDEX
3707       /* Do not fix up the index twice.  */
3708       || (TEMPLATE_PARM_NUM_SIBLINGS (i) != 0))
3709     return i;
3710
3711   decl = TEMPLATE_PARM_DECL (i);
3712   type = TREE_TYPE (decl);
3713
3714   index = build_template_parm_index (TEMPLATE_PARM_IDX (i),
3715                                      TEMPLATE_PARM_LEVEL (i),
3716                                      TEMPLATE_PARM_ORIG_LEVEL (i),
3717                                      num_parms,
3718                                      decl, type);
3719
3720   TEMPLATE_PARM_DESCENDANTS (index) = TEMPLATE_PARM_DESCENDANTS (i);
3721   TEMPLATE_PARM_PARAMETER_PACK (index) = TEMPLATE_PARM_PARAMETER_PACK (i);
3722
3723   type = tsubst (type, args, tf_none, NULL_TREE);
3724   
3725   TREE_TYPE (decl) = type;
3726   TREE_TYPE (index) = type;
3727
3728   return index;
3729 }
3730
3731 /* 
3732    This is a subroutine of fixup_template_parms.
3733
3734    It computes the canonical type of the type of the template
3735    parameter PARM_DESC and update all references to that type so that
3736    they use the newly computed canonical type. No access check is
3737    performed during the fixup. PARM_DESC is a TREE_LIST which
3738    TREE_VALUE is the template parameter and its TREE_PURPOSE is the
3739    default argument of the template parm if any. IDX is the index of
3740    the template parameter, starting at 0. NUM_PARMS is the number of
3741    template parameters in the set PARM_DESC belongs to. ARGLIST is a
3742    TREE_VEC containing the full set of template parameters in a form
3743    suitable to be passed to substs functions as their ARGS
3744    argument. This is what current_template_args returns for a given
3745    template. The innermost vector of args in ARGLIST is the set of
3746    template parms that have been fixed up so far. This function adds
3747    the fixed up parameter into that vector.  */
3748
3749 static void
3750 fixup_template_parm (tree parm_desc,
3751                      int idx,
3752                      int num_parms,
3753                      tree arglist)
3754 {
3755   tree parm = TREE_VALUE (parm_desc);
3756   tree fixedup_args = INNERMOST_TEMPLATE_ARGS (arglist);
3757
3758   push_deferring_access_checks (dk_no_check);
3759
3760   if (TREE_CODE (parm) == TYPE_DECL)
3761     {
3762       /* PARM is a template type parameter. Fix up its type, add
3763          the fixed-up template parm to the vector of fixed-up
3764          template parms so far, and substitute the fixed-up
3765          template parms into the default argument of this
3766          parameter.  */
3767       tree t =
3768         fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
3769       TREE_TYPE (parm) = t;
3770
3771       TREE_VEC_ELT (fixedup_args, idx) = template_parm_to_arg (parm_desc);
3772     }
3773   else if (TREE_CODE (parm) == TEMPLATE_DECL)
3774     {
3775       /* PARM is a template template parameter. This is going to
3776          be interesting.  */
3777       tree tparms, targs, innermost_args;
3778       int j;
3779
3780       /* First, fix up the type of the parm.  */
3781
3782       tree t =
3783         fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
3784       TREE_TYPE (parm) = t;
3785
3786       TREE_VEC_ELT (fixedup_args, idx) =
3787         template_parm_to_arg (parm_desc);
3788
3789       /* Now we need to substitute the template parm types that
3790          have been fixed up so far into the non-type template
3791          parms of this template template parm. E.g, consider this:
3792
3793          template<class T, template<T u> class TT> class S;
3794
3795          In this case we want to substitute T into the
3796          template parameters of TT.
3797
3798          So let's walk the template parms of PARM here, and
3799          tsubst ARGLIST into into each of the template
3800          parms.   */
3801
3802       /* For this substitution we need to build the full set of
3803          template parameters and use that as arguments for the
3804          tsubsting function.  */
3805       tparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
3806
3807       /* This will contain the innermost parms of PARM into which
3808          we have substituted so far.  */
3809       innermost_args = make_tree_vec (TREE_VEC_LENGTH (tparms));
3810       targs = add_to_template_args (arglist, innermost_args);
3811       for (j = 0; j < TREE_VEC_LENGTH (tparms); ++j)
3812         {
3813           tree parameter;
3814
3815           parameter = TREE_VEC_ELT (tparms, j);
3816
3817           /* INNERMOST_ARGS needs to have at least the same number
3818              of elements as the index PARAMETER, ortherwise
3819              tsubsting into PARAMETER will result in partially
3820              instantiating it, reducing its tempate parm
3821              level. Let's tactically fill INNERMOST_ARGS for that
3822              purpose.  */
3823           TREE_VEC_ELT (innermost_args, j) =
3824             template_parm_to_arg (parameter);
3825
3826           fixup_template_parm (parameter, j,
3827                                TREE_VEC_LENGTH (tparms),
3828                                targs);
3829         }
3830     }
3831   else if (TREE_CODE (parm) == PARM_DECL)
3832     {
3833       /* PARM is a non-type template parameter. We need to:
3834
3835        * Fix up its TEMPLATE_PARM_INDEX to make it carry the
3836        proper number of sibling parameters.
3837
3838        * Make lookups of the template parameter return a reference
3839        to the fixed-up index. No lookup should return references
3840        to the former index anymore.
3841
3842        * Substitute the template parms that got fixed up so far
3843
3844        * into the type of PARM.  */
3845
3846       tree index = DECL_INITIAL (parm);
3847
3848       /* PUSHED_DECL is the decl added to the symbol table with
3849          the name of the parameter. E,g:
3850              
3851          template<class T, T u> //#0
3852          auto my_function(T t) -> decltype(u); //#1
3853
3854          Here, when looking up u at //#1, we get the decl of u
3855          resulting from the declaration in #0. This is what
3856          PUSHED_DECL is. We need to replace the reference to the
3857          old TEMPLATE_PARM_INDEX carried by PUSHED_DECL by the
3858          fixed-up TEMPLATE_PARM_INDEX.  */
3859       tree pushed_decl = TEMPLATE_PARM_DECL (index);
3860
3861       /* Let's fix up the TEMPLATE_PARM_INDEX then. Note that we must
3862          fixup the type of PUSHED_DECL as well and luckily
3863          fixup_template_parm_index does it for us too.  */
3864       tree fixed_up_index =
3865         fixup_template_parm_index (index, arglist, num_parms);
3866
3867       DECL_INITIAL (pushed_decl) = DECL_INITIAL (parm) = fixed_up_index;
3868
3869       /* Add this fixed up PARM to the template parms we've fixed
3870          up so far and use that to substitute the fixed-up
3871          template parms into the type of PARM.  */
3872       TREE_VEC_ELT (fixedup_args, idx) =
3873         template_parm_to_arg (parm_desc);
3874       TREE_TYPE (parm) = tsubst (TREE_TYPE (parm), arglist,
3875                                  tf_none, NULL_TREE);
3876     }
3877
3878   TREE_PURPOSE (parm_desc) =
3879     tsubst_template_arg (TREE_PURPOSE (parm_desc),
3880                          arglist, tf_none, parm);
3881
3882   pop_deferring_access_checks ();
3883 }
3884
3885 /* Walk current the template parms and properly compute the canonical
3886    types of the dependent types created during
3887    cp_parser_template_parameter_list.  */
3888
3889 static void
3890 fixup_template_parms (void)
3891 {
3892   tree arglist;
3893   tree parameter_vec;
3894   tree fixedup_args;
3895   int i, num_parms;
3896
3897   parameter_vec = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3898   if (parameter_vec == NULL_TREE)
3899     return;
3900
3901   num_parms = TREE_VEC_LENGTH (parameter_vec);
3902
3903   /* This vector contains the current innermost template parms that
3904      have been fixed up so far.  The form of FIXEDUP_ARGS is suitable
3905      to be passed to tsubst* functions as their ARGS argument.  */
3906   fixedup_args = make_tree_vec (num_parms);
3907
3908   /* This vector contains the full set of template parms in a form
3909      suitable to be passed to substs functions as their ARGS
3910      argument.  */
3911   arglist = current_template_args ();
3912   arglist = add_outermost_template_args (arglist, fixedup_args);
3913
3914   fixedup_args = INNERMOST_TEMPLATE_ARGS (arglist);
3915
3916   /* Let's do the proper fixup now.  */
3917   for (i = 0; i < num_parms; ++i)
3918     fixup_template_parm (TREE_VEC_ELT (parameter_vec, i),
3919                          i, num_parms, arglist);
3920 }
3921
3922 /* end_template_decl is called after a template declaration is seen.  */
3923
3924 void
3925 end_template_decl (void)
3926 {
3927   reset_specialization ();
3928
3929   if (! processing_template_decl)
3930     return;
3931
3932   /* This matches the pushlevel in begin_template_parm_list.  */
3933   finish_scope ();
3934
3935   --processing_template_decl;
3936   current_template_parms = TREE_CHAIN (current_template_parms);
3937 }
3938
3939 /* Takes a TREE_LIST representing a template parameter and convert it
3940    into an argument suitable to be passed to the type substitution
3941    functions.  Note that If the TREE_LIST contains an error_mark
3942    node, the returned argument is error_mark_node.  */
3943
3944 static tree
3945 template_parm_to_arg (tree t)
3946 {
3947
3948   if (t == NULL_TREE
3949       || TREE_CODE (t) != TREE_LIST)
3950     return t;
3951
3952   if (error_operand_p (TREE_VALUE (t)))
3953     return error_mark_node;
3954
3955   t = TREE_VALUE (t);
3956
3957   if (TREE_CODE (t) == TYPE_DECL
3958       || TREE_CODE (t) == TEMPLATE_DECL)
3959     {
3960       t = TREE_TYPE (t);
3961
3962       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3963         {
3964           /* Turn this argument into a TYPE_ARGUMENT_PACK
3965              with a single element, which expands T.  */
3966           tree vec = make_tree_vec (1);
3967 #ifdef ENABLE_CHECKING
3968           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3969             (vec, TREE_VEC_LENGTH (vec));
3970 #endif
3971           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3972
3973           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3974           SET_ARGUMENT_PACK_ARGS (t, vec);
3975         }
3976     }
3977   else
3978     {
3979       t = DECL_INITIAL (t);
3980
3981       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3982         {
3983           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3984              with a single element, which expands T.  */
3985           tree vec = make_tree_vec (1);
3986           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3987 #ifdef ENABLE_CHECKING
3988           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3989             (vec, TREE_VEC_LENGTH (vec));
3990 #endif
3991           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3992
3993           t  = make_node (NONTYPE_ARGUMENT_PACK);
3994           SET_ARGUMENT_PACK_ARGS (t, vec);
3995           TREE_TYPE (t) = type;
3996         }
3997     }
3998   return t;
3999 }
4000
4001 /* Within the declaration of a template, return all levels of template
4002    parameters that apply.  The template parameters are represented as
4003    a TREE_VEC, in the form documented in cp-tree.h for template
4004    arguments.  */
4005
4006 static tree
4007 current_template_args (void)
4008 {
4009   tree header;
4010   tree args = NULL_TREE;
4011   int length = TMPL_PARMS_DEPTH (current_template_parms);
4012   int l = length;
4013
4014   /* If there is only one level of template parameters, we do not
4015      create a TREE_VEC of TREE_VECs.  Instead, we return a single
4016      TREE_VEC containing the arguments.  */
4017   if (length > 1)
4018     args = make_tree_vec (length);
4019
4020   for (header = current_template_parms; header; header = TREE_CHAIN (header))
4021     {
4022       tree a = copy_node (TREE_VALUE (header));
4023       int i;
4024
4025       TREE_TYPE (a) = NULL_TREE;
4026       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4027         TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4028
4029 #ifdef ENABLE_CHECKING
4030       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4031 #endif
4032
4033       if (length > 1)
4034         TREE_VEC_ELT (args, --l) = a;
4035       else
4036         args = a;
4037     }
4038
4039     if (length > 1 && TREE_VEC_ELT (args, 0) == NULL_TREE)
4040       /* This can happen for template parms of a template template
4041          parameter, e.g:
4042
4043          template<template<class T, class U> class TT> struct S;
4044
4045          Consider the level of the parms of TT; T and U both have
4046          level 2; TT has no template parm of level 1. So in this case
4047          the first element of full_template_args is NULL_TREE. If we
4048          leave it like this TMPL_ARG_DEPTH on args returns 1 instead
4049          of 2. This will make tsubst wrongly consider that T and U
4050          have level 1. Instead, let's create a dummy vector as the
4051          first element of full_template_args so that TMPL_ARG_DEPTH
4052          returns the correct depth for args.  */
4053       TREE_VEC_ELT (args, 0) = make_tree_vec (1);
4054   return args;
4055 }
4056
4057 /* Update the declared TYPE by doing any lookups which were thought to be
4058    dependent, but are not now that we know the SCOPE of the declarator.  */
4059
4060 tree
4061 maybe_update_decl_type (tree orig_type, tree scope)
4062 {
4063   tree type = orig_type;
4064
4065   if (type == NULL_TREE)
4066     return type;
4067
4068   if (TREE_CODE (orig_type) == TYPE_DECL)
4069     type = TREE_TYPE (type);
4070
4071   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4072       && dependent_type_p (type)
4073       /* Don't bother building up the args in this case.  */
4074       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4075     {
4076       /* tsubst in the args corresponding to the template parameters,
4077          including auto if present.  Most things will be unchanged, but
4078          make_typename_type and tsubst_qualified_id will resolve
4079          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4080       tree args = current_template_args ();
4081       tree auto_node = type_uses_auto (type);
4082       tree pushed;
4083       if (auto_node)
4084         {
4085           tree auto_vec = make_tree_vec (1);
4086           TREE_VEC_ELT (auto_vec, 0) = auto_node;
4087           args = add_to_template_args (args, auto_vec);
4088         }
4089       pushed = push_scope (scope);
4090       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4091       if (pushed)
4092         pop_scope (scope);
4093     }
4094
4095   if (type == error_mark_node)
4096     return orig_type;
4097
4098   if (TREE_CODE (orig_type) == TYPE_DECL)
4099     {
4100       if (same_type_p (type, TREE_TYPE (orig_type)))
4101         type = orig_type;
4102       else
4103         type = TYPE_NAME (type);
4104     }
4105   return type;
4106 }
4107
4108 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4109    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
4110    a member template.  Used by push_template_decl below.  */
4111
4112 static tree
4113 build_template_decl (tree decl, tree parms, bool member_template_p)
4114 {
4115   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4116   DECL_TEMPLATE_PARMS (tmpl) = parms;
4117   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4118   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4119
4120   return tmpl;
4121 }
4122
4123 struct template_parm_data
4124 {
4125   /* The level of the template parameters we are currently
4126      processing.  */
4127   int level;
4128
4129   /* The index of the specialization argument we are currently
4130      processing.  */
4131   int current_arg;
4132
4133   /* An array whose size is the number of template parameters.  The
4134      elements are nonzero if the parameter has been used in any one
4135      of the arguments processed so far.  */
4136   int* parms;
4137
4138   /* An array whose size is the number of template arguments.  The
4139      elements are nonzero if the argument makes use of template
4140      parameters of this level.  */
4141   int* arg_uses_template_parms;
4142 };
4143
4144 /* Subroutine of push_template_decl used to see if each template
4145    parameter in a partial specialization is used in the explicit
4146    argument list.  If T is of the LEVEL given in DATA (which is
4147    treated as a template_parm_data*), then DATA->PARMS is marked
4148    appropriately.  */
4149
4150 static int
4151 mark_template_parm (tree t, void* data)
4152 {
4153   int level;
4154   int idx;
4155   struct template_parm_data* tpd = (struct template_parm_data*) data;
4156
4157   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4158     {
4159       level = TEMPLATE_PARM_LEVEL (t);
4160       idx = TEMPLATE_PARM_IDX (t);
4161     }
4162   else
4163     {
4164       level = TEMPLATE_TYPE_LEVEL (t);
4165       idx = TEMPLATE_TYPE_IDX (t);
4166     }
4167
4168   if (level == tpd->level)
4169     {
4170       tpd->parms[idx] = 1;
4171       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4172     }
4173
4174   /* Return zero so that for_each_template_parm will continue the
4175      traversal of the tree; we want to mark *every* template parm.  */
4176   return 0;
4177 }
4178
4179 /* Process the partial specialization DECL.  */
4180
4181 static tree
4182 process_partial_specialization (tree decl)
4183 {
4184   tree type = TREE_TYPE (decl);
4185   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
4186   tree specargs = CLASSTYPE_TI_ARGS (type);
4187   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4188   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4189   tree inner_parms;
4190   tree inst;
4191   int nargs = TREE_VEC_LENGTH (inner_args);
4192   int ntparms;
4193   int  i;
4194   bool did_error_intro = false;
4195   struct template_parm_data tpd;
4196   struct template_parm_data tpd2;
4197
4198   gcc_assert (current_template_parms);
4199
4200   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4201   ntparms = TREE_VEC_LENGTH (inner_parms);
4202
4203   /* We check that each of the template parameters given in the
4204      partial specialization is used in the argument list to the
4205      specialization.  For example:
4206
4207        template <class T> struct S;
4208        template <class T> struct S<T*>;
4209
4210      The second declaration is OK because `T*' uses the template
4211      parameter T, whereas
4212
4213        template <class T> struct S<int>;
4214
4215      is no good.  Even trickier is:
4216
4217        template <class T>
4218        struct S1
4219        {
4220           template <class U>
4221           struct S2;
4222           template <class U>
4223           struct S2<T>;
4224        };
4225
4226      The S2<T> declaration is actually invalid; it is a
4227      full-specialization.  Of course,
4228
4229           template <class U>
4230           struct S2<T (*)(U)>;
4231
4232      or some such would have been OK.  */
4233   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4234   tpd.parms = XALLOCAVEC (int, ntparms);
4235   memset (tpd.parms, 0, sizeof (int) * ntparms);
4236
4237   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4238   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4239   for (i = 0; i < nargs; ++i)
4240     {
4241       tpd.current_arg = i;
4242       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4243                               &mark_template_parm,
4244                               &tpd,
4245                               NULL,
4246                               /*include_nondeduced_p=*/false);
4247     }
4248   for (i = 0; i < ntparms; ++i)
4249     if (tpd.parms[i] == 0)
4250       {
4251         /* One of the template parms was not used in the
4252            specialization.  */
4253         if (!did_error_intro)
4254           {
4255             error ("template parameters not used in partial specialization:");
4256             did_error_intro = true;
4257           }
4258
4259         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
4260       }
4261
4262   if (did_error_intro)
4263     return error_mark_node;
4264
4265   /* [temp.class.spec]
4266
4267      The argument list of the specialization shall not be identical to
4268      the implicit argument list of the primary template.  */
4269   if (comp_template_args
4270       (inner_args,
4271        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
4272                                                    (maintmpl)))))
4273     error ("partial specialization %qT does not specialize any template arguments", type);
4274
4275   /* [temp.class.spec]
4276
4277      A partially specialized non-type argument expression shall not
4278      involve template parameters of the partial specialization except
4279      when the argument expression is a simple identifier.
4280
4281      The type of a template parameter corresponding to a specialized
4282      non-type argument shall not be dependent on a parameter of the
4283      specialization. 
4284
4285      Also, we verify that pack expansions only occur at the
4286      end of the argument list.  */
4287   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
4288   tpd2.parms = 0;
4289   for (i = 0; i < nargs; ++i)
4290     {
4291       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
4292       tree arg = TREE_VEC_ELT (inner_args, i);
4293       tree packed_args = NULL_TREE;
4294       int j, len = 1;
4295
4296       if (ARGUMENT_PACK_P (arg))
4297         {
4298           /* Extract the arguments from the argument pack. We'll be
4299              iterating over these in the following loop.  */
4300           packed_args = ARGUMENT_PACK_ARGS (arg);
4301           len = TREE_VEC_LENGTH (packed_args);
4302         }
4303
4304       for (j = 0; j < len; j++)
4305         {
4306           if (packed_args)
4307             /* Get the Jth argument in the parameter pack.  */
4308             arg = TREE_VEC_ELT (packed_args, j);
4309
4310           if (PACK_EXPANSION_P (arg))
4311             {
4312               /* Pack expansions must come at the end of the
4313                  argument list.  */
4314               if ((packed_args && j < len - 1)
4315                   || (!packed_args && i < nargs - 1))
4316                 {
4317                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4318                     error ("parameter pack argument %qE must be at the "
4319                            "end of the template argument list", arg);
4320                   else
4321                     error ("parameter pack argument %qT must be at the "
4322                            "end of the template argument list", arg);
4323                 }
4324             }
4325
4326           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4327             /* We only care about the pattern.  */
4328             arg = PACK_EXPANSION_PATTERN (arg);
4329
4330           if (/* These first two lines are the `non-type' bit.  */
4331               !TYPE_P (arg)
4332               && TREE_CODE (arg) != TEMPLATE_DECL
4333               /* This next line is the `argument expression is not just a
4334                  simple identifier' condition and also the `specialized
4335                  non-type argument' bit.  */
4336               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
4337             {
4338               if ((!packed_args && tpd.arg_uses_template_parms[i])
4339                   || (packed_args && uses_template_parms (arg)))
4340                 error ("template argument %qE involves template parameter(s)",
4341                        arg);
4342               else 
4343                 {
4344                   /* Look at the corresponding template parameter,
4345                      marking which template parameters its type depends
4346                      upon.  */
4347                   tree type = TREE_TYPE (parm);
4348
4349                   if (!tpd2.parms)
4350                     {
4351                       /* We haven't yet initialized TPD2.  Do so now.  */
4352                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4353                       /* The number of parameters here is the number in the
4354                          main template, which, as checked in the assertion
4355                          above, is NARGS.  */
4356                       tpd2.parms = XALLOCAVEC (int, nargs);
4357                       tpd2.level = 
4358                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4359                     }
4360
4361                   /* Mark the template parameters.  But this time, we're
4362                      looking for the template parameters of the main
4363                      template, not in the specialization.  */
4364                   tpd2.current_arg = i;
4365                   tpd2.arg_uses_template_parms[i] = 0;
4366                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4367                   for_each_template_parm (type,
4368                                           &mark_template_parm,
4369                                           &tpd2,
4370                                           NULL,
4371                                           /*include_nondeduced_p=*/false);
4372
4373                   if (tpd2.arg_uses_template_parms [i])
4374                     {
4375                       /* The type depended on some template parameters.
4376                          If they are fully specialized in the
4377                          specialization, that's OK.  */
4378                       int j;
4379                       int count = 0;
4380                       for (j = 0; j < nargs; ++j)
4381                         if (tpd2.parms[j] != 0
4382                             && tpd.arg_uses_template_parms [j])
4383                           ++count;
4384                       if (count != 0)
4385                         error_n (input_location, count,
4386                                  "type %qT of template argument %qE depends "
4387                                  "on a template parameter",
4388                                  "type %qT of template argument %qE depends "
4389                                  "on template parameters",
4390                                  type,
4391                                  arg);
4392                     }
4393                 }
4394             }
4395         }
4396     }
4397
4398   /* We should only get here once.  */
4399   gcc_assert (!COMPLETE_TYPE_P (type));
4400
4401   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4402     = tree_cons (specargs, inner_parms,
4403                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4404   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4405
4406   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
4407        inst = TREE_CHAIN (inst))
4408     {
4409       tree inst_type = TREE_VALUE (inst);
4410       if (COMPLETE_TYPE_P (inst_type)
4411           && CLASSTYPE_IMPLICIT_INSTANTIATION (inst_type))
4412         {
4413           tree spec = most_specialized_class (inst_type, maintmpl, tf_none);
4414           if (spec && TREE_TYPE (spec) == type)
4415             permerror (input_location,
4416                        "partial specialization of %qT after instantiation "
4417                        "of %qT", type, inst_type);
4418         }
4419     }
4420
4421   return decl;
4422 }
4423
4424 /* Check that a template declaration's use of default arguments and
4425    parameter packs is not invalid.  Here, PARMS are the template
4426    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
4427    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
4428    specialization.
4429    
4430
4431    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4432    declaration (but not a definition); 1 indicates a declaration, 2
4433    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4434    emitted for extraneous default arguments.
4435
4436    Returns TRUE if there were no errors found, FALSE otherwise. */
4437
4438 bool
4439 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
4440                          int is_partial, int is_friend_decl)
4441 {
4442   const char *msg;
4443   int last_level_to_check;
4444   tree parm_level;
4445   bool no_errors = true;
4446
4447   /* [temp.param]
4448
4449      A default template-argument shall not be specified in a
4450      function template declaration or a function template definition, nor
4451      in the template-parameter-list of the definition of a member of a
4452      class template.  */
4453
4454   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
4455     /* You can't have a function template declaration in a local
4456        scope, nor you can you define a member of a class template in a
4457        local scope.  */
4458     return true;
4459
4460   if (current_class_type
4461       && !TYPE_BEING_DEFINED (current_class_type)
4462       && DECL_LANG_SPECIFIC (decl)
4463       && DECL_DECLARES_FUNCTION_P (decl)
4464       /* If this is either a friend defined in the scope of the class
4465          or a member function.  */
4466       && (DECL_FUNCTION_MEMBER_P (decl)
4467           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4468           : DECL_FRIEND_CONTEXT (decl)
4469           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4470           : false)
4471       /* And, if it was a member function, it really was defined in
4472          the scope of the class.  */
4473       && (!DECL_FUNCTION_MEMBER_P (decl)
4474           || DECL_INITIALIZED_IN_CLASS_P (decl)))
4475     /* We already checked these parameters when the template was
4476        declared, so there's no need to do it again now.  This function
4477        was defined in class scope, but we're processing it's body now
4478        that the class is complete.  */
4479     return true;
4480
4481   /* Core issue 226 (C++0x only): the following only applies to class
4482      templates.  */
4483   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
4484     {
4485       /* [temp.param]
4486
4487          If a template-parameter has a default template-argument, all
4488          subsequent template-parameters shall have a default
4489          template-argument supplied.  */
4490       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4491         {
4492           tree inner_parms = TREE_VALUE (parm_level);
4493           int ntparms = TREE_VEC_LENGTH (inner_parms);
4494           int seen_def_arg_p = 0;
4495           int i;
4496
4497           for (i = 0; i < ntparms; ++i)
4498             {
4499               tree parm = TREE_VEC_ELT (inner_parms, i);
4500
4501               if (parm == error_mark_node)
4502                 continue;
4503
4504               if (TREE_PURPOSE (parm))
4505                 seen_def_arg_p = 1;
4506               else if (seen_def_arg_p
4507                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4508                 {
4509                   error ("no default argument for %qD", TREE_VALUE (parm));
4510                   /* For better subsequent error-recovery, we indicate that
4511                      there should have been a default argument.  */
4512                   TREE_PURPOSE (parm) = error_mark_node;
4513                   no_errors = false;
4514                 }
4515               else if (is_primary
4516                        && !is_partial
4517                        && !is_friend_decl
4518                        /* Don't complain about an enclosing partial
4519                           specialization.  */
4520                        && parm_level == parms
4521                        && TREE_CODE (decl) == TYPE_DECL
4522                        && i < ntparms - 1
4523                        && template_parameter_pack_p (TREE_VALUE (parm)))
4524                 {
4525                   /* A primary class template can only have one
4526                      parameter pack, at the end of the template
4527                      parameter list.  */
4528
4529                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4530                     error ("parameter pack %qE must be at the end of the"
4531                            " template parameter list", TREE_VALUE (parm));
4532                   else
4533                     error ("parameter pack %qT must be at the end of the"
4534                            " template parameter list", 
4535                            TREE_TYPE (TREE_VALUE (parm)));
4536
4537                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4538                     = error_mark_node;
4539                   no_errors = false;
4540                 }
4541             }
4542         }
4543     }
4544
4545   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4546       || is_partial 
4547       || !is_primary
4548       || is_friend_decl)
4549     /* For an ordinary class template, default template arguments are
4550        allowed at the innermost level, e.g.:
4551          template <class T = int>
4552          struct S {};
4553        but, in a partial specialization, they're not allowed even
4554        there, as we have in [temp.class.spec]:
4555
4556          The template parameter list of a specialization shall not
4557          contain default template argument values.
4558
4559        So, for a partial specialization, or for a function template
4560        (in C++98/C++03), we look at all of them.  */
4561     ;
4562   else
4563     /* But, for a primary class template that is not a partial
4564        specialization we look at all template parameters except the
4565        innermost ones.  */
4566     parms = TREE_CHAIN (parms);
4567
4568   /* Figure out what error message to issue.  */
4569   if (is_friend_decl == 2)
4570     msg = G_("default template arguments may not be used in function template "
4571              "friend re-declaration");
4572   else if (is_friend_decl)
4573     msg = G_("default template arguments may not be used in function template "
4574              "friend declarations");
4575   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4576     msg = G_("default template arguments may not be used in function templates "
4577              "without -std=c++0x or -std=gnu++0x");
4578   else if (is_partial)
4579     msg = G_("default template arguments may not be used in "
4580              "partial specializations");
4581   else
4582     msg = G_("default argument for template parameter for class enclosing %qD");
4583
4584   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4585     /* If we're inside a class definition, there's no need to
4586        examine the parameters to the class itself.  On the one
4587        hand, they will be checked when the class is defined, and,
4588        on the other, default arguments are valid in things like:
4589          template <class T = double>
4590          struct S { template <class U> void f(U); };
4591        Here the default argument for `S' has no bearing on the
4592        declaration of `f'.  */
4593     last_level_to_check = template_class_depth (current_class_type) + 1;
4594   else
4595     /* Check everything.  */
4596     last_level_to_check = 0;
4597
4598   for (parm_level = parms;
4599        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4600        parm_level = TREE_CHAIN (parm_level))
4601     {
4602       tree inner_parms = TREE_VALUE (parm_level);
4603       int i;
4604       int ntparms;
4605
4606       ntparms = TREE_VEC_LENGTH (inner_parms);
4607       for (i = 0; i < ntparms; ++i)
4608         {
4609           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4610             continue;
4611
4612           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4613             {
4614               if (msg)
4615                 {
4616                   no_errors = false;
4617                   if (is_friend_decl == 2)
4618                     return no_errors;
4619
4620                   error (msg, decl);
4621                   msg = 0;
4622                 }
4623
4624               /* Clear out the default argument so that we are not
4625                  confused later.  */
4626               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4627             }
4628         }
4629
4630       /* At this point, if we're still interested in issuing messages,
4631          they must apply to classes surrounding the object declared.  */
4632       if (msg)
4633         msg = G_("default argument for template parameter for class "
4634                  "enclosing %qD");
4635     }
4636
4637   return no_errors;
4638 }
4639
4640 /* Worker for push_template_decl_real, called via
4641    for_each_template_parm.  DATA is really an int, indicating the
4642    level of the parameters we are interested in.  If T is a template
4643    parameter of that level, return nonzero.  */
4644
4645 static int
4646 template_parm_this_level_p (tree t, void* data)
4647 {
4648   int this_level = *(int *)data;
4649   int level;
4650
4651   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4652     level = TEMPLATE_PARM_LEVEL (t);
4653   else
4654     level = TEMPLATE_TYPE_LEVEL (t);
4655   return level == this_level;
4656 }
4657
4658 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4659    parameters given by current_template_args, or reuses a
4660    previously existing one, if appropriate.  Returns the DECL, or an
4661    equivalent one, if it is replaced via a call to duplicate_decls.
4662
4663    If IS_FRIEND is true, DECL is a friend declaration.  */
4664
4665 tree
4666 push_template_decl_real (tree decl, bool is_friend)
4667 {
4668   tree tmpl;
4669   tree args;
4670   tree info;
4671   tree ctx;
4672   int primary;
4673   int is_partial;
4674   int new_template_p = 0;
4675   /* True if the template is a member template, in the sense of
4676      [temp.mem].  */
4677   bool member_template_p = false;
4678
4679   if (decl == error_mark_node || !current_template_parms)
4680     return error_mark_node;
4681
4682   /* See if this is a partial specialization.  */
4683   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4684                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4685                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4686
4687   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4688     is_friend = true;
4689
4690   if (is_friend)
4691     /* For a friend, we want the context of the friend function, not
4692        the type of which it is a friend.  */
4693     ctx = CP_DECL_CONTEXT (decl);
4694   else if (CP_DECL_CONTEXT (decl)
4695            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4696     /* In the case of a virtual function, we want the class in which
4697        it is defined.  */
4698     ctx = CP_DECL_CONTEXT (decl);
4699   else
4700     /* Otherwise, if we're currently defining some class, the DECL
4701        is assumed to be a member of the class.  */
4702     ctx = current_scope ();
4703
4704   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4705     ctx = NULL_TREE;
4706
4707   if (!DECL_CONTEXT (decl))
4708     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4709
4710   /* See if this is a primary template.  */
4711   if (is_friend && ctx)
4712     /* A friend template that specifies a class context, i.e.
4713          template <typename T> friend void A<T>::f();
4714        is not primary.  */
4715     primary = 0;
4716   else
4717     primary = template_parm_scope_p ();
4718
4719   if (primary)
4720     {
4721       if (DECL_CLASS_SCOPE_P (decl))
4722         member_template_p = true;
4723       if (TREE_CODE (decl) == TYPE_DECL
4724           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4725         {
4726           error ("template class without a name");
4727           return error_mark_node;
4728         }
4729       else if (TREE_CODE (decl) == FUNCTION_DECL)
4730         {
4731           if (DECL_DESTRUCTOR_P (decl))
4732             {
4733               /* [temp.mem]
4734
4735                  A destructor shall not be a member template.  */
4736               error ("destructor %qD declared as member template", decl);
4737               return error_mark_node;
4738             }
4739           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4740               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
4741                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4742                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4743                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4744                       == void_list_node)))
4745             {
4746               /* [basic.stc.dynamic.allocation]
4747
4748                  An allocation function can be a function
4749                  template. ... Template allocation functions shall
4750                  have two or more parameters.  */
4751               error ("invalid template declaration of %qD", decl);
4752               return error_mark_node;
4753             }
4754         }
4755       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4756                && CLASS_TYPE_P (TREE_TYPE (decl)))
4757         /* OK */;
4758       else
4759         {
4760           error ("template declaration of %q#D", decl);
4761           return error_mark_node;
4762         }
4763     }
4764
4765   /* Check to see that the rules regarding the use of default
4766      arguments are not being violated.  */
4767   check_default_tmpl_args (decl, current_template_parms,
4768                            primary, is_partial, /*is_friend_decl=*/0);
4769
4770   /* Ensure that there are no parameter packs in the type of this
4771      declaration that have not been expanded.  */
4772   if (TREE_CODE (decl) == FUNCTION_DECL)
4773     {
4774       /* Check each of the arguments individually to see if there are
4775          any bare parameter packs.  */
4776       tree type = TREE_TYPE (decl);
4777       tree arg = DECL_ARGUMENTS (decl);
4778       tree argtype = TYPE_ARG_TYPES (type);
4779
4780       while (arg && argtype)
4781         {
4782           if (!FUNCTION_PARAMETER_PACK_P (arg)
4783               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4784             {
4785             /* This is a PARM_DECL that contains unexpanded parameter
4786                packs. We have already complained about this in the
4787                check_for_bare_parameter_packs call, so just replace
4788                these types with ERROR_MARK_NODE.  */
4789               TREE_TYPE (arg) = error_mark_node;
4790               TREE_VALUE (argtype) = error_mark_node;
4791             }
4792
4793           arg = DECL_CHAIN (arg);
4794           argtype = TREE_CHAIN (argtype);
4795         }
4796
4797       /* Check for bare parameter packs in the return type and the
4798          exception specifiers.  */
4799       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4800         /* Errors were already issued, set return type to int
4801            as the frontend doesn't expect error_mark_node as
4802            the return type.  */
4803         TREE_TYPE (type) = integer_type_node;
4804       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4805         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4806     }
4807   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4808     {
4809       TREE_TYPE (decl) = error_mark_node;
4810       return error_mark_node;
4811     }
4812
4813   if (is_partial)
4814     return process_partial_specialization (decl);
4815
4816   args = current_template_args ();
4817
4818   if (!ctx
4819       || TREE_CODE (ctx) == FUNCTION_DECL
4820       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4821       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4822     {
4823       if (DECL_LANG_SPECIFIC (decl)
4824           && DECL_TEMPLATE_INFO (decl)
4825           && DECL_TI_TEMPLATE (decl))
4826         tmpl = DECL_TI_TEMPLATE (decl);
4827       /* If DECL is a TYPE_DECL for a class-template, then there won't
4828          be DECL_LANG_SPECIFIC.  The information equivalent to
4829          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4830       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4831                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4832                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4833         {
4834           /* Since a template declaration already existed for this
4835              class-type, we must be redeclaring it here.  Make sure
4836              that the redeclaration is valid.  */
4837           redeclare_class_template (TREE_TYPE (decl),
4838                                     current_template_parms);
4839           /* We don't need to create a new TEMPLATE_DECL; just use the
4840              one we already had.  */
4841           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4842         }
4843       else
4844         {
4845           tmpl = build_template_decl (decl, current_template_parms,
4846                                       member_template_p);
4847           new_template_p = 1;
4848
4849           if (DECL_LANG_SPECIFIC (decl)
4850               && DECL_TEMPLATE_SPECIALIZATION (decl))
4851             {
4852               /* A specialization of a member template of a template
4853                  class.  */
4854               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4855               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4856               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4857             }
4858         }
4859     }
4860   else
4861     {
4862       tree a, t, current, parms;
4863       int i;
4864       tree tinfo = get_template_info (decl);
4865
4866       if (!tinfo)
4867         {
4868           error ("template definition of non-template %q#D", decl);
4869           return error_mark_node;
4870         }
4871
4872       tmpl = TI_TEMPLATE (tinfo);
4873
4874       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4875           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4876           && DECL_TEMPLATE_SPECIALIZATION (decl)
4877           && DECL_MEMBER_TEMPLATE_P (tmpl))
4878         {
4879           tree new_tmpl;
4880
4881           /* The declaration is a specialization of a member
4882              template, declared outside the class.  Therefore, the
4883              innermost template arguments will be NULL, so we
4884              replace them with the arguments determined by the
4885              earlier call to check_explicit_specialization.  */
4886           args = DECL_TI_ARGS (decl);
4887
4888           new_tmpl
4889             = build_template_decl (decl, current_template_parms,
4890                                    member_template_p);
4891           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4892           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4893           DECL_TI_TEMPLATE (decl) = new_tmpl;
4894           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4895           DECL_TEMPLATE_INFO (new_tmpl)
4896             = build_template_info (tmpl, args);
4897
4898           register_specialization (new_tmpl,
4899                                    most_general_template (tmpl),
4900                                    args,
4901                                    is_friend, 0);
4902           return decl;
4903         }
4904
4905       /* Make sure the template headers we got make sense.  */
4906
4907       parms = DECL_TEMPLATE_PARMS (tmpl);
4908       i = TMPL_PARMS_DEPTH (parms);
4909       if (TMPL_ARGS_DEPTH (args) != i)
4910         {
4911           error ("expected %d levels of template parms for %q#D, got %d",
4912                  i, decl, TMPL_ARGS_DEPTH (args));
4913         }
4914       else
4915         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4916           {
4917             a = TMPL_ARGS_LEVEL (args, i);
4918             t = INNERMOST_TEMPLATE_PARMS (parms);
4919
4920             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4921               {
4922                 if (current == decl)
4923                   error ("got %d template parameters for %q#D",
4924                          TREE_VEC_LENGTH (a), decl);
4925                 else
4926                   error ("got %d template parameters for %q#T",
4927                          TREE_VEC_LENGTH (a), current);
4928                 error ("  but %d required", TREE_VEC_LENGTH (t));
4929                 return error_mark_node;
4930               }
4931
4932             if (current == decl)
4933               current = ctx;
4934             else if (current == NULL_TREE)
4935               /* Can happen in erroneous input.  */
4936               break;
4937             else
4938               current = (TYPE_P (current)
4939                          ? TYPE_CONTEXT (current)
4940                          : DECL_CONTEXT (current));
4941           }
4942
4943       /* Check that the parms are used in the appropriate qualifying scopes
4944          in the declarator.  */
4945       if (!comp_template_args
4946           (TI_ARGS (tinfo),
4947            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4948         {
4949           error ("\
4950 template arguments to %qD do not match original template %qD",
4951                  decl, DECL_TEMPLATE_RESULT (tmpl));
4952           if (!uses_template_parms (TI_ARGS (tinfo)))
4953             inform (input_location, "use template<> for an explicit specialization");
4954           /* Avoid crash in import_export_decl.  */
4955           DECL_INTERFACE_KNOWN (decl) = 1;
4956           return error_mark_node;
4957         }
4958     }
4959
4960   DECL_TEMPLATE_RESULT (tmpl) = decl;
4961   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4962
4963   /* Push template declarations for global functions and types.  Note
4964      that we do not try to push a global template friend declared in a
4965      template class; such a thing may well depend on the template
4966      parameters of the class.  */
4967   if (new_template_p && !ctx
4968       && !(is_friend && template_class_depth (current_class_type) > 0))
4969     {
4970       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4971       if (tmpl == error_mark_node)
4972         return error_mark_node;
4973
4974       /* Hide template friend classes that haven't been declared yet.  */
4975       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4976         {
4977           DECL_ANTICIPATED (tmpl) = 1;
4978           DECL_FRIEND_P (tmpl) = 1;
4979         }
4980     }
4981
4982   if (primary)
4983     {
4984       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4985       int i;
4986
4987       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4988       if (DECL_CONV_FN_P (tmpl))
4989         {
4990           int depth = TMPL_PARMS_DEPTH (parms);
4991
4992           /* It is a conversion operator. See if the type converted to
4993              depends on innermost template operands.  */
4994
4995           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4996                                          depth))
4997             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4998         }
4999
5000       /* Give template template parms a DECL_CONTEXT of the template
5001          for which they are a parameter.  */
5002       parms = INNERMOST_TEMPLATE_PARMS (parms);
5003       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
5004         {
5005           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5006           if (TREE_CODE (parm) == TEMPLATE_DECL)
5007             DECL_CONTEXT (parm) = tmpl;
5008         }
5009     }
5010
5011   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
5012      back to its most general template.  If TMPL is a specialization,
5013      ARGS may only have the innermost set of arguments.  Add the missing
5014      argument levels if necessary.  */
5015   if (DECL_TEMPLATE_INFO (tmpl))
5016     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
5017
5018   info = build_template_info (tmpl, args);
5019
5020   if (DECL_IMPLICIT_TYPEDEF_P (decl))
5021     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
5022   else if (DECL_LANG_SPECIFIC (decl))
5023     DECL_TEMPLATE_INFO (decl) = info;
5024
5025   return DECL_TEMPLATE_RESULT (tmpl);
5026 }
5027
5028 tree
5029 push_template_decl (tree decl)
5030 {
5031   return push_template_decl_real (decl, false);
5032 }
5033
5034 /* Called when a class template TYPE is redeclared with the indicated
5035    template PARMS, e.g.:
5036
5037      template <class T> struct S;
5038      template <class T> struct S {};  */
5039
5040 bool
5041 redeclare_class_template (tree type, tree parms)
5042 {
5043   tree tmpl;
5044   tree tmpl_parms;
5045   int i;
5046
5047   if (!TYPE_TEMPLATE_INFO (type))
5048     {
5049       error ("%qT is not a template type", type);
5050       return false;
5051     }
5052
5053   tmpl = TYPE_TI_TEMPLATE (type);
5054   if (!PRIMARY_TEMPLATE_P (tmpl))
5055     /* The type is nested in some template class.  Nothing to worry
5056        about here; there are no new template parameters for the nested
5057        type.  */
5058     return true;
5059
5060   if (!parms)
5061     {
5062       error ("template specifiers not specified in declaration of %qD",
5063              tmpl);
5064       return false;
5065     }
5066
5067   parms = INNERMOST_TEMPLATE_PARMS (parms);
5068   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
5069
5070   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
5071     {
5072       error_n (input_location, TREE_VEC_LENGTH (parms),
5073                "redeclared with %d template parameter",
5074                "redeclared with %d template parameters",
5075                TREE_VEC_LENGTH (parms));
5076       inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
5077                 "previous declaration %q+D used %d template parameter",
5078                 "previous declaration %q+D used %d template parameters",
5079                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
5080       return false;
5081     }
5082
5083   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
5084     {
5085       tree tmpl_parm;
5086       tree parm;
5087       tree tmpl_default;
5088       tree parm_default;
5089
5090       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
5091           || TREE_VEC_ELT (parms, i) == error_mark_node)
5092         continue;
5093
5094       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
5095       if (tmpl_parm == error_mark_node)
5096         return false;
5097
5098       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5099       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
5100       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
5101
5102       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
5103          TEMPLATE_DECL.  */
5104       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
5105           || (TREE_CODE (tmpl_parm) != TYPE_DECL
5106               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
5107           || (TREE_CODE (tmpl_parm) != PARM_DECL
5108               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
5109                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
5110           || (TREE_CODE (tmpl_parm) == PARM_DECL
5111               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
5112                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
5113         {
5114           error ("template parameter %q+#D", tmpl_parm);
5115           error ("redeclared here as %q#D", parm);
5116           return false;
5117         }
5118
5119       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
5120         {
5121           /* We have in [temp.param]:
5122
5123              A template-parameter may not be given default arguments
5124              by two different declarations in the same scope.  */
5125           error_at (input_location, "redefinition of default argument for %q#D", parm);
5126           inform (DECL_SOURCE_LOCATION (tmpl_parm),
5127                   "original definition appeared here");
5128           return false;
5129         }
5130
5131       if (parm_default != NULL_TREE)
5132         /* Update the previous template parameters (which are the ones
5133            that will really count) with the new default value.  */
5134         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
5135       else if (tmpl_default != NULL_TREE)
5136         /* Update the new parameters, too; they'll be used as the
5137            parameters for any members.  */
5138         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
5139     }
5140
5141     return true;
5142 }
5143
5144 /* Simplify EXPR if it is a non-dependent expression.  Returns the
5145    (possibly simplified) expression.  */
5146
5147 static tree
5148 fold_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
5149 {
5150   if (expr == NULL_TREE)
5151     return NULL_TREE;
5152
5153   /* If we're in a template, but EXPR isn't value dependent, simplify
5154      it.  We're supposed to treat:
5155
5156        template <typename T> void f(T[1 + 1]);
5157        template <typename T> void f(T[2]);
5158
5159      as two declarations of the same function, for example.  */
5160   if (processing_template_decl
5161       && !type_dependent_expression_p (expr)
5162       && !value_dependent_expression_p (expr))
5163     {
5164       HOST_WIDE_INT saved_processing_template_decl;
5165
5166       saved_processing_template_decl = processing_template_decl;
5167       processing_template_decl = 0;
5168       expr = tsubst_copy_and_build (expr,
5169                                     /*args=*/NULL_TREE,
5170                                     complain,
5171                                     /*in_decl=*/NULL_TREE,
5172                                     /*function_p=*/false,
5173                                     /*integral_constant_expression_p=*/true);
5174       processing_template_decl = saved_processing_template_decl;
5175     }
5176   return expr;
5177 }
5178
5179 tree
5180 fold_non_dependent_expr (tree expr)
5181 {
5182   return fold_non_dependent_expr_sfinae (expr, tf_error);
5183 }
5184
5185 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
5186    must be a function or a pointer-to-function type, as specified
5187    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
5188    and check that the resulting function has external linkage.  */
5189
5190 static tree
5191 convert_nontype_argument_function (tree type, tree expr)
5192 {
5193   tree fns = expr;
5194   tree fn, fn_no_ptr;
5195
5196   fn = instantiate_type (type, fns, tf_none);
5197   if (fn == error_mark_node)
5198     return error_mark_node;
5199
5200   fn_no_ptr = fn;
5201   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
5202     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
5203   if (TREE_CODE (fn_no_ptr) == BASELINK)
5204     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
5205  
5206   /* [temp.arg.nontype]/1
5207
5208      A template-argument for a non-type, non-template template-parameter
5209      shall be one of:
5210      [...]
5211      -- the address of an object or function with external linkage.  */
5212   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
5213     {
5214       error ("%qE is not a valid template argument for type %qT "
5215              "because function %qD has not external linkage",
5216              expr, type, fn_no_ptr);
5217       return NULL_TREE;
5218     }
5219
5220   return fn;
5221 }
5222
5223 /* Subroutine of convert_nontype_argument.
5224    Check if EXPR of type TYPE is a valid pointer-to-member constant.
5225    Emit an error otherwise.  */
5226
5227 static bool
5228 check_valid_ptrmem_cst_expr (tree type, tree expr,
5229                              tsubst_flags_t complain)
5230 {
5231   STRIP_NOPS (expr);
5232   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
5233     return true;
5234   if (complain & tf_error)
5235     {
5236       error ("%qE is not a valid template argument for type %qT",
5237              expr, type);
5238       error ("it must be a pointer-to-member of the form %<&X::Y%>");
5239     }
5240   return false;
5241 }
5242
5243 /* Returns TRUE iff the address of OP is value-dependent.
5244
5245    14.6.2.4 [temp.dep.temp]:
5246    A non-integral non-type template-argument is dependent if its type is
5247    dependent or it has either of the following forms
5248      qualified-id
5249      & qualified-id
5250    and contains a nested-name-specifier which specifies a class-name that
5251    names a dependent type.
5252
5253    We generalize this to just say that the address of a member of a
5254    dependent class is value-dependent; the above doesn't cover the
5255    address of a static data member named with an unqualified-id.  */
5256
5257 static bool
5258 has_value_dependent_address (tree op)
5259 {
5260   /* We could use get_inner_reference here, but there's no need;
5261      this is only relevant for template non-type arguments, which
5262      can only be expressed as &id-expression.  */
5263   if (DECL_P (op))
5264     {
5265       tree ctx = CP_DECL_CONTEXT (op);
5266       if (TYPE_P (ctx) && dependent_type_p (ctx))
5267         return true;
5268     }
5269
5270   return false;
5271 }
5272
5273 /* Attempt to convert the non-type template parameter EXPR to the
5274    indicated TYPE.  If the conversion is successful, return the
5275    converted value.  If the conversion is unsuccessful, return
5276    NULL_TREE if we issued an error message, or error_mark_node if we
5277    did not.  We issue error messages for out-and-out bad template
5278    parameters, but not simply because the conversion failed, since we
5279    might be just trying to do argument deduction.  Both TYPE and EXPR
5280    must be non-dependent.
5281
5282    The conversion follows the special rules described in
5283    [temp.arg.nontype], and it is much more strict than an implicit
5284    conversion.
5285
5286    This function is called twice for each template argument (see
5287    lookup_template_class for a more accurate description of this
5288    problem). This means that we need to handle expressions which
5289    are not valid in a C++ source, but can be created from the
5290    first call (for instance, casts to perform conversions). These
5291    hacks can go away after we fix the double coercion problem.  */
5292
5293 static tree
5294 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
5295 {
5296   tree expr_type;
5297
5298   /* Detect immediately string literals as invalid non-type argument.
5299      This special-case is not needed for correctness (we would easily
5300      catch this later), but only to provide better diagnostic for this
5301      common user mistake. As suggested by DR 100, we do not mention
5302      linkage issues in the diagnostic as this is not the point.  */
5303   /* FIXME we're making this OK.  */
5304   if (TREE_CODE (expr) == STRING_CST)
5305     {
5306       if (complain & tf_error)
5307         error ("%qE is not a valid template argument for type %qT "
5308                "because string literals can never be used in this context",
5309                expr, type);
5310       return NULL_TREE;
5311     }
5312
5313   /* Add the ADDR_EXPR now for the benefit of
5314      value_dependent_expression_p.  */
5315   if (TYPE_PTROBV_P (type))
5316     expr = decay_conversion (expr);
5317
5318   /* If we are in a template, EXPR may be non-dependent, but still
5319      have a syntactic, rather than semantic, form.  For example, EXPR
5320      might be a SCOPE_REF, rather than the VAR_DECL to which the
5321      SCOPE_REF refers.  Preserving the qualifying scope is necessary
5322      so that access checking can be performed when the template is
5323      instantiated -- but here we need the resolved form so that we can
5324      convert the argument.  */
5325   if (TYPE_REF_OBJ_P (type)
5326       && has_value_dependent_address (expr))
5327     /* If we want the address and it's value-dependent, don't fold.  */;
5328   else if (!type_unknown_p (expr))
5329     expr = fold_non_dependent_expr_sfinae (expr, complain);
5330   if (error_operand_p (expr))
5331     return error_mark_node;
5332   expr_type = TREE_TYPE (expr);
5333   if (TREE_CODE (type) == REFERENCE_TYPE)
5334     expr = mark_lvalue_use (expr);
5335   else
5336     expr = mark_rvalue_use (expr);
5337
5338   /* HACK: Due to double coercion, we can get a
5339      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
5340      which is the tree that we built on the first call (see
5341      below when coercing to reference to object or to reference to
5342      function). We just strip everything and get to the arg.
5343      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
5344      for examples.  */
5345   if (TREE_CODE (expr) == NOP_EXPR)
5346     {
5347       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
5348         {
5349           /* ??? Maybe we could use convert_from_reference here, but we
5350              would need to relax its constraints because the NOP_EXPR
5351              could actually change the type to something more cv-qualified,
5352              and this is not folded by convert_from_reference.  */
5353           tree addr = TREE_OPERAND (expr, 0);
5354           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
5355           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
5356           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
5357           gcc_assert (same_type_ignoring_top_level_qualifiers_p
5358                       (TREE_TYPE (expr_type),
5359                        TREE_TYPE (TREE_TYPE (addr))));
5360
5361           expr = TREE_OPERAND (addr, 0);
5362           expr_type = TREE_TYPE (expr);
5363         }
5364
5365       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
5366          parameter is a pointer to object, through decay and
5367          qualification conversion. Let's strip everything.  */
5368       else if (TYPE_PTROBV_P (type))
5369         {
5370           STRIP_NOPS (expr);
5371           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
5372           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
5373           /* Skip the ADDR_EXPR only if it is part of the decay for
5374              an array. Otherwise, it is part of the original argument
5375              in the source code.  */
5376           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
5377             expr = TREE_OPERAND (expr, 0);
5378           expr_type = TREE_TYPE (expr);
5379         }
5380     }
5381
5382   /* [temp.arg.nontype]/5, bullet 1
5383
5384      For a non-type template-parameter of integral or enumeration type,
5385      integral promotions (_conv.prom_) and integral conversions
5386      (_conv.integral_) are applied.  */
5387   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5388     {
5389       tree t = build_integral_nontype_arg_conv (type, expr, complain);
5390       t = maybe_constant_value (t);
5391       if (t != error_mark_node)
5392         expr = t;
5393
5394       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
5395         return error_mark_node;
5396
5397       /* Notice that there are constant expressions like '4 % 0' which
5398          do not fold into integer constants.  */
5399       if (TREE_CODE (expr) != INTEGER_CST)
5400         {
5401           if (complain & tf_error)
5402             {
5403               error ("%qE is not a valid template argument for type %qT "
5404                      "because it is a non-constant expression", expr, type);
5405               cxx_constant_value (expr);
5406             }
5407           return NULL_TREE;
5408         }
5409     }
5410   /* [temp.arg.nontype]/5, bullet 2
5411
5412      For a non-type template-parameter of type pointer to object,
5413      qualification conversions (_conv.qual_) and the array-to-pointer
5414      conversion (_conv.array_) are applied.  */
5415   else if (TYPE_PTROBV_P (type))
5416     {
5417       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
5418
5419          A template-argument for a non-type, non-template template-parameter
5420          shall be one of: [...]
5421
5422          -- the name of a non-type template-parameter;
5423          -- the address of an object or function with external linkage, [...]
5424             expressed as "& id-expression" where the & is optional if the name
5425             refers to a function or array, or if the corresponding
5426             template-parameter is a reference.
5427
5428         Here, we do not care about functions, as they are invalid anyway
5429         for a parameter of type pointer-to-object.  */
5430
5431       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
5432         /* Non-type template parameters are OK.  */
5433         ;
5434       else if (TREE_CODE (expr) != ADDR_EXPR
5435                && TREE_CODE (expr_type) != ARRAY_TYPE)
5436         {
5437           if (TREE_CODE (expr) == VAR_DECL)
5438             {
5439               error ("%qD is not a valid template argument "
5440                      "because %qD is a variable, not the address of "
5441                      "a variable",
5442                      expr, expr);
5443               return NULL_TREE;
5444             }
5445           /* Other values, like integer constants, might be valid
5446              non-type arguments of some other type.  */
5447           return error_mark_node;
5448         }
5449       else
5450         {
5451           tree decl;
5452
5453           decl = ((TREE_CODE (expr) == ADDR_EXPR)
5454                   ? TREE_OPERAND (expr, 0) : expr);
5455           if (TREE_CODE (decl) != VAR_DECL)
5456             {
5457               error ("%qE is not a valid template argument of type %qT "
5458                      "because %qE is not a variable",
5459                      expr, type, decl);
5460               return NULL_TREE;
5461             }
5462           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
5463             {
5464               error ("%qE is not a valid template argument of type %qT "
5465                      "because %qD does not have external linkage",
5466                      expr, type, decl);
5467               return NULL_TREE;
5468             }
5469         }
5470
5471       expr = decay_conversion (expr);
5472       if (expr == error_mark_node)
5473         return error_mark_node;
5474
5475       expr = perform_qualification_conversions (type, expr);
5476       if (expr == error_mark_node)
5477         return error_mark_node;
5478     }
5479   /* [temp.arg.nontype]/5, bullet 3
5480
5481      For a non-type template-parameter of type reference to object, no
5482      conversions apply. The type referred to by the reference may be more
5483      cv-qualified than the (otherwise identical) type of the
5484      template-argument. The template-parameter is bound directly to the
5485      template-argument, which must be an lvalue.  */
5486   else if (TYPE_REF_OBJ_P (type))
5487     {
5488       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5489                                                       expr_type))
5490         return error_mark_node;
5491
5492       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5493         {
5494           error ("%qE is not a valid template argument for type %qT "
5495                  "because of conflicts in cv-qualification", expr, type);
5496           return NULL_TREE;
5497         }
5498
5499       if (!real_lvalue_p (expr))
5500         {
5501           error ("%qE is not a valid template argument for type %qT "
5502                  "because it is not an lvalue", expr, type);
5503           return NULL_TREE;
5504         }
5505
5506       /* [temp.arg.nontype]/1
5507
5508          A template-argument for a non-type, non-template template-parameter
5509          shall be one of: [...]
5510
5511          -- the address of an object or function with external linkage.  */
5512       if (TREE_CODE (expr) == INDIRECT_REF
5513           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5514         {
5515           expr = TREE_OPERAND (expr, 0);
5516           if (DECL_P (expr))
5517             {
5518               error ("%q#D is not a valid template argument for type %qT "
5519                      "because a reference variable does not have a constant "
5520                      "address", expr, type);
5521               return NULL_TREE;
5522             }
5523         }
5524
5525       if (!DECL_P (expr))
5526         {
5527           error ("%qE is not a valid template argument for type %qT "
5528                  "because it is not an object with external linkage",
5529                  expr, type);
5530           return NULL_TREE;
5531         }
5532
5533       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5534         {
5535           error ("%qE is not a valid template argument for type %qT "
5536                  "because object %qD has not external linkage",
5537                  expr, type, expr);
5538           return NULL_TREE;
5539         }
5540
5541       expr = build_nop (type, build_address (expr));
5542     }
5543   /* [temp.arg.nontype]/5, bullet 4
5544
5545      For a non-type template-parameter of type pointer to function, only
5546      the function-to-pointer conversion (_conv.func_) is applied. If the
5547      template-argument represents a set of overloaded functions (or a
5548      pointer to such), the matching function is selected from the set
5549      (_over.over_).  */
5550   else if (TYPE_PTRFN_P (type))
5551     {
5552       /* If the argument is a template-id, we might not have enough
5553          context information to decay the pointer.  */
5554       if (!type_unknown_p (expr_type))
5555         {
5556           expr = decay_conversion (expr);
5557           if (expr == error_mark_node)
5558             return error_mark_node;
5559         }
5560
5561       expr = convert_nontype_argument_function (type, expr);
5562       if (!expr || expr == error_mark_node)
5563         return expr;
5564
5565       if (TREE_CODE (expr) != ADDR_EXPR)
5566         {
5567           error ("%qE is not a valid template argument for type %qT", expr, type);
5568           error ("it must be the address of a function with external linkage");
5569           return NULL_TREE;
5570         }
5571     }
5572   /* [temp.arg.nontype]/5, bullet 5
5573
5574      For a non-type template-parameter of type reference to function, no
5575      conversions apply. If the template-argument represents a set of
5576      overloaded functions, the matching function is selected from the set
5577      (_over.over_).  */
5578   else if (TYPE_REFFN_P (type))
5579     {
5580       if (TREE_CODE (expr) == ADDR_EXPR)
5581         {
5582           error ("%qE is not a valid template argument for type %qT "
5583                  "because it is a pointer", expr, type);
5584           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5585           return NULL_TREE;
5586         }
5587
5588       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5589       if (!expr || expr == error_mark_node)
5590         return expr;
5591
5592       expr = build_nop (type, build_address (expr));
5593     }
5594   /* [temp.arg.nontype]/5, bullet 6
5595
5596      For a non-type template-parameter of type pointer to member function,
5597      no conversions apply. If the template-argument represents a set of
5598      overloaded member functions, the matching member function is selected
5599      from the set (_over.over_).  */
5600   else if (TYPE_PTRMEMFUNC_P (type))
5601     {
5602       expr = instantiate_type (type, expr, tf_none);
5603       if (expr == error_mark_node)
5604         return error_mark_node;
5605
5606       /* [temp.arg.nontype] bullet 1 says the pointer to member
5607          expression must be a pointer-to-member constant.  */
5608       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5609         return error_mark_node;
5610
5611       /* There is no way to disable standard conversions in
5612          resolve_address_of_overloaded_function (called by
5613          instantiate_type). It is possible that the call succeeded by
5614          converting &B::I to &D::I (where B is a base of D), so we need
5615          to reject this conversion here.
5616
5617          Actually, even if there was a way to disable standard conversions,
5618          it would still be better to reject them here so that we can
5619          provide a superior diagnostic.  */
5620       if (!same_type_p (TREE_TYPE (expr), type))
5621         {
5622           error ("%qE is not a valid template argument for type %qT "
5623                  "because it is of type %qT", expr, type,
5624                  TREE_TYPE (expr));
5625           /* If we are just one standard conversion off, explain.  */
5626           if (can_convert (type, TREE_TYPE (expr)))
5627             inform (input_location,
5628                     "standard conversions are not allowed in this context");
5629           return NULL_TREE;
5630         }
5631     }
5632   /* [temp.arg.nontype]/5, bullet 7
5633
5634      For a non-type template-parameter of type pointer to data member,
5635      qualification conversions (_conv.qual_) are applied.  */
5636   else if (TYPE_PTRMEM_P (type))
5637     {
5638       /* [temp.arg.nontype] bullet 1 says the pointer to member
5639          expression must be a pointer-to-member constant.  */
5640       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5641         return error_mark_node;
5642
5643       expr = perform_qualification_conversions (type, expr);
5644       if (expr == error_mark_node)
5645         return expr;
5646     }
5647   /* A template non-type parameter must be one of the above.  */
5648   else
5649     gcc_unreachable ();
5650
5651   /* Sanity check: did we actually convert the argument to the
5652      right type?  */
5653   gcc_assert (same_type_ignoring_top_level_qualifiers_p
5654               (type, TREE_TYPE (expr)));
5655   return expr;
5656 }
5657
5658 /* Subroutine of coerce_template_template_parms, which returns 1 if
5659    PARM_PARM and ARG_PARM match using the rule for the template
5660    parameters of template template parameters. Both PARM and ARG are
5661    template parameters; the rest of the arguments are the same as for
5662    coerce_template_template_parms.
5663  */
5664 static int
5665 coerce_template_template_parm (tree parm,
5666                               tree arg,
5667                               tsubst_flags_t complain,
5668                               tree in_decl,
5669                               tree outer_args)
5670 {
5671   if (arg == NULL_TREE || arg == error_mark_node
5672       || parm == NULL_TREE || parm == error_mark_node)
5673     return 0;
5674   
5675   if (TREE_CODE (arg) != TREE_CODE (parm))
5676     return 0;
5677   
5678   switch (TREE_CODE (parm))
5679     {
5680     case TEMPLATE_DECL:
5681       /* We encounter instantiations of templates like
5682          template <template <template <class> class> class TT>
5683          class C;  */
5684       {
5685         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5686         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5687         
5688         if (!coerce_template_template_parms
5689             (parmparm, argparm, complain, in_decl, outer_args))
5690           return 0;
5691       }
5692       /* Fall through.  */
5693       
5694     case TYPE_DECL:
5695       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5696           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5697         /* Argument is a parameter pack but parameter is not.  */
5698         return 0;
5699       break;
5700       
5701     case PARM_DECL:
5702       /* The tsubst call is used to handle cases such as
5703          
5704            template <int> class C {};
5705            template <class T, template <T> class TT> class D {};
5706            D<int, C> d;
5707
5708          i.e. the parameter list of TT depends on earlier parameters.  */
5709       if (!uses_template_parms (TREE_TYPE (arg))
5710           && !same_type_p
5711                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5712                  TREE_TYPE (arg)))
5713         return 0;
5714       
5715       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5716           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5717         /* Argument is a parameter pack but parameter is not.  */
5718         return 0;
5719       
5720       break;
5721
5722     default:
5723       gcc_unreachable ();
5724     }
5725
5726   return 1;
5727 }
5728
5729
5730 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5731    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5732    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5733    or PARM_DECL.
5734
5735    Consider the example:
5736      template <class T> class A;
5737      template<template <class U> class TT> class B;
5738
5739    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5740    the parameters to A, and OUTER_ARGS contains A.  */
5741
5742 static int
5743 coerce_template_template_parms (tree parm_parms,
5744                                 tree arg_parms,
5745                                 tsubst_flags_t complain,
5746                                 tree in_decl,
5747                                 tree outer_args)
5748 {
5749   int nparms, nargs, i;
5750   tree parm, arg;
5751   int variadic_p = 0;
5752
5753   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5754   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5755
5756   nparms = TREE_VEC_LENGTH (parm_parms);
5757   nargs = TREE_VEC_LENGTH (arg_parms);
5758
5759   /* Determine whether we have a parameter pack at the end of the
5760      template template parameter's template parameter list.  */
5761   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5762     {
5763       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5764       
5765       if (parm == error_mark_node)
5766         return 0;
5767
5768       switch (TREE_CODE (parm))
5769         {
5770         case TEMPLATE_DECL:
5771         case TYPE_DECL:
5772           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5773             variadic_p = 1;
5774           break;
5775           
5776         case PARM_DECL:
5777           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5778             variadic_p = 1;
5779           break;
5780           
5781         default:
5782           gcc_unreachable ();
5783         }
5784     }
5785  
5786   if (nargs != nparms
5787       && !(variadic_p && nargs >= nparms - 1))
5788     return 0;
5789
5790   /* Check all of the template parameters except the parameter pack at
5791      the end (if any).  */
5792   for (i = 0; i < nparms - variadic_p; ++i)
5793     {
5794       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5795           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5796         continue;
5797
5798       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5799       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5800
5801       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5802                                           outer_args))
5803         return 0;
5804
5805     }
5806
5807   if (variadic_p)
5808     {
5809       /* Check each of the template parameters in the template
5810          argument against the template parameter pack at the end of
5811          the template template parameter.  */
5812       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5813         return 0;
5814
5815       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5816
5817       for (; i < nargs; ++i)
5818         {
5819           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5820             continue;
5821  
5822           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5823  
5824           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5825                                               outer_args))
5826             return 0;
5827         }
5828     }
5829
5830   return 1;
5831 }
5832
5833 /* Verifies that the deduced template arguments (in TARGS) for the
5834    template template parameters (in TPARMS) represent valid bindings,
5835    by comparing the template parameter list of each template argument
5836    to the template parameter list of its corresponding template
5837    template parameter, in accordance with DR150. This
5838    routine can only be called after all template arguments have been
5839    deduced. It will return TRUE if all of the template template
5840    parameter bindings are okay, FALSE otherwise.  */
5841 bool 
5842 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5843 {
5844   int i, ntparms = TREE_VEC_LENGTH (tparms);
5845   bool ret = true;
5846
5847   /* We're dealing with template parms in this process.  */
5848   ++processing_template_decl;
5849
5850   targs = INNERMOST_TEMPLATE_ARGS (targs);
5851
5852   for (i = 0; i < ntparms; ++i)
5853     {
5854       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5855       tree targ = TREE_VEC_ELT (targs, i);
5856
5857       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5858         {
5859           tree packed_args = NULL_TREE;
5860           int idx, len = 1;
5861
5862           if (ARGUMENT_PACK_P (targ))
5863             {
5864               /* Look inside the argument pack.  */
5865               packed_args = ARGUMENT_PACK_ARGS (targ);
5866               len = TREE_VEC_LENGTH (packed_args);
5867             }
5868
5869           for (idx = 0; idx < len; ++idx)
5870             {
5871               tree targ_parms = NULL_TREE;
5872
5873               if (packed_args)
5874                 /* Extract the next argument from the argument
5875                    pack.  */
5876                 targ = TREE_VEC_ELT (packed_args, idx);
5877
5878               if (PACK_EXPANSION_P (targ))
5879                 /* Look at the pattern of the pack expansion.  */
5880                 targ = PACK_EXPANSION_PATTERN (targ);
5881
5882               /* Extract the template parameters from the template
5883                  argument.  */
5884               if (TREE_CODE (targ) == TEMPLATE_DECL)
5885                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5886               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5887                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5888
5889               /* Verify that we can coerce the template template
5890                  parameters from the template argument to the template
5891                  parameter.  This requires an exact match.  */
5892               if (targ_parms
5893                   && !coerce_template_template_parms
5894                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5895                         targ_parms,
5896                         tf_none,
5897                         tparm,
5898                         targs))
5899                 {
5900                   ret = false;
5901                   goto out;
5902                 }
5903             }
5904         }
5905     }
5906
5907  out:
5908
5909   --processing_template_decl;
5910   return ret;
5911 }
5912
5913 /* Convert the indicated template ARG as necessary to match the
5914    indicated template PARM.  Returns the converted ARG, or
5915    error_mark_node if the conversion was unsuccessful.  Error and
5916    warning messages are issued under control of COMPLAIN.  This
5917    conversion is for the Ith parameter in the parameter list.  ARGS is
5918    the full set of template arguments deduced so far.  */
5919
5920 static tree
5921 convert_template_argument (tree parm,
5922                            tree arg,
5923                            tree args,
5924                            tsubst_flags_t complain,
5925                            int i,
5926                            tree in_decl)
5927 {
5928   tree orig_arg;
5929   tree val;
5930   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5931
5932   if (TREE_CODE (arg) == TREE_LIST
5933       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5934     {
5935       /* The template argument was the name of some
5936          member function.  That's usually
5937          invalid, but static members are OK.  In any
5938          case, grab the underlying fields/functions
5939          and issue an error later if required.  */
5940       orig_arg = TREE_VALUE (arg);
5941       TREE_TYPE (arg) = unknown_type_node;
5942     }
5943
5944   orig_arg = arg;
5945
5946   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5947   requires_type = (TREE_CODE (parm) == TYPE_DECL
5948                    || requires_tmpl_type);
5949
5950   /* When determining whether an argument pack expansion is a template,
5951      look at the pattern.  */
5952   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5953     arg = PACK_EXPANSION_PATTERN (arg);
5954
5955   /* Deal with an injected-class-name used as a template template arg.  */
5956   if (requires_tmpl_type && CLASS_TYPE_P (arg))
5957     {
5958       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
5959       if (TREE_CODE (t) == TEMPLATE_DECL)
5960         {
5961           if (complain & tf_warning_or_error)
5962             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
5963                      " used as template template argument", TYPE_NAME (arg));
5964           else if (flag_pedantic_errors)
5965             t = arg;
5966
5967           arg = t;
5968         }
5969     }
5970
5971   is_tmpl_type = 
5972     ((TREE_CODE (arg) == TEMPLATE_DECL
5973       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5974      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5975      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5976
5977   if (is_tmpl_type
5978       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5979           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5980     arg = TYPE_STUB_DECL (arg);
5981
5982   is_type = TYPE_P (arg) || is_tmpl_type;
5983
5984   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
5985       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
5986     {
5987       permerror (input_location, "to refer to a type member of a template parameter, "
5988                  "use %<typename %E%>", orig_arg);
5989
5990       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
5991                                      TREE_OPERAND (arg, 1),
5992                                      typename_type,
5993                                      complain & tf_error);
5994       arg = orig_arg;
5995       is_type = 1;
5996     }
5997   if (is_type != requires_type)
5998     {
5999       if (in_decl)
6000         {
6001           if (complain & tf_error)
6002             {
6003               error ("type/value mismatch at argument %d in template "
6004                      "parameter list for %qD",
6005                      i + 1, in_decl);
6006               if (is_type)
6007                 error ("  expected a constant of type %qT, got %qT",
6008                        TREE_TYPE (parm),
6009                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
6010               else if (requires_tmpl_type)
6011                 error ("  expected a class template, got %qE", orig_arg);
6012               else
6013                 error ("  expected a type, got %qE", orig_arg);
6014             }
6015         }
6016       return error_mark_node;
6017     }
6018   if (is_tmpl_type ^ requires_tmpl_type)
6019     {
6020       if (in_decl && (complain & tf_error))
6021         {
6022           error ("type/value mismatch at argument %d in template "
6023                  "parameter list for %qD",
6024                  i + 1, in_decl);
6025           if (is_tmpl_type)
6026             error ("  expected a type, got %qT", DECL_NAME (arg));
6027           else
6028             error ("  expected a class template, got %qT", orig_arg);
6029         }
6030       return error_mark_node;
6031     }
6032
6033   if (is_type)
6034     {
6035       if (requires_tmpl_type)
6036         {
6037           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
6038             /* The number of argument required is not known yet.
6039                Just accept it for now.  */
6040             val = TREE_TYPE (arg);
6041           else
6042             {
6043               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
6044               tree argparm;
6045
6046               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
6047
6048               if (coerce_template_template_parms (parmparm, argparm,
6049                                                   complain, in_decl,
6050                                                   args))
6051                 {
6052                   val = arg;
6053
6054                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
6055                      TEMPLATE_DECL.  */
6056                   if (val != error_mark_node)
6057                     {
6058                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
6059                         val = TREE_TYPE (val);
6060                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
6061                         val = make_pack_expansion (val);
6062                     }
6063                 }
6064               else
6065                 {
6066                   if (in_decl && (complain & tf_error))
6067                     {
6068                       error ("type/value mismatch at argument %d in "
6069                              "template parameter list for %qD",
6070                              i + 1, in_decl);
6071                       error ("  expected a template of type %qD, got %qT",
6072                              parm, orig_arg);
6073                     }
6074
6075                   val = error_mark_node;
6076                 }
6077             }
6078         }
6079       else
6080         val = orig_arg;
6081       /* We only form one instance of each template specialization.
6082          Therefore, if we use a non-canonical variant (i.e., a
6083          typedef), any future messages referring to the type will use
6084          the typedef, which is confusing if those future uses do not
6085          themselves also use the typedef.  */
6086       if (TYPE_P (val))
6087         val = strip_typedefs (val);
6088     }
6089   else
6090     {
6091       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
6092
6093       if (invalid_nontype_parm_type_p (t, complain))
6094         return error_mark_node;
6095
6096       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
6097         {
6098           if (same_type_p (t, TREE_TYPE (orig_arg)))
6099             val = orig_arg;
6100           else
6101             {
6102               /* Not sure if this is reachable, but it doesn't hurt
6103                  to be robust.  */
6104               error ("type mismatch in nontype parameter pack");
6105               val = error_mark_node;
6106             }
6107         }
6108       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
6109         /* We used to call digest_init here.  However, digest_init
6110            will report errors, which we don't want when complain
6111            is zero.  More importantly, digest_init will try too
6112            hard to convert things: for example, `0' should not be
6113            converted to pointer type at this point according to
6114            the standard.  Accepting this is not merely an
6115            extension, since deciding whether or not these
6116            conversions can occur is part of determining which
6117            function template to call, or whether a given explicit
6118            argument specification is valid.  */
6119         val = convert_nontype_argument (t, orig_arg, complain);
6120       else
6121         val = orig_arg;
6122
6123       if (val == NULL_TREE)
6124         val = error_mark_node;
6125       else if (val == error_mark_node && (complain & tf_error))
6126         error ("could not convert template argument %qE to %qT",  orig_arg, t);
6127
6128       if (TREE_CODE (val) == SCOPE_REF)
6129         {
6130           /* Strip typedefs from the SCOPE_REF.  */
6131           tree type = strip_typedefs (TREE_TYPE (val));
6132           tree scope = strip_typedefs (TREE_OPERAND (val, 0));
6133           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
6134                                       QUALIFIED_NAME_IS_TEMPLATE (val));
6135         }
6136     }
6137
6138   return val;
6139 }
6140
6141 /* Coerces the remaining template arguments in INNER_ARGS (from
6142    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
6143    Returns the coerced argument pack. PARM_IDX is the position of this
6144    parameter in the template parameter list. ARGS is the original
6145    template argument list.  */
6146 static tree
6147 coerce_template_parameter_pack (tree parms,
6148                                 int parm_idx,
6149                                 tree args,
6150                                 tree inner_args,
6151                                 int arg_idx,
6152                                 tree new_args,
6153                                 int* lost,
6154                                 tree in_decl,
6155                                 tsubst_flags_t complain)
6156 {
6157   tree parm = TREE_VEC_ELT (parms, parm_idx);
6158   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6159   tree packed_args;
6160   tree argument_pack;
6161   tree packed_types = NULL_TREE;
6162
6163   if (arg_idx > nargs)
6164     arg_idx = nargs;
6165
6166   packed_args = make_tree_vec (nargs - arg_idx);
6167
6168   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
6169       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
6170     {
6171       /* When the template parameter is a non-type template
6172          parameter pack whose type uses parameter packs, we need
6173          to look at each of the template arguments
6174          separately. Build a vector of the types for these
6175          non-type template parameters in PACKED_TYPES.  */
6176       tree expansion 
6177         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
6178       packed_types = tsubst_pack_expansion (expansion, args,
6179                                             complain, in_decl);
6180
6181       if (packed_types == error_mark_node)
6182         return error_mark_node;
6183
6184       /* Check that we have the right number of arguments.  */
6185       if (arg_idx < nargs
6186           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
6187           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
6188         {
6189           int needed_parms 
6190             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
6191           error ("wrong number of template arguments (%d, should be %d)",
6192                  nargs, needed_parms);
6193           return error_mark_node;
6194         }
6195
6196       /* If we aren't able to check the actual arguments now
6197          (because they haven't been expanded yet), we can at least
6198          verify that all of the types used for the non-type
6199          template parameter pack are, in fact, valid for non-type
6200          template parameters.  */
6201       if (arg_idx < nargs 
6202           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
6203         {
6204           int j, len = TREE_VEC_LENGTH (packed_types);
6205           for (j = 0; j < len; ++j)
6206             {
6207               tree t = TREE_VEC_ELT (packed_types, j);
6208               if (invalid_nontype_parm_type_p (t, complain))
6209                 return error_mark_node;
6210             }
6211         }
6212     }
6213
6214   /* Convert the remaining arguments, which will be a part of the
6215      parameter pack "parm".  */
6216   for (; arg_idx < nargs; ++arg_idx)
6217     {
6218       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
6219       tree actual_parm = TREE_VALUE (parm);
6220
6221       if (packed_types && !PACK_EXPANSION_P (arg))
6222         {
6223           /* When we have a vector of types (corresponding to the
6224              non-type template parameter pack that uses parameter
6225              packs in its type, as mention above), and the
6226              argument is not an expansion (which expands to a
6227              currently unknown number of arguments), clone the
6228              parm and give it the next type in PACKED_TYPES.  */
6229           actual_parm = copy_node (actual_parm);
6230           TREE_TYPE (actual_parm) = 
6231             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
6232         }
6233
6234       if (arg != error_mark_node)
6235         arg = convert_template_argument (actual_parm, 
6236                                          arg, new_args, complain, parm_idx,
6237                                          in_decl);
6238       if (arg == error_mark_node)
6239         (*lost)++;
6240       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
6241     }
6242
6243   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
6244       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
6245     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
6246   else
6247     {
6248       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
6249       TREE_TYPE (argument_pack) 
6250         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
6251       TREE_CONSTANT (argument_pack) = 1;
6252     }
6253
6254   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
6255 #ifdef ENABLE_CHECKING
6256   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
6257                                        TREE_VEC_LENGTH (packed_args));
6258 #endif
6259   return argument_pack;
6260 }
6261
6262 /* Convert all template arguments to their appropriate types, and
6263    return a vector containing the innermost resulting template
6264    arguments.  If any error occurs, return error_mark_node. Error and
6265    warning messages are issued under control of COMPLAIN.
6266
6267    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
6268    for arguments not specified in ARGS.  Otherwise, if
6269    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
6270    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
6271    USE_DEFAULT_ARGS is false, then all arguments must be specified in
6272    ARGS.  */
6273
6274 static tree
6275 coerce_template_parms (tree parms,
6276                        tree args,
6277                        tree in_decl,
6278                        tsubst_flags_t complain,
6279                        bool require_all_args,
6280                        bool use_default_args)
6281 {
6282   int nparms, nargs, parm_idx, arg_idx, lost = 0;
6283   tree inner_args;
6284   tree new_args;
6285   tree new_inner_args;
6286   int saved_unevaluated_operand;
6287   int saved_inhibit_evaluation_warnings;
6288
6289   /* When used as a boolean value, indicates whether this is a
6290      variadic template parameter list. Since it's an int, we can also
6291      subtract it from nparms to get the number of non-variadic
6292      parameters.  */
6293   int variadic_p = 0;
6294
6295   if (args == error_mark_node)
6296     return error_mark_node;
6297
6298   nparms = TREE_VEC_LENGTH (parms);
6299
6300   /* Determine if there are any parameter packs.  */
6301   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
6302     {
6303       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
6304       if (template_parameter_pack_p (tparm))
6305         ++variadic_p;
6306     }
6307
6308   inner_args = INNERMOST_TEMPLATE_ARGS (args);
6309   /* If there are 0 or 1 parameter packs, we need to expand any argument
6310      packs so that we can deduce a parameter pack from some non-packed args
6311      followed by an argument pack, as in variadic85.C.  If there are more
6312      than that, we need to leave argument packs intact so the arguments are
6313      assigned to the right parameter packs.  This should only happen when
6314      dealing with a nested class inside a partial specialization of a class
6315      template, as in variadic92.C.  */
6316   if (variadic_p <= 1)
6317     inner_args = expand_template_argument_pack (inner_args);
6318
6319   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6320   if ((nargs > nparms && !variadic_p)
6321       || (nargs < nparms - variadic_p
6322           && require_all_args
6323           && (!use_default_args
6324               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
6325                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
6326     {
6327       if (complain & tf_error)
6328         {
6329           if (variadic_p)
6330             {
6331               --nparms;
6332               error ("wrong number of template arguments "
6333                      "(%d, should be %d or more)", nargs, nparms);
6334             }
6335           else
6336              error ("wrong number of template arguments "
6337                     "(%d, should be %d)", nargs, nparms);
6338
6339           if (in_decl)
6340             error ("provided for %q+D", in_decl);
6341         }
6342
6343       return error_mark_node;
6344     }
6345
6346   /* We need to evaluate the template arguments, even though this
6347      template-id may be nested within a "sizeof".  */
6348   saved_unevaluated_operand = cp_unevaluated_operand;
6349   cp_unevaluated_operand = 0;
6350   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
6351   c_inhibit_evaluation_warnings = 0;
6352   new_inner_args = make_tree_vec (nparms);
6353   new_args = add_outermost_template_args (args, new_inner_args);
6354   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
6355     {
6356       tree arg;
6357       tree parm;
6358
6359       /* Get the Ith template parameter.  */
6360       parm = TREE_VEC_ELT (parms, parm_idx);
6361  
6362       if (parm == error_mark_node)
6363       {
6364         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
6365         continue;
6366       }
6367
6368       /* Calculate the next argument.  */
6369       if (arg_idx < nargs)
6370         arg = TREE_VEC_ELT (inner_args, arg_idx);
6371       else
6372         arg = NULL_TREE;
6373
6374       if (template_parameter_pack_p (TREE_VALUE (parm))
6375           && !(arg && ARGUMENT_PACK_P (arg)))
6376         {
6377           /* All remaining arguments will be placed in the
6378              template parameter pack PARM.  */
6379           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
6380                                                 inner_args, arg_idx,
6381                                                 new_args, &lost,
6382                                                 in_decl, complain);
6383
6384           /* Store this argument.  */
6385           if (arg == error_mark_node)
6386             lost++;
6387           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
6388
6389           /* We are done with all of the arguments.  */
6390           arg_idx = nargs;
6391           
6392           continue;
6393         }
6394       else if (arg)
6395         {
6396           if (PACK_EXPANSION_P (arg))
6397             {
6398               if (complain & tf_error)
6399                 {
6400                   /* FIXME this restriction was removed by N2555; see
6401                      bug 35722.  */
6402                   /* If ARG is a pack expansion, but PARM is not a
6403                      template parameter pack (if it were, we would have
6404                      handled it above), we're trying to expand into a
6405                      fixed-length argument list.  */
6406                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
6407                     sorry ("cannot expand %<%E%> into a fixed-length "
6408                            "argument list", arg);
6409                   else
6410                     sorry ("cannot expand %<%T%> into a fixed-length "
6411                            "argument list", arg);
6412                 }
6413               return error_mark_node;
6414             }
6415         }
6416       else if (require_all_args)
6417         {
6418           /* There must be a default arg in this case.  */
6419           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
6420                                      complain, in_decl);
6421           /* The position of the first default template argument,
6422              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
6423              Record that.  */
6424           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6425             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
6426         }
6427       else
6428         break;
6429
6430       if (arg == error_mark_node)
6431         {
6432           if (complain & tf_error)
6433             error ("template argument %d is invalid", arg_idx + 1);
6434         }
6435       else if (!arg)
6436         /* This only occurs if there was an error in the template
6437            parameter list itself (which we would already have
6438            reported) that we are trying to recover from, e.g., a class
6439            template with a parameter list such as
6440            template<typename..., typename>.  */
6441         return error_mark_node;
6442       else
6443         arg = convert_template_argument (TREE_VALUE (parm),
6444                                          arg, new_args, complain, 
6445                                          parm_idx, in_decl);
6446
6447       if (arg == error_mark_node)
6448         lost++;
6449       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6450     }
6451   cp_unevaluated_operand = saved_unevaluated_operand;
6452   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6453
6454   if (lost)
6455     return error_mark_node;
6456
6457 #ifdef ENABLE_CHECKING
6458   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6459     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6460                                          TREE_VEC_LENGTH (new_inner_args));
6461 #endif
6462
6463   return new_inner_args;
6464 }
6465
6466 /* Returns 1 if template args OT and NT are equivalent.  */
6467
6468 static int
6469 template_args_equal (tree ot, tree nt)
6470 {
6471   if (nt == ot)
6472     return 1;
6473
6474   if (TREE_CODE (nt) == TREE_VEC)
6475     /* For member templates */
6476     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6477   else if (PACK_EXPANSION_P (ot))
6478     return PACK_EXPANSION_P (nt) 
6479       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6480                               PACK_EXPANSION_PATTERN (nt));
6481   else if (ARGUMENT_PACK_P (ot))
6482     {
6483       int i, len;
6484       tree opack, npack;
6485
6486       if (!ARGUMENT_PACK_P (nt))
6487         return 0;
6488
6489       opack = ARGUMENT_PACK_ARGS (ot);
6490       npack = ARGUMENT_PACK_ARGS (nt);
6491       len = TREE_VEC_LENGTH (opack);
6492       if (TREE_VEC_LENGTH (npack) != len)
6493         return 0;
6494       for (i = 0; i < len; ++i)
6495         if (!template_args_equal (TREE_VEC_ELT (opack, i),
6496                                   TREE_VEC_ELT (npack, i)))
6497           return 0;
6498       return 1;
6499     }
6500   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6501     {
6502       /* We get here probably because we are in the middle of substituting
6503          into the pattern of a pack expansion. In that case the
6504          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6505          interested in. So we want to use the initial pack argument for
6506          the comparison.  */
6507       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6508       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6509         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6510       return template_args_equal (ot, nt);
6511     }
6512   else if (TYPE_P (nt))
6513     return TYPE_P (ot) && same_type_p (ot, nt);
6514   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6515     return 0;
6516   else
6517     return cp_tree_equal (ot, nt);
6518 }
6519
6520 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6521    of template arguments.  Returns 0 otherwise.  */
6522
6523 int
6524 comp_template_args (tree oldargs, tree newargs)
6525 {
6526   int i;
6527
6528   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6529     return 0;
6530
6531   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6532     {
6533       tree nt = TREE_VEC_ELT (newargs, i);
6534       tree ot = TREE_VEC_ELT (oldargs, i);
6535
6536       if (! template_args_equal (ot, nt))
6537         return 0;
6538     }
6539   return 1;
6540 }
6541
6542 static void
6543 add_pending_template (tree d)
6544 {
6545   tree ti = (TYPE_P (d)
6546              ? CLASSTYPE_TEMPLATE_INFO (d)
6547              : DECL_TEMPLATE_INFO (d));
6548   struct pending_template *pt;
6549   int level;
6550
6551   if (TI_PENDING_TEMPLATE_FLAG (ti))
6552     return;
6553
6554   /* We are called both from instantiate_decl, where we've already had a
6555      tinst_level pushed, and instantiate_template, where we haven't.
6556      Compensate.  */
6557   level = !current_tinst_level || current_tinst_level->decl != d;
6558
6559   if (level)
6560     push_tinst_level (d);
6561
6562   pt = ggc_alloc_pending_template ();
6563   pt->next = NULL;
6564   pt->tinst = current_tinst_level;
6565   if (last_pending_template)
6566     last_pending_template->next = pt;
6567   else
6568     pending_templates = pt;
6569
6570   last_pending_template = pt;
6571
6572   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6573
6574   if (level)
6575     pop_tinst_level ();
6576 }
6577
6578
6579 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6580    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6581    documentation for TEMPLATE_ID_EXPR.  */
6582
6583 tree
6584 lookup_template_function (tree fns, tree arglist)
6585 {
6586   tree type;
6587
6588   if (fns == error_mark_node || arglist == error_mark_node)
6589     return error_mark_node;
6590
6591   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6592   gcc_assert (fns && (is_overloaded_fn (fns)
6593                       || TREE_CODE (fns) == IDENTIFIER_NODE));
6594
6595   if (BASELINK_P (fns))
6596     {
6597       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6598                                          unknown_type_node,
6599                                          BASELINK_FUNCTIONS (fns),
6600                                          arglist);
6601       return fns;
6602     }
6603
6604   type = TREE_TYPE (fns);
6605   if (TREE_CODE (fns) == OVERLOAD || !type)
6606     type = unknown_type_node;
6607
6608   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6609 }
6610
6611 /* Within the scope of a template class S<T>, the name S gets bound
6612    (in build_self_reference) to a TYPE_DECL for the class, not a
6613    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6614    or one of its enclosing classes, and that type is a template,
6615    return the associated TEMPLATE_DECL.  Otherwise, the original
6616    DECL is returned.
6617
6618    Also handle the case when DECL is a TREE_LIST of ambiguous
6619    injected-class-names from different bases.  */
6620
6621 tree
6622 maybe_get_template_decl_from_type_decl (tree decl)
6623 {
6624   if (decl == NULL_TREE)
6625     return decl;
6626
6627   /* DR 176: A lookup that finds an injected-class-name (10.2
6628      [class.member.lookup]) can result in an ambiguity in certain cases
6629      (for example, if it is found in more than one base class). If all of
6630      the injected-class-names that are found refer to specializations of
6631      the same class template, and if the name is followed by a
6632      template-argument-list, the reference refers to the class template
6633      itself and not a specialization thereof, and is not ambiguous.  */
6634   if (TREE_CODE (decl) == TREE_LIST)
6635     {
6636       tree t, tmpl = NULL_TREE;
6637       for (t = decl; t; t = TREE_CHAIN (t))
6638         {
6639           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6640           if (!tmpl)
6641             tmpl = elt;
6642           else if (tmpl != elt)
6643             break;
6644         }
6645       if (tmpl && t == NULL_TREE)
6646         return tmpl;
6647       else
6648         return decl;
6649     }
6650
6651   return (decl != NULL_TREE
6652           && DECL_SELF_REFERENCE_P (decl)
6653           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
6654     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
6655 }
6656
6657 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
6658    parameters, find the desired type.
6659
6660    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
6661
6662    IN_DECL, if non-NULL, is the template declaration we are trying to
6663    instantiate.
6664
6665    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
6666    the class we are looking up.
6667
6668    Issue error and warning messages under control of COMPLAIN.
6669
6670    If the template class is really a local class in a template
6671    function, then the FUNCTION_CONTEXT is the function in which it is
6672    being instantiated.
6673
6674    ??? Note that this function is currently called *twice* for each
6675    template-id: the first time from the parser, while creating the
6676    incomplete type (finish_template_type), and the second type during the
6677    real instantiation (instantiate_template_class). This is surely something
6678    that we want to avoid. It also causes some problems with argument
6679    coercion (see convert_nontype_argument for more information on this).  */
6680
6681 tree
6682 lookup_template_class (tree d1,
6683                        tree arglist,
6684                        tree in_decl,
6685                        tree context,
6686                        int entering_scope,
6687                        tsubst_flags_t complain)
6688 {
6689   tree templ = NULL_TREE, parmlist;
6690   tree t;
6691   spec_entry **slot;
6692   spec_entry *entry;
6693   spec_entry elt;
6694   hashval_t hash;
6695
6696   timevar_push (TV_NAME_LOOKUP);
6697
6698   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6699     {
6700       tree value = innermost_non_namespace_value (d1);
6701       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6702         templ = value;
6703       else
6704         {
6705           if (context)
6706             push_decl_namespace (context);
6707           templ = lookup_name (d1);
6708           templ = maybe_get_template_decl_from_type_decl (templ);
6709           if (context)
6710             pop_decl_namespace ();
6711         }
6712       if (templ)
6713         context = DECL_CONTEXT (templ);
6714     }
6715   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6716     {
6717       tree type = TREE_TYPE (d1);
6718
6719       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6720          an implicit typename for the second A.  Deal with it.  */
6721       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6722         type = TREE_TYPE (type);
6723
6724       if (CLASSTYPE_TEMPLATE_INFO (type))
6725         {
6726           templ = CLASSTYPE_TI_TEMPLATE (type);
6727           d1 = DECL_NAME (templ);
6728         }
6729     }
6730   else if (TREE_CODE (d1) == ENUMERAL_TYPE
6731            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6732     {
6733       templ = TYPE_TI_TEMPLATE (d1);
6734       d1 = DECL_NAME (templ);
6735     }
6736   else if (TREE_CODE (d1) == TEMPLATE_DECL
6737            && DECL_TEMPLATE_RESULT (d1)
6738            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6739     {
6740       templ = d1;
6741       d1 = DECL_NAME (templ);
6742       context = DECL_CONTEXT (templ);
6743     }
6744
6745   /* Issue an error message if we didn't find a template.  */
6746   if (! templ)
6747     {
6748       if (complain & tf_error)
6749         error ("%qT is not a template", d1);
6750       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6751     }
6752
6753   if (TREE_CODE (templ) != TEMPLATE_DECL
6754          /* Make sure it's a user visible template, if it was named by
6755             the user.  */
6756       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6757           && !PRIMARY_TEMPLATE_P (templ)))
6758     {
6759       if (complain & tf_error)
6760         {
6761           error ("non-template type %qT used as a template", d1);
6762           if (in_decl)
6763             error ("for template declaration %q+D", in_decl);
6764         }
6765       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6766     }
6767
6768   complain &= ~tf_user;
6769
6770   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6771     {
6772       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6773          template arguments */
6774
6775       tree parm;
6776       tree arglist2;
6777       tree outer;
6778
6779       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6780
6781       /* Consider an example where a template template parameter declared as
6782
6783            template <class T, class U = std::allocator<T> > class TT
6784
6785          The template parameter level of T and U are one level larger than
6786          of TT.  To proper process the default argument of U, say when an
6787          instantiation `TT<int>' is seen, we need to build the full
6788          arguments containing {int} as the innermost level.  Outer levels,
6789          available when not appearing as default template argument, can be
6790          obtained from the arguments of the enclosing template.
6791
6792          Suppose that TT is later substituted with std::vector.  The above
6793          instantiation is `TT<int, std::allocator<T> >' with TT at
6794          level 1, and T at level 2, while the template arguments at level 1
6795          becomes {std::vector} and the inner level 2 is {int}.  */
6796
6797       outer = DECL_CONTEXT (templ);
6798       if (outer)
6799         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
6800       else if (current_template_parms)
6801         /* This is an argument of the current template, so we haven't set
6802            DECL_CONTEXT yet.  */
6803         outer = current_template_args ();
6804
6805       if (outer)
6806         arglist = add_to_template_args (outer, arglist);
6807
6808       arglist2 = coerce_template_parms (parmlist, arglist, templ,
6809                                         complain,
6810                                         /*require_all_args=*/true,
6811                                         /*use_default_args=*/true);
6812       if (arglist2 == error_mark_node
6813           || (!uses_template_parms (arglist2)
6814               && check_instantiated_args (templ, arglist2, complain)))
6815         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6816
6817       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
6818       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
6819     }
6820   else
6821     {
6822       tree template_type = TREE_TYPE (templ);
6823       tree gen_tmpl;
6824       tree type_decl;
6825       tree found = NULL_TREE;
6826       int arg_depth;
6827       int parm_depth;
6828       int is_dependent_type;
6829       int use_partial_inst_tmpl = false;
6830
6831       gen_tmpl = most_general_template (templ);
6832       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
6833       parm_depth = TMPL_PARMS_DEPTH (parmlist);
6834       arg_depth = TMPL_ARGS_DEPTH (arglist);
6835
6836       if (arg_depth == 1 && parm_depth > 1)
6837         {
6838           /* We've been given an incomplete set of template arguments.
6839              For example, given:
6840
6841                template <class T> struct S1 {
6842                  template <class U> struct S2 {};
6843                  template <class U> struct S2<U*> {};
6844                 };
6845
6846              we will be called with an ARGLIST of `U*', but the
6847              TEMPLATE will be `template <class T> template
6848              <class U> struct S1<T>::S2'.  We must fill in the missing
6849              arguments.  */
6850           arglist
6851             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
6852                                            arglist);
6853           arg_depth = TMPL_ARGS_DEPTH (arglist);
6854         }
6855
6856       /* Now we should have enough arguments.  */
6857       gcc_assert (parm_depth == arg_depth);
6858
6859       /* From here on, we're only interested in the most general
6860          template.  */
6861
6862       /* Calculate the BOUND_ARGS.  These will be the args that are
6863          actually tsubst'd into the definition to create the
6864          instantiation.  */
6865       if (parm_depth > 1)
6866         {
6867           /* We have multiple levels of arguments to coerce, at once.  */
6868           int i;
6869           int saved_depth = TMPL_ARGS_DEPTH (arglist);
6870
6871           tree bound_args = make_tree_vec (parm_depth);
6872
6873           for (i = saved_depth,
6874                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
6875                i > 0 && t != NULL_TREE;
6876                --i, t = TREE_CHAIN (t))
6877             {
6878               tree a;
6879               if (i == saved_depth)
6880                 a = coerce_template_parms (TREE_VALUE (t),
6881                                            arglist, gen_tmpl,
6882                                            complain,
6883                                            /*require_all_args=*/true,
6884                                            /*use_default_args=*/true);
6885               else
6886                 /* Outer levels should have already been coerced.  */
6887                 a = TMPL_ARGS_LEVEL (arglist, i);
6888
6889               /* Don't process further if one of the levels fails.  */
6890               if (a == error_mark_node)
6891                 {
6892                   /* Restore the ARGLIST to its full size.  */
6893                   TREE_VEC_LENGTH (arglist) = saved_depth;
6894                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6895                 }
6896
6897               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6898
6899               /* We temporarily reduce the length of the ARGLIST so
6900                  that coerce_template_parms will see only the arguments
6901                  corresponding to the template parameters it is
6902                  examining.  */
6903               TREE_VEC_LENGTH (arglist)--;
6904             }
6905
6906           /* Restore the ARGLIST to its full size.  */
6907           TREE_VEC_LENGTH (arglist) = saved_depth;
6908
6909           arglist = bound_args;
6910         }
6911       else
6912         arglist
6913           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6914                                    INNERMOST_TEMPLATE_ARGS (arglist),
6915                                    gen_tmpl,
6916                                    complain,
6917                                    /*require_all_args=*/true,
6918                                    /*use_default_args=*/true);
6919
6920       if (arglist == error_mark_node)
6921         /* We were unable to bind the arguments.  */
6922         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6923
6924       /* In the scope of a template class, explicit references to the
6925          template class refer to the type of the template, not any
6926          instantiation of it.  For example, in:
6927
6928            template <class T> class C { void f(C<T>); }
6929
6930          the `C<T>' is just the same as `C'.  Outside of the
6931          class, however, such a reference is an instantiation.  */
6932       if ((entering_scope
6933            || !PRIMARY_TEMPLATE_P (gen_tmpl)
6934            || currently_open_class (template_type))
6935           /* comp_template_args is expensive, check it last.  */
6936           && comp_template_args (TYPE_TI_ARGS (template_type),
6937                                  arglist))
6938         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, template_type);
6939
6940       /* If we already have this specialization, return it.  */
6941       elt.tmpl = gen_tmpl;
6942       elt.args = arglist;
6943       hash = hash_specialization (&elt);
6944       entry = (spec_entry *) htab_find_with_hash (type_specializations,
6945                                                   &elt, hash);
6946
6947       if (entry)
6948         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->spec);
6949
6950       is_dependent_type = uses_template_parms (arglist);
6951
6952       /* If the deduced arguments are invalid, then the binding
6953          failed.  */
6954       if (!is_dependent_type
6955           && check_instantiated_args (gen_tmpl,
6956                                       INNERMOST_TEMPLATE_ARGS (arglist),
6957                                       complain))
6958         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6959
6960       if (!is_dependent_type
6961           && !PRIMARY_TEMPLATE_P (gen_tmpl)
6962           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
6963           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6964         {
6965           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6966                                       DECL_NAME (gen_tmpl),
6967                                       /*tag_scope=*/ts_global);
6968           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
6969         }
6970
6971       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
6972                         complain, in_decl);
6973       if (!context)
6974         context = global_namespace;
6975
6976       /* Create the type.  */
6977       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
6978         {
6979           if (!is_dependent_type)
6980             {
6981               set_current_access_from_decl (TYPE_NAME (template_type));
6982               t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
6983                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
6984                                       arglist, complain, in_decl),
6985                               SCOPED_ENUM_P (template_type), NULL);
6986             }
6987           else
6988             {
6989               /* We don't want to call start_enum for this type, since
6990                  the values for the enumeration constants may involve
6991                  template parameters.  And, no one should be interested
6992                  in the enumeration constants for such a type.  */
6993               t = cxx_make_type (ENUMERAL_TYPE);
6994               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
6995             }
6996           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
6997         }
6998       else
6999         {
7000           t = make_class_type (TREE_CODE (template_type));
7001           CLASSTYPE_DECLARED_CLASS (t)
7002             = CLASSTYPE_DECLARED_CLASS (template_type);
7003           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
7004           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
7005
7006           /* A local class.  Make sure the decl gets registered properly.  */
7007           if (context == current_function_decl)
7008             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
7009
7010           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
7011             /* This instantiation is another name for the primary
7012                template type. Set the TYPE_CANONICAL field
7013                appropriately. */
7014             TYPE_CANONICAL (t) = template_type;
7015           else if (any_template_arguments_need_structural_equality_p (arglist))
7016             /* Some of the template arguments require structural
7017                equality testing, so this template class requires
7018                structural equality testing. */
7019             SET_TYPE_STRUCTURAL_EQUALITY (t);
7020         }
7021
7022       /* If we called start_enum or pushtag above, this information
7023          will already be set up.  */
7024       if (!TYPE_NAME (t))
7025         {
7026           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
7027
7028           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
7029           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
7030           DECL_SOURCE_LOCATION (type_decl)
7031             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
7032         }
7033       else
7034         type_decl = TYPE_NAME (t);
7035
7036       TREE_PRIVATE (type_decl)
7037         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
7038       TREE_PROTECTED (type_decl)
7039         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
7040       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
7041         {
7042           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
7043           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
7044         }
7045
7046       /* Let's consider the explicit specialization of a member
7047          of a class template specialization that is implicitely instantiated,
7048          e.g.:
7049              template<class T>
7050              struct S
7051              {
7052                template<class U> struct M {}; //#0
7053              };
7054
7055              template<>
7056              template<>
7057              struct S<int>::M<char> //#1
7058              {
7059                int i;
7060              };
7061         [temp.expl.spec]/4 says this is valid.
7062
7063         In this case, when we write:
7064         S<int>::M<char> m;
7065
7066         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
7067         the one of #0.
7068
7069         When we encounter #1, we want to store the partial instantiation
7070         of M (template<class T> S<int>::M<T>) in it's CLASSTYPE_TI_TEMPLATE.
7071
7072         For all cases other than this "explicit specialization of member of a
7073         class template", we just want to store the most general template into
7074         the CLASSTYPE_TI_TEMPLATE of M.
7075
7076         This case of "explicit specialization of member of a class template"
7077         only happens when:
7078         1/ the enclosing class is an instantiation of, and therefore not
7079         the same as, the context of the most general template, and
7080         2/ we aren't looking at the partial instantiation itself, i.e.
7081         the innermost arguments are not the same as the innermost parms of
7082         the most general template.
7083
7084         So it's only when 1/ and 2/ happens that we want to use the partial
7085         instantiation of the member template in lieu of its most general
7086         template.  */
7087
7088       if (PRIMARY_TEMPLATE_P (gen_tmpl)
7089           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
7090           /* the enclosing class must be an instantiation...  */
7091           && CLASS_TYPE_P (context)
7092           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
7093         {
7094           tree partial_inst_args;
7095           TREE_VEC_LENGTH (arglist)--;
7096           ++processing_template_decl;
7097           partial_inst_args =
7098             tsubst (INNERMOST_TEMPLATE_ARGS
7099                         (CLASSTYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
7100                     arglist, complain, NULL_TREE);
7101           --processing_template_decl;
7102           TREE_VEC_LENGTH (arglist)++;
7103           use_partial_inst_tmpl =
7104             /*...and we must not be looking at the partial instantiation
7105              itself. */
7106             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
7107                                  partial_inst_args);
7108         }
7109
7110       if (!use_partial_inst_tmpl)
7111         /* This case is easy; there are no member templates involved.  */
7112         found = gen_tmpl;
7113       else
7114         {
7115           /* This is a full instantiation of a member template.  Find
7116              the partial instantiation of which this is an instance.  */
7117
7118           /* Temporarily reduce by one the number of levels in the ARGLIST
7119              so as to avoid comparing the last set of arguments.  */
7120           TREE_VEC_LENGTH (arglist)--;
7121           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
7122           TREE_VEC_LENGTH (arglist)++;
7123           found = CLASSTYPE_TI_TEMPLATE (found);
7124         }
7125
7126       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
7127
7128       elt.spec = t;
7129       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
7130                                                        &elt, hash, INSERT);
7131       *slot = ggc_alloc_spec_entry ();
7132       **slot = elt;
7133
7134       /* Note this use of the partial instantiation so we can check it
7135          later in maybe_process_partial_specialization.  */
7136       DECL_TEMPLATE_INSTANTIATIONS (templ)
7137         = tree_cons (arglist, t,
7138                      DECL_TEMPLATE_INSTANTIATIONS (templ));
7139
7140       if (TREE_CODE (t) == ENUMERAL_TYPE && !is_dependent_type)
7141         /* Now that the type has been registered on the instantiations
7142            list, we set up the enumerators.  Because the enumeration
7143            constants may involve the enumeration type itself, we make
7144            sure to register the type first, and then create the
7145            constants.  That way, doing tsubst_expr for the enumeration
7146            constants won't result in recursive calls here; we'll find
7147            the instantiation and exit above.  */
7148         tsubst_enum (template_type, t, arglist);
7149
7150       if (is_dependent_type)
7151         /* If the type makes use of template parameters, the
7152            code that generates debugging information will crash.  */
7153         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
7154
7155       /* Possibly limit visibility based on template args.  */
7156       TREE_PUBLIC (type_decl) = 1;
7157       determine_visibility (type_decl);
7158
7159       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
7160     }
7161   timevar_pop (TV_NAME_LOOKUP);
7162 }
7163 \f
7164 struct pair_fn_data
7165 {
7166   tree_fn_t fn;
7167   void *data;
7168   /* True when we should also visit template parameters that occur in
7169      non-deduced contexts.  */
7170   bool include_nondeduced_p;
7171   struct pointer_set_t *visited;
7172 };
7173
7174 /* Called from for_each_template_parm via walk_tree.  */
7175
7176 static tree
7177 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
7178 {
7179   tree t = *tp;
7180   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
7181   tree_fn_t fn = pfd->fn;
7182   void *data = pfd->data;
7183
7184   if (TYPE_P (t)
7185       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
7186       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
7187                                  pfd->include_nondeduced_p))
7188     return error_mark_node;
7189
7190   switch (TREE_CODE (t))
7191     {
7192     case RECORD_TYPE:
7193       if (TYPE_PTRMEMFUNC_P (t))
7194         break;
7195       /* Fall through.  */
7196
7197     case UNION_TYPE:
7198     case ENUMERAL_TYPE:
7199       if (!TYPE_TEMPLATE_INFO (t))
7200         *walk_subtrees = 0;
7201       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
7202                                        fn, data, pfd->visited, 
7203                                        pfd->include_nondeduced_p))
7204         return error_mark_node;
7205       break;
7206
7207     case INTEGER_TYPE:
7208       if (for_each_template_parm (TYPE_MIN_VALUE (t),
7209                                   fn, data, pfd->visited, 
7210                                   pfd->include_nondeduced_p)
7211           || for_each_template_parm (TYPE_MAX_VALUE (t),
7212                                      fn, data, pfd->visited,
7213                                      pfd->include_nondeduced_p))
7214         return error_mark_node;
7215       break;
7216
7217     case METHOD_TYPE:
7218       /* Since we're not going to walk subtrees, we have to do this
7219          explicitly here.  */
7220       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
7221                                   pfd->visited, pfd->include_nondeduced_p))
7222         return error_mark_node;
7223       /* Fall through.  */
7224
7225     case FUNCTION_TYPE:
7226       /* Check the return type.  */
7227       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7228                                   pfd->include_nondeduced_p))
7229         return error_mark_node;
7230
7231       /* Check the parameter types.  Since default arguments are not
7232          instantiated until they are needed, the TYPE_ARG_TYPES may
7233          contain expressions that involve template parameters.  But,
7234          no-one should be looking at them yet.  And, once they're
7235          instantiated, they don't contain template parameters, so
7236          there's no point in looking at them then, either.  */
7237       {
7238         tree parm;
7239
7240         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
7241           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
7242                                       pfd->visited, pfd->include_nondeduced_p))
7243             return error_mark_node;
7244
7245         /* Since we've already handled the TYPE_ARG_TYPES, we don't
7246            want walk_tree walking into them itself.  */
7247         *walk_subtrees = 0;
7248       }
7249       break;
7250
7251     case TYPEOF_TYPE:
7252       if (pfd->include_nondeduced_p
7253           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
7254                                      pfd->visited, 
7255                                      pfd->include_nondeduced_p))
7256         return error_mark_node;
7257       break;
7258
7259     case FUNCTION_DECL:
7260     case VAR_DECL:
7261       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
7262           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
7263                                      pfd->visited, pfd->include_nondeduced_p))
7264         return error_mark_node;
7265       /* Fall through.  */
7266
7267     case PARM_DECL:
7268     case CONST_DECL:
7269       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
7270           && for_each_template_parm (DECL_INITIAL (t), fn, data,
7271                                      pfd->visited, pfd->include_nondeduced_p))
7272         return error_mark_node;
7273       if (DECL_CONTEXT (t)
7274           && pfd->include_nondeduced_p
7275           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
7276                                      pfd->visited, pfd->include_nondeduced_p))
7277         return error_mark_node;
7278       break;
7279
7280     case BOUND_TEMPLATE_TEMPLATE_PARM:
7281       /* Record template parameters such as `T' inside `TT<T>'.  */
7282       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
7283                                   pfd->include_nondeduced_p))
7284         return error_mark_node;
7285       /* Fall through.  */
7286
7287     case TEMPLATE_TEMPLATE_PARM:
7288     case TEMPLATE_TYPE_PARM:
7289     case TEMPLATE_PARM_INDEX:
7290       if (fn && (*fn)(t, data))
7291         return error_mark_node;
7292       else if (!fn)
7293         return error_mark_node;
7294       break;
7295
7296     case TEMPLATE_DECL:
7297       /* A template template parameter is encountered.  */
7298       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
7299           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7300                                      pfd->include_nondeduced_p))
7301         return error_mark_node;
7302
7303       /* Already substituted template template parameter */
7304       *walk_subtrees = 0;
7305       break;
7306
7307     case TYPENAME_TYPE:
7308       if (!fn
7309           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
7310                                      data, pfd->visited, 
7311                                      pfd->include_nondeduced_p))
7312         return error_mark_node;
7313       break;
7314
7315     case CONSTRUCTOR:
7316       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
7317           && pfd->include_nondeduced_p
7318           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
7319                                      (TREE_TYPE (t)), fn, data,
7320                                      pfd->visited, pfd->include_nondeduced_p))
7321         return error_mark_node;
7322       break;
7323
7324     case INDIRECT_REF:
7325     case COMPONENT_REF:
7326       /* If there's no type, then this thing must be some expression
7327          involving template parameters.  */
7328       if (!fn && !TREE_TYPE (t))
7329         return error_mark_node;
7330       break;
7331
7332     case MODOP_EXPR:
7333     case CAST_EXPR:
7334     case REINTERPRET_CAST_EXPR:
7335     case CONST_CAST_EXPR:
7336     case STATIC_CAST_EXPR:
7337     case DYNAMIC_CAST_EXPR:
7338     case ARROW_EXPR:
7339     case DOTSTAR_EXPR:
7340     case TYPEID_EXPR:
7341     case PSEUDO_DTOR_EXPR:
7342       if (!fn)
7343         return error_mark_node;
7344       break;
7345
7346     default:
7347       break;
7348     }
7349
7350   /* We didn't find any template parameters we liked.  */
7351   return NULL_TREE;
7352 }
7353
7354 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
7355    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
7356    call FN with the parameter and the DATA.
7357    If FN returns nonzero, the iteration is terminated, and
7358    for_each_template_parm returns 1.  Otherwise, the iteration
7359    continues.  If FN never returns a nonzero value, the value
7360    returned by for_each_template_parm is 0.  If FN is NULL, it is
7361    considered to be the function which always returns 1.
7362
7363    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
7364    parameters that occur in non-deduced contexts.  When false, only
7365    visits those template parameters that can be deduced.  */
7366
7367 static int
7368 for_each_template_parm (tree t, tree_fn_t fn, void* data,
7369                         struct pointer_set_t *visited,
7370                         bool include_nondeduced_p)
7371 {
7372   struct pair_fn_data pfd;
7373   int result;
7374
7375   /* Set up.  */
7376   pfd.fn = fn;
7377   pfd.data = data;
7378   pfd.include_nondeduced_p = include_nondeduced_p;
7379
7380   /* Walk the tree.  (Conceptually, we would like to walk without
7381      duplicates, but for_each_template_parm_r recursively calls
7382      for_each_template_parm, so we would need to reorganize a fair
7383      bit to use walk_tree_without_duplicates, so we keep our own
7384      visited list.)  */
7385   if (visited)
7386     pfd.visited = visited;
7387   else
7388     pfd.visited = pointer_set_create ();
7389   result = cp_walk_tree (&t,
7390                          for_each_template_parm_r,
7391                          &pfd,
7392                          pfd.visited) != NULL_TREE;
7393
7394   /* Clean up.  */
7395   if (!visited)
7396     {
7397       pointer_set_destroy (pfd.visited);
7398       pfd.visited = 0;
7399     }
7400
7401   return result;
7402 }
7403
7404 /* Returns true if T depends on any template parameter.  */
7405
7406 int
7407 uses_template_parms (tree t)
7408 {
7409   bool dependent_p;
7410   int saved_processing_template_decl;
7411
7412   saved_processing_template_decl = processing_template_decl;
7413   if (!saved_processing_template_decl)
7414     processing_template_decl = 1;
7415   if (TYPE_P (t))
7416     dependent_p = dependent_type_p (t);
7417   else if (TREE_CODE (t) == TREE_VEC)
7418     dependent_p = any_dependent_template_arguments_p (t);
7419   else if (TREE_CODE (t) == TREE_LIST)
7420     dependent_p = (uses_template_parms (TREE_VALUE (t))
7421                    || uses_template_parms (TREE_CHAIN (t)));
7422   else if (TREE_CODE (t) == TYPE_DECL)
7423     dependent_p = dependent_type_p (TREE_TYPE (t));
7424   else if (DECL_P (t)
7425            || EXPR_P (t)
7426            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
7427            || TREE_CODE (t) == OVERLOAD
7428            || TREE_CODE (t) == BASELINK
7429            || TREE_CODE (t) == IDENTIFIER_NODE
7430            || TREE_CODE (t) == TRAIT_EXPR
7431            || TREE_CODE (t) == CONSTRUCTOR
7432            || CONSTANT_CLASS_P (t))
7433     dependent_p = (type_dependent_expression_p (t)
7434                    || value_dependent_expression_p (t));
7435   else
7436     {
7437       gcc_assert (t == error_mark_node);
7438       dependent_p = false;
7439     }
7440
7441   processing_template_decl = saved_processing_template_decl;
7442
7443   return dependent_p;
7444 }
7445
7446 /* Returns true if T depends on any template parameter with level LEVEL.  */
7447
7448 int
7449 uses_template_parms_level (tree t, int level)
7450 {
7451   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
7452                                  /*include_nondeduced_p=*/true);
7453 }
7454
7455 static int tinst_depth;
7456 extern int max_tinst_depth;
7457 #ifdef GATHER_STATISTICS
7458 int depth_reached;
7459 #endif
7460 static int tinst_level_tick;
7461 static int last_template_error_tick;
7462
7463 /* We're starting to instantiate D; record the template instantiation context
7464    for diagnostics and to restore it later.  */
7465
7466 int
7467 push_tinst_level (tree d)
7468 {
7469   struct tinst_level *new_level;
7470
7471   if (tinst_depth >= max_tinst_depth)
7472     {
7473       /* If the instantiation in question still has unbound template parms,
7474          we don't really care if we can't instantiate it, so just return.
7475          This happens with base instantiation for implicit `typename'.  */
7476       if (uses_template_parms (d))
7477         return 0;
7478
7479       last_template_error_tick = tinst_level_tick;
7480       error ("template instantiation depth exceeds maximum of %d (use "
7481              "-ftemplate-depth= to increase the maximum) instantiating %qD",
7482              max_tinst_depth, d);
7483
7484       print_instantiation_context ();
7485
7486       return 0;
7487     }
7488
7489   new_level = ggc_alloc_tinst_level ();
7490   new_level->decl = d;
7491   new_level->locus = input_location;
7492   new_level->in_system_header_p = in_system_header;
7493   new_level->next = current_tinst_level;
7494   current_tinst_level = new_level;
7495
7496   ++tinst_depth;
7497 #ifdef GATHER_STATISTICS
7498   if (tinst_depth > depth_reached)
7499     depth_reached = tinst_depth;
7500 #endif
7501
7502   ++tinst_level_tick;
7503   return 1;
7504 }
7505
7506 /* We're done instantiating this template; return to the instantiation
7507    context.  */
7508
7509 void
7510 pop_tinst_level (void)
7511 {
7512   /* Restore the filename and line number stashed away when we started
7513      this instantiation.  */
7514   input_location = current_tinst_level->locus;
7515   current_tinst_level = current_tinst_level->next;
7516   --tinst_depth;
7517   ++tinst_level_tick;
7518 }
7519
7520 /* We're instantiating a deferred template; restore the template
7521    instantiation context in which the instantiation was requested, which
7522    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
7523
7524 static tree
7525 reopen_tinst_level (struct tinst_level *level)
7526 {
7527   struct tinst_level *t;
7528
7529   tinst_depth = 0;
7530   for (t = level; t; t = t->next)
7531     ++tinst_depth;
7532
7533   current_tinst_level = level;
7534   pop_tinst_level ();
7535   return level->decl;
7536 }
7537
7538 /* Returns the TINST_LEVEL which gives the original instantiation
7539    context.  */
7540
7541 struct tinst_level *
7542 outermost_tinst_level (void)
7543 {
7544   struct tinst_level *level = current_tinst_level;
7545   if (level)
7546     while (level->next)
7547       level = level->next;
7548   return level;
7549 }
7550
7551 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
7552
7553 bool
7554 parameter_of_template_p (tree parm, tree templ)
7555 {
7556   tree parms;
7557   int i;
7558
7559   if (!parm || !templ)
7560     return false;
7561
7562   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
7563   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7564
7565   parms = DECL_TEMPLATE_PARMS (templ);
7566   parms = INNERMOST_TEMPLATE_PARMS (parms);
7567
7568   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
7569     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
7570       return true;
7571
7572   return false;
7573 }
7574
7575 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
7576    vector of template arguments, as for tsubst.
7577
7578    Returns an appropriate tsubst'd friend declaration.  */
7579
7580 static tree
7581 tsubst_friend_function (tree decl, tree args)
7582 {
7583   tree new_friend;
7584
7585   if (TREE_CODE (decl) == FUNCTION_DECL
7586       && DECL_TEMPLATE_INSTANTIATION (decl)
7587       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
7588     /* This was a friend declared with an explicit template
7589        argument list, e.g.:
7590
7591        friend void f<>(T);
7592
7593        to indicate that f was a template instantiation, not a new
7594        function declaration.  Now, we have to figure out what
7595        instantiation of what template.  */
7596     {
7597       tree template_id, arglist, fns;
7598       tree new_args;
7599       tree tmpl;
7600       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
7601
7602       /* Friend functions are looked up in the containing namespace scope.
7603          We must enter that scope, to avoid finding member functions of the
7604          current class with same name.  */
7605       push_nested_namespace (ns);
7606       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
7607                          tf_warning_or_error, NULL_TREE,
7608                          /*integral_constant_expression_p=*/false);
7609       pop_nested_namespace (ns);
7610       arglist = tsubst (DECL_TI_ARGS (decl), args,
7611                         tf_warning_or_error, NULL_TREE);
7612       template_id = lookup_template_function (fns, arglist);
7613
7614       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7615       tmpl = determine_specialization (template_id, new_friend,
7616                                        &new_args,
7617                                        /*need_member_template=*/0,
7618                                        TREE_VEC_LENGTH (args),
7619                                        tsk_none);
7620       return instantiate_template (tmpl, new_args, tf_error);
7621     }
7622
7623   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7624
7625   /* The NEW_FRIEND will look like an instantiation, to the
7626      compiler, but is not an instantiation from the point of view of
7627      the language.  For example, we might have had:
7628
7629      template <class T> struct S {
7630        template <class U> friend void f(T, U);
7631      };
7632
7633      Then, in S<int>, template <class U> void f(int, U) is not an
7634      instantiation of anything.  */
7635   if (new_friend == error_mark_node)
7636     return error_mark_node;
7637
7638   DECL_USE_TEMPLATE (new_friend) = 0;
7639   if (TREE_CODE (decl) == TEMPLATE_DECL)
7640     {
7641       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
7642       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
7643         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
7644     }
7645
7646   /* The mangled name for the NEW_FRIEND is incorrect.  The function
7647      is not a template instantiation and should not be mangled like
7648      one.  Therefore, we forget the mangling here; we'll recompute it
7649      later if we need it.  */
7650   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
7651     {
7652       SET_DECL_RTL (new_friend, NULL);
7653       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
7654     }
7655
7656   if (DECL_NAMESPACE_SCOPE_P (new_friend))
7657     {
7658       tree old_decl;
7659       tree new_friend_template_info;
7660       tree new_friend_result_template_info;
7661       tree ns;
7662       int  new_friend_is_defn;
7663
7664       /* We must save some information from NEW_FRIEND before calling
7665          duplicate decls since that function will free NEW_FRIEND if
7666          possible.  */
7667       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
7668       new_friend_is_defn =
7669             (DECL_INITIAL (DECL_TEMPLATE_RESULT
7670                            (template_for_substitution (new_friend)))
7671              != NULL_TREE);
7672       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
7673         {
7674           /* This declaration is a `primary' template.  */
7675           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
7676
7677           new_friend_result_template_info
7678             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
7679         }
7680       else
7681         new_friend_result_template_info = NULL_TREE;
7682
7683       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
7684       if (new_friend_is_defn)
7685         DECL_INITIAL (new_friend) = error_mark_node;
7686
7687       /* Inside pushdecl_namespace_level, we will push into the
7688          current namespace. However, the friend function should go
7689          into the namespace of the template.  */
7690       ns = decl_namespace_context (new_friend);
7691       push_nested_namespace (ns);
7692       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
7693       pop_nested_namespace (ns);
7694
7695       if (old_decl == error_mark_node)
7696         return error_mark_node;
7697
7698       if (old_decl != new_friend)
7699         {
7700           /* This new friend declaration matched an existing
7701              declaration.  For example, given:
7702
7703                template <class T> void f(T);
7704                template <class U> class C {
7705                  template <class T> friend void f(T) {}
7706                };
7707
7708              the friend declaration actually provides the definition
7709              of `f', once C has been instantiated for some type.  So,
7710              old_decl will be the out-of-class template declaration,
7711              while new_friend is the in-class definition.
7712
7713              But, if `f' was called before this point, the
7714              instantiation of `f' will have DECL_TI_ARGS corresponding
7715              to `T' but not to `U', references to which might appear
7716              in the definition of `f'.  Previously, the most general
7717              template for an instantiation of `f' was the out-of-class
7718              version; now it is the in-class version.  Therefore, we
7719              run through all specialization of `f', adding to their
7720              DECL_TI_ARGS appropriately.  In particular, they need a
7721              new set of outer arguments, corresponding to the
7722              arguments for this class instantiation.
7723
7724              The same situation can arise with something like this:
7725
7726                friend void f(int);
7727                template <class T> class C {
7728                  friend void f(T) {}
7729                };
7730
7731              when `C<int>' is instantiated.  Now, `f(int)' is defined
7732              in the class.  */
7733
7734           if (!new_friend_is_defn)
7735             /* On the other hand, if the in-class declaration does
7736                *not* provide a definition, then we don't want to alter
7737                existing definitions.  We can just leave everything
7738                alone.  */
7739             ;
7740           else
7741             {
7742               tree new_template = TI_TEMPLATE (new_friend_template_info);
7743               tree new_args = TI_ARGS (new_friend_template_info);
7744
7745               /* Overwrite whatever template info was there before, if
7746                  any, with the new template information pertaining to
7747                  the declaration.  */
7748               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
7749
7750               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
7751                 {
7752                   /* We should have called reregister_specialization in
7753                      duplicate_decls.  */
7754                   gcc_assert (retrieve_specialization (new_template,
7755                                                        new_args, 0)
7756                               == old_decl);
7757
7758                   /* Instantiate it if the global has already been used.  */
7759                   if (DECL_ODR_USED (old_decl))
7760                     instantiate_decl (old_decl, /*defer_ok=*/true,
7761                                       /*expl_inst_class_mem_p=*/false);
7762                 }
7763               else
7764                 {
7765                   tree t;
7766
7767                   /* Indicate that the old function template is a partial
7768                      instantiation.  */
7769                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
7770                     = new_friend_result_template_info;
7771
7772                   gcc_assert (new_template
7773                               == most_general_template (new_template));
7774                   gcc_assert (new_template != old_decl);
7775
7776                   /* Reassign any specializations already in the hash table
7777                      to the new more general template, and add the
7778                      additional template args.  */
7779                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
7780                        t != NULL_TREE;
7781                        t = TREE_CHAIN (t))
7782                     {
7783                       tree spec = TREE_VALUE (t);
7784                       spec_entry elt;
7785
7786                       elt.tmpl = old_decl;
7787                       elt.args = DECL_TI_ARGS (spec);
7788                       elt.spec = NULL_TREE;
7789
7790                       htab_remove_elt (decl_specializations, &elt);
7791
7792                       DECL_TI_ARGS (spec)
7793                         = add_outermost_template_args (new_args,
7794                                                        DECL_TI_ARGS (spec));
7795
7796                       register_specialization
7797                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
7798
7799                     }
7800                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
7801                 }
7802             }
7803
7804           /* The information from NEW_FRIEND has been merged into OLD_DECL
7805              by duplicate_decls.  */
7806           new_friend = old_decl;
7807         }
7808     }
7809   else
7810     {
7811       tree context = DECL_CONTEXT (new_friend);
7812       bool dependent_p;
7813
7814       /* In the code
7815            template <class T> class C {
7816              template <class U> friend void C1<U>::f (); // case 1
7817              friend void C2<T>::f ();                    // case 2
7818            };
7819          we only need to make sure CONTEXT is a complete type for
7820          case 2.  To distinguish between the two cases, we note that
7821          CONTEXT of case 1 remains dependent type after tsubst while
7822          this isn't true for case 2.  */
7823       ++processing_template_decl;
7824       dependent_p = dependent_type_p (context);
7825       --processing_template_decl;
7826
7827       if (!dependent_p
7828           && !complete_type_or_else (context, NULL_TREE))
7829         return error_mark_node;
7830
7831       if (COMPLETE_TYPE_P (context))
7832         {
7833           /* Check to see that the declaration is really present, and,
7834              possibly obtain an improved declaration.  */
7835           tree fn = check_classfn (context,
7836                                    new_friend, NULL_TREE);
7837
7838           if (fn)
7839             new_friend = fn;
7840         }
7841     }
7842
7843   return new_friend;
7844 }
7845
7846 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
7847    template arguments, as for tsubst.
7848
7849    Returns an appropriate tsubst'd friend type or error_mark_node on
7850    failure.  */
7851
7852 static tree
7853 tsubst_friend_class (tree friend_tmpl, tree args)
7854 {
7855   tree friend_type;
7856   tree tmpl;
7857   tree context;
7858
7859   context = CP_DECL_CONTEXT (friend_tmpl);
7860
7861   if (context != global_namespace)
7862     {
7863       if (TREE_CODE (context) == NAMESPACE_DECL)
7864         push_nested_namespace (context);
7865       else
7866         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
7867     }
7868
7869   /* Look for a class template declaration.  We look for hidden names
7870      because two friend declarations of the same template are the
7871      same.  For example, in:
7872
7873        struct A { 
7874          template <typename> friend class F;
7875        };
7876        template <typename> struct B { 
7877          template <typename> friend class F;
7878        };
7879
7880      both F templates are the same.  */
7881   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
7882                            /*block_p=*/true, 0, 
7883                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
7884
7885   /* But, if we don't find one, it might be because we're in a
7886      situation like this:
7887
7888        template <class T>
7889        struct S {
7890          template <class U>
7891          friend struct S;
7892        };
7893
7894      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
7895      for `S<int>', not the TEMPLATE_DECL.  */
7896   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
7897     {
7898       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
7899       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
7900     }
7901
7902   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
7903     {
7904       /* The friend template has already been declared.  Just
7905          check to see that the declarations match, and install any new
7906          default parameters.  We must tsubst the default parameters,
7907          of course.  We only need the innermost template parameters
7908          because that is all that redeclare_class_template will look
7909          at.  */
7910       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
7911           > TMPL_ARGS_DEPTH (args))
7912         {
7913           tree parms;
7914           location_t saved_input_location;
7915           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
7916                                          args, tf_warning_or_error);
7917
7918           saved_input_location = input_location;
7919           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
7920           redeclare_class_template (TREE_TYPE (tmpl), parms);
7921           input_location = saved_input_location;
7922           
7923         }
7924
7925       friend_type = TREE_TYPE (tmpl);
7926     }
7927   else
7928     {
7929       /* The friend template has not already been declared.  In this
7930          case, the instantiation of the template class will cause the
7931          injection of this template into the global scope.  */
7932       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7933       if (tmpl == error_mark_node)
7934         return error_mark_node;
7935
7936       /* The new TMPL is not an instantiation of anything, so we
7937          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7938          the new type because that is supposed to be the corresponding
7939          template decl, i.e., TMPL.  */
7940       DECL_USE_TEMPLATE (tmpl) = 0;
7941       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7942       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7943       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7944         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7945
7946       /* Inject this template into the global scope.  */
7947       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7948     }
7949
7950   if (context != global_namespace)
7951     {
7952       if (TREE_CODE (context) == NAMESPACE_DECL)
7953         pop_nested_namespace (context);
7954       else
7955         pop_nested_class ();
7956     }
7957
7958   return friend_type;
7959 }
7960
7961 /* Returns zero if TYPE cannot be completed later due to circularity.
7962    Otherwise returns one.  */
7963
7964 static int
7965 can_complete_type_without_circularity (tree type)
7966 {
7967   if (type == NULL_TREE || type == error_mark_node)
7968     return 0;
7969   else if (COMPLETE_TYPE_P (type))
7970     return 1;
7971   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
7972     return can_complete_type_without_circularity (TREE_TYPE (type));
7973   else if (CLASS_TYPE_P (type)
7974            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
7975     return 0;
7976   else
7977     return 1;
7978 }
7979
7980 /* Apply any attributes which had to be deferred until instantiation
7981    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
7982    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
7983
7984 static void
7985 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
7986                                 tree args, tsubst_flags_t complain, tree in_decl)
7987 {
7988   tree last_dep = NULL_TREE;
7989   tree t;
7990   tree *p;
7991
7992   for (t = attributes; t; t = TREE_CHAIN (t))
7993     if (ATTR_IS_DEPENDENT (t))
7994       {
7995         last_dep = t;
7996         attributes = copy_list (attributes);
7997         break;
7998       }
7999
8000   if (DECL_P (*decl_p))
8001     {
8002       if (TREE_TYPE (*decl_p) == error_mark_node)
8003         return;
8004       p = &DECL_ATTRIBUTES (*decl_p);
8005     }
8006   else
8007     p = &TYPE_ATTRIBUTES (*decl_p);
8008
8009   if (last_dep)
8010     {
8011       tree late_attrs = NULL_TREE;
8012       tree *q = &late_attrs;
8013
8014       for (*p = attributes; *p; )
8015         {
8016           t = *p;
8017           if (ATTR_IS_DEPENDENT (t))
8018             {
8019               *p = TREE_CHAIN (t);
8020               TREE_CHAIN (t) = NULL_TREE;
8021               /* If the first attribute argument is an identifier, don't
8022                  pass it through tsubst.  Attributes like mode, format,
8023                  cleanup and several target specific attributes expect it
8024                  unmodified.  */
8025               if (TREE_VALUE (t)
8026                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
8027                   && TREE_VALUE (TREE_VALUE (t))
8028                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
8029                       == IDENTIFIER_NODE))
8030                 {
8031                   tree chain
8032                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
8033                                    in_decl,
8034                                    /*integral_constant_expression_p=*/false);
8035                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
8036                     TREE_VALUE (t)
8037                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
8038                                    chain);
8039                 }
8040               else
8041                 TREE_VALUE (t)
8042                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
8043                                  /*integral_constant_expression_p=*/false);
8044               *q = t;
8045               q = &TREE_CHAIN (t);
8046             }
8047           else
8048             p = &TREE_CHAIN (t);
8049         }
8050
8051       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
8052     }
8053 }
8054
8055 /* Perform (or defer) access check for typedefs that were referenced
8056    from within the template TMPL code.
8057    This is a subroutine of instantiate_template and instantiate_class_template.
8058    TMPL is the template to consider and TARGS is the list of arguments of
8059    that template.  */
8060
8061 static void
8062 perform_typedefs_access_check (tree tmpl, tree targs)
8063 {
8064   location_t saved_location;
8065   int i;
8066   qualified_typedef_usage_t *iter;
8067
8068   if (!tmpl
8069       || (!CLASS_TYPE_P (tmpl)
8070           && TREE_CODE (tmpl) != FUNCTION_DECL))
8071     return;
8072
8073   saved_location = input_location;
8074   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
8075                     get_types_needing_access_check (tmpl),
8076                     i, iter)
8077     {
8078       tree type_decl = iter->typedef_decl;
8079       tree type_scope = iter->context;
8080
8081       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
8082         continue;
8083
8084       if (uses_template_parms (type_decl))
8085         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
8086       if (uses_template_parms (type_scope))
8087         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
8088
8089       /* Make access check error messages point to the location
8090          of the use of the typedef.  */
8091       input_location = iter->locus;
8092       perform_or_defer_access_check (TYPE_BINFO (type_scope),
8093                                      type_decl, type_decl);
8094     }
8095     input_location = saved_location;
8096 }
8097
8098 tree
8099 instantiate_class_template (tree type)
8100 {
8101   tree templ, args, pattern, t, member;
8102   tree typedecl;
8103   tree pbinfo;
8104   tree base_list;
8105   unsigned int saved_maximum_field_alignment;
8106
8107   if (type == error_mark_node)
8108     return error_mark_node;
8109
8110   if (COMPLETE_OR_OPEN_TYPE_P (type)
8111       || uses_template_parms (type))
8112     return type;
8113
8114   /* Figure out which template is being instantiated.  */
8115   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
8116   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
8117
8118   /* Determine what specialization of the original template to
8119      instantiate.  */
8120   t = most_specialized_class (type, templ, tf_warning_or_error);
8121   if (t == error_mark_node)
8122     {
8123       TYPE_BEING_DEFINED (type) = 1;
8124       return error_mark_node;
8125     }
8126   else if (t)
8127     {
8128       /* This TYPE is actually an instantiation of a partial
8129          specialization.  We replace the innermost set of ARGS with
8130          the arguments appropriate for substitution.  For example,
8131          given:
8132
8133            template <class T> struct S {};
8134            template <class T> struct S<T*> {};
8135
8136          and supposing that we are instantiating S<int*>, ARGS will
8137          presently be {int*} -- but we need {int}.  */
8138       pattern = TREE_TYPE (t);
8139       args = TREE_PURPOSE (t);
8140     }
8141   else
8142     {
8143       pattern = TREE_TYPE (templ);
8144       args = CLASSTYPE_TI_ARGS (type);
8145     }
8146
8147   /* If the template we're instantiating is incomplete, then clearly
8148      there's nothing we can do.  */
8149   if (!COMPLETE_TYPE_P (pattern))
8150     return type;
8151
8152   /* If we've recursively instantiated too many templates, stop.  */
8153   if (! push_tinst_level (type))
8154     return type;
8155
8156   /* Now we're really doing the instantiation.  Mark the type as in
8157      the process of being defined.  */
8158   TYPE_BEING_DEFINED (type) = 1;
8159
8160   /* We may be in the middle of deferred access check.  Disable
8161      it now.  */
8162   push_deferring_access_checks (dk_no_deferred);
8163
8164   push_to_top_level ();
8165   /* Use #pragma pack from the template context.  */
8166   saved_maximum_field_alignment = maximum_field_alignment;
8167   maximum_field_alignment = TYPE_PRECISION (pattern);
8168
8169   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
8170
8171   /* Set the input location to the most specialized template definition.
8172      This is needed if tsubsting causes an error.  */
8173   typedecl = TYPE_MAIN_DECL (pattern);
8174   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
8175     DECL_SOURCE_LOCATION (typedecl);
8176
8177   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
8178   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
8179   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
8180   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
8181   TYPE_HAS_COPY_ASSIGN (type) = TYPE_HAS_COPY_ASSIGN (pattern);
8182   TYPE_HAS_CONST_COPY_ASSIGN (type) = TYPE_HAS_CONST_COPY_ASSIGN (pattern);
8183   TYPE_HAS_COPY_CTOR (type) = TYPE_HAS_COPY_CTOR (pattern);
8184   TYPE_HAS_CONST_COPY_CTOR (type) = TYPE_HAS_CONST_COPY_CTOR (pattern);
8185   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
8186   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
8187   TYPE_PACKED (type) = TYPE_PACKED (pattern);
8188   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
8189   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
8190   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
8191   if (ANON_AGGR_TYPE_P (pattern))
8192     SET_ANON_AGGR_TYPE_P (type);
8193   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
8194     {
8195       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
8196       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
8197     }
8198
8199   pbinfo = TYPE_BINFO (pattern);
8200
8201   /* We should never instantiate a nested class before its enclosing
8202      class; we need to look up the nested class by name before we can
8203      instantiate it, and that lookup should instantiate the enclosing
8204      class.  */
8205   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
8206               || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
8207
8208   base_list = NULL_TREE;
8209   if (BINFO_N_BASE_BINFOS (pbinfo))
8210     {
8211       tree pbase_binfo;
8212       tree pushed_scope;
8213       int i;
8214
8215       /* We must enter the scope containing the type, as that is where
8216          the accessibility of types named in dependent bases are
8217          looked up from.  */
8218       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
8219
8220       /* Substitute into each of the bases to determine the actual
8221          basetypes.  */
8222       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
8223         {
8224           tree base;
8225           tree access = BINFO_BASE_ACCESS (pbinfo, i);
8226           tree expanded_bases = NULL_TREE;
8227           int idx, len = 1;
8228
8229           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
8230             {
8231               expanded_bases = 
8232                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
8233                                        args, tf_error, NULL_TREE);
8234               if (expanded_bases == error_mark_node)
8235                 continue;
8236
8237               len = TREE_VEC_LENGTH (expanded_bases);
8238             }
8239
8240           for (idx = 0; idx < len; idx++)
8241             {
8242               if (expanded_bases)
8243                 /* Extract the already-expanded base class.  */
8244                 base = TREE_VEC_ELT (expanded_bases, idx);
8245               else
8246                 /* Substitute to figure out the base class.  */
8247                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
8248                                NULL_TREE);
8249
8250               if (base == error_mark_node)
8251                 continue;
8252
8253               base_list = tree_cons (access, base, base_list);
8254               if (BINFO_VIRTUAL_P (pbase_binfo))
8255                 TREE_TYPE (base_list) = integer_type_node;
8256             }
8257         }
8258
8259       /* The list is now in reverse order; correct that.  */
8260       base_list = nreverse (base_list);
8261
8262       if (pushed_scope)
8263         pop_scope (pushed_scope);
8264     }
8265   /* Now call xref_basetypes to set up all the base-class
8266      information.  */
8267   xref_basetypes (type, base_list);
8268
8269   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
8270                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
8271                                   args, tf_error, NULL_TREE);
8272   fixup_attribute_variants (type);
8273
8274   /* Now that our base classes are set up, enter the scope of the
8275      class, so that name lookups into base classes, etc. will work
8276      correctly.  This is precisely analogous to what we do in
8277      begin_class_definition when defining an ordinary non-template
8278      class, except we also need to push the enclosing classes.  */
8279   push_nested_class (type);
8280
8281   /* Now members are processed in the order of declaration.  */
8282   for (member = CLASSTYPE_DECL_LIST (pattern);
8283        member; member = TREE_CHAIN (member))
8284     {
8285       tree t = TREE_VALUE (member);
8286
8287       if (TREE_PURPOSE (member))
8288         {
8289           if (TYPE_P (t))
8290             {
8291               /* Build new CLASSTYPE_NESTED_UTDS.  */
8292
8293               tree newtag;
8294               bool class_template_p;
8295
8296               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
8297                                   && TYPE_LANG_SPECIFIC (t)
8298                                   && CLASSTYPE_IS_TEMPLATE (t));
8299               /* If the member is a class template, then -- even after
8300                  substitution -- there may be dependent types in the
8301                  template argument list for the class.  We increment
8302                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
8303                  that function will assume that no types are dependent
8304                  when outside of a template.  */
8305               if (class_template_p)
8306                 ++processing_template_decl;
8307               newtag = tsubst (t, args, tf_error, NULL_TREE);
8308               if (class_template_p)
8309                 --processing_template_decl;
8310               if (newtag == error_mark_node)
8311                 continue;
8312
8313               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
8314                 {
8315                   tree name = TYPE_IDENTIFIER (t);
8316
8317                   if (class_template_p)
8318                     /* Unfortunately, lookup_template_class sets
8319                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
8320                        instantiation (i.e., for the type of a member
8321                        template class nested within a template class.)
8322                        This behavior is required for
8323                        maybe_process_partial_specialization to work
8324                        correctly, but is not accurate in this case;
8325                        the TAG is not an instantiation of anything.
8326                        (The corresponding TEMPLATE_DECL is an
8327                        instantiation, but the TYPE is not.) */
8328                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
8329
8330                   /* Now, we call pushtag to put this NEWTAG into the scope of
8331                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
8332                      pushtag calling push_template_decl.  We don't have to do
8333                      this for enums because it will already have been done in
8334                      tsubst_enum.  */
8335                   if (name)
8336                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
8337                   pushtag (name, newtag, /*tag_scope=*/ts_current);
8338                 }
8339             }
8340           else if (TREE_CODE (t) == FUNCTION_DECL
8341                    || DECL_FUNCTION_TEMPLATE_P (t))
8342             {
8343               /* Build new TYPE_METHODS.  */
8344               tree r;
8345
8346               if (TREE_CODE (t) == TEMPLATE_DECL)
8347                 ++processing_template_decl;
8348               r = tsubst (t, args, tf_error, NULL_TREE);
8349               if (TREE_CODE (t) == TEMPLATE_DECL)
8350                 --processing_template_decl;
8351               set_current_access_from_decl (r);
8352               finish_member_declaration (r);
8353             }
8354           else
8355             {
8356               /* Build new TYPE_FIELDS.  */
8357               if (TREE_CODE (t) == STATIC_ASSERT)
8358                 {
8359                   tree condition = 
8360                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
8361                                  tf_warning_or_error, NULL_TREE,
8362                                  /*integral_constant_expression_p=*/true);
8363                   finish_static_assert (condition,
8364                                         STATIC_ASSERT_MESSAGE (t), 
8365                                         STATIC_ASSERT_SOURCE_LOCATION (t),
8366                                         /*member_p=*/true);
8367                 }
8368               else if (TREE_CODE (t) != CONST_DECL)
8369                 {
8370                   tree r;
8371
8372                   /* The file and line for this declaration, to
8373                      assist in error message reporting.  Since we
8374                      called push_tinst_level above, we don't need to
8375                      restore these.  */
8376                   input_location = DECL_SOURCE_LOCATION (t);
8377
8378                   if (TREE_CODE (t) == TEMPLATE_DECL)
8379                     ++processing_template_decl;
8380                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
8381                   if (TREE_CODE (t) == TEMPLATE_DECL)
8382                     --processing_template_decl;
8383                   if (TREE_CODE (r) == VAR_DECL)
8384                     {
8385                       /* In [temp.inst]:
8386
8387                            [t]he initialization (and any associated
8388                            side-effects) of a static data member does
8389                            not occur unless the static data member is
8390                            itself used in a way that requires the
8391                            definition of the static data member to
8392                            exist.
8393
8394                          Therefore, we do not substitute into the
8395                          initialized for the static data member here.  */
8396                       finish_static_data_member_decl
8397                         (r,
8398                          /*init=*/NULL_TREE,
8399                          /*init_const_expr_p=*/false,
8400                          /*asmspec_tree=*/NULL_TREE,
8401                          /*flags=*/0);
8402                       if (DECL_INITIALIZED_IN_CLASS_P (r))
8403                         check_static_variable_definition (r, TREE_TYPE (r));
8404                     }
8405                   else if (TREE_CODE (r) == FIELD_DECL)
8406                     {
8407                       /* Determine whether R has a valid type and can be
8408                          completed later.  If R is invalid, then it is
8409                          replaced by error_mark_node so that it will not be
8410                          added to TYPE_FIELDS.  */
8411                       tree rtype = TREE_TYPE (r);
8412                       if (can_complete_type_without_circularity (rtype))
8413                         complete_type (rtype);
8414
8415                       if (!COMPLETE_TYPE_P (rtype))
8416                         {
8417                           cxx_incomplete_type_error (r, rtype);
8418                           r = error_mark_node;
8419                         }
8420                     }
8421
8422                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
8423                      such a thing will already have been added to the field
8424                      list by tsubst_enum in finish_member_declaration in the
8425                      CLASSTYPE_NESTED_UTDS case above.  */
8426                   if (!(TREE_CODE (r) == TYPE_DECL
8427                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
8428                         && DECL_ARTIFICIAL (r)))
8429                     {
8430                       set_current_access_from_decl (r);
8431                       finish_member_declaration (r);
8432                     }
8433                 }
8434             }
8435         }
8436       else
8437         {
8438           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
8439             {
8440               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
8441
8442               tree friend_type = t;
8443               bool adjust_processing_template_decl = false;
8444
8445               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8446                 {
8447                   /* template <class T> friend class C;  */
8448                   friend_type = tsubst_friend_class (friend_type, args);
8449                   adjust_processing_template_decl = true;
8450                 }
8451               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
8452                 {
8453                   /* template <class T> friend class C::D;  */
8454                   friend_type = tsubst (friend_type, args,
8455                                         tf_warning_or_error, NULL_TREE);
8456                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8457                     friend_type = TREE_TYPE (friend_type);
8458                   adjust_processing_template_decl = true;
8459                 }
8460               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
8461                 {
8462                   /* This could be either
8463
8464                        friend class T::C;
8465
8466                      when dependent_type_p is false or
8467
8468                        template <class U> friend class T::C;
8469
8470                      otherwise.  */
8471                   friend_type = tsubst (friend_type, args,
8472                                         tf_warning_or_error, NULL_TREE);
8473                   /* Bump processing_template_decl for correct
8474                      dependent_type_p calculation.  */
8475                   ++processing_template_decl;
8476                   if (dependent_type_p (friend_type))
8477                     adjust_processing_template_decl = true;
8478                   --processing_template_decl;
8479                 }
8480               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
8481                        && hidden_name_p (TYPE_NAME (friend_type)))
8482                 {
8483                   /* friend class C;
8484
8485                      where C hasn't been declared yet.  Let's lookup name
8486                      from namespace scope directly, bypassing any name that
8487                      come from dependent base class.  */
8488                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
8489
8490                   /* The call to xref_tag_from_type does injection for friend
8491                      classes.  */
8492                   push_nested_namespace (ns);
8493                   friend_type =
8494                     xref_tag_from_type (friend_type, NULL_TREE,
8495                                         /*tag_scope=*/ts_current);
8496                   pop_nested_namespace (ns);
8497                 }
8498               else if (uses_template_parms (friend_type))
8499                 /* friend class C<T>;  */
8500                 friend_type = tsubst (friend_type, args,
8501                                       tf_warning_or_error, NULL_TREE);
8502               /* Otherwise it's
8503
8504                    friend class C;
8505
8506                  where C is already declared or
8507
8508                    friend class C<int>;
8509
8510                  We don't have to do anything in these cases.  */
8511
8512               if (adjust_processing_template_decl)
8513                 /* Trick make_friend_class into realizing that the friend
8514                    we're adding is a template, not an ordinary class.  It's
8515                    important that we use make_friend_class since it will
8516                    perform some error-checking and output cross-reference
8517                    information.  */
8518                 ++processing_template_decl;
8519
8520               if (friend_type != error_mark_node)
8521                 make_friend_class (type, friend_type, /*complain=*/false);
8522
8523               if (adjust_processing_template_decl)
8524                 --processing_template_decl;
8525             }
8526           else
8527             {
8528               /* Build new DECL_FRIENDLIST.  */
8529               tree r;
8530
8531               /* The file and line for this declaration, to
8532                  assist in error message reporting.  Since we
8533                  called push_tinst_level above, we don't need to
8534                  restore these.  */
8535               input_location = DECL_SOURCE_LOCATION (t);
8536
8537               if (TREE_CODE (t) == TEMPLATE_DECL)
8538                 {
8539                   ++processing_template_decl;
8540                   push_deferring_access_checks (dk_no_check);
8541                 }
8542
8543               r = tsubst_friend_function (t, args);
8544               add_friend (type, r, /*complain=*/false);
8545               if (TREE_CODE (t) == TEMPLATE_DECL)
8546                 {
8547                   pop_deferring_access_checks ();
8548                   --processing_template_decl;
8549                 }
8550             }
8551         }
8552     }
8553
8554   /* Set the file and line number information to whatever is given for
8555      the class itself.  This puts error messages involving generated
8556      implicit functions at a predictable point, and the same point
8557      that would be used for non-template classes.  */
8558   input_location = DECL_SOURCE_LOCATION (typedecl);
8559
8560   unreverse_member_declarations (type);
8561   finish_struct_1 (type);
8562   TYPE_BEING_DEFINED (type) = 0;
8563
8564   /* We don't instantiate default arguments for member functions.  14.7.1:
8565
8566      The implicit instantiation of a class template specialization causes
8567      the implicit instantiation of the declarations, but not of the
8568      definitions or default arguments, of the class member functions,
8569      member classes, static data members and member templates....  */
8570
8571   /* Some typedefs referenced from within the template code need to be access
8572      checked at template instantiation time, i.e now. These types were
8573      added to the template at parsing time. Let's get those and perform
8574      the access checks then.  */
8575   perform_typedefs_access_check (pattern, args);
8576   perform_deferred_access_checks ();
8577   pop_nested_class ();
8578   maximum_field_alignment = saved_maximum_field_alignment;
8579   pop_from_top_level ();
8580   pop_deferring_access_checks ();
8581   pop_tinst_level ();
8582
8583   /* The vtable for a template class can be emitted in any translation
8584      unit in which the class is instantiated.  When there is no key
8585      method, however, finish_struct_1 will already have added TYPE to
8586      the keyed_classes list.  */
8587   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
8588     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
8589
8590   return type;
8591 }
8592
8593 static tree
8594 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8595 {
8596   tree r;
8597
8598   if (!t)
8599     r = t;
8600   else if (TYPE_P (t))
8601     r = tsubst (t, args, complain, in_decl);
8602   else
8603     {
8604       if (!(complain & tf_warning))
8605         ++c_inhibit_evaluation_warnings;
8606       r = tsubst_expr (t, args, complain, in_decl,
8607                        /*integral_constant_expression_p=*/true);
8608       if (!(complain & tf_warning))
8609         --c_inhibit_evaluation_warnings;
8610     }
8611   return r;
8612 }
8613
8614 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
8615    NONTYPE_ARGUMENT_PACK.  */
8616
8617 static tree
8618 make_fnparm_pack (tree spec_parm)
8619 {
8620   /* Collect all of the extra "packed" parameters into an
8621      argument pack.  */
8622   tree parmvec;
8623   tree parmtypevec;
8624   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
8625   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
8626   int i, len = list_length (spec_parm);
8627
8628   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
8629   parmvec = make_tree_vec (len);
8630   parmtypevec = make_tree_vec (len);
8631   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
8632     {
8633       TREE_VEC_ELT (parmvec, i) = spec_parm;
8634       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
8635     }
8636
8637   /* Build the argument packs.  */
8638   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
8639   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
8640   TREE_TYPE (argpack) = argtypepack;
8641
8642   return argpack;
8643 }        
8644
8645 /* Substitute ARGS into T, which is an pack expansion
8646    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
8647    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
8648    (if only a partial substitution could be performed) or
8649    ERROR_MARK_NODE if there was an error.  */
8650 tree
8651 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
8652                        tree in_decl)
8653 {
8654   tree pattern;
8655   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
8656   int i, len = -1;
8657   tree result;
8658   int incomplete = 0;
8659   htab_t saved_local_specializations = NULL;
8660
8661   gcc_assert (PACK_EXPANSION_P (t));
8662   pattern = PACK_EXPANSION_PATTERN (t);
8663
8664   /* Determine the argument packs that will instantiate the parameter
8665      packs used in the expansion expression. While we're at it,
8666      compute the number of arguments to be expanded and make sure it
8667      is consistent.  */
8668   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
8669        pack = TREE_CHAIN (pack))
8670     {
8671       tree parm_pack = TREE_VALUE (pack);
8672       tree arg_pack = NULL_TREE;
8673       tree orig_arg = NULL_TREE;
8674
8675       if (TREE_CODE (parm_pack) == PARM_DECL)
8676         {
8677           if (!cp_unevaluated_operand)
8678             arg_pack = retrieve_local_specialization (parm_pack);
8679           else
8680             {
8681               /* We can't rely on local_specializations for a parameter
8682                  name used later in a function declaration (such as in a
8683                  late-specified return type).  Even if it exists, it might
8684                  have the wrong value for a recursive call.  Just make a
8685                  dummy decl, since it's only used for its type.  */
8686               arg_pack = tsubst_decl (parm_pack, args, complain);
8687               arg_pack = make_fnparm_pack (arg_pack);
8688             }
8689         }
8690       else
8691         {
8692           int level, idx, levels;
8693           template_parm_level_and_index (parm_pack, &level, &idx);
8694
8695           levels = TMPL_ARGS_DEPTH (args);
8696           if (level <= levels)
8697             arg_pack = TMPL_ARG (args, level, idx);
8698         }
8699
8700       orig_arg = arg_pack;
8701       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
8702         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
8703       
8704       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
8705         /* This can only happen if we forget to expand an argument
8706            pack somewhere else. Just return an error, silently.  */
8707         {
8708           result = make_tree_vec (1);
8709           TREE_VEC_ELT (result, 0) = error_mark_node;
8710           return result;
8711         }
8712
8713       if (arg_pack
8714           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
8715           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
8716         {
8717           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
8718           tree pattern = PACK_EXPANSION_PATTERN (expansion);
8719           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
8720               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
8721             /* The argument pack that the parameter maps to is just an
8722                expansion of the parameter itself, such as one would
8723                find in the implicit typedef of a class inside the
8724                class itself.  Consider this parameter "unsubstituted",
8725                so that we will maintain the outer pack expansion.  */
8726             arg_pack = NULL_TREE;
8727         }
8728           
8729       if (arg_pack)
8730         {
8731           int my_len = 
8732             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
8733
8734           /* It's all-or-nothing with incomplete argument packs.  */
8735           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8736             return error_mark_node;
8737           
8738           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8739             incomplete = 1;
8740
8741           if (len < 0)
8742             len = my_len;
8743           else if (len != my_len)
8744             {
8745               if (incomplete)
8746                 /* We got explicit args for some packs but not others;
8747                    do nothing now and try again after deduction.  */
8748                 return t;
8749               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
8750                 error ("mismatched argument pack lengths while expanding "
8751                        "%<%T%>",
8752                        pattern);
8753               else
8754                 error ("mismatched argument pack lengths while expanding "
8755                        "%<%E%>",
8756                        pattern);
8757               return error_mark_node;
8758             }
8759
8760           /* Keep track of the parameter packs and their corresponding
8761              argument packs.  */
8762           packs = tree_cons (parm_pack, arg_pack, packs);
8763           TREE_TYPE (packs) = orig_arg;
8764         }
8765       else
8766         /* We can't substitute for this parameter pack.  */
8767         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
8768                                          TREE_VALUE (pack),
8769                                          unsubstituted_packs);
8770     }
8771
8772   /* We cannot expand this expansion expression, because we don't have
8773      all of the argument packs we need. Substitute into the pattern
8774      and return a PACK_EXPANSION_*. The caller will need to deal with
8775      that.  */
8776   if (unsubstituted_packs)
8777     {
8778       tree new_pat;
8779       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8780         new_pat = tsubst_expr (pattern, args, complain, in_decl,
8781                                /*integral_constant_expression_p=*/false);
8782       else
8783         new_pat = tsubst (pattern, args, complain, in_decl);
8784       return make_pack_expansion (new_pat);
8785     }
8786
8787   /* We could not find any argument packs that work.  */
8788   if (len < 0)
8789     return error_mark_node;
8790
8791   if (cp_unevaluated_operand)
8792     {
8793       /* We're in a late-specified return type, so create our own local
8794          specializations table; the current table is either NULL or (in the
8795          case of recursive unification) might have bindings that we don't
8796          want to use or alter.  */
8797       saved_local_specializations = local_specializations;
8798       local_specializations = htab_create (37,
8799                                            hash_local_specialization,
8800                                            eq_local_specializations,
8801                                            NULL);
8802     }
8803
8804   /* For each argument in each argument pack, substitute into the
8805      pattern.  */
8806   result = make_tree_vec (len + incomplete);
8807   for (i = 0; i < len + incomplete; ++i)
8808     {
8809       /* For parameter pack, change the substitution of the parameter
8810          pack to the ith argument in its argument pack, then expand
8811          the pattern.  */
8812       for (pack = packs; pack; pack = TREE_CHAIN (pack))
8813         {
8814           tree parm = TREE_PURPOSE (pack);
8815
8816           if (TREE_CODE (parm) == PARM_DECL)
8817             {
8818               /* Select the Ith argument from the pack.  */
8819               tree arg = make_node (ARGUMENT_PACK_SELECT);
8820               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
8821               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
8822               mark_used (parm);
8823               register_local_specialization (arg, parm);
8824             }
8825           else
8826             {
8827               tree value = parm;
8828               int idx, level;
8829               template_parm_level_and_index (parm, &level, &idx);
8830               
8831               if (i < len) 
8832                 {
8833                   /* Select the Ith argument from the pack. */
8834                   value = make_node (ARGUMENT_PACK_SELECT);
8835                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
8836                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
8837                 }
8838
8839               /* Update the corresponding argument.  */
8840               TMPL_ARG (args, level, idx) = value;
8841             }
8842         }
8843
8844       /* Substitute into the PATTERN with the altered arguments.  */
8845       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8846         TREE_VEC_ELT (result, i) = 
8847           tsubst_expr (pattern, args, complain, in_decl,
8848                        /*integral_constant_expression_p=*/false);
8849       else
8850         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
8851
8852       if (i == len)
8853         /* When we have incomplete argument packs, the last "expanded"
8854            result is itself a pack expansion, which allows us
8855            to deduce more arguments.  */
8856         TREE_VEC_ELT (result, i) = 
8857           make_pack_expansion (TREE_VEC_ELT (result, i));
8858
8859       if (TREE_VEC_ELT (result, i) == error_mark_node)
8860         {
8861           result = error_mark_node;
8862           break;
8863         }
8864     }
8865
8866   /* Update ARGS to restore the substitution from parameter packs to
8867      their argument packs.  */
8868   for (pack = packs; pack; pack = TREE_CHAIN (pack))
8869     {
8870       tree parm = TREE_PURPOSE (pack);
8871
8872       if (TREE_CODE (parm) == PARM_DECL)
8873         register_local_specialization (TREE_TYPE (pack), parm);
8874       else
8875         {
8876           int idx, level;
8877           template_parm_level_and_index (parm, &level, &idx);
8878           
8879           /* Update the corresponding argument.  */
8880           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
8881             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
8882               TREE_TYPE (pack);
8883           else
8884             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
8885         }
8886     }
8887
8888   if (saved_local_specializations)
8889     {
8890       htab_delete (local_specializations);
8891       local_specializations = saved_local_specializations;
8892     }
8893   
8894   return result;
8895 }
8896
8897 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
8898    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
8899    parameter packs; all parms generated from a function parameter pack will
8900    have the same DECL_PARM_INDEX.  */
8901
8902 tree
8903 get_pattern_parm (tree parm, tree tmpl)
8904 {
8905   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
8906   tree patparm;
8907
8908   if (DECL_ARTIFICIAL (parm))
8909     {
8910       for (patparm = DECL_ARGUMENTS (pattern);
8911            patparm; patparm = DECL_CHAIN (patparm))
8912         if (DECL_ARTIFICIAL (patparm)
8913             && DECL_NAME (parm) == DECL_NAME (patparm))
8914           break;
8915     }
8916   else
8917     {
8918       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
8919       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
8920       gcc_assert (DECL_PARM_INDEX (patparm)
8921                   == DECL_PARM_INDEX (parm));
8922     }
8923
8924   return patparm;
8925 }
8926
8927 /* Substitute ARGS into the vector or list of template arguments T.  */
8928
8929 static tree
8930 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8931 {
8932   tree orig_t = t;
8933   int len = TREE_VEC_LENGTH (t);
8934   int need_new = 0, i, expanded_len_adjust = 0, out;
8935   tree *elts = XALLOCAVEC (tree, len);
8936
8937   for (i = 0; i < len; i++)
8938     {
8939       tree orig_arg = TREE_VEC_ELT (t, i);
8940       tree new_arg;
8941
8942       if (TREE_CODE (orig_arg) == TREE_VEC)
8943         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
8944       else if (PACK_EXPANSION_P (orig_arg))
8945         {
8946           /* Substitute into an expansion expression.  */
8947           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
8948
8949           if (TREE_CODE (new_arg) == TREE_VEC)
8950             /* Add to the expanded length adjustment the number of
8951                expanded arguments. We subtract one from this
8952                measurement, because the argument pack expression
8953                itself is already counted as 1 in
8954                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
8955                the argument pack is empty.  */
8956             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
8957         }
8958       else if (ARGUMENT_PACK_P (orig_arg))
8959         {
8960           /* Substitute into each of the arguments.  */
8961           new_arg = TYPE_P (orig_arg)
8962             ? cxx_make_type (TREE_CODE (orig_arg))
8963             : make_node (TREE_CODE (orig_arg));
8964           
8965           SET_ARGUMENT_PACK_ARGS (
8966             new_arg,
8967             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
8968                                   args, complain, in_decl));
8969
8970           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
8971             new_arg = error_mark_node;
8972
8973           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
8974             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
8975                                           complain, in_decl);
8976             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
8977
8978             if (TREE_TYPE (new_arg) == error_mark_node)
8979               new_arg = error_mark_node;
8980           }
8981         }
8982       else
8983         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
8984
8985       if (new_arg == error_mark_node)
8986         return error_mark_node;
8987
8988       elts[i] = new_arg;
8989       if (new_arg != orig_arg)
8990         need_new = 1;
8991     }
8992
8993   if (!need_new)
8994     return t;
8995
8996   /* Make space for the expanded arguments coming from template
8997      argument packs.  */
8998   t = make_tree_vec (len + expanded_len_adjust);
8999   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
9000      arguments for a member template.
9001      In that case each TREE_VEC in ORIG_T represents a level of template
9002      arguments, and ORIG_T won't carry any non defaulted argument count.
9003      It will rather be the nested TREE_VECs that will carry one.
9004      In other words, ORIG_T carries a non defaulted argument count only
9005      if it doesn't contain any nested TREE_VEC.  */
9006   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
9007     {
9008       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
9009       count += expanded_len_adjust;
9010       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
9011     }
9012   for (i = 0, out = 0; i < len; i++)
9013     {
9014       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
9015            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
9016           && TREE_CODE (elts[i]) == TREE_VEC)
9017         {
9018           int idx;
9019
9020           /* Now expand the template argument pack "in place".  */
9021           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
9022             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
9023         }
9024       else
9025         {
9026           TREE_VEC_ELT (t, out) = elts[i];
9027           out++;
9028         }
9029     }
9030
9031   return t;
9032 }
9033
9034 /* Return the result of substituting ARGS into the template parameters
9035    given by PARMS.  If there are m levels of ARGS and m + n levels of
9036    PARMS, then the result will contain n levels of PARMS.  For
9037    example, if PARMS is `template <class T> template <class U>
9038    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
9039    result will be `template <int*, double, class V>'.  */
9040
9041 static tree
9042 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
9043 {
9044   tree r = NULL_TREE;
9045   tree* new_parms;
9046
9047   /* When substituting into a template, we must set
9048      PROCESSING_TEMPLATE_DECL as the template parameters may be
9049      dependent if they are based on one-another, and the dependency
9050      predicates are short-circuit outside of templates.  */
9051   ++processing_template_decl;
9052
9053   for (new_parms = &r;
9054        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
9055        new_parms = &(TREE_CHAIN (*new_parms)),
9056          parms = TREE_CHAIN (parms))
9057     {
9058       tree new_vec =
9059         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
9060       int i;
9061
9062       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
9063         {
9064           tree tuple;
9065
9066           if (parms == error_mark_node)
9067             continue;
9068
9069           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
9070
9071           if (tuple == error_mark_node)
9072             continue;
9073
9074           TREE_VEC_ELT (new_vec, i) =
9075             tsubst_template_parm (tuple, args, complain);
9076         }
9077
9078       *new_parms =
9079         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
9080                              - TMPL_ARGS_DEPTH (args)),
9081                    new_vec, NULL_TREE);
9082     }
9083
9084   --processing_template_decl;
9085
9086   return r;
9087 }
9088
9089 /* Return the result of substituting ARGS into one template parameter
9090    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
9091    parameter and which TREE_PURPOSE is the default argument of the
9092    template parameter.  */
9093
9094 static tree
9095 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
9096 {
9097   tree default_value, parm_decl;
9098
9099   if (args == NULL_TREE
9100       || t == NULL_TREE
9101       || t == error_mark_node)
9102     return t;
9103
9104   gcc_assert (TREE_CODE (t) == TREE_LIST);
9105
9106   default_value = TREE_PURPOSE (t);
9107   parm_decl = TREE_VALUE (t);
9108
9109   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
9110   if (TREE_CODE (parm_decl) == PARM_DECL
9111       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
9112     parm_decl = error_mark_node;
9113   default_value = tsubst_template_arg (default_value, args,
9114                                        complain, NULL_TREE);
9115
9116   return build_tree_list (default_value, parm_decl);
9117 }
9118
9119 /* Substitute the ARGS into the indicated aggregate (or enumeration)
9120    type T.  If T is not an aggregate or enumeration type, it is
9121    handled as if by tsubst.  IN_DECL is as for tsubst.  If
9122    ENTERING_SCOPE is nonzero, T is the context for a template which
9123    we are presently tsubst'ing.  Return the substituted value.  */
9124
9125 static tree
9126 tsubst_aggr_type (tree t,
9127                   tree args,
9128                   tsubst_flags_t complain,
9129                   tree in_decl,
9130                   int entering_scope)
9131 {
9132   if (t == NULL_TREE)
9133     return NULL_TREE;
9134
9135   switch (TREE_CODE (t))
9136     {
9137     case RECORD_TYPE:
9138       if (TYPE_PTRMEMFUNC_P (t))
9139         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
9140
9141       /* Else fall through.  */
9142     case ENUMERAL_TYPE:
9143     case UNION_TYPE:
9144       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
9145         {
9146           tree argvec;
9147           tree context;
9148           tree r;
9149           int saved_unevaluated_operand;
9150           int saved_inhibit_evaluation_warnings;
9151
9152           /* In "sizeof(X<I>)" we need to evaluate "I".  */
9153           saved_unevaluated_operand = cp_unevaluated_operand;
9154           cp_unevaluated_operand = 0;
9155           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
9156           c_inhibit_evaluation_warnings = 0;
9157
9158           /* First, determine the context for the type we are looking
9159              up.  */
9160           context = TYPE_CONTEXT (t);
9161           if (context)
9162             {
9163               context = tsubst_aggr_type (context, args, complain,
9164                                           in_decl, /*entering_scope=*/1);
9165               /* If context is a nested class inside a class template,
9166                  it may still need to be instantiated (c++/33959).  */
9167               if (TYPE_P (context))
9168                 context = complete_type (context);
9169             }
9170
9171           /* Then, figure out what arguments are appropriate for the
9172              type we are trying to find.  For example, given:
9173
9174                template <class T> struct S;
9175                template <class T, class U> void f(T, U) { S<U> su; }
9176
9177              and supposing that we are instantiating f<int, double>,
9178              then our ARGS will be {int, double}, but, when looking up
9179              S we only want {double}.  */
9180           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
9181                                          complain, in_decl);
9182           if (argvec == error_mark_node)
9183             r = error_mark_node;
9184           else
9185             {
9186               r = lookup_template_class (t, argvec, in_decl, context,
9187                                          entering_scope, complain);
9188               r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
9189             }
9190
9191           cp_unevaluated_operand = saved_unevaluated_operand;
9192           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
9193
9194           return r;
9195         }
9196       else
9197         /* This is not a template type, so there's nothing to do.  */
9198         return t;
9199
9200     default:
9201       return tsubst (t, args, complain, in_decl);
9202     }
9203 }
9204
9205 /* Substitute into the default argument ARG (a default argument for
9206    FN), which has the indicated TYPE.  */
9207
9208 tree
9209 tsubst_default_argument (tree fn, tree type, tree arg)
9210 {
9211   tree saved_class_ptr = NULL_TREE;
9212   tree saved_class_ref = NULL_TREE;
9213
9214   /* This can happen in invalid code.  */
9215   if (TREE_CODE (arg) == DEFAULT_ARG)
9216     return arg;
9217
9218   /* This default argument came from a template.  Instantiate the
9219      default argument here, not in tsubst.  In the case of
9220      something like:
9221
9222        template <class T>
9223        struct S {
9224          static T t();
9225          void f(T = t());
9226        };
9227
9228      we must be careful to do name lookup in the scope of S<T>,
9229      rather than in the current class.  */
9230   push_access_scope (fn);
9231   /* The "this" pointer is not valid in a default argument.  */
9232   if (cfun)
9233     {
9234       saved_class_ptr = current_class_ptr;
9235       cp_function_chain->x_current_class_ptr = NULL_TREE;
9236       saved_class_ref = current_class_ref;
9237       cp_function_chain->x_current_class_ref = NULL_TREE;
9238     }
9239
9240   push_deferring_access_checks(dk_no_deferred);
9241   /* The default argument expression may cause implicitly defined
9242      member functions to be synthesized, which will result in garbage
9243      collection.  We must treat this situation as if we were within
9244      the body of function so as to avoid collecting live data on the
9245      stack.  */
9246   ++function_depth;
9247   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
9248                      tf_warning_or_error, NULL_TREE,
9249                      /*integral_constant_expression_p=*/false);
9250   --function_depth;
9251   pop_deferring_access_checks();
9252
9253   /* Restore the "this" pointer.  */
9254   if (cfun)
9255     {
9256       cp_function_chain->x_current_class_ptr = saved_class_ptr;
9257       cp_function_chain->x_current_class_ref = saved_class_ref;
9258     }
9259
9260   /* Make sure the default argument is reasonable.  */
9261   arg = check_default_argument (type, arg);
9262
9263   pop_access_scope (fn);
9264
9265   return arg;
9266 }
9267
9268 /* Substitute into all the default arguments for FN.  */
9269
9270 static void
9271 tsubst_default_arguments (tree fn)
9272 {
9273   tree arg;
9274   tree tmpl_args;
9275
9276   tmpl_args = DECL_TI_ARGS (fn);
9277
9278   /* If this function is not yet instantiated, we certainly don't need
9279      its default arguments.  */
9280   if (uses_template_parms (tmpl_args))
9281     return;
9282   /* Don't do this again for clones.  */
9283   if (DECL_CLONED_FUNCTION_P (fn))
9284     return;
9285
9286   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
9287        arg;
9288        arg = TREE_CHAIN (arg))
9289     if (TREE_PURPOSE (arg))
9290       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
9291                                                     TREE_VALUE (arg),
9292                                                     TREE_PURPOSE (arg));
9293 }
9294
9295 /* Substitute the ARGS into the T, which is a _DECL.  Return the
9296    result of the substitution.  Issue error and warning messages under
9297    control of COMPLAIN.  */
9298
9299 static tree
9300 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
9301 {
9302 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
9303   location_t saved_loc;
9304   tree r = NULL_TREE;
9305   tree in_decl = t;
9306   hashval_t hash = 0;
9307
9308   /* Set the filename and linenumber to improve error-reporting.  */
9309   saved_loc = input_location;
9310   input_location = DECL_SOURCE_LOCATION (t);
9311
9312   switch (TREE_CODE (t))
9313     {
9314     case TEMPLATE_DECL:
9315       {
9316         /* We can get here when processing a member function template,
9317            member class template, or template template parameter.  */
9318         tree decl = DECL_TEMPLATE_RESULT (t);
9319         tree spec;
9320         tree tmpl_args;
9321         tree full_args;
9322
9323         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9324           {
9325             /* Template template parameter is treated here.  */
9326             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9327             if (new_type == error_mark_node)
9328               RETURN (error_mark_node);
9329
9330             r = copy_decl (t);
9331             DECL_CHAIN (r) = NULL_TREE;
9332             TREE_TYPE (r) = new_type;
9333             DECL_TEMPLATE_RESULT (r)
9334               = build_decl (DECL_SOURCE_LOCATION (decl),
9335                             TYPE_DECL, DECL_NAME (decl), new_type);
9336             DECL_TEMPLATE_PARMS (r)
9337               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9338                                        complain);
9339             TYPE_NAME (new_type) = r;
9340             break;
9341           }
9342
9343         /* We might already have an instance of this template.
9344            The ARGS are for the surrounding class type, so the
9345            full args contain the tsubst'd args for the context,
9346            plus the innermost args from the template decl.  */
9347         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
9348           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
9349           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
9350         /* Because this is a template, the arguments will still be
9351            dependent, even after substitution.  If
9352            PROCESSING_TEMPLATE_DECL is not set, the dependency
9353            predicates will short-circuit.  */
9354         ++processing_template_decl;
9355         full_args = tsubst_template_args (tmpl_args, args,
9356                                           complain, in_decl);
9357         --processing_template_decl;
9358         if (full_args == error_mark_node)
9359           RETURN (error_mark_node);
9360
9361         /* If this is a default template template argument,
9362            tsubst might not have changed anything.  */
9363         if (full_args == tmpl_args)
9364           RETURN (t);
9365
9366         hash = hash_tmpl_and_args (t, full_args);
9367         spec = retrieve_specialization (t, full_args, hash);
9368         if (spec != NULL_TREE)
9369           {
9370             r = spec;
9371             break;
9372           }
9373
9374         /* Make a new template decl.  It will be similar to the
9375            original, but will record the current template arguments.
9376            We also create a new function declaration, which is just
9377            like the old one, but points to this new template, rather
9378            than the old one.  */
9379         r = copy_decl (t);
9380         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
9381         DECL_CHAIN (r) = NULL_TREE;
9382
9383         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
9384
9385         if (TREE_CODE (decl) == TYPE_DECL)
9386           {
9387             tree new_type;
9388             ++processing_template_decl;
9389             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9390             --processing_template_decl;
9391             if (new_type == error_mark_node)
9392               RETURN (error_mark_node);
9393
9394             TREE_TYPE (r) = new_type;
9395             CLASSTYPE_TI_TEMPLATE (new_type) = r;
9396             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
9397             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
9398             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
9399           }
9400         else
9401           {
9402             tree new_decl;
9403             ++processing_template_decl;
9404             new_decl = tsubst (decl, args, complain, in_decl);
9405             --processing_template_decl;
9406             if (new_decl == error_mark_node)
9407               RETURN (error_mark_node);
9408
9409             DECL_TEMPLATE_RESULT (r) = new_decl;
9410             DECL_TI_TEMPLATE (new_decl) = r;
9411             TREE_TYPE (r) = TREE_TYPE (new_decl);
9412             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
9413             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
9414           }
9415
9416         SET_DECL_IMPLICIT_INSTANTIATION (r);
9417         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
9418         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
9419
9420         /* The template parameters for this new template are all the
9421            template parameters for the old template, except the
9422            outermost level of parameters.  */
9423         DECL_TEMPLATE_PARMS (r)
9424           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9425                                    complain);
9426
9427         if (PRIMARY_TEMPLATE_P (t))
9428           DECL_PRIMARY_TEMPLATE (r) = r;
9429
9430         if (TREE_CODE (decl) != TYPE_DECL)
9431           /* Record this non-type partial instantiation.  */
9432           register_specialization (r, t,
9433                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
9434                                    false, hash);
9435       }
9436       break;
9437
9438     case FUNCTION_DECL:
9439       {
9440         tree ctx;
9441         tree argvec = NULL_TREE;
9442         tree *friends;
9443         tree gen_tmpl;
9444         tree type;
9445         int member;
9446         int args_depth;
9447         int parms_depth;
9448
9449         /* Nobody should be tsubst'ing into non-template functions.  */
9450         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
9451
9452         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
9453           {
9454             tree spec;
9455             bool dependent_p;
9456
9457             /* If T is not dependent, just return it.  We have to
9458                increment PROCESSING_TEMPLATE_DECL because
9459                value_dependent_expression_p assumes that nothing is
9460                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
9461             ++processing_template_decl;
9462             dependent_p = value_dependent_expression_p (t);
9463             --processing_template_decl;
9464             if (!dependent_p)
9465               RETURN (t);
9466
9467             /* Calculate the most general template of which R is a
9468                specialization, and the complete set of arguments used to
9469                specialize R.  */
9470             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
9471             argvec = tsubst_template_args (DECL_TI_ARGS
9472                                           (DECL_TEMPLATE_RESULT
9473                                                  (DECL_TI_TEMPLATE (t))),
9474                                            args, complain, in_decl);
9475
9476             /* Check to see if we already have this specialization.  */
9477             hash = hash_tmpl_and_args (gen_tmpl, argvec);
9478             spec = retrieve_specialization (gen_tmpl, argvec, hash);
9479
9480             if (spec)
9481               {
9482                 r = spec;
9483                 break;
9484               }
9485
9486             /* We can see more levels of arguments than parameters if
9487                there was a specialization of a member template, like
9488                this:
9489
9490                  template <class T> struct S { template <class U> void f(); }
9491                  template <> template <class U> void S<int>::f(U);
9492
9493                Here, we'll be substituting into the specialization,
9494                because that's where we can find the code we actually
9495                want to generate, but we'll have enough arguments for
9496                the most general template.
9497
9498                We also deal with the peculiar case:
9499
9500                  template <class T> struct S {
9501                    template <class U> friend void f();
9502                  };
9503                  template <class U> void f() {}
9504                  template S<int>;
9505                  template void f<double>();
9506
9507                Here, the ARGS for the instantiation of will be {int,
9508                double}.  But, we only need as many ARGS as there are
9509                levels of template parameters in CODE_PATTERN.  We are
9510                careful not to get fooled into reducing the ARGS in
9511                situations like:
9512
9513                  template <class T> struct S { template <class U> void f(U); }
9514                  template <class T> template <> void S<T>::f(int) {}
9515
9516                which we can spot because the pattern will be a
9517                specialization in this case.  */
9518             args_depth = TMPL_ARGS_DEPTH (args);
9519             parms_depth =
9520               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
9521             if (args_depth > parms_depth
9522                 && !DECL_TEMPLATE_SPECIALIZATION (t))
9523               args = get_innermost_template_args (args, parms_depth);
9524           }
9525         else
9526           {
9527             /* This special case arises when we have something like this:
9528
9529                  template <class T> struct S {
9530                    friend void f<int>(int, double);
9531                  };
9532
9533                Here, the DECL_TI_TEMPLATE for the friend declaration
9534                will be an IDENTIFIER_NODE.  We are being called from
9535                tsubst_friend_function, and we want only to create a
9536                new decl (R) with appropriate types so that we can call
9537                determine_specialization.  */
9538             gen_tmpl = NULL_TREE;
9539           }
9540
9541         if (DECL_CLASS_SCOPE_P (t))
9542           {
9543             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
9544               member = 2;
9545             else
9546               member = 1;
9547             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
9548                                     complain, t, /*entering_scope=*/1);
9549           }
9550         else
9551           {
9552             member = 0;
9553             ctx = DECL_CONTEXT (t);
9554           }
9555         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9556         if (type == error_mark_node)
9557           RETURN (error_mark_node);
9558
9559         /* We do NOT check for matching decls pushed separately at this
9560            point, as they may not represent instantiations of this
9561            template, and in any case are considered separate under the
9562            discrete model.  */
9563         r = copy_decl (t);
9564         DECL_USE_TEMPLATE (r) = 0;
9565         TREE_TYPE (r) = type;
9566         /* Clear out the mangled name and RTL for the instantiation.  */
9567         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9568         SET_DECL_RTL (r, NULL);
9569         /* Leave DECL_INITIAL set on deleted instantiations.  */
9570         if (!DECL_DELETED_FN (r))
9571           DECL_INITIAL (r) = NULL_TREE;
9572         DECL_CONTEXT (r) = ctx;
9573
9574         if (member && DECL_CONV_FN_P (r))
9575           /* Type-conversion operator.  Reconstruct the name, in
9576              case it's the name of one of the template's parameters.  */
9577           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
9578
9579         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
9580                                      complain, t);
9581         DECL_RESULT (r) = NULL_TREE;
9582
9583         TREE_STATIC (r) = 0;
9584         TREE_PUBLIC (r) = TREE_PUBLIC (t);
9585         DECL_EXTERNAL (r) = 1;
9586         /* If this is an instantiation of a function with internal
9587            linkage, we already know what object file linkage will be
9588            assigned to the instantiation.  */
9589         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
9590         DECL_DEFER_OUTPUT (r) = 0;
9591         DECL_CHAIN (r) = NULL_TREE;
9592         DECL_PENDING_INLINE_INFO (r) = 0;
9593         DECL_PENDING_INLINE_P (r) = 0;
9594         DECL_SAVED_TREE (r) = NULL_TREE;
9595         DECL_STRUCT_FUNCTION (r) = NULL;
9596         TREE_USED (r) = 0;
9597         /* We'll re-clone as appropriate in instantiate_template.  */
9598         DECL_CLONED_FUNCTION (r) = NULL_TREE;
9599
9600         /* If we aren't complaining now, return on error before we register
9601            the specialization so that we'll complain eventually.  */
9602         if ((complain & tf_error) == 0
9603             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9604             && !grok_op_properties (r, /*complain=*/false))
9605           RETURN (error_mark_node);
9606
9607         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
9608            this in the special friend case mentioned above where
9609            GEN_TMPL is NULL.  */
9610         if (gen_tmpl)
9611           {
9612             DECL_TEMPLATE_INFO (r)
9613               = build_template_info (gen_tmpl, argvec);
9614             SET_DECL_IMPLICIT_INSTANTIATION (r);
9615             register_specialization (r, gen_tmpl, argvec, false, hash);
9616
9617             /* We're not supposed to instantiate default arguments
9618                until they are called, for a template.  But, for a
9619                declaration like:
9620
9621                  template <class T> void f ()
9622                  { extern void g(int i = T()); }
9623
9624                we should do the substitution when the template is
9625                instantiated.  We handle the member function case in
9626                instantiate_class_template since the default arguments
9627                might refer to other members of the class.  */
9628             if (!member
9629                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
9630                 && !uses_template_parms (argvec))
9631               tsubst_default_arguments (r);
9632           }
9633         else
9634           DECL_TEMPLATE_INFO (r) = NULL_TREE;
9635
9636         /* Copy the list of befriending classes.  */
9637         for (friends = &DECL_BEFRIENDING_CLASSES (r);
9638              *friends;
9639              friends = &TREE_CHAIN (*friends))
9640           {
9641             *friends = copy_node (*friends);
9642             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
9643                                             args, complain,
9644                                             in_decl);
9645           }
9646
9647         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
9648           {
9649             maybe_retrofit_in_chrg (r);
9650             if (DECL_CONSTRUCTOR_P (r))
9651               grok_ctor_properties (ctx, r);
9652             /* If this is an instantiation of a member template, clone it.
9653                If it isn't, that'll be handled by
9654                clone_constructors_and_destructors.  */
9655             if (PRIMARY_TEMPLATE_P (gen_tmpl))
9656               clone_function_decl (r, /*update_method_vec_p=*/0);
9657           }
9658         else if ((complain & tf_error) != 0
9659                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9660                  && !grok_op_properties (r, /*complain=*/true))
9661           RETURN (error_mark_node);
9662
9663         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
9664           SET_DECL_FRIEND_CONTEXT (r,
9665                                    tsubst (DECL_FRIEND_CONTEXT (t),
9666                                             args, complain, in_decl));
9667
9668         /* Possibly limit visibility based on template args.  */
9669         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9670         if (DECL_VISIBILITY_SPECIFIED (t))
9671           {
9672             DECL_VISIBILITY_SPECIFIED (r) = 0;
9673             DECL_ATTRIBUTES (r)
9674               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9675           }
9676         determine_visibility (r);
9677         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
9678             && !processing_template_decl)
9679           defaulted_late_check (r);
9680
9681         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9682                                         args, complain, in_decl);
9683       }
9684       break;
9685
9686     case PARM_DECL:
9687       {
9688         tree type = NULL_TREE;
9689         int i, len = 1;
9690         tree expanded_types = NULL_TREE;
9691         tree prev_r = NULL_TREE;
9692         tree first_r = NULL_TREE;
9693
9694         if (FUNCTION_PARAMETER_PACK_P (t))
9695           {
9696             /* If there is a local specialization that isn't a
9697                parameter pack, it means that we're doing a "simple"
9698                substitution from inside tsubst_pack_expansion. Just
9699                return the local specialization (which will be a single
9700                parm).  */
9701             tree spec = retrieve_local_specialization (t);
9702             if (spec 
9703                 && TREE_CODE (spec) == PARM_DECL
9704                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
9705               RETURN (spec);
9706
9707             /* Expand the TYPE_PACK_EXPANSION that provides the types for
9708                the parameters in this function parameter pack.  */
9709             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
9710                                                     complain, in_decl);
9711             if (TREE_CODE (expanded_types) == TREE_VEC)
9712               {
9713                 len = TREE_VEC_LENGTH (expanded_types);
9714
9715                 /* Zero-length parameter packs are boring. Just substitute
9716                    into the chain.  */
9717                 if (len == 0)
9718                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
9719                                   TREE_CHAIN (t)));
9720               }
9721             else
9722               {
9723                 /* All we did was update the type. Make a note of that.  */
9724                 type = expanded_types;
9725                 expanded_types = NULL_TREE;
9726               }
9727           }
9728
9729         /* Loop through all of the parameter's we'll build. When T is
9730            a function parameter pack, LEN is the number of expanded
9731            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
9732         r = NULL_TREE;
9733         for (i = 0; i < len; ++i)
9734           {
9735             prev_r = r;
9736             r = copy_node (t);
9737             if (DECL_TEMPLATE_PARM_P (t))
9738               SET_DECL_TEMPLATE_PARM_P (r);
9739
9740             /* An argument of a function parameter pack is not a parameter
9741                pack.  */
9742             FUNCTION_PARAMETER_PACK_P (r) = false;
9743
9744             if (expanded_types)
9745               /* We're on the Ith parameter of the function parameter
9746                  pack.  */
9747               {
9748                 /* Get the Ith type.  */
9749                 type = TREE_VEC_ELT (expanded_types, i);
9750
9751                 if (DECL_NAME (r))
9752                   /* Rename the parameter to include the index.  */
9753                   DECL_NAME (r) =
9754                     make_ith_pack_parameter_name (DECL_NAME (r), i);
9755               }
9756             else if (!type)
9757               /* We're dealing with a normal parameter.  */
9758               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9759
9760             type = type_decays_to (type);
9761             TREE_TYPE (r) = type;
9762             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9763
9764             if (DECL_INITIAL (r))
9765               {
9766                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
9767                   DECL_INITIAL (r) = TREE_TYPE (r);
9768                 else
9769                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
9770                                              complain, in_decl);
9771               }
9772
9773             DECL_CONTEXT (r) = NULL_TREE;
9774
9775             if (!DECL_TEMPLATE_PARM_P (r))
9776               DECL_ARG_TYPE (r) = type_passed_as (type);
9777
9778             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9779                                             args, complain, in_decl);
9780
9781             /* Keep track of the first new parameter we
9782                generate. That's what will be returned to the
9783                caller.  */
9784             if (!first_r)
9785               first_r = r;
9786
9787             /* Build a proper chain of parameters when substituting
9788                into a function parameter pack.  */
9789             if (prev_r)
9790               DECL_CHAIN (prev_r) = r;
9791           }
9792
9793         if (DECL_CHAIN (t))
9794           DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
9795                                    complain, DECL_CHAIN (t));
9796
9797         /* FIRST_R contains the start of the chain we've built.  */
9798         r = first_r;
9799       }
9800       break;
9801
9802     case FIELD_DECL:
9803       {
9804         tree type;
9805
9806         r = copy_decl (t);
9807         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9808         if (type == error_mark_node)
9809           RETURN (error_mark_node);
9810         TREE_TYPE (r) = type;
9811         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9812
9813         /* DECL_INITIAL gives the number of bits in a bit-field.  */
9814         DECL_INITIAL (r)
9815           = tsubst_expr (DECL_INITIAL (t), args,
9816                          complain, in_decl,
9817                          /*integral_constant_expression_p=*/true);
9818         /* We don't have to set DECL_CONTEXT here; it is set by
9819            finish_member_declaration.  */
9820         DECL_CHAIN (r) = NULL_TREE;
9821         if (VOID_TYPE_P (type))
9822           error ("instantiation of %q+D as type %qT", r, type);
9823
9824         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9825                                         args, complain, in_decl);
9826       }
9827       break;
9828
9829     case USING_DECL:
9830       /* We reach here only for member using decls.  */
9831       if (DECL_DEPENDENT_P (t))
9832         {
9833           r = do_class_using_decl
9834             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
9835              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
9836           if (!r)
9837             r = error_mark_node;
9838           else
9839             {
9840               TREE_PROTECTED (r) = TREE_PROTECTED (t);
9841               TREE_PRIVATE (r) = TREE_PRIVATE (t);
9842             }
9843         }
9844       else
9845         {
9846           r = copy_node (t);
9847           DECL_CHAIN (r) = NULL_TREE;
9848         }
9849       break;
9850
9851     case TYPE_DECL:
9852     case VAR_DECL:
9853       {
9854         tree argvec = NULL_TREE;
9855         tree gen_tmpl = NULL_TREE;
9856         tree spec;
9857         tree tmpl = NULL_TREE;
9858         tree ctx;
9859         tree type = NULL_TREE;
9860         bool local_p;
9861
9862         if (TREE_CODE (t) == TYPE_DECL
9863             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
9864           {
9865             /* If this is the canonical decl, we don't have to
9866                mess with instantiations, and often we can't (for
9867                typename, template type parms and such).  Note that
9868                TYPE_NAME is not correct for the above test if
9869                we've copied the type for a typedef.  */
9870             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9871             if (type == error_mark_node)
9872               RETURN (error_mark_node);
9873             r = TYPE_NAME (type);
9874             break;
9875           }
9876
9877         /* Check to see if we already have the specialization we
9878            need.  */
9879         spec = NULL_TREE;
9880         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
9881           {
9882             /* T is a static data member or namespace-scope entity.
9883                We have to substitute into namespace-scope variables
9884                (even though such entities are never templates) because
9885                of cases like:
9886                
9887                  template <class T> void f() { extern T t; }
9888
9889                where the entity referenced is not known until
9890                instantiation time.  */
9891             local_p = false;
9892             ctx = DECL_CONTEXT (t);
9893             if (DECL_CLASS_SCOPE_P (t))
9894               {
9895                 ctx = tsubst_aggr_type (ctx, args,
9896                                         complain,
9897                                         in_decl, /*entering_scope=*/1);
9898                 /* If CTX is unchanged, then T is in fact the
9899                    specialization we want.  That situation occurs when
9900                    referencing a static data member within in its own
9901                    class.  We can use pointer equality, rather than
9902                    same_type_p, because DECL_CONTEXT is always
9903                    canonical.  */
9904                 if (ctx == DECL_CONTEXT (t))
9905                   spec = t;
9906               }
9907
9908             if (!spec)
9909               {
9910                 tmpl = DECL_TI_TEMPLATE (t);
9911                 gen_tmpl = most_general_template (tmpl);
9912                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
9913                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
9914                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
9915               }
9916           }
9917         else
9918           {
9919             /* A local variable.  */
9920             local_p = true;
9921             /* Subsequent calls to pushdecl will fill this in.  */
9922             ctx = NULL_TREE;
9923             spec = retrieve_local_specialization (t);
9924           }
9925         /* If we already have the specialization we need, there is
9926            nothing more to do.  */ 
9927         if (spec)
9928           {
9929             r = spec;
9930             break;
9931           }
9932
9933         /* Create a new node for the specialization we need.  */
9934         r = copy_decl (t);
9935         if (type == NULL_TREE)
9936           {
9937             if (is_typedef_decl (t))
9938               type = DECL_ORIGINAL_TYPE (t);
9939             else
9940               type = TREE_TYPE (t);
9941             if (TREE_CODE (t) == VAR_DECL && VAR_HAD_UNKNOWN_BOUND (t))
9942               type = strip_array_domain (type);
9943             type = tsubst (type, args, complain, in_decl);
9944           }
9945         if (TREE_CODE (r) == VAR_DECL)
9946           {
9947             /* Even if the original location is out of scope, the
9948                newly substituted one is not.  */
9949             DECL_DEAD_FOR_LOCAL (r) = 0;
9950             DECL_INITIALIZED_P (r) = 0;
9951             DECL_TEMPLATE_INSTANTIATED (r) = 0;
9952             if (type == error_mark_node)
9953               RETURN (error_mark_node);
9954             if (TREE_CODE (type) == FUNCTION_TYPE)
9955               {
9956                 /* It may seem that this case cannot occur, since:
9957
9958                      typedef void f();
9959                      void g() { f x; }
9960
9961                    declares a function, not a variable.  However:
9962       
9963                      typedef void f();
9964                      template <typename T> void g() { T t; }
9965                      template void g<f>();
9966
9967                    is an attempt to declare a variable with function
9968                    type.  */
9969                 error ("variable %qD has function type",
9970                        /* R is not yet sufficiently initialized, so we
9971                           just use its name.  */
9972                        DECL_NAME (r));
9973                 RETURN (error_mark_node);
9974               }
9975             type = complete_type (type);
9976             /* Wait until cp_finish_decl to set this again, to handle
9977                circular dependency (template/instantiate6.C). */
9978             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
9979             type = check_var_type (DECL_NAME (r), type);
9980
9981             if (DECL_HAS_VALUE_EXPR_P (t))
9982               {
9983                 tree ve = DECL_VALUE_EXPR (t);
9984                 ve = tsubst_expr (ve, args, complain, in_decl,
9985                                   /*constant_expression_p=*/false);
9986                 SET_DECL_VALUE_EXPR (r, ve);
9987               }
9988           }
9989         else if (DECL_SELF_REFERENCE_P (t))
9990           SET_DECL_SELF_REFERENCE_P (r);
9991         TREE_TYPE (r) = type;
9992         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9993         DECL_CONTEXT (r) = ctx;
9994         /* Clear out the mangled name and RTL for the instantiation.  */
9995         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9996         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9997           SET_DECL_RTL (r, NULL);
9998         /* The initializer must not be expanded until it is required;
9999            see [temp.inst].  */
10000         DECL_INITIAL (r) = NULL_TREE;
10001         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10002           SET_DECL_RTL (r, NULL);
10003         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
10004         if (TREE_CODE (r) == VAR_DECL)
10005           {
10006             /* Possibly limit visibility based on template args.  */
10007             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10008             if (DECL_VISIBILITY_SPECIFIED (t))
10009               {
10010                 DECL_VISIBILITY_SPECIFIED (r) = 0;
10011                 DECL_ATTRIBUTES (r)
10012                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10013               }
10014             determine_visibility (r);
10015           }
10016
10017         if (!local_p)
10018           {
10019             /* A static data member declaration is always marked
10020                external when it is declared in-class, even if an
10021                initializer is present.  We mimic the non-template
10022                processing here.  */
10023             DECL_EXTERNAL (r) = 1;
10024
10025             register_specialization (r, gen_tmpl, argvec, false, hash);
10026             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
10027             SET_DECL_IMPLICIT_INSTANTIATION (r);
10028           }
10029         else if (cp_unevaluated_operand)
10030           {
10031             /* We're substituting this var in a decltype outside of its
10032                scope, such as for a lambda return type.  Don't add it to
10033                local_specializations, do perform auto deduction.  */
10034             tree auto_node = type_uses_auto (type);
10035             tree init
10036               = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
10037                              /*constant_expression_p=*/false);
10038
10039             if (auto_node && init)
10040               {
10041                 init = resolve_nondeduced_context (init);
10042                 if (describable_type (init))
10043                   {
10044                     type = do_auto_deduction (type, init, auto_node);
10045                     TREE_TYPE (r) = type;
10046                   }
10047               }
10048           }
10049         else
10050           register_local_specialization (r, t);
10051
10052         DECL_CHAIN (r) = NULL_TREE;
10053
10054         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
10055                                         /*flags=*/0,
10056                                         args, complain, in_decl);
10057
10058         /* Preserve a typedef that names a type.  */
10059         if (is_typedef_decl (r))
10060           {
10061             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
10062             set_underlying_type (r);
10063           }
10064
10065         layout_decl (r, 0);
10066       }
10067       break;
10068
10069     default:
10070       gcc_unreachable ();
10071     }
10072 #undef RETURN
10073
10074  out:
10075   /* Restore the file and line information.  */
10076   input_location = saved_loc;
10077
10078   return r;
10079 }
10080
10081 /* Substitute into the ARG_TYPES of a function type.  */
10082
10083 static tree
10084 tsubst_arg_types (tree arg_types,
10085                   tree args,
10086                   tsubst_flags_t complain,
10087                   tree in_decl)
10088 {
10089   tree remaining_arg_types;
10090   tree type = NULL_TREE;
10091   int i = 1;
10092   tree expanded_args = NULL_TREE;
10093   tree default_arg;
10094
10095   if (!arg_types || arg_types == void_list_node)
10096     return arg_types;
10097
10098   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
10099                                           args, complain, in_decl);
10100   if (remaining_arg_types == error_mark_node)
10101     return error_mark_node;
10102
10103   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
10104     {
10105       /* For a pack expansion, perform substitution on the
10106          entire expression. Later on, we'll handle the arguments
10107          one-by-one.  */
10108       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
10109                                             args, complain, in_decl);
10110
10111       if (TREE_CODE (expanded_args) == TREE_VEC)
10112         /* So that we'll spin through the parameters, one by one.  */
10113         i = TREE_VEC_LENGTH (expanded_args);
10114       else
10115         {
10116           /* We only partially substituted into the parameter
10117              pack. Our type is TYPE_PACK_EXPANSION.  */
10118           type = expanded_args;
10119           expanded_args = NULL_TREE;
10120         }
10121     }
10122
10123   while (i > 0) {
10124     --i;
10125     
10126     if (expanded_args)
10127       type = TREE_VEC_ELT (expanded_args, i);
10128     else if (!type)
10129       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
10130
10131     if (type == error_mark_node)
10132       return error_mark_node;
10133     if (VOID_TYPE_P (type))
10134       {
10135         if (complain & tf_error)
10136           {
10137             error ("invalid parameter type %qT", type);
10138             if (in_decl)
10139               error ("in declaration %q+D", in_decl);
10140           }
10141         return error_mark_node;
10142     }
10143     
10144     /* Do array-to-pointer, function-to-pointer conversion, and ignore
10145        top-level qualifiers as required.  */
10146     type = TYPE_MAIN_VARIANT (type_decays_to (type));
10147
10148     /* We do not substitute into default arguments here.  The standard
10149        mandates that they be instantiated only when needed, which is
10150        done in build_over_call.  */
10151     default_arg = TREE_PURPOSE (arg_types);
10152
10153     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
10154       {
10155         /* We've instantiated a template before its default arguments
10156            have been parsed.  This can happen for a nested template
10157            class, and is not an error unless we require the default
10158            argument in a call of this function.  */
10159         remaining_arg_types = 
10160           tree_cons (default_arg, type, remaining_arg_types);
10161         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
10162                        remaining_arg_types);
10163       }
10164     else
10165       remaining_arg_types = 
10166         hash_tree_cons (default_arg, type, remaining_arg_types);
10167   }
10168         
10169   return remaining_arg_types;
10170 }
10171
10172 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
10173    *not* handle the exception-specification for FNTYPE, because the
10174    initial substitution of explicitly provided template parameters
10175    during argument deduction forbids substitution into the
10176    exception-specification:
10177
10178      [temp.deduct]
10179
10180      All references in the function type of the function template to  the
10181      corresponding template parameters are replaced by the specified tem-
10182      plate argument values.  If a substitution in a template parameter or
10183      in  the function type of the function template results in an invalid
10184      type, type deduction fails.  [Note: The equivalent  substitution  in
10185      exception specifications is done only when the function is instanti-
10186      ated, at which point a program is  ill-formed  if  the  substitution
10187      results in an invalid type.]  */
10188
10189 static tree
10190 tsubst_function_type (tree t,
10191                       tree args,
10192                       tsubst_flags_t complain,
10193                       tree in_decl)
10194 {
10195   tree return_type;
10196   tree arg_types;
10197   tree fntype;
10198
10199   /* The TYPE_CONTEXT is not used for function/method types.  */
10200   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
10201
10202   /* Substitute the return type.  */
10203   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10204   if (return_type == error_mark_node)
10205     return error_mark_node;
10206   /* The standard does not presently indicate that creation of a
10207      function type with an invalid return type is a deduction failure.
10208      However, that is clearly analogous to creating an array of "void"
10209      or a reference to a reference.  This is core issue #486.  */
10210   if (TREE_CODE (return_type) == ARRAY_TYPE
10211       || TREE_CODE (return_type) == FUNCTION_TYPE)
10212     {
10213       if (complain & tf_error)
10214         {
10215           if (TREE_CODE (return_type) == ARRAY_TYPE)
10216             error ("function returning an array");
10217           else
10218             error ("function returning a function");
10219         }
10220       return error_mark_node;
10221     }
10222
10223   /* Substitute the argument types.  */
10224   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
10225                                 complain, in_decl);
10226   if (arg_types == error_mark_node)
10227     return error_mark_node;
10228
10229   /* Construct a new type node and return it.  */
10230   if (TREE_CODE (t) == FUNCTION_TYPE)
10231     {
10232       fntype = build_function_type (return_type, arg_types);
10233       fntype = apply_memfn_quals (fntype, type_memfn_quals (t));
10234     }
10235   else
10236     {
10237       tree r = TREE_TYPE (TREE_VALUE (arg_types));
10238       if (! MAYBE_CLASS_TYPE_P (r))
10239         {
10240           /* [temp.deduct]
10241
10242              Type deduction may fail for any of the following
10243              reasons:
10244
10245              -- Attempting to create "pointer to member of T" when T
10246              is not a class type.  */
10247           if (complain & tf_error)
10248             error ("creating pointer to member function of non-class type %qT",
10249                       r);
10250           return error_mark_node;
10251         }
10252
10253       fntype = build_method_type_directly (r, return_type,
10254                                            TREE_CHAIN (arg_types));
10255     }
10256   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
10257
10258   return fntype;
10259 }
10260
10261 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
10262    ARGS into that specification, and return the substituted
10263    specification.  If there is no specification, return NULL_TREE.  */
10264
10265 static tree
10266 tsubst_exception_specification (tree fntype,
10267                                 tree args,
10268                                 tsubst_flags_t complain,
10269                                 tree in_decl)
10270 {
10271   tree specs;
10272   tree new_specs;
10273
10274   specs = TYPE_RAISES_EXCEPTIONS (fntype);
10275   new_specs = NULL_TREE;
10276   if (specs && TREE_PURPOSE (specs))
10277     {
10278       /* A noexcept-specifier.  */
10279       new_specs = tsubst_copy_and_build
10280         (TREE_PURPOSE (specs), args, complain, in_decl, /*function_p=*/false,
10281          /*integral_constant_expression_p=*/true);
10282       new_specs = build_noexcept_spec (new_specs, complain);
10283     }
10284   else if (specs)
10285     {
10286       if (! TREE_VALUE (specs))
10287         new_specs = specs;
10288       else
10289         while (specs)
10290           {
10291             tree spec;
10292             int i, len = 1;
10293             tree expanded_specs = NULL_TREE;
10294
10295             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
10296               {
10297                 /* Expand the pack expansion type.  */
10298                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
10299                                                        args, complain,
10300                                                        in_decl);
10301
10302                 if (expanded_specs == error_mark_node)
10303                   return error_mark_node;
10304                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
10305                   len = TREE_VEC_LENGTH (expanded_specs);
10306                 else
10307                   {
10308                     /* We're substituting into a member template, so
10309                        we got a TYPE_PACK_EXPANSION back.  Add that
10310                        expansion and move on.  */
10311                     gcc_assert (TREE_CODE (expanded_specs) 
10312                                 == TYPE_PACK_EXPANSION);
10313                     new_specs = add_exception_specifier (new_specs,
10314                                                          expanded_specs,
10315                                                          complain);
10316                     specs = TREE_CHAIN (specs);
10317                     continue;
10318                   }
10319               }
10320
10321             for (i = 0; i < len; ++i)
10322               {
10323                 if (expanded_specs)
10324                   spec = TREE_VEC_ELT (expanded_specs, i);
10325                 else
10326                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
10327                 if (spec == error_mark_node)
10328                   return spec;
10329                 new_specs = add_exception_specifier (new_specs, spec, 
10330                                                      complain);
10331               }
10332
10333             specs = TREE_CHAIN (specs);
10334           }
10335     }
10336   return new_specs;
10337 }
10338
10339 /* Take the tree structure T and replace template parameters used
10340    therein with the argument vector ARGS.  IN_DECL is an associated
10341    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
10342    Issue error and warning messages under control of COMPLAIN.  Note
10343    that we must be relatively non-tolerant of extensions here, in
10344    order to preserve conformance; if we allow substitutions that
10345    should not be allowed, we may allow argument deductions that should
10346    not succeed, and therefore report ambiguous overload situations
10347    where there are none.  In theory, we could allow the substitution,
10348    but indicate that it should have failed, and allow our caller to
10349    make sure that the right thing happens, but we don't try to do this
10350    yet.
10351
10352    This function is used for dealing with types, decls and the like;
10353    for expressions, use tsubst_expr or tsubst_copy.  */
10354
10355 tree
10356 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10357 {
10358   enum tree_code code;
10359   tree type, r;
10360
10361   if (t == NULL_TREE || t == error_mark_node
10362       || t == integer_type_node
10363       || t == void_type_node
10364       || t == char_type_node
10365       || t == unknown_type_node
10366       || TREE_CODE (t) == NAMESPACE_DECL
10367       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
10368     return t;
10369
10370   if (DECL_P (t))
10371     return tsubst_decl (t, args, complain);
10372
10373   if (args == NULL_TREE)
10374     return t;
10375
10376   code = TREE_CODE (t);
10377
10378   if (code == IDENTIFIER_NODE)
10379     type = IDENTIFIER_TYPE_VALUE (t);
10380   else
10381     type = TREE_TYPE (t);
10382
10383   gcc_assert (type != unknown_type_node);
10384
10385   /* Reuse typedefs.  We need to do this to handle dependent attributes,
10386      such as attribute aligned.  */
10387   if (TYPE_P (t)
10388       && typedef_variant_p (t))
10389     {
10390       tree decl = TYPE_NAME (t);
10391       
10392       if (DECL_CLASS_SCOPE_P (decl)
10393           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
10394           && uses_template_parms (DECL_CONTEXT (decl)))
10395         {
10396           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
10397           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
10398           r = retrieve_specialization (tmpl, gen_args, 0);
10399         }
10400       else if (DECL_FUNCTION_SCOPE_P (decl)
10401                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
10402                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
10403         r = retrieve_local_specialization (decl);
10404       else
10405         /* The typedef is from a non-template context.  */
10406         return t;
10407
10408       if (r)
10409         {
10410           r = TREE_TYPE (r);
10411           r = cp_build_qualified_type_real
10412             (r, cp_type_quals (t) | cp_type_quals (r),
10413              complain | tf_ignore_bad_quals);
10414           return r;
10415         }
10416       /* Else we must be instantiating the typedef, so fall through.  */
10417     }
10418
10419   if (type
10420       && code != TYPENAME_TYPE
10421       && code != TEMPLATE_TYPE_PARM
10422       && code != IDENTIFIER_NODE
10423       && code != FUNCTION_TYPE
10424       && code != METHOD_TYPE)
10425     type = tsubst (type, args, complain, in_decl);
10426   if (type == error_mark_node)
10427     return error_mark_node;
10428
10429   switch (code)
10430     {
10431     case RECORD_TYPE:
10432     case UNION_TYPE:
10433     case ENUMERAL_TYPE:
10434       return tsubst_aggr_type (t, args, complain, in_decl,
10435                                /*entering_scope=*/0);
10436
10437     case ERROR_MARK:
10438     case IDENTIFIER_NODE:
10439     case VOID_TYPE:
10440     case REAL_TYPE:
10441     case COMPLEX_TYPE:
10442     case VECTOR_TYPE:
10443     case BOOLEAN_TYPE:
10444     case NULLPTR_TYPE:
10445     case LANG_TYPE:
10446       return t;
10447
10448     case INTEGER_TYPE:
10449       if (t == integer_type_node)
10450         return t;
10451
10452       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
10453           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
10454         return t;
10455
10456       {
10457         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
10458
10459         max = tsubst_expr (omax, args, complain, in_decl,
10460                            /*integral_constant_expression_p=*/false);
10461
10462         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
10463            needed.  */
10464         if (TREE_CODE (max) == NOP_EXPR
10465             && TREE_SIDE_EFFECTS (omax)
10466             && !TREE_TYPE (max))
10467           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
10468
10469         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
10470            with TREE_SIDE_EFFECTS that indicates this is not an integral
10471            constant expression.  */
10472         if (processing_template_decl
10473             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
10474           {
10475             gcc_assert (TREE_CODE (max) == NOP_EXPR);
10476             TREE_SIDE_EFFECTS (max) = 1;
10477           }
10478
10479         return compute_array_index_type (NULL_TREE, max, complain);
10480       }
10481
10482     case TEMPLATE_TYPE_PARM:
10483     case TEMPLATE_TEMPLATE_PARM:
10484     case BOUND_TEMPLATE_TEMPLATE_PARM:
10485     case TEMPLATE_PARM_INDEX:
10486       {
10487         int idx;
10488         int level;
10489         int levels;
10490         tree arg = NULL_TREE;
10491
10492         r = NULL_TREE;
10493
10494         gcc_assert (TREE_VEC_LENGTH (args) > 0);
10495         template_parm_level_and_index (t, &level, &idx); 
10496
10497         levels = TMPL_ARGS_DEPTH (args);
10498         if (level <= levels)
10499           {
10500             arg = TMPL_ARG (args, level, idx);
10501
10502             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
10503               /* See through ARGUMENT_PACK_SELECT arguments. */
10504               arg = ARGUMENT_PACK_SELECT_ARG (arg);
10505           }
10506
10507         if (arg == error_mark_node)
10508           return error_mark_node;
10509         else if (arg != NULL_TREE)
10510           {
10511             if (ARGUMENT_PACK_P (arg))
10512               /* If ARG is an argument pack, we don't actually want to
10513                  perform a substitution here, because substitutions
10514                  for argument packs are only done
10515                  element-by-element. We can get to this point when
10516                  substituting the type of a non-type template
10517                  parameter pack, when that type actually contains
10518                  template parameter packs from an outer template, e.g.,
10519
10520                  template<typename... Types> struct A {
10521                    template<Types... Values> struct B { };
10522                  };  */
10523               return t;
10524
10525             if (code == TEMPLATE_TYPE_PARM)
10526               {
10527                 int quals;
10528                 gcc_assert (TYPE_P (arg));
10529
10530                 quals = cp_type_quals (arg) | cp_type_quals (t);
10531                   
10532                 return cp_build_qualified_type_real
10533                   (arg, quals, complain | tf_ignore_bad_quals);
10534               }
10535             else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
10536               {
10537                 /* We are processing a type constructed from a
10538                    template template parameter.  */
10539                 tree argvec = tsubst (TYPE_TI_ARGS (t),
10540                                       args, complain, in_decl);
10541                 if (argvec == error_mark_node)
10542                   return error_mark_node;
10543
10544                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
10545                    are resolving nested-types in the signature of a
10546                    member function templates.  Otherwise ARG is a
10547                    TEMPLATE_DECL and is the real template to be
10548                    instantiated.  */
10549                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
10550                   arg = TYPE_NAME (arg);
10551
10552                 r = lookup_template_class (arg,
10553                                            argvec, in_decl,
10554                                            DECL_CONTEXT (arg),
10555                                             /*entering_scope=*/0,
10556                                            complain);
10557                 return cp_build_qualified_type_real
10558                   (r, cp_type_quals (t), complain);
10559               }
10560             else
10561               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
10562               return unshare_expr (arg);
10563           }
10564
10565         if (level == 1)
10566           /* This can happen during the attempted tsubst'ing in
10567              unify.  This means that we don't yet have any information
10568              about the template parameter in question.  */
10569           return t;
10570
10571         /* If we get here, we must have been looking at a parm for a
10572            more deeply nested template.  Make a new version of this
10573            template parameter, but with a lower level.  */
10574         switch (code)
10575           {
10576           case TEMPLATE_TYPE_PARM:
10577           case TEMPLATE_TEMPLATE_PARM:
10578           case BOUND_TEMPLATE_TEMPLATE_PARM:
10579             if (cp_type_quals (t))
10580               {
10581                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
10582                 r = cp_build_qualified_type_real
10583                   (r, cp_type_quals (t),
10584                    complain | (code == TEMPLATE_TYPE_PARM
10585                                ? tf_ignore_bad_quals : 0));
10586               }
10587             else
10588               {
10589                 r = copy_type (t);
10590                 TEMPLATE_TYPE_PARM_INDEX (r)
10591                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
10592                                                 r, levels, args, complain);
10593                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
10594                 TYPE_MAIN_VARIANT (r) = r;
10595                 TYPE_POINTER_TO (r) = NULL_TREE;
10596                 TYPE_REFERENCE_TO (r) = NULL_TREE;
10597
10598                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
10599                   /* We have reduced the level of the template
10600                      template parameter, but not the levels of its
10601                      template parameters, so canonical_type_parameter
10602                      will not be able to find the canonical template
10603                      template parameter for this level. Thus, we
10604                      require structural equality checking to compare
10605                      TEMPLATE_TEMPLATE_PARMs. */
10606                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10607                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
10608                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10609                 else
10610                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
10611
10612                 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
10613                   {
10614                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
10615                                           complain, in_decl);
10616                     if (argvec == error_mark_node)
10617                       return error_mark_node;
10618
10619                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
10620                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
10621                   }
10622               }
10623             break;
10624
10625           case TEMPLATE_PARM_INDEX:
10626             r = reduce_template_parm_level (t, type, levels, args, complain);
10627             break;
10628
10629           default:
10630             gcc_unreachable ();
10631           }
10632
10633         return r;
10634       }
10635
10636     case TREE_LIST:
10637       {
10638         tree purpose, value, chain;
10639
10640         if (t == void_list_node)
10641           return t;
10642
10643         purpose = TREE_PURPOSE (t);
10644         if (purpose)
10645           {
10646             purpose = tsubst (purpose, args, complain, in_decl);
10647             if (purpose == error_mark_node)
10648               return error_mark_node;
10649           }
10650         value = TREE_VALUE (t);
10651         if (value)
10652           {
10653             value = tsubst (value, args, complain, in_decl);
10654             if (value == error_mark_node)
10655               return error_mark_node;
10656           }
10657         chain = TREE_CHAIN (t);
10658         if (chain && chain != void_type_node)
10659           {
10660             chain = tsubst (chain, args, complain, in_decl);
10661             if (chain == error_mark_node)
10662               return error_mark_node;
10663           }
10664         if (purpose == TREE_PURPOSE (t)
10665             && value == TREE_VALUE (t)
10666             && chain == TREE_CHAIN (t))
10667           return t;
10668         return hash_tree_cons (purpose, value, chain);
10669       }
10670
10671     case TREE_BINFO:
10672       /* We should never be tsubsting a binfo.  */
10673       gcc_unreachable ();
10674
10675     case TREE_VEC:
10676       /* A vector of template arguments.  */
10677       gcc_assert (!type);
10678       return tsubst_template_args (t, args, complain, in_decl);
10679
10680     case POINTER_TYPE:
10681     case REFERENCE_TYPE:
10682       {
10683         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
10684           return t;
10685
10686         /* [temp.deduct]
10687
10688            Type deduction may fail for any of the following
10689            reasons:
10690
10691            -- Attempting to create a pointer to reference type.
10692            -- Attempting to create a reference to a reference type or
10693               a reference to void.
10694
10695           Core issue 106 says that creating a reference to a reference
10696           during instantiation is no longer a cause for failure. We
10697           only enforce this check in strict C++98 mode.  */
10698         if ((TREE_CODE (type) == REFERENCE_TYPE
10699              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
10700             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
10701           {
10702             static location_t last_loc;
10703
10704             /* We keep track of the last time we issued this error
10705                message to avoid spewing a ton of messages during a
10706                single bad template instantiation.  */
10707             if (complain & tf_error
10708                 && last_loc != input_location)
10709               {
10710                 if (TREE_CODE (type) == VOID_TYPE)
10711                   error ("forming reference to void");
10712                else if (code == POINTER_TYPE)
10713                  error ("forming pointer to reference type %qT", type);
10714                else
10715                   error ("forming reference to reference type %qT", type);
10716                 last_loc = input_location;
10717               }
10718
10719             return error_mark_node;
10720           }
10721         else if (code == POINTER_TYPE)
10722           {
10723             r = build_pointer_type (type);
10724             if (TREE_CODE (type) == METHOD_TYPE)
10725               r = build_ptrmemfunc_type (r);
10726           }
10727         else if (TREE_CODE (type) == REFERENCE_TYPE)
10728           /* In C++0x, during template argument substitution, when there is an
10729              attempt to create a reference to a reference type, reference
10730              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
10731
10732              "If a template-argument for a template-parameter T names a type
10733              that is a reference to a type A, an attempt to create the type
10734              'lvalue reference to cv T' creates the type 'lvalue reference to
10735              A,' while an attempt to create the type type rvalue reference to
10736              cv T' creates the type T"
10737           */
10738           r = cp_build_reference_type
10739               (TREE_TYPE (type),
10740                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
10741         else
10742           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
10743         r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
10744
10745         if (r != error_mark_node)
10746           /* Will this ever be needed for TYPE_..._TO values?  */
10747           layout_type (r);
10748
10749         return r;
10750       }
10751     case OFFSET_TYPE:
10752       {
10753         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
10754         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
10755           {
10756             /* [temp.deduct]
10757
10758                Type deduction may fail for any of the following
10759                reasons:
10760
10761                -- Attempting to create "pointer to member of T" when T
10762                   is not a class type.  */
10763             if (complain & tf_error)
10764               error ("creating pointer to member of non-class type %qT", r);
10765             return error_mark_node;
10766           }
10767         if (TREE_CODE (type) == REFERENCE_TYPE)
10768           {
10769             if (complain & tf_error)
10770               error ("creating pointer to member reference type %qT", type);
10771             return error_mark_node;
10772           }
10773         if (TREE_CODE (type) == VOID_TYPE)
10774           {
10775             if (complain & tf_error)
10776               error ("creating pointer to member of type void");
10777             return error_mark_node;
10778           }
10779         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
10780         if (TREE_CODE (type) == FUNCTION_TYPE)
10781           {
10782             /* The type of the implicit object parameter gets its
10783                cv-qualifiers from the FUNCTION_TYPE. */
10784             tree memptr;
10785             tree method_type = build_memfn_type (type, r, type_memfn_quals (type));
10786             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
10787             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
10788                                                  complain);
10789           }
10790         else
10791           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
10792                                                cp_type_quals (t),
10793                                                complain);
10794       }
10795     case FUNCTION_TYPE:
10796     case METHOD_TYPE:
10797       {
10798         tree fntype;
10799         tree specs;
10800         fntype = tsubst_function_type (t, args, complain, in_decl);
10801         if (fntype == error_mark_node)
10802           return error_mark_node;
10803
10804         /* Substitute the exception specification.  */
10805         specs = tsubst_exception_specification (t, args, complain,
10806                                                 in_decl);
10807         if (specs == error_mark_node)
10808           return error_mark_node;
10809         if (specs)
10810           fntype = build_exception_variant (fntype, specs);
10811         return fntype;
10812       }
10813     case ARRAY_TYPE:
10814       {
10815         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
10816         if (domain == error_mark_node)
10817           return error_mark_node;
10818
10819         /* As an optimization, we avoid regenerating the array type if
10820            it will obviously be the same as T.  */
10821         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
10822           return t;
10823
10824         /* These checks should match the ones in grokdeclarator.
10825
10826            [temp.deduct]
10827
10828            The deduction may fail for any of the following reasons:
10829
10830            -- Attempting to create an array with an element type that
10831               is void, a function type, or a reference type, or [DR337]
10832               an abstract class type.  */
10833         if (TREE_CODE (type) == VOID_TYPE
10834             || TREE_CODE (type) == FUNCTION_TYPE
10835             || TREE_CODE (type) == REFERENCE_TYPE)
10836           {
10837             if (complain & tf_error)
10838               error ("creating array of %qT", type);
10839             return error_mark_node;
10840           }
10841         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
10842           {
10843             if (complain & tf_error)
10844               error ("creating array of %qT, which is an abstract class type",
10845                      type);
10846             return error_mark_node;
10847           }
10848
10849         r = build_cplus_array_type (type, domain);
10850
10851         if (TYPE_USER_ALIGN (t))
10852           {
10853             TYPE_ALIGN (r) = TYPE_ALIGN (t);
10854             TYPE_USER_ALIGN (r) = 1;
10855           }
10856
10857         return r;
10858       }
10859
10860     case TYPENAME_TYPE:
10861       {
10862         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10863                                      in_decl, /*entering_scope=*/1);
10864         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
10865                               complain, in_decl);
10866
10867         if (ctx == error_mark_node || f == error_mark_node)
10868           return error_mark_node;
10869
10870         if (!MAYBE_CLASS_TYPE_P (ctx))
10871           {
10872             if (complain & tf_error)
10873               error ("%qT is not a class, struct, or union type", ctx);
10874             return error_mark_node;
10875           }
10876         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
10877           {
10878             /* Normally, make_typename_type does not require that the CTX
10879                have complete type in order to allow things like:
10880
10881                  template <class T> struct S { typename S<T>::X Y; };
10882
10883                But, such constructs have already been resolved by this
10884                point, so here CTX really should have complete type, unless
10885                it's a partial instantiation.  */
10886             ctx = complete_type (ctx);
10887             if (!COMPLETE_TYPE_P (ctx))
10888               {
10889                 if (complain & tf_error)
10890                   cxx_incomplete_type_error (NULL_TREE, ctx);
10891                 return error_mark_node;
10892               }
10893           }
10894
10895         f = make_typename_type (ctx, f, typename_type,
10896                                 (complain & tf_error) | tf_keep_type_decl);
10897         if (f == error_mark_node)
10898           return f;
10899         if (TREE_CODE (f) == TYPE_DECL)
10900           {
10901             complain |= tf_ignore_bad_quals;
10902             f = TREE_TYPE (f);
10903           }
10904
10905         if (TREE_CODE (f) != TYPENAME_TYPE)
10906           {
10907             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
10908               error ("%qT resolves to %qT, which is not an enumeration type",
10909                      t, f);
10910             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
10911               error ("%qT resolves to %qT, which is is not a class type",
10912                      t, f);
10913           }
10914
10915         return cp_build_qualified_type_real
10916           (f, cp_type_quals (f) | cp_type_quals (t), complain);
10917       }
10918
10919     case UNBOUND_CLASS_TEMPLATE:
10920       {
10921         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10922                                      in_decl, /*entering_scope=*/1);
10923         tree name = TYPE_IDENTIFIER (t);
10924         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
10925
10926         if (ctx == error_mark_node || name == error_mark_node)
10927           return error_mark_node;
10928
10929         if (parm_list)
10930           parm_list = tsubst_template_parms (parm_list, args, complain);
10931         return make_unbound_class_template (ctx, name, parm_list, complain);
10932       }
10933
10934     case TYPEOF_TYPE:
10935       {
10936         tree type;
10937
10938         ++cp_unevaluated_operand;
10939         ++c_inhibit_evaluation_warnings;
10940
10941         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
10942                             complain, in_decl,
10943                             /*integral_constant_expression_p=*/false);
10944
10945         --cp_unevaluated_operand;
10946         --c_inhibit_evaluation_warnings;
10947
10948         type = finish_typeof (type);
10949         return cp_build_qualified_type_real (type,
10950                                              cp_type_quals (t)
10951                                              | cp_type_quals (type),
10952                                              complain);
10953       }
10954
10955     case DECLTYPE_TYPE:
10956       {
10957         tree type;
10958
10959         ++cp_unevaluated_operand;
10960         ++c_inhibit_evaluation_warnings;
10961
10962         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
10963                             complain, in_decl,
10964                             /*integral_constant_expression_p=*/false);
10965
10966         --cp_unevaluated_operand;
10967         --c_inhibit_evaluation_warnings;
10968
10969         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
10970           type = lambda_capture_field_type (type);
10971         else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
10972           type = lambda_return_type (type);
10973         else
10974           type = finish_decltype_type
10975             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
10976         return cp_build_qualified_type_real (type,
10977                                              cp_type_quals (t)
10978                                              | cp_type_quals (type),
10979                                              complain);
10980       }
10981
10982     case TYPE_ARGUMENT_PACK:
10983     case NONTYPE_ARGUMENT_PACK:
10984       {
10985         tree r = TYPE_P (t) ? cxx_make_type (code) : make_node (code);
10986         tree packed_out = 
10987           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
10988                                 args,
10989                                 complain,
10990                                 in_decl);
10991         SET_ARGUMENT_PACK_ARGS (r, packed_out);
10992
10993         /* For template nontype argument packs, also substitute into
10994            the type.  */
10995         if (code == NONTYPE_ARGUMENT_PACK)
10996           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
10997
10998         return r;
10999       }
11000       break;
11001
11002     case INTEGER_CST:
11003     case REAL_CST:
11004     case STRING_CST:
11005     case PLUS_EXPR:
11006     case MINUS_EXPR:
11007     case NEGATE_EXPR:
11008     case NOP_EXPR:
11009     case INDIRECT_REF:
11010     case ADDR_EXPR:
11011     case CALL_EXPR:
11012     case ARRAY_REF:
11013     case SCOPE_REF:
11014       /* We should use one of the expression tsubsts for these codes.  */
11015       gcc_unreachable ();
11016
11017     default:
11018       sorry ("use of %qs in template", tree_code_name [(int) code]);
11019       return error_mark_node;
11020     }
11021 }
11022
11023 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
11024    type of the expression on the left-hand side of the "." or "->"
11025    operator.  */
11026
11027 static tree
11028 tsubst_baselink (tree baselink, tree object_type,
11029                  tree args, tsubst_flags_t complain, tree in_decl)
11030 {
11031     tree name;
11032     tree qualifying_scope;
11033     tree fns;
11034     tree optype;
11035     tree template_args = 0;
11036     bool template_id_p = false;
11037
11038     /* A baselink indicates a function from a base class.  Both the
11039        BASELINK_ACCESS_BINFO and the base class referenced may
11040        indicate bases of the template class, rather than the
11041        instantiated class.  In addition, lookups that were not
11042        ambiguous before may be ambiguous now.  Therefore, we perform
11043        the lookup again.  */
11044     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
11045     qualifying_scope = tsubst (qualifying_scope, args,
11046                                complain, in_decl);
11047     fns = BASELINK_FUNCTIONS (baselink);
11048     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
11049     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
11050       {
11051         template_id_p = true;
11052         template_args = TREE_OPERAND (fns, 1);
11053         fns = TREE_OPERAND (fns, 0);
11054         if (template_args)
11055           template_args = tsubst_template_args (template_args, args,
11056                                                 complain, in_decl);
11057       }
11058     name = DECL_NAME (get_first_fn (fns));
11059     if (IDENTIFIER_TYPENAME_P (name))
11060       name = mangle_conv_op_name_for_type (optype);
11061     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
11062     if (!baselink)
11063       return error_mark_node;
11064
11065     /* If lookup found a single function, mark it as used at this
11066        point.  (If it lookup found multiple functions the one selected
11067        later by overload resolution will be marked as used at that
11068        point.)  */
11069     if (BASELINK_P (baselink))
11070       fns = BASELINK_FUNCTIONS (baselink);
11071     if (!template_id_p && !really_overloaded_fn (fns))
11072       mark_used (OVL_CURRENT (fns));
11073
11074     /* Add back the template arguments, if present.  */
11075     if (BASELINK_P (baselink) && template_id_p)
11076       BASELINK_FUNCTIONS (baselink)
11077         = build_nt (TEMPLATE_ID_EXPR,
11078                     BASELINK_FUNCTIONS (baselink),
11079                     template_args);
11080     /* Update the conversion operator type.  */
11081     BASELINK_OPTYPE (baselink) = optype;
11082
11083     if (!object_type)
11084       object_type = current_class_type;
11085     return adjust_result_of_qualified_name_lookup (baselink,
11086                                                    qualifying_scope,
11087                                                    object_type);
11088 }
11089
11090 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
11091    true if the qualified-id will be a postfix-expression in-and-of
11092    itself; false if more of the postfix-expression follows the
11093    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
11094    of "&".  */
11095
11096 static tree
11097 tsubst_qualified_id (tree qualified_id, tree args,
11098                      tsubst_flags_t complain, tree in_decl,
11099                      bool done, bool address_p)
11100 {
11101   tree expr;
11102   tree scope;
11103   tree name;
11104   bool is_template;
11105   tree template_args;
11106
11107   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
11108
11109   /* Figure out what name to look up.  */
11110   name = TREE_OPERAND (qualified_id, 1);
11111   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
11112     {
11113       is_template = true;
11114       template_args = TREE_OPERAND (name, 1);
11115       if (template_args)
11116         template_args = tsubst_template_args (template_args, args,
11117                                               complain, in_decl);
11118       name = TREE_OPERAND (name, 0);
11119     }
11120   else
11121     {
11122       is_template = false;
11123       template_args = NULL_TREE;
11124     }
11125
11126   /* Substitute into the qualifying scope.  When there are no ARGS, we
11127      are just trying to simplify a non-dependent expression.  In that
11128      case the qualifying scope may be dependent, and, in any case,
11129      substituting will not help.  */
11130   scope = TREE_OPERAND (qualified_id, 0);
11131   if (args)
11132     {
11133       scope = tsubst (scope, args, complain, in_decl);
11134       expr = tsubst_copy (name, args, complain, in_decl);
11135     }
11136   else
11137     expr = name;
11138
11139   if (dependent_scope_p (scope))
11140     return build_qualified_name (NULL_TREE, scope, expr,
11141                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
11142
11143   if (!BASELINK_P (name) && !DECL_P (expr))
11144     {
11145       if (TREE_CODE (expr) == BIT_NOT_EXPR)
11146         {
11147           /* A BIT_NOT_EXPR is used to represent a destructor.  */
11148           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
11149             {
11150               error ("qualifying type %qT does not match destructor name ~%qT",
11151                      scope, TREE_OPERAND (expr, 0));
11152               expr = error_mark_node;
11153             }
11154           else
11155             expr = lookup_qualified_name (scope, complete_dtor_identifier,
11156                                           /*is_type_p=*/0, false);
11157         }
11158       else
11159         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
11160       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
11161                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
11162         {
11163           if (complain & tf_error)
11164             {
11165               error ("dependent-name %qE is parsed as a non-type, but "
11166                      "instantiation yields a type", qualified_id);
11167               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
11168             }
11169           return error_mark_node;
11170         }
11171     }
11172
11173   if (DECL_P (expr))
11174     {
11175       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
11176                                            scope);
11177       /* Remember that there was a reference to this entity.  */
11178       mark_used (expr);
11179     }
11180
11181   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
11182     {
11183       if (complain & tf_error)
11184         qualified_name_lookup_error (scope,
11185                                      TREE_OPERAND (qualified_id, 1),
11186                                      expr, input_location);
11187       return error_mark_node;
11188     }
11189
11190   if (is_template)
11191     expr = lookup_template_function (expr, template_args);
11192
11193   if (expr == error_mark_node && complain & tf_error)
11194     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
11195                                  expr, input_location);
11196   else if (TYPE_P (scope))
11197     {
11198       expr = (adjust_result_of_qualified_name_lookup
11199               (expr, scope, current_class_type));
11200       expr = (finish_qualified_id_expr
11201               (scope, expr, done, address_p,
11202                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
11203                /*template_arg_p=*/false));
11204     }
11205
11206   /* Expressions do not generally have reference type.  */
11207   if (TREE_CODE (expr) != SCOPE_REF
11208       /* However, if we're about to form a pointer-to-member, we just
11209          want the referenced member referenced.  */
11210       && TREE_CODE (expr) != OFFSET_REF)
11211     expr = convert_from_reference (expr);
11212
11213   return expr;
11214 }
11215
11216 /* Like tsubst, but deals with expressions.  This function just replaces
11217    template parms; to finish processing the resultant expression, use
11218    tsubst_expr.  */
11219
11220 static tree
11221 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11222 {
11223   enum tree_code code;
11224   tree r;
11225
11226   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
11227     return t;
11228
11229   code = TREE_CODE (t);
11230
11231   switch (code)
11232     {
11233     case PARM_DECL:
11234       r = retrieve_local_specialization (t);
11235
11236       if (r == NULL)
11237         {
11238           tree c;
11239           /* This can happen for a parameter name used later in a function
11240              declaration (such as in a late-specified return type).  Just
11241              make a dummy decl, since it's only used for its type.  */
11242           gcc_assert (cp_unevaluated_operand != 0);
11243           /* We copy T because want to tsubst the PARM_DECL only,
11244              not the following PARM_DECLs that are chained to T.  */
11245           c = copy_node (t);
11246           r = tsubst_decl (c, args, complain);
11247           /* Give it the template pattern as its context; its true context
11248              hasn't been instantiated yet and this is good enough for
11249              mangling.  */
11250           DECL_CONTEXT (r) = DECL_CONTEXT (t);
11251         }
11252       
11253       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
11254         r = ARGUMENT_PACK_SELECT_ARG (r);
11255       mark_used (r);
11256       return r;
11257
11258     case CONST_DECL:
11259       {
11260         tree enum_type;
11261         tree v;
11262
11263         if (DECL_TEMPLATE_PARM_P (t))
11264           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
11265         /* There is no need to substitute into namespace-scope
11266            enumerators.  */
11267         if (DECL_NAMESPACE_SCOPE_P (t))
11268           return t;
11269         /* If ARGS is NULL, then T is known to be non-dependent.  */
11270         if (args == NULL_TREE)
11271           return integral_constant_value (t);
11272
11273         /* Unfortunately, we cannot just call lookup_name here.
11274            Consider:
11275
11276              template <int I> int f() {
11277              enum E { a = I };
11278              struct S { void g() { E e = a; } };
11279              };
11280
11281            When we instantiate f<7>::S::g(), say, lookup_name is not
11282            clever enough to find f<7>::a.  */
11283         enum_type
11284           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
11285                               /*entering_scope=*/0);
11286
11287         for (v = TYPE_VALUES (enum_type);
11288              v != NULL_TREE;
11289              v = TREE_CHAIN (v))
11290           if (TREE_PURPOSE (v) == DECL_NAME (t))
11291             return TREE_VALUE (v);
11292
11293           /* We didn't find the name.  That should never happen; if
11294              name-lookup found it during preliminary parsing, we
11295              should find it again here during instantiation.  */
11296         gcc_unreachable ();
11297       }
11298       return t;
11299
11300     case FIELD_DECL:
11301       if (DECL_CONTEXT (t))
11302         {
11303           tree ctx;
11304
11305           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
11306                                   /*entering_scope=*/1);
11307           if (ctx != DECL_CONTEXT (t))
11308             {
11309               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
11310               if (!r)
11311                 {
11312                   if (complain & tf_error)
11313                     error ("using invalid field %qD", t);
11314                   return error_mark_node;
11315                 }
11316               return r;
11317             }
11318         }
11319
11320       return t;
11321
11322     case VAR_DECL:
11323     case FUNCTION_DECL:
11324       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
11325           || local_variable_p (t))
11326         t = tsubst (t, args, complain, in_decl);
11327       mark_used (t);
11328       return t;
11329
11330     case OVERLOAD:
11331       /* An OVERLOAD will always be a non-dependent overload set; an
11332          overload set from function scope will just be represented with an
11333          IDENTIFIER_NODE, and from class scope with a BASELINK.  */
11334       gcc_assert (!uses_template_parms (t));
11335       return t;
11336
11337     case BASELINK:
11338       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
11339
11340     case TEMPLATE_DECL:
11341       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11342         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
11343                        args, complain, in_decl);
11344       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
11345         return tsubst (t, args, complain, in_decl);
11346       else if (DECL_CLASS_SCOPE_P (t)
11347                && uses_template_parms (DECL_CONTEXT (t)))
11348         {
11349           /* Template template argument like the following example need
11350              special treatment:
11351
11352                template <template <class> class TT> struct C {};
11353                template <class T> struct D {
11354                  template <class U> struct E {};
11355                  C<E> c;                                // #1
11356                };
11357                D<int> d;                                // #2
11358
11359              We are processing the template argument `E' in #1 for
11360              the template instantiation #2.  Originally, `E' is a
11361              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
11362              have to substitute this with one having context `D<int>'.  */
11363
11364           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
11365           return lookup_field (context, DECL_NAME(t), 0, false);
11366         }
11367       else
11368         /* Ordinary template template argument.  */
11369         return t;
11370
11371     case CAST_EXPR:
11372     case REINTERPRET_CAST_EXPR:
11373     case CONST_CAST_EXPR:
11374     case STATIC_CAST_EXPR:
11375     case DYNAMIC_CAST_EXPR:
11376     case NOP_EXPR:
11377       return build1
11378         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11379          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11380
11381     case SIZEOF_EXPR:
11382       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11383         {
11384           /* We only want to compute the number of arguments.  */
11385           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
11386                                                 complain, in_decl);
11387           int len = 0;
11388
11389           if (TREE_CODE (expanded) == TREE_VEC)
11390             len = TREE_VEC_LENGTH (expanded);
11391
11392           if (expanded == error_mark_node)
11393             return error_mark_node;
11394           else if (PACK_EXPANSION_P (expanded)
11395                    || (TREE_CODE (expanded) == TREE_VEC
11396                        && len > 0
11397                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
11398             {
11399               if (TREE_CODE (expanded) == TREE_VEC)
11400                 expanded = TREE_VEC_ELT (expanded, len - 1);
11401
11402               if (TYPE_P (expanded))
11403                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
11404                                                    complain & tf_error);
11405               else
11406                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
11407                                                    complain & tf_error);
11408             }
11409           else
11410             return build_int_cst (size_type_node, len);
11411         }
11412       /* Fall through */
11413
11414     case INDIRECT_REF:
11415     case NEGATE_EXPR:
11416     case TRUTH_NOT_EXPR:
11417     case BIT_NOT_EXPR:
11418     case ADDR_EXPR:
11419     case UNARY_PLUS_EXPR:      /* Unary + */
11420     case ALIGNOF_EXPR:
11421     case AT_ENCODE_EXPR:
11422     case ARROW_EXPR:
11423     case THROW_EXPR:
11424     case TYPEID_EXPR:
11425     case REALPART_EXPR:
11426     case IMAGPART_EXPR:
11427       return build1
11428         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11429          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11430
11431     case COMPONENT_REF:
11432       {
11433         tree object;
11434         tree name;
11435
11436         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
11437         name = TREE_OPERAND (t, 1);
11438         if (TREE_CODE (name) == BIT_NOT_EXPR)
11439           {
11440             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11441                                 complain, in_decl);
11442             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11443           }
11444         else if (TREE_CODE (name) == SCOPE_REF
11445                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
11446           {
11447             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
11448                                      complain, in_decl);
11449             name = TREE_OPERAND (name, 1);
11450             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11451                                 complain, in_decl);
11452             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11453             name = build_qualified_name (/*type=*/NULL_TREE,
11454                                          base, name,
11455                                          /*template_p=*/false);
11456           }
11457         else if (TREE_CODE (name) == BASELINK)
11458           name = tsubst_baselink (name,
11459                                   non_reference (TREE_TYPE (object)),
11460                                   args, complain,
11461                                   in_decl);
11462         else
11463           name = tsubst_copy (name, args, complain, in_decl);
11464         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
11465       }
11466
11467     case PLUS_EXPR:
11468     case MINUS_EXPR:
11469     case MULT_EXPR:
11470     case TRUNC_DIV_EXPR:
11471     case CEIL_DIV_EXPR:
11472     case FLOOR_DIV_EXPR:
11473     case ROUND_DIV_EXPR:
11474     case EXACT_DIV_EXPR:
11475     case BIT_AND_EXPR:
11476     case BIT_IOR_EXPR:
11477     case BIT_XOR_EXPR:
11478     case TRUNC_MOD_EXPR:
11479     case FLOOR_MOD_EXPR:
11480     case TRUTH_ANDIF_EXPR:
11481     case TRUTH_ORIF_EXPR:
11482     case TRUTH_AND_EXPR:
11483     case TRUTH_OR_EXPR:
11484     case RSHIFT_EXPR:
11485     case LSHIFT_EXPR:
11486     case RROTATE_EXPR:
11487     case LROTATE_EXPR:
11488     case EQ_EXPR:
11489     case NE_EXPR:
11490     case MAX_EXPR:
11491     case MIN_EXPR:
11492     case LE_EXPR:
11493     case GE_EXPR:
11494     case LT_EXPR:
11495     case GT_EXPR:
11496     case COMPOUND_EXPR:
11497     case DOTSTAR_EXPR:
11498     case MEMBER_REF:
11499     case PREDECREMENT_EXPR:
11500     case PREINCREMENT_EXPR:
11501     case POSTDECREMENT_EXPR:
11502     case POSTINCREMENT_EXPR:
11503       return build_nt
11504         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11505          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11506
11507     case SCOPE_REF:
11508       return build_qualified_name (/*type=*/NULL_TREE,
11509                                    tsubst_copy (TREE_OPERAND (t, 0),
11510                                                 args, complain, in_decl),
11511                                    tsubst_copy (TREE_OPERAND (t, 1),
11512                                                 args, complain, in_decl),
11513                                    QUALIFIED_NAME_IS_TEMPLATE (t));
11514
11515     case ARRAY_REF:
11516       return build_nt
11517         (ARRAY_REF,
11518          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11519          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11520          NULL_TREE, NULL_TREE);
11521
11522     case CALL_EXPR:
11523       {
11524         int n = VL_EXP_OPERAND_LENGTH (t);
11525         tree result = build_vl_exp (CALL_EXPR, n);
11526         int i;
11527         for (i = 0; i < n; i++)
11528           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
11529                                              complain, in_decl);
11530         return result;
11531       }
11532
11533     case COND_EXPR:
11534     case MODOP_EXPR:
11535     case PSEUDO_DTOR_EXPR:
11536       {
11537         r = build_nt
11538           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11539            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11540            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11541         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11542         return r;
11543       }
11544
11545     case NEW_EXPR:
11546       {
11547         r = build_nt
11548         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11549          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11550          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11551         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
11552         return r;
11553       }
11554
11555     case DELETE_EXPR:
11556       {
11557         r = build_nt
11558         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11559          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11560         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
11561         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
11562         return r;
11563       }
11564
11565     case TEMPLATE_ID_EXPR:
11566       {
11567         /* Substituted template arguments */
11568         tree fn = TREE_OPERAND (t, 0);
11569         tree targs = TREE_OPERAND (t, 1);
11570
11571         fn = tsubst_copy (fn, args, complain, in_decl);
11572         if (targs)
11573           targs = tsubst_template_args (targs, args, complain, in_decl);
11574
11575         return lookup_template_function (fn, targs);
11576       }
11577
11578     case TREE_LIST:
11579       {
11580         tree purpose, value, chain;
11581
11582         if (t == void_list_node)
11583           return t;
11584
11585         purpose = TREE_PURPOSE (t);
11586         if (purpose)
11587           purpose = tsubst_copy (purpose, args, complain, in_decl);
11588         value = TREE_VALUE (t);
11589         if (value)
11590           value = tsubst_copy (value, args, complain, in_decl);
11591         chain = TREE_CHAIN (t);
11592         if (chain && chain != void_type_node)
11593           chain = tsubst_copy (chain, args, complain, in_decl);
11594         if (purpose == TREE_PURPOSE (t)
11595             && value == TREE_VALUE (t)
11596             && chain == TREE_CHAIN (t))
11597           return t;
11598         return tree_cons (purpose, value, chain);
11599       }
11600
11601     case RECORD_TYPE:
11602     case UNION_TYPE:
11603     case ENUMERAL_TYPE:
11604     case INTEGER_TYPE:
11605     case TEMPLATE_TYPE_PARM:
11606     case TEMPLATE_TEMPLATE_PARM:
11607     case BOUND_TEMPLATE_TEMPLATE_PARM:
11608     case TEMPLATE_PARM_INDEX:
11609     case POINTER_TYPE:
11610     case REFERENCE_TYPE:
11611     case OFFSET_TYPE:
11612     case FUNCTION_TYPE:
11613     case METHOD_TYPE:
11614     case ARRAY_TYPE:
11615     case TYPENAME_TYPE:
11616     case UNBOUND_CLASS_TEMPLATE:
11617     case TYPEOF_TYPE:
11618     case DECLTYPE_TYPE:
11619     case TYPE_DECL:
11620       return tsubst (t, args, complain, in_decl);
11621
11622     case IDENTIFIER_NODE:
11623       if (IDENTIFIER_TYPENAME_P (t))
11624         {
11625           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11626           return mangle_conv_op_name_for_type (new_type);
11627         }
11628       else
11629         return t;
11630
11631     case CONSTRUCTOR:
11632       /* This is handled by tsubst_copy_and_build.  */
11633       gcc_unreachable ();
11634
11635     case VA_ARG_EXPR:
11636       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
11637                                           in_decl),
11638                              tsubst (TREE_TYPE (t), args, complain, in_decl));
11639
11640     case CLEANUP_POINT_EXPR:
11641       /* We shouldn't have built any of these during initial template
11642          generation.  Instead, they should be built during instantiation
11643          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
11644       gcc_unreachable ();
11645
11646     case OFFSET_REF:
11647       r = build2
11648         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11649          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11650          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11651       PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
11652       mark_used (TREE_OPERAND (r, 1));
11653       return r;
11654
11655     case EXPR_PACK_EXPANSION:
11656       error ("invalid use of pack expansion expression");
11657       return error_mark_node;
11658
11659     case NONTYPE_ARGUMENT_PACK:
11660       error ("use %<...%> to expand argument pack");
11661       return error_mark_node;
11662
11663     case INTEGER_CST:
11664     case REAL_CST:
11665     case STRING_CST:
11666     case COMPLEX_CST:
11667       {
11668         /* Instantiate any typedefs in the type.  */
11669         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11670         r = fold_convert (type, t);
11671         gcc_assert (TREE_CODE (r) == code);
11672         return r;
11673       }
11674
11675     case PTRMEM_CST:
11676       /* These can sometimes show up in a partial instantiation, but never
11677          involve template parms.  */
11678       gcc_assert (!uses_template_parms (t));
11679       return t;
11680
11681     default:
11682       gcc_unreachable ();
11683     }
11684 }
11685
11686 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
11687
11688 static tree
11689 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
11690                     tree in_decl)
11691 {
11692   tree new_clauses = NULL, nc, oc;
11693
11694   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
11695     {
11696       nc = copy_node (oc);
11697       OMP_CLAUSE_CHAIN (nc) = new_clauses;
11698       new_clauses = nc;
11699
11700       switch (OMP_CLAUSE_CODE (nc))
11701         {
11702         case OMP_CLAUSE_LASTPRIVATE:
11703           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
11704             {
11705               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
11706               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
11707                            in_decl, /*integral_constant_expression_p=*/false);
11708               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
11709                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
11710             }
11711           /* FALLTHRU */
11712         case OMP_CLAUSE_PRIVATE:
11713         case OMP_CLAUSE_SHARED:
11714         case OMP_CLAUSE_FIRSTPRIVATE:
11715         case OMP_CLAUSE_REDUCTION:
11716         case OMP_CLAUSE_COPYIN:
11717         case OMP_CLAUSE_COPYPRIVATE:
11718         case OMP_CLAUSE_IF:
11719         case OMP_CLAUSE_NUM_THREADS:
11720         case OMP_CLAUSE_SCHEDULE:
11721         case OMP_CLAUSE_COLLAPSE:
11722           OMP_CLAUSE_OPERAND (nc, 0)
11723             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
11724                            in_decl, /*integral_constant_expression_p=*/false);
11725           break;
11726         case OMP_CLAUSE_NOWAIT:
11727         case OMP_CLAUSE_ORDERED:
11728         case OMP_CLAUSE_DEFAULT:
11729         case OMP_CLAUSE_UNTIED:
11730           break;
11731         default:
11732           gcc_unreachable ();
11733         }
11734     }
11735
11736   return finish_omp_clauses (nreverse (new_clauses));
11737 }
11738
11739 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
11740
11741 static tree
11742 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
11743                           tree in_decl)
11744 {
11745 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
11746
11747   tree purpose, value, chain;
11748
11749   if (t == NULL)
11750     return t;
11751
11752   if (TREE_CODE (t) != TREE_LIST)
11753     return tsubst_copy_and_build (t, args, complain, in_decl,
11754                                   /*function_p=*/false,
11755                                   /*integral_constant_expression_p=*/false);
11756
11757   if (t == void_list_node)
11758     return t;
11759
11760   purpose = TREE_PURPOSE (t);
11761   if (purpose)
11762     purpose = RECUR (purpose);
11763   value = TREE_VALUE (t);
11764   if (value && TREE_CODE (value) != LABEL_DECL)
11765     value = RECUR (value);
11766   chain = TREE_CHAIN (t);
11767   if (chain && chain != void_type_node)
11768     chain = RECUR (chain);
11769   return tree_cons (purpose, value, chain);
11770 #undef RECUR
11771 }
11772
11773 /* Substitute one OMP_FOR iterator.  */
11774
11775 static void
11776 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
11777                          tree condv, tree incrv, tree *clauses,
11778                          tree args, tsubst_flags_t complain, tree in_decl,
11779                          bool integral_constant_expression_p)
11780 {
11781 #define RECUR(NODE)                             \
11782   tsubst_expr ((NODE), args, complain, in_decl, \
11783                integral_constant_expression_p)
11784   tree decl, init, cond, incr, auto_node;
11785
11786   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
11787   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
11788   decl = RECUR (TREE_OPERAND (init, 0));
11789   init = TREE_OPERAND (init, 1);
11790   auto_node = type_uses_auto (TREE_TYPE (decl));
11791   if (auto_node && init)
11792     {
11793       tree init_expr = init;
11794       if (TREE_CODE (init_expr) == DECL_EXPR)
11795         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
11796       init_expr = RECUR (init_expr);
11797       TREE_TYPE (decl)
11798         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
11799     }
11800   gcc_assert (!type_dependent_expression_p (decl));
11801
11802   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
11803     {
11804       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
11805       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11806       if (TREE_CODE (incr) == MODIFY_EXPR)
11807         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
11808                                     RECUR (TREE_OPERAND (incr, 1)),
11809                                     complain);
11810       else
11811         incr = RECUR (incr);
11812       TREE_VEC_ELT (declv, i) = decl;
11813       TREE_VEC_ELT (initv, i) = init;
11814       TREE_VEC_ELT (condv, i) = cond;
11815       TREE_VEC_ELT (incrv, i) = incr;
11816       return;
11817     }
11818
11819   if (init && TREE_CODE (init) != DECL_EXPR)
11820     {
11821       tree c;
11822       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
11823         {
11824           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
11825                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
11826               && OMP_CLAUSE_DECL (c) == decl)
11827             break;
11828           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
11829                    && OMP_CLAUSE_DECL (c) == decl)
11830             error ("iteration variable %qD should not be firstprivate", decl);
11831           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
11832                    && OMP_CLAUSE_DECL (c) == decl)
11833             error ("iteration variable %qD should not be reduction", decl);
11834         }
11835       if (c == NULL)
11836         {
11837           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
11838           OMP_CLAUSE_DECL (c) = decl;
11839           c = finish_omp_clauses (c);
11840           if (c)
11841             {
11842               OMP_CLAUSE_CHAIN (c) = *clauses;
11843               *clauses = c;
11844             }
11845         }
11846     }
11847   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
11848   if (COMPARISON_CLASS_P (cond))
11849     cond = build2 (TREE_CODE (cond), boolean_type_node,
11850                    RECUR (TREE_OPERAND (cond, 0)),
11851                    RECUR (TREE_OPERAND (cond, 1)));
11852   else
11853     cond = RECUR (cond);
11854   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11855   switch (TREE_CODE (incr))
11856     {
11857     case PREINCREMENT_EXPR:
11858     case PREDECREMENT_EXPR:
11859     case POSTINCREMENT_EXPR:
11860     case POSTDECREMENT_EXPR:
11861       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
11862                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
11863       break;
11864     case MODIFY_EXPR:
11865       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11866           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11867         {
11868           tree rhs = TREE_OPERAND (incr, 1);
11869           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11870                          RECUR (TREE_OPERAND (incr, 0)),
11871                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11872                                  RECUR (TREE_OPERAND (rhs, 0)),
11873                                  RECUR (TREE_OPERAND (rhs, 1))));
11874         }
11875       else
11876         incr = RECUR (incr);
11877       break;
11878     case MODOP_EXPR:
11879       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11880           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11881         {
11882           tree lhs = RECUR (TREE_OPERAND (incr, 0));
11883           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
11884                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
11885                                  TREE_TYPE (decl), lhs,
11886                                  RECUR (TREE_OPERAND (incr, 2))));
11887         }
11888       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
11889                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
11890                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
11891         {
11892           tree rhs = TREE_OPERAND (incr, 2);
11893           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11894                          RECUR (TREE_OPERAND (incr, 0)),
11895                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11896                                  RECUR (TREE_OPERAND (rhs, 0)),
11897                                  RECUR (TREE_OPERAND (rhs, 1))));
11898         }
11899       else
11900         incr = RECUR (incr);
11901       break;
11902     default:
11903       incr = RECUR (incr);
11904       break;
11905     }
11906
11907   TREE_VEC_ELT (declv, i) = decl;
11908   TREE_VEC_ELT (initv, i) = init;
11909   TREE_VEC_ELT (condv, i) = cond;
11910   TREE_VEC_ELT (incrv, i) = incr;
11911 #undef RECUR
11912 }
11913
11914 /* Like tsubst_copy for expressions, etc. but also does semantic
11915    processing.  */
11916
11917 static tree
11918 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
11919              bool integral_constant_expression_p)
11920 {
11921 #define RECUR(NODE)                             \
11922   tsubst_expr ((NODE), args, complain, in_decl, \
11923                integral_constant_expression_p)
11924
11925   tree stmt, tmp;
11926
11927   if (t == NULL_TREE || t == error_mark_node)
11928     return t;
11929
11930   if (EXPR_HAS_LOCATION (t))
11931     input_location = EXPR_LOCATION (t);
11932   if (STATEMENT_CODE_P (TREE_CODE (t)))
11933     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
11934
11935   switch (TREE_CODE (t))
11936     {
11937     case STATEMENT_LIST:
11938       {
11939         tree_stmt_iterator i;
11940         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
11941           RECUR (tsi_stmt (i));
11942         break;
11943       }
11944
11945     case CTOR_INITIALIZER:
11946       finish_mem_initializers (tsubst_initializer_list
11947                                (TREE_OPERAND (t, 0), args));
11948       break;
11949
11950     case RETURN_EXPR:
11951       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
11952       break;
11953
11954     case EXPR_STMT:
11955       tmp = RECUR (EXPR_STMT_EXPR (t));
11956       if (EXPR_STMT_STMT_EXPR_RESULT (t))
11957         finish_stmt_expr_expr (tmp, cur_stmt_expr);
11958       else
11959         finish_expr_stmt (tmp);
11960       break;
11961
11962     case USING_STMT:
11963       do_using_directive (USING_STMT_NAMESPACE (t));
11964       break;
11965
11966     case DECL_EXPR:
11967       {
11968         tree decl, pattern_decl;
11969         tree init;
11970
11971         pattern_decl = decl = DECL_EXPR_DECL (t);
11972         if (TREE_CODE (decl) == LABEL_DECL)
11973           finish_label_decl (DECL_NAME (decl));
11974         else if (TREE_CODE (decl) == USING_DECL)
11975           {
11976             tree scope = USING_DECL_SCOPE (decl);
11977             tree name = DECL_NAME (decl);
11978             tree decl;
11979
11980             scope = tsubst (scope, args, complain, in_decl);
11981             decl = lookup_qualified_name (scope, name,
11982                                           /*is_type_p=*/false,
11983                                           /*complain=*/false);
11984             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
11985               qualified_name_lookup_error (scope, name, decl, input_location);
11986             else
11987               do_local_using_decl (decl, scope, name);
11988           }
11989         else
11990           {
11991             init = DECL_INITIAL (decl);
11992             decl = tsubst (decl, args, complain, in_decl);
11993             if (decl != error_mark_node)
11994               {
11995                 /* By marking the declaration as instantiated, we avoid
11996                    trying to instantiate it.  Since instantiate_decl can't
11997                    handle local variables, and since we've already done
11998                    all that needs to be done, that's the right thing to
11999                    do.  */
12000                 if (TREE_CODE (decl) == VAR_DECL)
12001                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12002                 if (TREE_CODE (decl) == VAR_DECL
12003                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
12004                   /* Anonymous aggregates are a special case.  */
12005                   finish_anon_union (decl);
12006                 else
12007                   {
12008                     int const_init = false;
12009                     maybe_push_decl (decl);
12010                     if (TREE_CODE (decl) == VAR_DECL
12011                         && DECL_PRETTY_FUNCTION_P (decl))
12012                       {
12013                         /* For __PRETTY_FUNCTION__ we have to adjust the
12014                            initializer.  */
12015                         const char *const name
12016                           = cxx_printable_name (current_function_decl, 2);
12017                         init = cp_fname_init (name, &TREE_TYPE (decl));
12018                       }
12019                     else
12020                       {
12021                         tree t = RECUR (init);
12022
12023                         if (init && !t)
12024                           {
12025                             /* If we had an initializer but it
12026                                instantiated to nothing,
12027                                value-initialize the object.  This will
12028                                only occur when the initializer was a
12029                                pack expansion where the parameter packs
12030                                used in that expansion were of length
12031                                zero.  */
12032                             init = build_value_init (TREE_TYPE (decl),
12033                                                      complain);
12034                             if (TREE_CODE (init) == AGGR_INIT_EXPR)
12035                               init = get_target_expr (init);
12036                           }
12037                         else
12038                           init = t;
12039                       }
12040
12041                     if (TREE_CODE (decl) == VAR_DECL)
12042                       const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
12043                                     (pattern_decl));
12044                     cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
12045                   }
12046               }
12047           }
12048
12049         /* A DECL_EXPR can also be used as an expression, in the condition
12050            clause of an if/for/while construct.  */
12051         return decl;
12052       }
12053
12054     case FOR_STMT:
12055       stmt = begin_for_stmt ();
12056       RECUR (FOR_INIT_STMT (t));
12057       finish_for_init_stmt (stmt);
12058       tmp = RECUR (FOR_COND (t));
12059       finish_for_cond (tmp, stmt);
12060       tmp = RECUR (FOR_EXPR (t));
12061       finish_for_expr (tmp, stmt);
12062       RECUR (FOR_BODY (t));
12063       finish_for_stmt (stmt);
12064       break;
12065
12066     case RANGE_FOR_STMT:
12067       {
12068         tree decl, expr;
12069         stmt = begin_for_stmt ();
12070         decl = RANGE_FOR_DECL (t);
12071         decl = tsubst (decl, args, complain, in_decl);
12072         maybe_push_decl (decl);
12073         expr = RECUR (RANGE_FOR_EXPR (t));
12074         stmt = cp_convert_range_for (stmt, decl, expr);
12075         RECUR (RANGE_FOR_BODY (t));
12076         finish_for_stmt (stmt);
12077       }
12078       break;
12079
12080     case WHILE_STMT:
12081       stmt = begin_while_stmt ();
12082       tmp = RECUR (WHILE_COND (t));
12083       finish_while_stmt_cond (tmp, stmt);
12084       RECUR (WHILE_BODY (t));
12085       finish_while_stmt (stmt);
12086       break;
12087
12088     case DO_STMT:
12089       stmt = begin_do_stmt ();
12090       RECUR (DO_BODY (t));
12091       finish_do_body (stmt);
12092       tmp = RECUR (DO_COND (t));
12093       finish_do_stmt (tmp, stmt);
12094       break;
12095
12096     case IF_STMT:
12097       stmt = begin_if_stmt ();
12098       tmp = RECUR (IF_COND (t));
12099       finish_if_stmt_cond (tmp, stmt);
12100       RECUR (THEN_CLAUSE (t));
12101       finish_then_clause (stmt);
12102
12103       if (ELSE_CLAUSE (t))
12104         {
12105           begin_else_clause (stmt);
12106           RECUR (ELSE_CLAUSE (t));
12107           finish_else_clause (stmt);
12108         }
12109
12110       finish_if_stmt (stmt);
12111       break;
12112
12113     case BIND_EXPR:
12114       if (BIND_EXPR_BODY_BLOCK (t))
12115         stmt = begin_function_body ();
12116       else
12117         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
12118                                     ? BCS_TRY_BLOCK : 0);
12119
12120       RECUR (BIND_EXPR_BODY (t));
12121
12122       if (BIND_EXPR_BODY_BLOCK (t))
12123         finish_function_body (stmt);
12124       else
12125         finish_compound_stmt (stmt);
12126       break;
12127
12128     case BREAK_STMT:
12129       finish_break_stmt ();
12130       break;
12131
12132     case CONTINUE_STMT:
12133       finish_continue_stmt ();
12134       break;
12135
12136     case SWITCH_STMT:
12137       stmt = begin_switch_stmt ();
12138       tmp = RECUR (SWITCH_STMT_COND (t));
12139       finish_switch_cond (tmp, stmt);
12140       RECUR (SWITCH_STMT_BODY (t));
12141       finish_switch_stmt (stmt);
12142       break;
12143
12144     case CASE_LABEL_EXPR:
12145       finish_case_label (EXPR_LOCATION (t),
12146                          RECUR (CASE_LOW (t)),
12147                          RECUR (CASE_HIGH (t)));
12148       break;
12149
12150     case LABEL_EXPR:
12151       {
12152         tree decl = LABEL_EXPR_LABEL (t);
12153         tree label;
12154
12155         label = finish_label_stmt (DECL_NAME (decl));
12156         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
12157           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
12158       }
12159       break;
12160
12161     case GOTO_EXPR:
12162       tmp = GOTO_DESTINATION (t);
12163       if (TREE_CODE (tmp) != LABEL_DECL)
12164         /* Computed goto's must be tsubst'd into.  On the other hand,
12165            non-computed gotos must not be; the identifier in question
12166            will have no binding.  */
12167         tmp = RECUR (tmp);
12168       else
12169         tmp = DECL_NAME (tmp);
12170       finish_goto_stmt (tmp);
12171       break;
12172
12173     case ASM_EXPR:
12174       tmp = finish_asm_stmt
12175         (ASM_VOLATILE_P (t),
12176          RECUR (ASM_STRING (t)),
12177          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
12178          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
12179          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
12180          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
12181       {
12182         tree asm_expr = tmp;
12183         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
12184           asm_expr = TREE_OPERAND (asm_expr, 0);
12185         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
12186       }
12187       break;
12188
12189     case TRY_BLOCK:
12190       if (CLEANUP_P (t))
12191         {
12192           stmt = begin_try_block ();
12193           RECUR (TRY_STMTS (t));
12194           finish_cleanup_try_block (stmt);
12195           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
12196         }
12197       else
12198         {
12199           tree compound_stmt = NULL_TREE;
12200
12201           if (FN_TRY_BLOCK_P (t))
12202             stmt = begin_function_try_block (&compound_stmt);
12203           else
12204             stmt = begin_try_block ();
12205
12206           RECUR (TRY_STMTS (t));
12207
12208           if (FN_TRY_BLOCK_P (t))
12209             finish_function_try_block (stmt);
12210           else
12211             finish_try_block (stmt);
12212
12213           RECUR (TRY_HANDLERS (t));
12214           if (FN_TRY_BLOCK_P (t))
12215             finish_function_handler_sequence (stmt, compound_stmt);
12216           else
12217             finish_handler_sequence (stmt);
12218         }
12219       break;
12220
12221     case HANDLER:
12222       {
12223         tree decl = HANDLER_PARMS (t);
12224
12225         if (decl)
12226           {
12227             decl = tsubst (decl, args, complain, in_decl);
12228             /* Prevent instantiate_decl from trying to instantiate
12229                this variable.  We've already done all that needs to be
12230                done.  */
12231             if (decl != error_mark_node)
12232               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12233           }
12234         stmt = begin_handler ();
12235         finish_handler_parms (decl, stmt);
12236         RECUR (HANDLER_BODY (t));
12237         finish_handler (stmt);
12238       }
12239       break;
12240
12241     case TAG_DEFN:
12242       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12243       break;
12244
12245     case STATIC_ASSERT:
12246       {
12247         tree condition = 
12248           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
12249                        args,
12250                        complain, in_decl,
12251                        /*integral_constant_expression_p=*/true);
12252         finish_static_assert (condition,
12253                               STATIC_ASSERT_MESSAGE (t),
12254                               STATIC_ASSERT_SOURCE_LOCATION (t),
12255                               /*member_p=*/false);
12256       }
12257       break;
12258
12259     case OMP_PARALLEL:
12260       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
12261                                 args, complain, in_decl);
12262       stmt = begin_omp_parallel ();
12263       RECUR (OMP_PARALLEL_BODY (t));
12264       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
12265         = OMP_PARALLEL_COMBINED (t);
12266       break;
12267
12268     case OMP_TASK:
12269       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
12270                                 args, complain, in_decl);
12271       stmt = begin_omp_task ();
12272       RECUR (OMP_TASK_BODY (t));
12273       finish_omp_task (tmp, stmt);
12274       break;
12275
12276     case OMP_FOR:
12277       {
12278         tree clauses, body, pre_body;
12279         tree declv, initv, condv, incrv;
12280         int i;
12281
12282         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
12283                                       args, complain, in_decl);
12284         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12285         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12286         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12287         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12288
12289         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
12290           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
12291                                    &clauses, args, complain, in_decl,
12292                                    integral_constant_expression_p);
12293
12294         stmt = begin_omp_structured_block ();
12295
12296         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
12297           if (TREE_VEC_ELT (initv, i) == NULL
12298               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
12299             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
12300           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
12301             {
12302               tree init = RECUR (TREE_VEC_ELT (initv, i));
12303               gcc_assert (init == TREE_VEC_ELT (declv, i));
12304               TREE_VEC_ELT (initv, i) = NULL_TREE;
12305             }
12306           else
12307             {
12308               tree decl_expr = TREE_VEC_ELT (initv, i);
12309               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
12310               gcc_assert (init != NULL);
12311               TREE_VEC_ELT (initv, i) = RECUR (init);
12312               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
12313               RECUR (decl_expr);
12314               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
12315             }
12316
12317         pre_body = push_stmt_list ();
12318         RECUR (OMP_FOR_PRE_BODY (t));
12319         pre_body = pop_stmt_list (pre_body);
12320
12321         body = push_stmt_list ();
12322         RECUR (OMP_FOR_BODY (t));
12323         body = pop_stmt_list (body);
12324
12325         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
12326                             body, pre_body, clauses);
12327
12328         add_stmt (finish_omp_structured_block (stmt));
12329       }
12330       break;
12331
12332     case OMP_SECTIONS:
12333     case OMP_SINGLE:
12334       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
12335       stmt = push_stmt_list ();
12336       RECUR (OMP_BODY (t));
12337       stmt = pop_stmt_list (stmt);
12338
12339       t = copy_node (t);
12340       OMP_BODY (t) = stmt;
12341       OMP_CLAUSES (t) = tmp;
12342       add_stmt (t);
12343       break;
12344
12345     case OMP_SECTION:
12346     case OMP_CRITICAL:
12347     case OMP_MASTER:
12348     case OMP_ORDERED:
12349       stmt = push_stmt_list ();
12350       RECUR (OMP_BODY (t));
12351       stmt = pop_stmt_list (stmt);
12352
12353       t = copy_node (t);
12354       OMP_BODY (t) = stmt;
12355       add_stmt (t);
12356       break;
12357
12358     case OMP_ATOMIC:
12359       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
12360       {
12361         tree op1 = TREE_OPERAND (t, 1);
12362         tree lhs = RECUR (TREE_OPERAND (op1, 0));
12363         tree rhs = RECUR (TREE_OPERAND (op1, 1));
12364         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
12365       }
12366       break;
12367
12368     case EXPR_PACK_EXPANSION:
12369       error ("invalid use of pack expansion expression");
12370       return error_mark_node;
12371
12372     case NONTYPE_ARGUMENT_PACK:
12373       error ("use %<...%> to expand argument pack");
12374       return error_mark_node;
12375
12376     default:
12377       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
12378
12379       return tsubst_copy_and_build (t, args, complain, in_decl,
12380                                     /*function_p=*/false,
12381                                     integral_constant_expression_p);
12382     }
12383
12384   return NULL_TREE;
12385 #undef RECUR
12386 }
12387
12388 /* T is a postfix-expression that is not being used in a function
12389    call.  Return the substituted version of T.  */
12390
12391 static tree
12392 tsubst_non_call_postfix_expression (tree t, tree args,
12393                                     tsubst_flags_t complain,
12394                                     tree in_decl)
12395 {
12396   if (TREE_CODE (t) == SCOPE_REF)
12397     t = tsubst_qualified_id (t, args, complain, in_decl,
12398                              /*done=*/false, /*address_p=*/false);
12399   else
12400     t = tsubst_copy_and_build (t, args, complain, in_decl,
12401                                /*function_p=*/false,
12402                                /*integral_constant_expression_p=*/false);
12403
12404   return t;
12405 }
12406
12407 /* Like tsubst but deals with expressions and performs semantic
12408    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
12409
12410 tree
12411 tsubst_copy_and_build (tree t,
12412                        tree args,
12413                        tsubst_flags_t complain,
12414                        tree in_decl,
12415                        bool function_p,
12416                        bool integral_constant_expression_p)
12417 {
12418 #define RECUR(NODE)                                             \
12419   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
12420                          /*function_p=*/false,                  \
12421                          integral_constant_expression_p)
12422
12423   tree op1;
12424
12425   if (t == NULL_TREE || t == error_mark_node)
12426     return t;
12427
12428   switch (TREE_CODE (t))
12429     {
12430     case USING_DECL:
12431       t = DECL_NAME (t);
12432       /* Fall through.  */
12433     case IDENTIFIER_NODE:
12434       {
12435         tree decl;
12436         cp_id_kind idk;
12437         bool non_integral_constant_expression_p;
12438         const char *error_msg;
12439
12440         if (IDENTIFIER_TYPENAME_P (t))
12441           {
12442             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12443             t = mangle_conv_op_name_for_type (new_type);
12444           }
12445
12446         /* Look up the name.  */
12447         decl = lookup_name (t);
12448
12449         /* By convention, expressions use ERROR_MARK_NODE to indicate
12450            failure, not NULL_TREE.  */
12451         if (decl == NULL_TREE)
12452           decl = error_mark_node;
12453
12454         decl = finish_id_expression (t, decl, NULL_TREE,
12455                                      &idk,
12456                                      integral_constant_expression_p,
12457                                      /*allow_non_integral_constant_expression_p=*/false,
12458                                      &non_integral_constant_expression_p,
12459                                      /*template_p=*/false,
12460                                      /*done=*/true,
12461                                      /*address_p=*/false,
12462                                      /*template_arg_p=*/false,
12463                                      &error_msg,
12464                                      input_location);
12465         if (error_msg)
12466           error (error_msg);
12467         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
12468           decl = unqualified_name_lookup_error (decl);
12469         return decl;
12470       }
12471
12472     case TEMPLATE_ID_EXPR:
12473       {
12474         tree object;
12475         tree templ = RECUR (TREE_OPERAND (t, 0));
12476         tree targs = TREE_OPERAND (t, 1);
12477
12478         if (targs)
12479           targs = tsubst_template_args (targs, args, complain, in_decl);
12480
12481         if (TREE_CODE (templ) == COMPONENT_REF)
12482           {
12483             object = TREE_OPERAND (templ, 0);
12484             templ = TREE_OPERAND (templ, 1);
12485           }
12486         else
12487           object = NULL_TREE;
12488         templ = lookup_template_function (templ, targs);
12489
12490         if (object)
12491           return build3 (COMPONENT_REF, TREE_TYPE (templ),
12492                          object, templ, NULL_TREE);
12493         else
12494           return baselink_for_fns (templ);
12495       }
12496
12497     case INDIRECT_REF:
12498       {
12499         tree r = RECUR (TREE_OPERAND (t, 0));
12500
12501         if (REFERENCE_REF_P (t))
12502           {
12503             /* A type conversion to reference type will be enclosed in
12504                such an indirect ref, but the substitution of the cast
12505                will have also added such an indirect ref.  */
12506             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
12507               r = convert_from_reference (r);
12508           }
12509         else
12510           r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
12511         return r;
12512       }
12513
12514     case NOP_EXPR:
12515       return build_nop
12516         (tsubst (TREE_TYPE (t), args, complain, in_decl),
12517          RECUR (TREE_OPERAND (t, 0)));
12518
12519     case CAST_EXPR:
12520     case REINTERPRET_CAST_EXPR:
12521     case CONST_CAST_EXPR:
12522     case DYNAMIC_CAST_EXPR:
12523     case STATIC_CAST_EXPR:
12524       {
12525         tree type;
12526         tree op;
12527
12528         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12529         if (integral_constant_expression_p
12530             && !cast_valid_in_integral_constant_expression_p (type))
12531           {
12532             if (complain & tf_error)
12533               error ("a cast to a type other than an integral or "
12534                      "enumeration type cannot appear in a constant-expression");
12535             return error_mark_node; 
12536           }
12537
12538         op = RECUR (TREE_OPERAND (t, 0));
12539
12540         switch (TREE_CODE (t))
12541           {
12542           case CAST_EXPR:
12543             return build_functional_cast (type, op, complain);
12544           case REINTERPRET_CAST_EXPR:
12545             return build_reinterpret_cast (type, op, complain);
12546           case CONST_CAST_EXPR:
12547             return build_const_cast (type, op, complain);
12548           case DYNAMIC_CAST_EXPR:
12549             return build_dynamic_cast (type, op, complain);
12550           case STATIC_CAST_EXPR:
12551             return build_static_cast (type, op, complain);
12552           default:
12553             gcc_unreachable ();
12554           }
12555       }
12556
12557     case POSTDECREMENT_EXPR:
12558     case POSTINCREMENT_EXPR:
12559       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12560                                                 args, complain, in_decl);
12561       return build_x_unary_op (TREE_CODE (t), op1, complain);
12562
12563     case PREDECREMENT_EXPR:
12564     case PREINCREMENT_EXPR:
12565     case NEGATE_EXPR:
12566     case BIT_NOT_EXPR:
12567     case ABS_EXPR:
12568     case TRUTH_NOT_EXPR:
12569     case UNARY_PLUS_EXPR:  /* Unary + */
12570     case REALPART_EXPR:
12571     case IMAGPART_EXPR:
12572       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
12573                                complain);
12574
12575     case ADDR_EXPR:
12576       op1 = TREE_OPERAND (t, 0);
12577       if (TREE_CODE (op1) == LABEL_DECL)
12578         return finish_label_address_expr (DECL_NAME (op1),
12579                                           EXPR_LOCATION (op1));
12580       if (TREE_CODE (op1) == SCOPE_REF)
12581         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
12582                                    /*done=*/true, /*address_p=*/true);
12583       else
12584         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
12585                                                   in_decl);
12586       return build_x_unary_op (ADDR_EXPR, op1, complain);
12587
12588     case PLUS_EXPR:
12589     case MINUS_EXPR:
12590     case MULT_EXPR:
12591     case TRUNC_DIV_EXPR:
12592     case CEIL_DIV_EXPR:
12593     case FLOOR_DIV_EXPR:
12594     case ROUND_DIV_EXPR:
12595     case EXACT_DIV_EXPR:
12596     case BIT_AND_EXPR:
12597     case BIT_IOR_EXPR:
12598     case BIT_XOR_EXPR:
12599     case TRUNC_MOD_EXPR:
12600     case FLOOR_MOD_EXPR:
12601     case TRUTH_ANDIF_EXPR:
12602     case TRUTH_ORIF_EXPR:
12603     case TRUTH_AND_EXPR:
12604     case TRUTH_OR_EXPR:
12605     case RSHIFT_EXPR:
12606     case LSHIFT_EXPR:
12607     case RROTATE_EXPR:
12608     case LROTATE_EXPR:
12609     case EQ_EXPR:
12610     case NE_EXPR:
12611     case MAX_EXPR:
12612     case MIN_EXPR:
12613     case LE_EXPR:
12614     case GE_EXPR:
12615     case LT_EXPR:
12616     case GT_EXPR:
12617     case MEMBER_REF:
12618     case DOTSTAR_EXPR:
12619       return build_x_binary_op
12620         (TREE_CODE (t),
12621          RECUR (TREE_OPERAND (t, 0)),
12622          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
12623           ? ERROR_MARK
12624           : TREE_CODE (TREE_OPERAND (t, 0))),
12625          RECUR (TREE_OPERAND (t, 1)),
12626          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
12627           ? ERROR_MARK
12628           : TREE_CODE (TREE_OPERAND (t, 1))),
12629          /*overloaded_p=*/NULL,
12630          complain);
12631
12632     case SCOPE_REF:
12633       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
12634                                   /*address_p=*/false);
12635     case ARRAY_REF:
12636       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12637                                                 args, complain, in_decl);
12638       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
12639
12640     case SIZEOF_EXPR:
12641       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
12642         return tsubst_copy (t, args, complain, in_decl);
12643       /* Fall through */
12644       
12645     case ALIGNOF_EXPR:
12646       op1 = TREE_OPERAND (t, 0);
12647       if (!args)
12648         {
12649           /* When there are no ARGS, we are trying to evaluate a
12650              non-dependent expression from the parser.  Trying to do
12651              the substitutions may not work.  */
12652           if (!TYPE_P (op1))
12653             op1 = TREE_TYPE (op1);
12654         }
12655       else
12656         {
12657           ++cp_unevaluated_operand;
12658           ++c_inhibit_evaluation_warnings;
12659           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12660                                        /*function_p=*/false,
12661                                        /*integral_constant_expression_p=*/false);
12662           --cp_unevaluated_operand;
12663           --c_inhibit_evaluation_warnings;
12664         }
12665       if (TYPE_P (op1))
12666         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
12667                                            complain & tf_error);
12668       else
12669         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
12670                                            complain & tf_error);
12671
12672     case AT_ENCODE_EXPR:
12673       {
12674         op1 = TREE_OPERAND (t, 0);
12675         ++cp_unevaluated_operand;
12676         ++c_inhibit_evaluation_warnings;
12677         op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12678                                      /*function_p=*/false,
12679                                      /*integral_constant_expression_p=*/false);
12680         --cp_unevaluated_operand;
12681         --c_inhibit_evaluation_warnings;
12682         return objc_build_encode_expr (op1);
12683       }
12684
12685     case NOEXCEPT_EXPR:
12686       op1 = TREE_OPERAND (t, 0);
12687       ++cp_unevaluated_operand;
12688       ++c_inhibit_evaluation_warnings;
12689       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12690                                    /*function_p=*/false,
12691                                    /*integral_constant_expression_p=*/false);
12692       --cp_unevaluated_operand;
12693       --c_inhibit_evaluation_warnings;
12694       return finish_noexcept_expr (op1, complain);
12695
12696     case MODOP_EXPR:
12697       {
12698         tree r = build_x_modify_expr
12699           (RECUR (TREE_OPERAND (t, 0)),
12700            TREE_CODE (TREE_OPERAND (t, 1)),
12701            RECUR (TREE_OPERAND (t, 2)),
12702            complain);
12703         /* TREE_NO_WARNING must be set if either the expression was
12704            parenthesized or it uses an operator such as >>= rather
12705            than plain assignment.  In the former case, it was already
12706            set and must be copied.  In the latter case,
12707            build_x_modify_expr sets it and it must not be reset
12708            here.  */
12709         if (TREE_NO_WARNING (t))
12710           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12711         return r;
12712       }
12713
12714     case ARROW_EXPR:
12715       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12716                                                 args, complain, in_decl);
12717       /* Remember that there was a reference to this entity.  */
12718       if (DECL_P (op1))
12719         mark_used (op1);
12720       return build_x_arrow (op1);
12721
12722     case NEW_EXPR:
12723       {
12724         tree placement = RECUR (TREE_OPERAND (t, 0));
12725         tree init = RECUR (TREE_OPERAND (t, 3));
12726         VEC(tree,gc) *placement_vec;
12727         VEC(tree,gc) *init_vec;
12728         tree ret;
12729
12730         if (placement == NULL_TREE)
12731           placement_vec = NULL;
12732         else
12733           {
12734             placement_vec = make_tree_vector ();
12735             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
12736               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
12737           }
12738
12739         /* If there was an initializer in the original tree, but it
12740            instantiated to an empty list, then we should pass a
12741            non-NULL empty vector to tell build_new that it was an
12742            empty initializer() rather than no initializer.  This can
12743            only happen when the initializer is a pack expansion whose
12744            parameter packs are of length zero.  */
12745         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
12746           init_vec = NULL;
12747         else
12748           {
12749             init_vec = make_tree_vector ();
12750             if (init == void_zero_node)
12751               gcc_assert (init_vec != NULL);
12752             else
12753               {
12754                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
12755                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
12756               }
12757           }
12758
12759         ret = build_new (&placement_vec,
12760                          tsubst (TREE_OPERAND (t, 1), args, complain, in_decl),
12761                          RECUR (TREE_OPERAND (t, 2)),
12762                          &init_vec,
12763                          NEW_EXPR_USE_GLOBAL (t),
12764                          complain);
12765
12766         if (placement_vec != NULL)
12767           release_tree_vector (placement_vec);
12768         if (init_vec != NULL)
12769           release_tree_vector (init_vec);
12770
12771         return ret;
12772       }
12773
12774     case DELETE_EXPR:
12775      return delete_sanity
12776        (RECUR (TREE_OPERAND (t, 0)),
12777         RECUR (TREE_OPERAND (t, 1)),
12778         DELETE_EXPR_USE_VEC (t),
12779         DELETE_EXPR_USE_GLOBAL (t));
12780
12781     case COMPOUND_EXPR:
12782       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
12783                                     RECUR (TREE_OPERAND (t, 1)),
12784                                     complain);
12785
12786     case CALL_EXPR:
12787       {
12788         tree function;
12789         VEC(tree,gc) *call_args;
12790         unsigned int nargs, i;
12791         bool qualified_p;
12792         bool koenig_p;
12793         tree ret;
12794
12795         function = CALL_EXPR_FN (t);
12796         /* When we parsed the expression,  we determined whether or
12797            not Koenig lookup should be performed.  */
12798         koenig_p = KOENIG_LOOKUP_P (t);
12799         if (TREE_CODE (function) == SCOPE_REF)
12800           {
12801             qualified_p = true;
12802             function = tsubst_qualified_id (function, args, complain, in_decl,
12803                                             /*done=*/false,
12804                                             /*address_p=*/false);
12805           }
12806         else
12807           {
12808             if (TREE_CODE (function) == COMPONENT_REF)
12809               {
12810                 tree op = TREE_OPERAND (function, 1);
12811
12812                 qualified_p = (TREE_CODE (op) == SCOPE_REF
12813                                || (BASELINK_P (op)
12814                                    && BASELINK_QUALIFIED_P (op)));
12815               }
12816             else
12817               qualified_p = false;
12818
12819             function = tsubst_copy_and_build (function, args, complain,
12820                                               in_decl,
12821                                               !qualified_p,
12822                                               integral_constant_expression_p);
12823
12824             if (BASELINK_P (function))
12825               qualified_p = true;
12826           }
12827
12828         nargs = call_expr_nargs (t);
12829         call_args = make_tree_vector ();
12830         for (i = 0; i < nargs; ++i)
12831           {
12832             tree arg = CALL_EXPR_ARG (t, i);
12833
12834             if (!PACK_EXPANSION_P (arg))
12835               VEC_safe_push (tree, gc, call_args,
12836                              RECUR (CALL_EXPR_ARG (t, i)));
12837             else
12838               {
12839                 /* Expand the pack expansion and push each entry onto
12840                    CALL_ARGS.  */
12841                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
12842                 if (TREE_CODE (arg) == TREE_VEC)
12843                   {
12844                     unsigned int len, j;
12845
12846                     len = TREE_VEC_LENGTH (arg);
12847                     for (j = 0; j < len; ++j)
12848                       {
12849                         tree value = TREE_VEC_ELT (arg, j);
12850                         if (value != NULL_TREE)
12851                           value = convert_from_reference (value);
12852                         VEC_safe_push (tree, gc, call_args, value);
12853                       }
12854                   }
12855                 else
12856                   {
12857                     /* A partial substitution.  Add one entry.  */
12858                     VEC_safe_push (tree, gc, call_args, arg);
12859                   }
12860               }
12861           }
12862
12863         /* We do not perform argument-dependent lookup if normal
12864            lookup finds a non-function, in accordance with the
12865            expected resolution of DR 218.  */
12866         if (koenig_p
12867             && ((is_overloaded_fn (function)
12868                  /* If lookup found a member function, the Koenig lookup is
12869                     not appropriate, even if an unqualified-name was used
12870                     to denote the function.  */
12871                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
12872                 || TREE_CODE (function) == IDENTIFIER_NODE)
12873             /* Only do this when substitution turns a dependent call
12874                into a non-dependent call.  */
12875             && type_dependent_expression_p_push (t)
12876             && !any_type_dependent_arguments_p (call_args))
12877           function = perform_koenig_lookup (function, call_args, false);
12878
12879         if (TREE_CODE (function) == IDENTIFIER_NODE)
12880           {
12881             unqualified_name_lookup_error (function);
12882             release_tree_vector (call_args);
12883             return error_mark_node;
12884           }
12885
12886         /* Remember that there was a reference to this entity.  */
12887         if (DECL_P (function))
12888           mark_used (function);
12889
12890         if (TREE_CODE (function) == OFFSET_REF)
12891           ret = build_offset_ref_call_from_tree (function, &call_args);
12892         else if (TREE_CODE (function) == COMPONENT_REF)
12893           {
12894             tree instance = TREE_OPERAND (function, 0);
12895             tree fn = TREE_OPERAND (function, 1);
12896
12897             if (processing_template_decl
12898                 && (type_dependent_expression_p (instance)
12899                     || (!BASELINK_P (fn)
12900                         && TREE_CODE (fn) != FIELD_DECL)
12901                     || type_dependent_expression_p (fn)
12902                     || any_type_dependent_arguments_p (call_args)))
12903               ret = build_nt_call_vec (function, call_args);
12904             else if (!BASELINK_P (fn))
12905               ret = finish_call_expr (function, &call_args,
12906                                        /*disallow_virtual=*/false,
12907                                        /*koenig_p=*/false,
12908                                        complain);
12909             else
12910               ret = (build_new_method_call
12911                       (instance, fn,
12912                        &call_args, NULL_TREE,
12913                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
12914                        /*fn_p=*/NULL,
12915                        complain));
12916           }
12917         else
12918           ret = finish_call_expr (function, &call_args,
12919                                   /*disallow_virtual=*/qualified_p,
12920                                   koenig_p,
12921                                   complain);
12922
12923         release_tree_vector (call_args);
12924
12925         return ret;
12926       }
12927
12928     case COND_EXPR:
12929       return build_x_conditional_expr
12930         (RECUR (TREE_OPERAND (t, 0)),
12931          RECUR (TREE_OPERAND (t, 1)),
12932          RECUR (TREE_OPERAND (t, 2)),
12933          complain);
12934
12935     case PSEUDO_DTOR_EXPR:
12936       return finish_pseudo_destructor_expr
12937         (RECUR (TREE_OPERAND (t, 0)),
12938          RECUR (TREE_OPERAND (t, 1)),
12939          RECUR (TREE_OPERAND (t, 2)));
12940
12941     case TREE_LIST:
12942       {
12943         tree purpose, value, chain;
12944
12945         if (t == void_list_node)
12946           return t;
12947
12948         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
12949             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
12950           {
12951             /* We have pack expansions, so expand those and
12952                create a new list out of it.  */
12953             tree purposevec = NULL_TREE;
12954             tree valuevec = NULL_TREE;
12955             tree chain;
12956             int i, len = -1;
12957
12958             /* Expand the argument expressions.  */
12959             if (TREE_PURPOSE (t))
12960               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
12961                                                  complain, in_decl);
12962             if (TREE_VALUE (t))
12963               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
12964                                                complain, in_decl);
12965
12966             /* Build the rest of the list.  */
12967             chain = TREE_CHAIN (t);
12968             if (chain && chain != void_type_node)
12969               chain = RECUR (chain);
12970
12971             /* Determine the number of arguments.  */
12972             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
12973               {
12974                 len = TREE_VEC_LENGTH (purposevec);
12975                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
12976               }
12977             else if (TREE_CODE (valuevec) == TREE_VEC)
12978               len = TREE_VEC_LENGTH (valuevec);
12979             else
12980               {
12981                 /* Since we only performed a partial substitution into
12982                    the argument pack, we only return a single list
12983                    node.  */
12984                 if (purposevec == TREE_PURPOSE (t)
12985                     && valuevec == TREE_VALUE (t)
12986                     && chain == TREE_CHAIN (t))
12987                   return t;
12988
12989                 return tree_cons (purposevec, valuevec, chain);
12990               }
12991             
12992             /* Convert the argument vectors into a TREE_LIST */
12993             i = len;
12994             while (i > 0)
12995               {
12996                 /* Grab the Ith values.  */
12997                 i--;
12998                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
12999                                      : NULL_TREE;
13000                 value 
13001                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
13002                              : NULL_TREE;
13003
13004                 /* Build the list (backwards).  */
13005                 chain = tree_cons (purpose, value, chain);
13006               }
13007
13008             return chain;
13009           }
13010
13011         purpose = TREE_PURPOSE (t);
13012         if (purpose)
13013           purpose = RECUR (purpose);
13014         value = TREE_VALUE (t);
13015         if (value)
13016           value = RECUR (value);
13017         chain = TREE_CHAIN (t);
13018         if (chain && chain != void_type_node)
13019           chain = RECUR (chain);
13020         if (purpose == TREE_PURPOSE (t)
13021             && value == TREE_VALUE (t)
13022             && chain == TREE_CHAIN (t))
13023           return t;
13024         return tree_cons (purpose, value, chain);
13025       }
13026
13027     case COMPONENT_REF:
13028       {
13029         tree object;
13030         tree object_type;
13031         tree member;
13032
13033         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13034                                                      args, complain, in_decl);
13035         /* Remember that there was a reference to this entity.  */
13036         if (DECL_P (object))
13037           mark_used (object);
13038         object_type = TREE_TYPE (object);
13039
13040         member = TREE_OPERAND (t, 1);
13041         if (BASELINK_P (member))
13042           member = tsubst_baselink (member,
13043                                     non_reference (TREE_TYPE (object)),
13044                                     args, complain, in_decl);
13045         else
13046           member = tsubst_copy (member, args, complain, in_decl);
13047         if (member == error_mark_node)
13048           return error_mark_node;
13049
13050         if (object_type && !CLASS_TYPE_P (object_type))
13051           {
13052             if (SCALAR_TYPE_P (object_type))
13053               {
13054                 tree s = NULL_TREE;
13055                 tree dtor = member;
13056
13057                 if (TREE_CODE (dtor) == SCOPE_REF)
13058                   {
13059                     s = TREE_OPERAND (dtor, 0);
13060                     dtor = TREE_OPERAND (dtor, 1);
13061                   }
13062                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
13063                   {
13064                     dtor = TREE_OPERAND (dtor, 0);
13065                     if (TYPE_P (dtor))
13066                       return finish_pseudo_destructor_expr (object, s, dtor);
13067                   }
13068               }
13069           }
13070         else if (TREE_CODE (member) == SCOPE_REF
13071                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
13072           {
13073             tree tmpl;
13074             tree args;
13075
13076             /* Lookup the template functions now that we know what the
13077                scope is.  */
13078             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
13079             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
13080             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
13081                                             /*is_type_p=*/false,
13082                                             /*complain=*/false);
13083             if (BASELINK_P (member))
13084               {
13085                 BASELINK_FUNCTIONS (member)
13086                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
13087                               args);
13088                 member = (adjust_result_of_qualified_name_lookup
13089                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
13090                            object_type));
13091               }
13092             else
13093               {
13094                 qualified_name_lookup_error (object_type, tmpl, member,
13095                                              input_location);
13096                 return error_mark_node;
13097               }
13098           }
13099         else if (TREE_CODE (member) == SCOPE_REF
13100                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
13101                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
13102           {
13103             if (complain & tf_error)
13104               {
13105                 if (TYPE_P (TREE_OPERAND (member, 0)))
13106                   error ("%qT is not a class or namespace",
13107                          TREE_OPERAND (member, 0));
13108                 else
13109                   error ("%qD is not a class or namespace",
13110                          TREE_OPERAND (member, 0));
13111               }
13112             return error_mark_node;
13113           }
13114         else if (TREE_CODE (member) == FIELD_DECL)
13115           return finish_non_static_data_member (member, object, NULL_TREE);
13116
13117         return finish_class_member_access_expr (object, member,
13118                                                 /*template_p=*/false,
13119                                                 complain);
13120       }
13121
13122     case THROW_EXPR:
13123       return build_throw
13124         (RECUR (TREE_OPERAND (t, 0)));
13125
13126     case CONSTRUCTOR:
13127       {
13128         VEC(constructor_elt,gc) *n;
13129         constructor_elt *ce;
13130         unsigned HOST_WIDE_INT idx;
13131         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13132         bool process_index_p;
13133         int newlen;
13134         bool need_copy_p = false;
13135         tree r;
13136
13137         if (type == error_mark_node)
13138           return error_mark_node;
13139
13140         /* digest_init will do the wrong thing if we let it.  */
13141         if (type && TYPE_PTRMEMFUNC_P (type))
13142           return t;
13143
13144         /* We do not want to process the index of aggregate
13145            initializers as they are identifier nodes which will be
13146            looked up by digest_init.  */
13147         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
13148
13149         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
13150         newlen = VEC_length (constructor_elt, n);
13151         FOR_EACH_VEC_ELT (constructor_elt, n, idx, ce)
13152           {
13153             if (ce->index && process_index_p)
13154               ce->index = RECUR (ce->index);
13155
13156             if (PACK_EXPANSION_P (ce->value))
13157               {
13158                 /* Substitute into the pack expansion.  */
13159                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
13160                                                   in_decl);
13161
13162                 if (ce->value == error_mark_node)
13163                   ;
13164                 else if (TREE_VEC_LENGTH (ce->value) == 1)
13165                   /* Just move the argument into place.  */
13166                   ce->value = TREE_VEC_ELT (ce->value, 0);
13167                 else
13168                   {
13169                     /* Update the length of the final CONSTRUCTOR
13170                        arguments vector, and note that we will need to
13171                        copy.*/
13172                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
13173                     need_copy_p = true;
13174                   }
13175               }
13176             else
13177               ce->value = RECUR (ce->value);
13178           }
13179
13180         if (need_copy_p)
13181           {
13182             VEC(constructor_elt,gc) *old_n = n;
13183
13184             n = VEC_alloc (constructor_elt, gc, newlen);
13185             FOR_EACH_VEC_ELT (constructor_elt, old_n, idx, ce)
13186               {
13187                 if (TREE_CODE (ce->value) == TREE_VEC)
13188                   {
13189                     int i, len = TREE_VEC_LENGTH (ce->value);
13190                     for (i = 0; i < len; ++i)
13191                       CONSTRUCTOR_APPEND_ELT (n, 0,
13192                                               TREE_VEC_ELT (ce->value, i));
13193                   }
13194                 else
13195                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
13196               }
13197           }
13198
13199         r = build_constructor (init_list_type_node, n);
13200         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
13201
13202         if (TREE_HAS_CONSTRUCTOR (t))
13203           return finish_compound_literal (type, r);
13204
13205         TREE_TYPE (r) = type;
13206         return r;
13207       }
13208
13209     case TYPEID_EXPR:
13210       {
13211         tree operand_0 = TREE_OPERAND (t, 0);
13212         if (TYPE_P (operand_0))
13213           {
13214             operand_0 = tsubst (operand_0, args, complain, in_decl);
13215             return get_typeid (operand_0);
13216           }
13217         else
13218           {
13219             operand_0 = RECUR (operand_0);
13220             return build_typeid (operand_0);
13221           }
13222       }
13223
13224     case VAR_DECL:
13225       if (!args)
13226         return t;
13227       /* Fall through */
13228
13229     case PARM_DECL:
13230       {
13231         tree r = tsubst_copy (t, args, complain, in_decl);
13232
13233         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
13234           /* If the original type was a reference, we'll be wrapped in
13235              the appropriate INDIRECT_REF.  */
13236           r = convert_from_reference (r);
13237         return r;
13238       }
13239
13240     case VA_ARG_EXPR:
13241       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
13242                              tsubst_copy (TREE_TYPE (t), args, complain,
13243                                           in_decl));
13244
13245     case OFFSETOF_EXPR:
13246       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
13247
13248     case TRAIT_EXPR:
13249       {
13250         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
13251                                   complain, in_decl);
13252
13253         tree type2 = TRAIT_EXPR_TYPE2 (t);
13254         if (type2)
13255           type2 = tsubst_copy (type2, args, complain, in_decl);
13256         
13257         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
13258       }
13259
13260     case STMT_EXPR:
13261       {
13262         tree old_stmt_expr = cur_stmt_expr;
13263         tree stmt_expr = begin_stmt_expr ();
13264
13265         cur_stmt_expr = stmt_expr;
13266         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
13267                      integral_constant_expression_p);
13268         stmt_expr = finish_stmt_expr (stmt_expr, false);
13269         cur_stmt_expr = old_stmt_expr;
13270
13271         /* If the resulting list of expression statement is empty,
13272            fold it further into void_zero_node.  */
13273         if (empty_expr_stmt_p (stmt_expr))
13274           stmt_expr = void_zero_node;
13275
13276         return stmt_expr;
13277       }
13278
13279     case CONST_DECL:
13280       t = tsubst_copy (t, args, complain, in_decl);
13281       /* As in finish_id_expression, we resolve enumeration constants
13282          to their underlying values.  */
13283       if (TREE_CODE (t) == CONST_DECL)
13284         {
13285           used_types_insert (TREE_TYPE (t));
13286           return DECL_INITIAL (t);
13287         }
13288       return t;
13289
13290     case LAMBDA_EXPR:
13291       {
13292         tree r = build_lambda_expr ();
13293
13294         tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
13295         TREE_TYPE (r) = type;
13296         CLASSTYPE_LAMBDA_EXPR (type) = r;
13297
13298         LAMBDA_EXPR_LOCATION (r)
13299           = LAMBDA_EXPR_LOCATION (t);
13300         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
13301           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
13302         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
13303         LAMBDA_EXPR_DISCRIMINATOR (r)
13304           = (LAMBDA_EXPR_DISCRIMINATOR (t));
13305         LAMBDA_EXPR_CAPTURE_LIST (r)
13306           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
13307         LAMBDA_EXPR_THIS_CAPTURE (r)
13308           = RECUR (LAMBDA_EXPR_THIS_CAPTURE (t));
13309         LAMBDA_EXPR_EXTRA_SCOPE (r)
13310           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
13311
13312         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
13313         determine_visibility (TYPE_NAME (type));
13314         /* Now that we know visibility, instantiate the type so we have a
13315            declaration of the op() for later calls to lambda_function.  */
13316         complete_type (type);
13317
13318         type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
13319         if (type)
13320           apply_lambda_return_type (r, type);
13321
13322         return build_lambda_object (r);
13323       }
13324
13325     case TARGET_EXPR:
13326       /* We can get here for a constant initializer of non-dependent type.
13327          FIXME stop folding in cp_parser_initializer_clause.  */
13328       gcc_assert (TREE_CONSTANT (t));
13329       return get_target_expr (RECUR (TARGET_EXPR_INITIAL (t)));
13330
13331     default:
13332       /* Handle Objective-C++ constructs, if appropriate.  */
13333       {
13334         tree subst
13335           = objcp_tsubst_copy_and_build (t, args, complain,
13336                                          in_decl, /*function_p=*/false);
13337         if (subst)
13338           return subst;
13339       }
13340       return tsubst_copy (t, args, complain, in_decl);
13341     }
13342
13343 #undef RECUR
13344 }
13345
13346 /* Verify that the instantiated ARGS are valid. For type arguments,
13347    make sure that the type's linkage is ok. For non-type arguments,
13348    make sure they are constants if they are integral or enumerations.
13349    Emit an error under control of COMPLAIN, and return TRUE on error.  */
13350
13351 static bool
13352 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
13353 {
13354   if (ARGUMENT_PACK_P (t))
13355     {
13356       tree vec = ARGUMENT_PACK_ARGS (t);
13357       int len = TREE_VEC_LENGTH (vec);
13358       bool result = false;
13359       int i;
13360
13361       for (i = 0; i < len; ++i)
13362         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
13363           result = true;
13364       return result;
13365     }
13366   else if (TYPE_P (t))
13367     {
13368       /* [basic.link]: A name with no linkage (notably, the name
13369          of a class or enumeration declared in a local scope)
13370          shall not be used to declare an entity with linkage.
13371          This implies that names with no linkage cannot be used as
13372          template arguments
13373
13374          DR 757 relaxes this restriction for C++0x.  */
13375       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
13376                  : no_linkage_check (t, /*relaxed_p=*/false));
13377
13378       if (nt)
13379         {
13380           /* DR 488 makes use of a type with no linkage cause
13381              type deduction to fail.  */
13382           if (complain & tf_error)
13383             {
13384               if (TYPE_ANONYMOUS_P (nt))
13385                 error ("%qT is/uses anonymous type", t);
13386               else
13387                 error ("template argument for %qD uses local type %qT",
13388                        tmpl, t);
13389             }
13390           return true;
13391         }
13392       /* In order to avoid all sorts of complications, we do not
13393          allow variably-modified types as template arguments.  */
13394       else if (variably_modified_type_p (t, NULL_TREE))
13395         {
13396           if (complain & tf_error)
13397             error ("%qT is a variably modified type", t);
13398           return true;
13399         }
13400     }
13401   /* A non-type argument of integral or enumerated type must be a
13402      constant.  */
13403   else if (TREE_TYPE (t)
13404            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
13405            && !TREE_CONSTANT (t))
13406     {
13407       if (complain & tf_error)
13408         error ("integral expression %qE is not constant", t);
13409       return true;
13410     }
13411   return false;
13412 }
13413
13414 static bool
13415 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
13416 {
13417   int ix, len = DECL_NTPARMS (tmpl);
13418   bool result = false;
13419
13420   for (ix = 0; ix != len; ix++)
13421     {
13422       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
13423         result = true;
13424     }
13425   if (result && (complain & tf_error))
13426     error ("  trying to instantiate %qD", tmpl);
13427   return result;
13428 }
13429
13430 /* Instantiate the indicated variable or function template TMPL with
13431    the template arguments in TARG_PTR.  */
13432
13433 tree
13434 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
13435 {
13436   tree targ_ptr = orig_args;
13437   tree fndecl;
13438   tree gen_tmpl;
13439   tree spec;
13440   HOST_WIDE_INT saved_processing_template_decl;
13441
13442   if (tmpl == error_mark_node)
13443     return error_mark_node;
13444
13445   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
13446
13447   /* If this function is a clone, handle it specially.  */
13448   if (DECL_CLONED_FUNCTION_P (tmpl))
13449     {
13450       tree spec;
13451       tree clone;
13452
13453       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
13454          DECL_CLONED_FUNCTION.  */
13455       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
13456                                    targ_ptr, complain);
13457       if (spec == error_mark_node)
13458         return error_mark_node;
13459
13460       /* Look for the clone.  */
13461       FOR_EACH_CLONE (clone, spec)
13462         if (DECL_NAME (clone) == DECL_NAME (tmpl))
13463           return clone;
13464       /* We should always have found the clone by now.  */
13465       gcc_unreachable ();
13466       return NULL_TREE;
13467     }
13468
13469   /* Check to see if we already have this specialization.  */
13470   gen_tmpl = most_general_template (tmpl);
13471   if (tmpl != gen_tmpl)
13472     /* The TMPL is a partial instantiation.  To get a full set of
13473        arguments we must add the arguments used to perform the
13474        partial instantiation.  */
13475     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
13476                                             targ_ptr);
13477
13478   /* It would be nice to avoid hashing here and then again in tsubst_decl,
13479      but it doesn't seem to be on the hot path.  */
13480   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
13481
13482   gcc_assert (tmpl == gen_tmpl
13483               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
13484                   == spec)
13485               || fndecl == NULL_TREE);
13486
13487   if (spec != NULL_TREE)
13488     return spec;
13489
13490   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
13491                                complain))
13492     return error_mark_node;
13493
13494   /* We are building a FUNCTION_DECL, during which the access of its
13495      parameters and return types have to be checked.  However this
13496      FUNCTION_DECL which is the desired context for access checking
13497      is not built yet.  We solve this chicken-and-egg problem by
13498      deferring all checks until we have the FUNCTION_DECL.  */
13499   push_deferring_access_checks (dk_deferred);
13500
13501   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
13502      (because, for example, we have encountered a non-dependent
13503      function call in the body of a template function and must now
13504      determine which of several overloaded functions will be called),
13505      within the instantiation itself we are not processing a
13506      template.  */  
13507   saved_processing_template_decl = processing_template_decl;
13508   processing_template_decl = 0;
13509   /* Substitute template parameters to obtain the specialization.  */
13510   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
13511                    targ_ptr, complain, gen_tmpl);
13512   processing_template_decl = saved_processing_template_decl;
13513   if (fndecl == error_mark_node)
13514     return error_mark_node;
13515
13516   /* Now we know the specialization, compute access previously
13517      deferred.  */
13518   push_access_scope (fndecl);
13519
13520   /* Some typedefs referenced from within the template code need to be access
13521      checked at template instantiation time, i.e now. These types were
13522      added to the template at parsing time. Let's get those and perfom
13523      the acces checks then.  */
13524   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
13525   perform_deferred_access_checks ();
13526   pop_access_scope (fndecl);
13527   pop_deferring_access_checks ();
13528
13529   /* The DECL_TI_TEMPLATE should always be the immediate parent
13530      template, not the most general template.  */
13531   DECL_TI_TEMPLATE (fndecl) = tmpl;
13532
13533   /* If we've just instantiated the main entry point for a function,
13534      instantiate all the alternate entry points as well.  We do this
13535      by cloning the instantiation of the main entry point, not by
13536      instantiating the template clones.  */
13537   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
13538     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
13539
13540   return fndecl;
13541 }
13542
13543 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
13544    NARGS elements of the arguments that are being used when calling
13545    it.  TARGS is a vector into which the deduced template arguments
13546    are placed.
13547
13548    Return zero for success, 2 for an incomplete match that doesn't resolve
13549    all the types, and 1 for complete failure.  An error message will be
13550    printed only for an incomplete match.
13551
13552    If FN is a conversion operator, or we are trying to produce a specific
13553    specialization, RETURN_TYPE is the return type desired.
13554
13555    The EXPLICIT_TARGS are explicit template arguments provided via a
13556    template-id.
13557
13558    The parameter STRICT is one of:
13559
13560    DEDUCE_CALL:
13561      We are deducing arguments for a function call, as in
13562      [temp.deduct.call].
13563
13564    DEDUCE_CONV:
13565      We are deducing arguments for a conversion function, as in
13566      [temp.deduct.conv].
13567
13568    DEDUCE_EXACT:
13569      We are deducing arguments when doing an explicit instantiation
13570      as in [temp.explicit], when determining an explicit specialization
13571      as in [temp.expl.spec], or when taking the address of a function
13572      template, as in [temp.deduct.funcaddr].  */
13573
13574 int
13575 fn_type_unification (tree fn,
13576                      tree explicit_targs,
13577                      tree targs,
13578                      const tree *args,
13579                      unsigned int nargs,
13580                      tree return_type,
13581                      unification_kind_t strict,
13582                      int flags)
13583 {
13584   tree parms;
13585   tree fntype;
13586   int result;
13587   bool incomplete_argument_packs_p = false;
13588
13589   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
13590
13591   fntype = TREE_TYPE (fn);
13592   if (explicit_targs)
13593     {
13594       /* [temp.deduct]
13595
13596          The specified template arguments must match the template
13597          parameters in kind (i.e., type, nontype, template), and there
13598          must not be more arguments than there are parameters;
13599          otherwise type deduction fails.
13600
13601          Nontype arguments must match the types of the corresponding
13602          nontype template parameters, or must be convertible to the
13603          types of the corresponding nontype parameters as specified in
13604          _temp.arg.nontype_, otherwise type deduction fails.
13605
13606          All references in the function type of the function template
13607          to the corresponding template parameters are replaced by the
13608          specified template argument values.  If a substitution in a
13609          template parameter or in the function type of the function
13610          template results in an invalid type, type deduction fails.  */
13611       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
13612       int i, len = TREE_VEC_LENGTH (tparms);
13613       tree converted_args;
13614       bool incomplete = false;
13615
13616       if (explicit_targs == error_mark_node)
13617         return 1;
13618
13619       converted_args
13620         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
13621                                   /*require_all_args=*/false,
13622                                   /*use_default_args=*/false));
13623       if (converted_args == error_mark_node)
13624         return 1;
13625
13626       /* Substitute the explicit args into the function type.  This is
13627          necessary so that, for instance, explicitly declared function
13628          arguments can match null pointed constants.  If we were given
13629          an incomplete set of explicit args, we must not do semantic
13630          processing during substitution as we could create partial
13631          instantiations.  */
13632       for (i = 0; i < len; i++)
13633         {
13634           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13635           bool parameter_pack = false;
13636
13637           /* Dig out the actual parm.  */
13638           if (TREE_CODE (parm) == TYPE_DECL
13639               || TREE_CODE (parm) == TEMPLATE_DECL)
13640             {
13641               parm = TREE_TYPE (parm);
13642               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
13643             }
13644           else if (TREE_CODE (parm) == PARM_DECL)
13645             {
13646               parm = DECL_INITIAL (parm);
13647               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
13648             }
13649
13650           if (parameter_pack)
13651             {
13652               int level, idx;
13653               tree targ;
13654               template_parm_level_and_index (parm, &level, &idx);
13655
13656               /* Mark the argument pack as "incomplete". We could
13657                  still deduce more arguments during unification.  */
13658               targ = TMPL_ARG (converted_args, level, idx);
13659               if (targ)
13660                 {
13661                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
13662                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
13663                     = ARGUMENT_PACK_ARGS (targ);
13664                 }
13665
13666               /* We have some incomplete argument packs.  */
13667               incomplete_argument_packs_p = true;
13668             }
13669         }
13670
13671       if (incomplete_argument_packs_p)
13672         /* Any substitution is guaranteed to be incomplete if there
13673            are incomplete argument packs, because we can still deduce
13674            more arguments.  */
13675         incomplete = 1;
13676       else
13677         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
13678
13679       processing_template_decl += incomplete;
13680       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
13681       processing_template_decl -= incomplete;
13682
13683       if (fntype == error_mark_node)
13684         return 1;
13685
13686       /* Place the explicitly specified arguments in TARGS.  */
13687       for (i = NUM_TMPL_ARGS (converted_args); i--;)
13688         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
13689     }
13690
13691   /* Never do unification on the 'this' parameter.  */
13692   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
13693
13694   if (return_type)
13695     {
13696       tree *new_args;
13697
13698       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
13699       new_args = XALLOCAVEC (tree, nargs + 1);
13700       new_args[0] = return_type;
13701       memcpy (new_args + 1, args, nargs * sizeof (tree));
13702       args = new_args;
13703       ++nargs;
13704     }
13705
13706   /* We allow incomplete unification without an error message here
13707      because the standard doesn't seem to explicitly prohibit it.  Our
13708      callers must be ready to deal with unification failures in any
13709      event.  */
13710   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
13711                                   targs, parms, args, nargs, /*subr=*/0,
13712                                   strict, flags);
13713
13714   if (result == 0 && incomplete_argument_packs_p)
13715     {
13716       int i, len = NUM_TMPL_ARGS (targs);
13717
13718       /* Clear the "incomplete" flags on all argument packs.  */
13719       for (i = 0; i < len; i++)
13720         {
13721           tree arg = TREE_VEC_ELT (targs, i);
13722           if (ARGUMENT_PACK_P (arg))
13723             {
13724               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
13725               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
13726             }
13727         }
13728     }
13729
13730   /* Now that we have bindings for all of the template arguments,
13731      ensure that the arguments deduced for the template template
13732      parameters have compatible template parameter lists.  We cannot
13733      check this property before we have deduced all template
13734      arguments, because the template parameter types of a template
13735      template parameter might depend on prior template parameters
13736      deduced after the template template parameter.  The following
13737      ill-formed example illustrates this issue:
13738
13739        template<typename T, template<T> class C> void f(C<5>, T);
13740
13741        template<int N> struct X {};
13742
13743        void g() {
13744          f(X<5>(), 5l); // error: template argument deduction fails
13745        }
13746
13747      The template parameter list of 'C' depends on the template type
13748      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
13749      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
13750      time that we deduce 'C'.  */
13751   if (result == 0
13752       && !template_template_parm_bindings_ok_p 
13753            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
13754     return 1;
13755
13756   if (result == 0)
13757     /* All is well so far.  Now, check:
13758
13759        [temp.deduct]
13760
13761        When all template arguments have been deduced, all uses of
13762        template parameters in nondeduced contexts are replaced with
13763        the corresponding deduced argument values.  If the
13764        substitution results in an invalid type, as described above,
13765        type deduction fails.  */
13766     {
13767       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
13768       if (substed == error_mark_node)
13769         return 1;
13770
13771       /* If we're looking for an exact match, check that what we got
13772          is indeed an exact match.  It might not be if some template
13773          parameters are used in non-deduced contexts.  */
13774       if (strict == DEDUCE_EXACT)
13775         {
13776           unsigned int i;
13777
13778           tree sarg
13779             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
13780           if (return_type)
13781             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
13782           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
13783             if (!same_type_p (args[i], TREE_VALUE (sarg)))
13784               return 1;
13785         }
13786     }
13787
13788   return result;
13789 }
13790
13791 /* Adjust types before performing type deduction, as described in
13792    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
13793    sections are symmetric.  PARM is the type of a function parameter
13794    or the return type of the conversion function.  ARG is the type of
13795    the argument passed to the call, or the type of the value
13796    initialized with the result of the conversion function.
13797    ARG_EXPR is the original argument expression, which may be null.  */
13798
13799 static int
13800 maybe_adjust_types_for_deduction (unification_kind_t strict,
13801                                   tree* parm,
13802                                   tree* arg,
13803                                   tree arg_expr)
13804 {
13805   int result = 0;
13806
13807   switch (strict)
13808     {
13809     case DEDUCE_CALL:
13810       break;
13811
13812     case DEDUCE_CONV:
13813       {
13814         /* Swap PARM and ARG throughout the remainder of this
13815            function; the handling is precisely symmetric since PARM
13816            will initialize ARG rather than vice versa.  */
13817         tree* temp = parm;
13818         parm = arg;
13819         arg = temp;
13820         break;
13821       }
13822
13823     case DEDUCE_EXACT:
13824       /* Core issue #873: Do the DR606 thing (see below) for these cases,
13825          too, but here handle it by stripping the reference from PARM
13826          rather than by adding it to ARG.  */
13827       if (TREE_CODE (*parm) == REFERENCE_TYPE
13828           && TYPE_REF_IS_RVALUE (*parm)
13829           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13830           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13831           && TREE_CODE (*arg) == REFERENCE_TYPE
13832           && !TYPE_REF_IS_RVALUE (*arg))
13833         *parm = TREE_TYPE (*parm);
13834       /* Nothing else to do in this case.  */
13835       return 0;
13836
13837     default:
13838       gcc_unreachable ();
13839     }
13840
13841   if (TREE_CODE (*parm) != REFERENCE_TYPE)
13842     {
13843       /* [temp.deduct.call]
13844
13845          If P is not a reference type:
13846
13847          --If A is an array type, the pointer type produced by the
13848          array-to-pointer standard conversion (_conv.array_) is
13849          used in place of A for type deduction; otherwise,
13850
13851          --If A is a function type, the pointer type produced by
13852          the function-to-pointer standard conversion
13853          (_conv.func_) is used in place of A for type deduction;
13854          otherwise,
13855
13856          --If A is a cv-qualified type, the top level
13857          cv-qualifiers of A's type are ignored for type
13858          deduction.  */
13859       if (TREE_CODE (*arg) == ARRAY_TYPE)
13860         *arg = build_pointer_type (TREE_TYPE (*arg));
13861       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
13862         *arg = build_pointer_type (*arg);
13863       else
13864         *arg = TYPE_MAIN_VARIANT (*arg);
13865     }
13866
13867   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
13868      of the form T&&, where T is a template parameter, and the argument
13869      is an lvalue, T is deduced as A& */
13870   if (TREE_CODE (*parm) == REFERENCE_TYPE
13871       && TYPE_REF_IS_RVALUE (*parm)
13872       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13873       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13874       && arg_expr && real_lvalue_p (arg_expr))
13875     *arg = build_reference_type (*arg);
13876
13877   /* [temp.deduct.call]
13878
13879      If P is a cv-qualified type, the top level cv-qualifiers
13880      of P's type are ignored for type deduction.  If P is a
13881      reference type, the type referred to by P is used for
13882      type deduction.  */
13883   *parm = TYPE_MAIN_VARIANT (*parm);
13884   if (TREE_CODE (*parm) == REFERENCE_TYPE)
13885     {
13886       *parm = TREE_TYPE (*parm);
13887       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13888     }
13889
13890   /* DR 322. For conversion deduction, remove a reference type on parm
13891      too (which has been swapped into ARG).  */
13892   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
13893     *arg = TREE_TYPE (*arg);
13894
13895   return result;
13896 }
13897
13898 /* Most parms like fn_type_unification.
13899
13900    If SUBR is 1, we're being called recursively (to unify the
13901    arguments of a function or method parameter of a function
13902    template). */
13903
13904 static int
13905 type_unification_real (tree tparms,
13906                        tree targs,
13907                        tree xparms,
13908                        const tree *xargs,
13909                        unsigned int xnargs,
13910                        int subr,
13911                        unification_kind_t strict,
13912                        int flags)
13913 {
13914   tree parm, arg, arg_expr;
13915   int i;
13916   int ntparms = TREE_VEC_LENGTH (tparms);
13917   int sub_strict;
13918   int saw_undeduced = 0;
13919   tree parms;
13920   const tree *args;
13921   unsigned int nargs;
13922   unsigned int ia;
13923
13924   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
13925   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
13926   gcc_assert (ntparms > 0);
13927
13928   /* Reset the number of non-defaulted template arguments contained
13929      in in TARGS.  */
13930   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
13931
13932   switch (strict)
13933     {
13934     case DEDUCE_CALL:
13935       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
13936                     | UNIFY_ALLOW_DERIVED);
13937       break;
13938
13939     case DEDUCE_CONV:
13940       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13941       break;
13942
13943     case DEDUCE_EXACT:
13944       sub_strict = UNIFY_ALLOW_NONE;
13945       break;
13946
13947     default:
13948       gcc_unreachable ();
13949     }
13950
13951  again:
13952   parms = xparms;
13953   args = xargs;
13954   nargs = xnargs;
13955
13956   ia = 0;
13957   while (parms && parms != void_list_node
13958          && ia < nargs)
13959     {
13960       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13961         break;
13962
13963       parm = TREE_VALUE (parms);
13964       parms = TREE_CHAIN (parms);
13965       arg = args[ia];
13966       ++ia;
13967       arg_expr = NULL;
13968
13969       if (arg == error_mark_node)
13970         return 1;
13971       if (arg == unknown_type_node)
13972         /* We can't deduce anything from this, but we might get all the
13973            template args from other function args.  */
13974         continue;
13975
13976       /* Conversions will be performed on a function argument that
13977          corresponds with a function parameter that contains only
13978          non-deducible template parameters and explicitly specified
13979          template parameters.  */
13980       if (!uses_template_parms (parm))
13981         {
13982           tree type;
13983
13984           if (!TYPE_P (arg))
13985             type = TREE_TYPE (arg);
13986           else
13987             type = arg;
13988
13989           if (same_type_p (parm, type))
13990             continue;
13991           if (strict != DEDUCE_EXACT
13992               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
13993                                   flags))
13994             continue;
13995
13996           return 1;
13997         }
13998
13999       if (!TYPE_P (arg))
14000         {
14001           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14002           if (type_unknown_p (arg))
14003             {
14004               /* [temp.deduct.type] 
14005
14006                  A template-argument can be deduced from a pointer to
14007                  function or pointer to member function argument if
14008                  the set of overloaded functions does not contain
14009                  function templates and at most one of a set of
14010                  overloaded functions provides a unique match.  */
14011               if (resolve_overloaded_unification
14012                   (tparms, targs, parm, arg, strict, sub_strict))
14013                 continue;
14014
14015               return 1;
14016             }
14017           arg_expr = arg;
14018           arg = unlowered_expr_type (arg);
14019           if (arg == error_mark_node)
14020             return 1;
14021         }
14022
14023       {
14024         int arg_strict = sub_strict;
14025
14026         if (!subr)
14027           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
14028                                                           arg_expr);
14029
14030         if (arg == init_list_type_node && arg_expr)
14031           arg = arg_expr;
14032         if (unify (tparms, targs, parm, arg, arg_strict))
14033           return 1;
14034       }
14035     }
14036
14037
14038   if (parms 
14039       && parms != void_list_node
14040       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
14041     {
14042       /* Unify the remaining arguments with the pack expansion type.  */
14043       tree argvec;
14044       tree parmvec = make_tree_vec (1);
14045
14046       /* Allocate a TREE_VEC and copy in all of the arguments */ 
14047       argvec = make_tree_vec (nargs - ia);
14048       for (i = 0; ia < nargs; ++ia, ++i)
14049         TREE_VEC_ELT (argvec, i) = args[ia];
14050
14051       /* Copy the parameter into parmvec.  */
14052       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
14053       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
14054                                 /*call_args_p=*/true, /*subr=*/subr))
14055         return 1;
14056
14057       /* Advance to the end of the list of parameters.  */
14058       parms = TREE_CHAIN (parms);
14059     }
14060
14061   /* Fail if we've reached the end of the parm list, and more args
14062      are present, and the parm list isn't variadic.  */
14063   if (ia < nargs && parms == void_list_node)
14064     return 1;
14065   /* Fail if parms are left and they don't have default values.  */
14066   if (parms && parms != void_list_node
14067       && TREE_PURPOSE (parms) == NULL_TREE)
14068     return 1;
14069
14070   if (!subr)
14071     for (i = 0; i < ntparms; i++)
14072       if (!TREE_VEC_ELT (targs, i))
14073         {
14074           tree tparm;
14075
14076           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
14077             continue;
14078
14079           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
14080
14081           /* If this is an undeduced nontype parameter that depends on
14082              a type parameter, try another pass; its type may have been
14083              deduced from a later argument than the one from which
14084              this parameter can be deduced.  */
14085           if (TREE_CODE (tparm) == PARM_DECL
14086               && uses_template_parms (TREE_TYPE (tparm))
14087               && !saw_undeduced++)
14088             goto again;
14089
14090           /* Core issue #226 (C++0x) [temp.deduct]:
14091
14092                If a template argument has not been deduced, its
14093                default template argument, if any, is used. 
14094
14095              When we are in C++98 mode, TREE_PURPOSE will either
14096              be NULL_TREE or ERROR_MARK_NODE, so we do not need
14097              to explicitly check cxx_dialect here.  */
14098           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
14099             {
14100               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
14101               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
14102               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
14103               arg = convert_template_argument (parm, arg, targs, tf_none,
14104                                                i, NULL_TREE);
14105               if (arg == error_mark_node)
14106                 return 1;
14107               else
14108                 {
14109                   TREE_VEC_ELT (targs, i) = arg;
14110                   /* The position of the first default template argument,
14111                      is also the number of non-defaulted arguments in TARGS.
14112                      Record that.  */
14113                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
14114                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
14115                   continue;
14116                 }
14117             }
14118
14119           /* If the type parameter is a parameter pack, then it will
14120              be deduced to an empty parameter pack.  */
14121           if (template_parameter_pack_p (tparm))
14122             {
14123               tree arg;
14124
14125               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
14126                 {
14127                   arg = make_node (NONTYPE_ARGUMENT_PACK);
14128                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
14129                   TREE_CONSTANT (arg) = 1;
14130                 }
14131               else
14132                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
14133
14134               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
14135
14136               TREE_VEC_ELT (targs, i) = arg;
14137               continue;
14138             }
14139
14140           return 2;
14141         }
14142 #ifdef ENABLE_CHECKING
14143   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
14144     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
14145 #endif
14146
14147   return 0;
14148 }
14149
14150 /* Subroutine of type_unification_real.  Args are like the variables
14151    at the call site.  ARG is an overloaded function (or template-id);
14152    we try deducing template args from each of the overloads, and if
14153    only one succeeds, we go with that.  Modifies TARGS and returns
14154    true on success.  */
14155
14156 static bool
14157 resolve_overloaded_unification (tree tparms,
14158                                 tree targs,
14159                                 tree parm,
14160                                 tree arg,
14161                                 unification_kind_t strict,
14162                                 int sub_strict)
14163 {
14164   tree tempargs = copy_node (targs);
14165   int good = 0;
14166   tree goodfn = NULL_TREE;
14167   bool addr_p;
14168
14169   if (TREE_CODE (arg) == ADDR_EXPR)
14170     {
14171       arg = TREE_OPERAND (arg, 0);
14172       addr_p = true;
14173     }
14174   else
14175     addr_p = false;
14176
14177   if (TREE_CODE (arg) == COMPONENT_REF)
14178     /* Handle `&x' where `x' is some static or non-static member
14179        function name.  */
14180     arg = TREE_OPERAND (arg, 1);
14181
14182   if (TREE_CODE (arg) == OFFSET_REF)
14183     arg = TREE_OPERAND (arg, 1);
14184
14185   /* Strip baselink information.  */
14186   if (BASELINK_P (arg))
14187     arg = BASELINK_FUNCTIONS (arg);
14188
14189   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
14190     {
14191       /* If we got some explicit template args, we need to plug them into
14192          the affected templates before we try to unify, in case the
14193          explicit args will completely resolve the templates in question.  */
14194
14195       tree expl_subargs = TREE_OPERAND (arg, 1);
14196       arg = TREE_OPERAND (arg, 0);
14197
14198       for (; arg; arg = OVL_NEXT (arg))
14199         {
14200           tree fn = OVL_CURRENT (arg);
14201           tree subargs, elem;
14202
14203           if (TREE_CODE (fn) != TEMPLATE_DECL)
14204             continue;
14205
14206           ++processing_template_decl;
14207           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
14208                                   expl_subargs, /*check_ret=*/false);
14209           if (subargs)
14210             {
14211               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
14212               if (try_one_overload (tparms, targs, tempargs, parm,
14213                                     elem, strict, sub_strict, addr_p)
14214                   && (!goodfn || !decls_match (goodfn, elem)))
14215                 {
14216                   goodfn = elem;
14217                   ++good;
14218                 }
14219             }
14220           --processing_template_decl;
14221         }
14222     }
14223   else if (TREE_CODE (arg) != OVERLOAD
14224            && TREE_CODE (arg) != FUNCTION_DECL)
14225     /* If ARG is, for example, "(0, &f)" then its type will be unknown
14226        -- but the deduction does not succeed because the expression is
14227        not just the function on its own.  */
14228     return false;
14229   else
14230     for (; arg; arg = OVL_NEXT (arg))
14231       if (try_one_overload (tparms, targs, tempargs, parm,
14232                             TREE_TYPE (OVL_CURRENT (arg)),
14233                             strict, sub_strict, addr_p)
14234           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
14235         {
14236           goodfn = OVL_CURRENT (arg);
14237           ++good;
14238         }
14239
14240   /* [temp.deduct.type] A template-argument can be deduced from a pointer
14241      to function or pointer to member function argument if the set of
14242      overloaded functions does not contain function templates and at most
14243      one of a set of overloaded functions provides a unique match.
14244
14245      So if we found multiple possibilities, we return success but don't
14246      deduce anything.  */
14247
14248   if (good == 1)
14249     {
14250       int i = TREE_VEC_LENGTH (targs);
14251       for (; i--; )
14252         if (TREE_VEC_ELT (tempargs, i))
14253           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
14254     }
14255   if (good)
14256     return true;
14257
14258   return false;
14259 }
14260
14261 /* Core DR 115: In contexts where deduction is done and fails, or in
14262    contexts where deduction is not done, if a template argument list is
14263    specified and it, along with any default template arguments, identifies
14264    a single function template specialization, then the template-id is an
14265    lvalue for the function template specialization.  */
14266
14267 tree
14268 resolve_nondeduced_context (tree orig_expr)
14269 {
14270   tree expr, offset, baselink;
14271   bool addr;
14272
14273   if (!type_unknown_p (orig_expr))
14274     return orig_expr;
14275
14276   expr = orig_expr;
14277   addr = false;
14278   offset = NULL_TREE;
14279   baselink = NULL_TREE;
14280
14281   if (TREE_CODE (expr) == ADDR_EXPR)
14282     {
14283       expr = TREE_OPERAND (expr, 0);
14284       addr = true;
14285     }
14286   if (TREE_CODE (expr) == OFFSET_REF)
14287     {
14288       offset = expr;
14289       expr = TREE_OPERAND (expr, 1);
14290     }
14291   if (TREE_CODE (expr) == BASELINK)
14292     {
14293       baselink = expr;
14294       expr = BASELINK_FUNCTIONS (expr);
14295     }
14296
14297   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
14298     {
14299       int good = 0;
14300       tree goodfn = NULL_TREE;
14301
14302       /* If we got some explicit template args, we need to plug them into
14303          the affected templates before we try to unify, in case the
14304          explicit args will completely resolve the templates in question.  */
14305
14306       tree expl_subargs = TREE_OPERAND (expr, 1);
14307       tree arg = TREE_OPERAND (expr, 0);
14308       tree badfn = NULL_TREE;
14309       tree badargs = NULL_TREE;
14310
14311       for (; arg; arg = OVL_NEXT (arg))
14312         {
14313           tree fn = OVL_CURRENT (arg);
14314           tree subargs, elem;
14315
14316           if (TREE_CODE (fn) != TEMPLATE_DECL)
14317             continue;
14318
14319           ++processing_template_decl;
14320           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
14321                                   expl_subargs, /*check_ret=*/false);
14322           if (subargs && !any_dependent_template_arguments_p (subargs))
14323             {
14324               elem = instantiate_template (fn, subargs, tf_none);
14325               if (elem == error_mark_node)
14326                 {
14327                   badfn = fn;
14328                   badargs = subargs;
14329                 }
14330               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
14331                 {
14332                   goodfn = elem;
14333                   ++good;
14334                 }
14335             }
14336           --processing_template_decl;
14337         }
14338       if (good == 1)
14339         {
14340           expr = goodfn;
14341           if (baselink)
14342             expr = build_baselink (BASELINK_BINFO (baselink),
14343                                    BASELINK_ACCESS_BINFO (baselink),
14344                                    expr, BASELINK_OPTYPE (baselink));
14345           if (offset)
14346             {
14347               tree base
14348                 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
14349               expr = build_offset_ref (base, expr, addr);
14350             }
14351           if (addr)
14352             expr = cp_build_addr_expr (expr, tf_warning_or_error);
14353           return expr;
14354         }
14355       else if (good == 0 && badargs)
14356         /* There were no good options and at least one bad one, so let the
14357            user know what the problem is.  */
14358         instantiate_template (badfn, badargs, tf_warning_or_error);
14359     }
14360   return orig_expr;
14361 }
14362
14363 /* Subroutine of resolve_overloaded_unification; does deduction for a single
14364    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
14365    different overloads deduce different arguments for a given parm.
14366    ADDR_P is true if the expression for which deduction is being
14367    performed was of the form "& fn" rather than simply "fn".
14368
14369    Returns 1 on success.  */
14370
14371 static int
14372 try_one_overload (tree tparms,
14373                   tree orig_targs,
14374                   tree targs,
14375                   tree parm,
14376                   tree arg,
14377                   unification_kind_t strict,
14378                   int sub_strict,
14379                   bool addr_p)
14380 {
14381   int nargs;
14382   tree tempargs;
14383   int i;
14384
14385   /* [temp.deduct.type] A template-argument can be deduced from a pointer
14386      to function or pointer to member function argument if the set of
14387      overloaded functions does not contain function templates and at most
14388      one of a set of overloaded functions provides a unique match.
14389
14390      So if this is a template, just return success.  */
14391
14392   if (uses_template_parms (arg))
14393     return 1;
14394
14395   if (TREE_CODE (arg) == METHOD_TYPE)
14396     arg = build_ptrmemfunc_type (build_pointer_type (arg));
14397   else if (addr_p)
14398     arg = build_pointer_type (arg);
14399
14400   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
14401
14402   /* We don't copy orig_targs for this because if we have already deduced
14403      some template args from previous args, unify would complain when we
14404      try to deduce a template parameter for the same argument, even though
14405      there isn't really a conflict.  */
14406   nargs = TREE_VEC_LENGTH (targs);
14407   tempargs = make_tree_vec (nargs);
14408
14409   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
14410     return 0;
14411
14412   /* First make sure we didn't deduce anything that conflicts with
14413      explicitly specified args.  */
14414   for (i = nargs; i--; )
14415     {
14416       tree elt = TREE_VEC_ELT (tempargs, i);
14417       tree oldelt = TREE_VEC_ELT (orig_targs, i);
14418
14419       if (!elt)
14420         /*NOP*/;
14421       else if (uses_template_parms (elt))
14422         /* Since we're unifying against ourselves, we will fill in
14423            template args used in the function parm list with our own
14424            template parms.  Discard them.  */
14425         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
14426       else if (oldelt && !template_args_equal (oldelt, elt))
14427         return 0;
14428     }
14429
14430   for (i = nargs; i--; )
14431     {
14432       tree elt = TREE_VEC_ELT (tempargs, i);
14433
14434       if (elt)
14435         TREE_VEC_ELT (targs, i) = elt;
14436     }
14437
14438   return 1;
14439 }
14440
14441 /* PARM is a template class (perhaps with unbound template
14442    parameters).  ARG is a fully instantiated type.  If ARG can be
14443    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
14444    TARGS are as for unify.  */
14445
14446 static tree
14447 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
14448 {
14449   tree copy_of_targs;
14450
14451   if (!CLASSTYPE_TEMPLATE_INFO (arg)
14452       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
14453           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
14454     return NULL_TREE;
14455
14456   /* We need to make a new template argument vector for the call to
14457      unify.  If we used TARGS, we'd clutter it up with the result of
14458      the attempted unification, even if this class didn't work out.
14459      We also don't want to commit ourselves to all the unifications
14460      we've already done, since unification is supposed to be done on
14461      an argument-by-argument basis.  In other words, consider the
14462      following pathological case:
14463
14464        template <int I, int J, int K>
14465        struct S {};
14466
14467        template <int I, int J>
14468        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
14469
14470        template <int I, int J, int K>
14471        void f(S<I, J, K>, S<I, I, I>);
14472
14473        void g() {
14474          S<0, 0, 0> s0;
14475          S<0, 1, 2> s2;
14476
14477          f(s0, s2);
14478        }
14479
14480      Now, by the time we consider the unification involving `s2', we
14481      already know that we must have `f<0, 0, 0>'.  But, even though
14482      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
14483      because there are two ways to unify base classes of S<0, 1, 2>
14484      with S<I, I, I>.  If we kept the already deduced knowledge, we
14485      would reject the possibility I=1.  */
14486   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
14487
14488   /* If unification failed, we're done.  */
14489   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
14490              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
14491     return NULL_TREE;
14492
14493   return arg;
14494 }
14495
14496 /* Given a template type PARM and a class type ARG, find the unique
14497    base type in ARG that is an instance of PARM.  We do not examine
14498    ARG itself; only its base-classes.  If there is not exactly one
14499    appropriate base class, return NULL_TREE.  PARM may be the type of
14500    a partial specialization, as well as a plain template type.  Used
14501    by unify.  */
14502
14503 static tree
14504 get_template_base (tree tparms, tree targs, tree parm, tree arg)
14505 {
14506   tree rval = NULL_TREE;
14507   tree binfo;
14508
14509   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
14510
14511   binfo = TYPE_BINFO (complete_type (arg));
14512   if (!binfo)
14513     /* The type could not be completed.  */
14514     return NULL_TREE;
14515
14516   /* Walk in inheritance graph order.  The search order is not
14517      important, and this avoids multiple walks of virtual bases.  */
14518   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
14519     {
14520       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
14521
14522       if (r)
14523         {
14524           /* If there is more than one satisfactory baseclass, then:
14525
14526                [temp.deduct.call]
14527
14528               If they yield more than one possible deduced A, the type
14529               deduction fails.
14530
14531              applies.  */
14532           if (rval && !same_type_p (r, rval))
14533             return NULL_TREE;
14534
14535           rval = r;
14536         }
14537     }
14538
14539   return rval;
14540 }
14541
14542 /* Returns the level of DECL, which declares a template parameter.  */
14543
14544 static int
14545 template_decl_level (tree decl)
14546 {
14547   switch (TREE_CODE (decl))
14548     {
14549     case TYPE_DECL:
14550     case TEMPLATE_DECL:
14551       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
14552
14553     case PARM_DECL:
14554       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
14555
14556     default:
14557       gcc_unreachable ();
14558     }
14559   return 0;
14560 }
14561
14562 /* Decide whether ARG can be unified with PARM, considering only the
14563    cv-qualifiers of each type, given STRICT as documented for unify.
14564    Returns nonzero iff the unification is OK on that basis.  */
14565
14566 static int
14567 check_cv_quals_for_unify (int strict, tree arg, tree parm)
14568 {
14569   int arg_quals = cp_type_quals (arg);
14570   int parm_quals = cp_type_quals (parm);
14571
14572   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14573       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14574     {
14575       /*  Although a CVR qualifier is ignored when being applied to a
14576           substituted template parameter ([8.3.2]/1 for example), that
14577           does not allow us to unify "const T" with "int&" because both
14578           types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
14579           It is ok when we're allowing additional CV qualifiers
14580           at the outer level [14.8.2.1]/3,1st bullet.  */
14581       if ((TREE_CODE (arg) == REFERENCE_TYPE
14582            || TREE_CODE (arg) == FUNCTION_TYPE
14583            || TREE_CODE (arg) == METHOD_TYPE)
14584           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
14585         return 0;
14586
14587       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
14588           && (parm_quals & TYPE_QUAL_RESTRICT))
14589         return 0;
14590     }
14591
14592   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14593       && (arg_quals & parm_quals) != parm_quals)
14594     return 0;
14595
14596   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
14597       && (parm_quals & arg_quals) != arg_quals)
14598     return 0;
14599
14600   return 1;
14601 }
14602
14603 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
14604 void 
14605 template_parm_level_and_index (tree parm, int* level, int* index)
14606 {
14607   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14608       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14609       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14610     {
14611       *index = TEMPLATE_TYPE_IDX (parm);
14612       *level = TEMPLATE_TYPE_LEVEL (parm);
14613     }
14614   else
14615     {
14616       *index = TEMPLATE_PARM_IDX (parm);
14617       *level = TEMPLATE_PARM_LEVEL (parm);
14618     }
14619 }
14620
14621 /* Unifies the remaining arguments in PACKED_ARGS with the pack
14622    expansion at the end of PACKED_PARMS. Returns 0 if the type
14623    deduction succeeds, 1 otherwise. STRICT is the same as in
14624    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
14625    call argument list. We'll need to adjust the arguments to make them
14626    types. SUBR tells us if this is from a recursive call to
14627    type_unification_real.  */
14628 int
14629 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
14630                       tree packed_args, int strict, bool call_args_p,
14631                       bool subr)
14632 {
14633   tree parm 
14634     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
14635   tree pattern = PACK_EXPANSION_PATTERN (parm);
14636   tree pack, packs = NULL_TREE;
14637   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
14638   int len = TREE_VEC_LENGTH (packed_args);
14639
14640   /* Determine the parameter packs we will be deducing from the
14641      pattern, and record their current deductions.  */
14642   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
14643        pack; pack = TREE_CHAIN (pack))
14644     {
14645       tree parm_pack = TREE_VALUE (pack);
14646       int idx, level;
14647
14648       /* Determine the index and level of this parameter pack.  */
14649       template_parm_level_and_index (parm_pack, &level, &idx);
14650
14651       /* Keep track of the parameter packs and their corresponding
14652          argument packs.  */
14653       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
14654       TREE_TYPE (packs) = make_tree_vec (len - start);
14655     }
14656   
14657   /* Loop through all of the arguments that have not yet been
14658      unified and unify each with the pattern.  */
14659   for (i = start; i < len; i++)
14660     {
14661       tree parm = pattern;
14662
14663       /* For each parameter pack, clear out the deduced value so that
14664          we can deduce it again.  */
14665       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14666         {
14667           int idx, level;
14668           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14669
14670           TMPL_ARG (targs, level, idx) = NULL_TREE;
14671         }
14672
14673       /* Unify the pattern with the current argument.  */
14674       {
14675         tree arg = TREE_VEC_ELT (packed_args, i);
14676         tree arg_expr = NULL_TREE;
14677         int arg_strict = strict;
14678         bool skip_arg_p = false;
14679
14680         if (call_args_p)
14681           {
14682             int sub_strict;
14683
14684             /* This mirrors what we do in type_unification_real.  */
14685             switch (strict)
14686               {
14687               case DEDUCE_CALL:
14688                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
14689                               | UNIFY_ALLOW_MORE_CV_QUAL
14690                               | UNIFY_ALLOW_DERIVED);
14691                 break;
14692                 
14693               case DEDUCE_CONV:
14694                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14695                 break;
14696                 
14697               case DEDUCE_EXACT:
14698                 sub_strict = UNIFY_ALLOW_NONE;
14699                 break;
14700                 
14701               default:
14702                 gcc_unreachable ();
14703               }
14704
14705             if (!TYPE_P (arg))
14706               {
14707                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14708                 if (type_unknown_p (arg))
14709                   {
14710                     /* [temp.deduct.type] A template-argument can be
14711                        deduced from a pointer to function or pointer
14712                        to member function argument if the set of
14713                        overloaded functions does not contain function
14714                        templates and at most one of a set of
14715                        overloaded functions provides a unique
14716                        match.  */
14717
14718                     if (resolve_overloaded_unification
14719                         (tparms, targs, parm, arg,
14720                          (unification_kind_t) strict,
14721                          sub_strict)
14722                         != 0)
14723                       return 1;
14724                     skip_arg_p = true;
14725                   }
14726
14727                 if (!skip_arg_p)
14728                   {
14729                     arg_expr = arg;
14730                     arg = unlowered_expr_type (arg);
14731                     if (arg == error_mark_node)
14732                       return 1;
14733                   }
14734               }
14735       
14736             arg_strict = sub_strict;
14737
14738             if (!subr)
14739               arg_strict |= 
14740                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
14741                                                   &parm, &arg, arg_expr);
14742           }
14743
14744         if (!skip_arg_p)
14745           {
14746             /* For deduction from an init-list we need the actual list.  */
14747             if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
14748               arg = arg_expr;
14749             if (unify (tparms, targs, parm, arg, arg_strict))
14750               return 1;
14751           }
14752       }
14753
14754       /* For each parameter pack, collect the deduced value.  */
14755       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14756         {
14757           int idx, level;
14758           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14759
14760           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
14761             TMPL_ARG (targs, level, idx);
14762         }
14763     }
14764
14765   /* Verify that the results of unification with the parameter packs
14766      produce results consistent with what we've seen before, and make
14767      the deduced argument packs available.  */
14768   for (pack = packs; pack; pack = TREE_CHAIN (pack))
14769     {
14770       tree old_pack = TREE_VALUE (pack);
14771       tree new_args = TREE_TYPE (pack);
14772       int i, len = TREE_VEC_LENGTH (new_args);
14773       int idx, level;
14774       bool nondeduced_p = false;
14775
14776       /* By default keep the original deduced argument pack.
14777          If necessary, more specific code is going to update the
14778          resulting deduced argument later down in this function.  */
14779       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14780       TMPL_ARG (targs, level, idx) = old_pack;
14781
14782       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
14783          actually deduce anything.  */
14784       for (i = 0; i < len && !nondeduced_p; ++i)
14785         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
14786           nondeduced_p = true;
14787       if (nondeduced_p)
14788         continue;
14789
14790       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
14791         {
14792           /* Prepend the explicit arguments onto NEW_ARGS.  */
14793           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14794           tree old_args = new_args;
14795           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
14796           int len = explicit_len + TREE_VEC_LENGTH (old_args);
14797
14798           /* Copy the explicit arguments.  */
14799           new_args = make_tree_vec (len);
14800           for (i = 0; i < explicit_len; i++)
14801             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
14802
14803           /* Copy the deduced arguments.  */
14804           for (; i < len; i++)
14805             TREE_VEC_ELT (new_args, i) =
14806               TREE_VEC_ELT (old_args, i - explicit_len);
14807         }
14808
14809       if (!old_pack)
14810         {
14811           tree result;
14812           /* Build the deduced *_ARGUMENT_PACK.  */
14813           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
14814             {
14815               result = make_node (NONTYPE_ARGUMENT_PACK);
14816               TREE_TYPE (result) = 
14817                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
14818               TREE_CONSTANT (result) = 1;
14819             }
14820           else
14821             result = cxx_make_type (TYPE_ARGUMENT_PACK);
14822
14823           SET_ARGUMENT_PACK_ARGS (result, new_args);
14824
14825           /* Note the deduced argument packs for this parameter
14826              pack.  */
14827           TMPL_ARG (targs, level, idx) = result;
14828         }
14829       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
14830                && (ARGUMENT_PACK_ARGS (old_pack) 
14831                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
14832         {
14833           /* We only had the explicitly-provided arguments before, but
14834              now we have a complete set of arguments.  */
14835           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14836
14837           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
14838           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
14839           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
14840         }
14841       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
14842                                     new_args))
14843         /* Inconsistent unification of this parameter pack.  */
14844         return 1;
14845     }
14846
14847   return 0;
14848 }
14849
14850 /* Deduce the value of template parameters.  TPARMS is the (innermost)
14851    set of template parameters to a template.  TARGS is the bindings
14852    for those template parameters, as determined thus far; TARGS may
14853    include template arguments for outer levels of template parameters
14854    as well.  PARM is a parameter to a template function, or a
14855    subcomponent of that parameter; ARG is the corresponding argument.
14856    This function attempts to match PARM with ARG in a manner
14857    consistent with the existing assignments in TARGS.  If more values
14858    are deduced, then TARGS is updated.
14859
14860    Returns 0 if the type deduction succeeds, 1 otherwise.  The
14861    parameter STRICT is a bitwise or of the following flags:
14862
14863      UNIFY_ALLOW_NONE:
14864        Require an exact match between PARM and ARG.
14865      UNIFY_ALLOW_MORE_CV_QUAL:
14866        Allow the deduced ARG to be more cv-qualified (by qualification
14867        conversion) than ARG.
14868      UNIFY_ALLOW_LESS_CV_QUAL:
14869        Allow the deduced ARG to be less cv-qualified than ARG.
14870      UNIFY_ALLOW_DERIVED:
14871        Allow the deduced ARG to be a template base class of ARG,
14872        or a pointer to a template base class of the type pointed to by
14873        ARG.
14874      UNIFY_ALLOW_INTEGER:
14875        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
14876        case for more information.
14877      UNIFY_ALLOW_OUTER_LEVEL:
14878        This is the outermost level of a deduction. Used to determine validity
14879        of qualification conversions. A valid qualification conversion must
14880        have const qualified pointers leading up to the inner type which
14881        requires additional CV quals, except at the outer level, where const
14882        is not required [conv.qual]. It would be normal to set this flag in
14883        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
14884      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
14885        This is the outermost level of a deduction, and PARM can be more CV
14886        qualified at this point.
14887      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
14888        This is the outermost level of a deduction, and PARM can be less CV
14889        qualified at this point.  */
14890
14891 static int
14892 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
14893 {
14894   int idx;
14895   tree targ;
14896   tree tparm;
14897   int strict_in = strict;
14898
14899   /* I don't think this will do the right thing with respect to types.
14900      But the only case I've seen it in so far has been array bounds, where
14901      signedness is the only information lost, and I think that will be
14902      okay.  */
14903   while (TREE_CODE (parm) == NOP_EXPR)
14904     parm = TREE_OPERAND (parm, 0);
14905
14906   if (arg == error_mark_node)
14907     return 1;
14908   if (arg == unknown_type_node
14909       || arg == init_list_type_node)
14910     /* We can't deduce anything from this, but we might get all the
14911        template args from other function args.  */
14912     return 0;
14913
14914   /* If PARM uses template parameters, then we can't bail out here,
14915      even if ARG == PARM, since we won't record unifications for the
14916      template parameters.  We might need them if we're trying to
14917      figure out which of two things is more specialized.  */
14918   if (arg == parm && !uses_template_parms (parm))
14919     return 0;
14920
14921   /* Handle init lists early, so the rest of the function can assume
14922      we're dealing with a type. */
14923   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
14924     {
14925       tree elt, elttype;
14926       unsigned i;
14927       tree orig_parm = parm;
14928
14929       /* Replace T with std::initializer_list<T> for deduction.  */
14930       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14931           && flag_deduce_init_list)
14932         parm = listify (parm);
14933
14934       if (!is_std_init_list (parm))
14935         /* We can only deduce from an initializer list argument if the
14936            parameter is std::initializer_list; otherwise this is a
14937            non-deduced context. */
14938         return 0;
14939
14940       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
14941
14942       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
14943         {
14944           int elt_strict = strict;
14945
14946           if (elt == error_mark_node)
14947             return 1;
14948
14949           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
14950             {
14951               tree type = TREE_TYPE (elt);
14952               /* It should only be possible to get here for a call.  */
14953               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
14954               elt_strict |= maybe_adjust_types_for_deduction
14955                 (DEDUCE_CALL, &elttype, &type, elt);
14956               elt = type;
14957             }
14958
14959           if (unify (tparms, targs, elttype, elt, elt_strict))
14960             return 1;
14961         }
14962
14963       /* If the std::initializer_list<T> deduction worked, replace the
14964          deduced A with std::initializer_list<A>.  */
14965       if (orig_parm != parm)
14966         {
14967           idx = TEMPLATE_TYPE_IDX (orig_parm);
14968           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14969           targ = listify (targ);
14970           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
14971         }
14972       return 0;
14973     }
14974
14975   /* Immediately reject some pairs that won't unify because of
14976      cv-qualification mismatches.  */
14977   if (TREE_CODE (arg) == TREE_CODE (parm)
14978       && TYPE_P (arg)
14979       /* It is the elements of the array which hold the cv quals of an array
14980          type, and the elements might be template type parms. We'll check
14981          when we recurse.  */
14982       && TREE_CODE (arg) != ARRAY_TYPE
14983       /* We check the cv-qualifiers when unifying with template type
14984          parameters below.  We want to allow ARG `const T' to unify with
14985          PARM `T' for example, when computing which of two templates
14986          is more specialized, for example.  */
14987       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
14988       && !check_cv_quals_for_unify (strict_in, arg, parm))
14989     return 1;
14990
14991   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
14992       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
14993     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
14994   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
14995   strict &= ~UNIFY_ALLOW_DERIVED;
14996   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14997   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
14998
14999   switch (TREE_CODE (parm))
15000     {
15001     case TYPENAME_TYPE:
15002     case SCOPE_REF:
15003     case UNBOUND_CLASS_TEMPLATE:
15004       /* In a type which contains a nested-name-specifier, template
15005          argument values cannot be deduced for template parameters used
15006          within the nested-name-specifier.  */
15007       return 0;
15008
15009     case TEMPLATE_TYPE_PARM:
15010     case TEMPLATE_TEMPLATE_PARM:
15011     case BOUND_TEMPLATE_TEMPLATE_PARM:
15012       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
15013       if (tparm == error_mark_node)
15014         return 1;
15015
15016       if (TEMPLATE_TYPE_LEVEL (parm)
15017           != template_decl_level (tparm))
15018         /* The PARM is not one we're trying to unify.  Just check
15019            to see if it matches ARG.  */
15020         return (TREE_CODE (arg) == TREE_CODE (parm)
15021                 && same_type_p (parm, arg)) ? 0 : 1;
15022       idx = TEMPLATE_TYPE_IDX (parm);
15023       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15024       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
15025
15026       /* Check for mixed types and values.  */
15027       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15028            && TREE_CODE (tparm) != TYPE_DECL)
15029           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15030               && TREE_CODE (tparm) != TEMPLATE_DECL))
15031         return 1;
15032
15033       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15034         {
15035           /* ARG must be constructed from a template class or a template
15036              template parameter.  */
15037           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
15038               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
15039             return 1;
15040
15041           {
15042             tree parmvec = TYPE_TI_ARGS (parm);
15043             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
15044             tree full_argvec = add_to_template_args (targs, argvec);
15045             tree parm_parms 
15046               = DECL_INNERMOST_TEMPLATE_PARMS
15047                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
15048             int i, len;
15049             int parm_variadic_p = 0;
15050
15051             /* The resolution to DR150 makes clear that default
15052                arguments for an N-argument may not be used to bind T
15053                to a template template parameter with fewer than N
15054                parameters.  It is not safe to permit the binding of
15055                default arguments as an extension, as that may change
15056                the meaning of a conforming program.  Consider:
15057
15058                   struct Dense { static const unsigned int dim = 1; };
15059
15060                   template <template <typename> class View,
15061                             typename Block>
15062                   void operator+(float, View<Block> const&);
15063
15064                   template <typename Block,
15065                             unsigned int Dim = Block::dim>
15066                   struct Lvalue_proxy { operator float() const; };
15067
15068                   void
15069                   test_1d (void) {
15070                     Lvalue_proxy<Dense> p;
15071                     float b;
15072                     b + p;
15073                   }
15074
15075               Here, if Lvalue_proxy is permitted to bind to View, then
15076               the global operator+ will be used; if they are not, the
15077               Lvalue_proxy will be converted to float.  */
15078             if (coerce_template_parms (parm_parms,
15079                                        full_argvec,
15080                                        TYPE_TI_TEMPLATE (parm),
15081                                        tf_none,
15082                                        /*require_all_args=*/true,
15083                                        /*use_default_args=*/false)
15084                 == error_mark_node)
15085               return 1;
15086
15087             /* Deduce arguments T, i from TT<T> or TT<i>.
15088                We check each element of PARMVEC and ARGVEC individually
15089                rather than the whole TREE_VEC since they can have
15090                different number of elements.  */
15091
15092             parmvec = expand_template_argument_pack (parmvec);
15093             argvec = expand_template_argument_pack (argvec);
15094
15095             len = TREE_VEC_LENGTH (parmvec);
15096
15097             /* Check if the parameters end in a pack, making them
15098                variadic.  */
15099             if (len > 0
15100                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
15101               parm_variadic_p = 1;
15102             
15103             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
15104               return 1;
15105
15106              for (i = 0; i < len - parm_variadic_p; ++i)
15107               {
15108                 if (unify (tparms, targs,
15109                            TREE_VEC_ELT (parmvec, i),
15110                            TREE_VEC_ELT (argvec, i),
15111                            UNIFY_ALLOW_NONE))
15112                   return 1;
15113               }
15114
15115             if (parm_variadic_p
15116                 && unify_pack_expansion (tparms, targs,
15117                                          parmvec, argvec,
15118                                          UNIFY_ALLOW_NONE,
15119                                          /*call_args_p=*/false,
15120                                          /*subr=*/false))
15121               return 1;
15122           }
15123           arg = TYPE_TI_TEMPLATE (arg);
15124
15125           /* Fall through to deduce template name.  */
15126         }
15127
15128       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15129           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15130         {
15131           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
15132
15133           /* Simple cases: Value already set, does match or doesn't.  */
15134           if (targ != NULL_TREE && template_args_equal (targ, arg))
15135             return 0;
15136           else if (targ)
15137             return 1;
15138         }
15139       else
15140         {
15141           /* If PARM is `const T' and ARG is only `int', we don't have
15142              a match unless we are allowing additional qualification.
15143              If ARG is `const int' and PARM is just `T' that's OK;
15144              that binds `const int' to `T'.  */
15145           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
15146                                          arg, parm))
15147             return 1;
15148
15149           /* Consider the case where ARG is `const volatile int' and
15150              PARM is `const T'.  Then, T should be `volatile int'.  */
15151           arg = cp_build_qualified_type_real
15152             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
15153           if (arg == error_mark_node)
15154             return 1;
15155
15156           /* Simple cases: Value already set, does match or doesn't.  */
15157           if (targ != NULL_TREE && same_type_p (targ, arg))
15158             return 0;
15159           else if (targ)
15160             return 1;
15161
15162           /* Make sure that ARG is not a variable-sized array.  (Note
15163              that were talking about variable-sized arrays (like
15164              `int[n]'), rather than arrays of unknown size (like
15165              `int[]').)  We'll get very confused by such a type since
15166              the bound of the array will not be computable in an
15167              instantiation.  Besides, such types are not allowed in
15168              ISO C++, so we can do as we please here.  */
15169           if (variably_modified_type_p (arg, NULL_TREE))
15170             return 1;
15171
15172           /* Strip typedefs as in convert_template_argument.  */
15173           arg = strip_typedefs (arg);
15174         }
15175
15176       /* If ARG is a parameter pack or an expansion, we cannot unify
15177          against it unless PARM is also a parameter pack.  */
15178       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
15179           && !template_parameter_pack_p (parm))
15180         return 1;
15181
15182       /* If the argument deduction results is a METHOD_TYPE,
15183          then there is a problem.
15184          METHOD_TYPE doesn't map to any real C++ type the result of
15185          the deduction can not be of that type.  */
15186       if (TREE_CODE (arg) == METHOD_TYPE)
15187         return 1;
15188
15189       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
15190       return 0;
15191
15192     case TEMPLATE_PARM_INDEX:
15193       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
15194       if (tparm == error_mark_node)
15195         return 1;
15196
15197       if (TEMPLATE_PARM_LEVEL (parm)
15198           != template_decl_level (tparm))
15199         /* The PARM is not one we're trying to unify.  Just check
15200            to see if it matches ARG.  */
15201         return !(TREE_CODE (arg) == TREE_CODE (parm)
15202                  && cp_tree_equal (parm, arg));
15203
15204       idx = TEMPLATE_PARM_IDX (parm);
15205       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15206
15207       if (targ)
15208         return !cp_tree_equal (targ, arg);
15209
15210       /* [temp.deduct.type] If, in the declaration of a function template
15211          with a non-type template-parameter, the non-type
15212          template-parameter is used in an expression in the function
15213          parameter-list and, if the corresponding template-argument is
15214          deduced, the template-argument type shall match the type of the
15215          template-parameter exactly, except that a template-argument
15216          deduced from an array bound may be of any integral type.
15217          The non-type parameter might use already deduced type parameters.  */
15218       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
15219       if (!TREE_TYPE (arg))
15220         /* Template-parameter dependent expression.  Just accept it for now.
15221            It will later be processed in convert_template_argument.  */
15222         ;
15223       else if (same_type_p (TREE_TYPE (arg), tparm))
15224         /* OK */;
15225       else if ((strict & UNIFY_ALLOW_INTEGER)
15226                && (TREE_CODE (tparm) == INTEGER_TYPE
15227                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
15228         /* Convert the ARG to the type of PARM; the deduced non-type
15229            template argument must exactly match the types of the
15230            corresponding parameter.  */
15231         arg = fold (build_nop (tparm, arg));
15232       else if (uses_template_parms (tparm))
15233         /* We haven't deduced the type of this parameter yet.  Try again
15234            later.  */
15235         return 0;
15236       else
15237         return 1;
15238
15239       /* If ARG is a parameter pack or an expansion, we cannot unify
15240          against it unless PARM is also a parameter pack.  */
15241       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
15242           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
15243         return 1;
15244
15245       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
15246       return 0;
15247
15248     case PTRMEM_CST:
15249      {
15250         /* A pointer-to-member constant can be unified only with
15251          another constant.  */
15252       if (TREE_CODE (arg) != PTRMEM_CST)
15253         return 1;
15254
15255       /* Just unify the class member. It would be useless (and possibly
15256          wrong, depending on the strict flags) to unify also
15257          PTRMEM_CST_CLASS, because we want to be sure that both parm and
15258          arg refer to the same variable, even if through different
15259          classes. For instance:
15260
15261          struct A { int x; };
15262          struct B : A { };
15263
15264          Unification of &A::x and &B::x must succeed.  */
15265       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
15266                     PTRMEM_CST_MEMBER (arg), strict);
15267      }
15268
15269     case POINTER_TYPE:
15270       {
15271         if (TREE_CODE (arg) != POINTER_TYPE)
15272           return 1;
15273
15274         /* [temp.deduct.call]
15275
15276            A can be another pointer or pointer to member type that can
15277            be converted to the deduced A via a qualification
15278            conversion (_conv.qual_).
15279
15280            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
15281            This will allow for additional cv-qualification of the
15282            pointed-to types if appropriate.  */
15283
15284         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
15285           /* The derived-to-base conversion only persists through one
15286              level of pointers.  */
15287           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
15288
15289         return unify (tparms, targs, TREE_TYPE (parm),
15290                       TREE_TYPE (arg), strict);
15291       }
15292
15293     case REFERENCE_TYPE:
15294       if (TREE_CODE (arg) != REFERENCE_TYPE)
15295         return 1;
15296       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15297                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
15298
15299     case ARRAY_TYPE:
15300       if (TREE_CODE (arg) != ARRAY_TYPE)
15301         return 1;
15302       if ((TYPE_DOMAIN (parm) == NULL_TREE)
15303           != (TYPE_DOMAIN (arg) == NULL_TREE))
15304         return 1;
15305       if (TYPE_DOMAIN (parm) != NULL_TREE)
15306         {
15307           tree parm_max;
15308           tree arg_max;
15309           bool parm_cst;
15310           bool arg_cst;
15311
15312           /* Our representation of array types uses "N - 1" as the
15313              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
15314              not an integer constant.  We cannot unify arbitrarily
15315              complex expressions, so we eliminate the MINUS_EXPRs
15316              here.  */
15317           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
15318           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
15319           if (!parm_cst)
15320             {
15321               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
15322               parm_max = TREE_OPERAND (parm_max, 0);
15323             }
15324           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
15325           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
15326           if (!arg_cst)
15327             {
15328               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
15329                  trying to unify the type of a variable with the type
15330                  of a template parameter.  For example:
15331
15332                    template <unsigned int N>
15333                    void f (char (&) [N]);
15334                    int g(); 
15335                    void h(int i) {
15336                      char a[g(i)];
15337                      f(a); 
15338                    }
15339
15340                 Here, the type of the ARG will be "int [g(i)]", and
15341                 may be a SAVE_EXPR, etc.  */
15342               if (TREE_CODE (arg_max) != MINUS_EXPR)
15343                 return 1;
15344               arg_max = TREE_OPERAND (arg_max, 0);
15345             }
15346
15347           /* If only one of the bounds used a MINUS_EXPR, compensate
15348              by adding one to the other bound.  */
15349           if (parm_cst && !arg_cst)
15350             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
15351                                     integer_type_node,
15352                                     parm_max,
15353                                     integer_one_node);
15354           else if (arg_cst && !parm_cst)
15355             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
15356                                    integer_type_node,
15357                                    arg_max,
15358                                    integer_one_node);
15359
15360           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
15361             return 1;
15362         }
15363       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15364                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
15365
15366     case REAL_TYPE:
15367     case COMPLEX_TYPE:
15368     case VECTOR_TYPE:
15369     case INTEGER_TYPE:
15370     case BOOLEAN_TYPE:
15371     case ENUMERAL_TYPE:
15372     case VOID_TYPE:
15373       if (TREE_CODE (arg) != TREE_CODE (parm))
15374         return 1;
15375
15376       /* We have already checked cv-qualification at the top of the
15377          function.  */
15378       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
15379         return 1;
15380
15381       /* As far as unification is concerned, this wins.  Later checks
15382          will invalidate it if necessary.  */
15383       return 0;
15384
15385       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
15386       /* Type INTEGER_CST can come from ordinary constant template args.  */
15387     case INTEGER_CST:
15388       while (TREE_CODE (arg) == NOP_EXPR)
15389         arg = TREE_OPERAND (arg, 0);
15390
15391       if (TREE_CODE (arg) != INTEGER_CST)
15392         return 1;
15393       return !tree_int_cst_equal (parm, arg);
15394
15395     case TREE_VEC:
15396       {
15397         int i;
15398         if (TREE_CODE (arg) != TREE_VEC)
15399           return 1;
15400         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
15401           return 1;
15402         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
15403           if (unify (tparms, targs,
15404                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
15405                      UNIFY_ALLOW_NONE))
15406             return 1;
15407         return 0;
15408       }
15409
15410     case RECORD_TYPE:
15411     case UNION_TYPE:
15412       if (TREE_CODE (arg) != TREE_CODE (parm))
15413         return 1;
15414
15415       if (TYPE_PTRMEMFUNC_P (parm))
15416         {
15417           if (!TYPE_PTRMEMFUNC_P (arg))
15418             return 1;
15419
15420           return unify (tparms, targs,
15421                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
15422                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
15423                         strict);
15424         }
15425
15426       if (CLASSTYPE_TEMPLATE_INFO (parm))
15427         {
15428           tree t = NULL_TREE;
15429
15430           if (strict_in & UNIFY_ALLOW_DERIVED)
15431             {
15432               /* First, we try to unify the PARM and ARG directly.  */
15433               t = try_class_unification (tparms, targs,
15434                                          parm, arg);
15435
15436               if (!t)
15437                 {
15438                   /* Fallback to the special case allowed in
15439                      [temp.deduct.call]:
15440
15441                        If P is a class, and P has the form
15442                        template-id, then A can be a derived class of
15443                        the deduced A.  Likewise, if P is a pointer to
15444                        a class of the form template-id, A can be a
15445                        pointer to a derived class pointed to by the
15446                        deduced A.  */
15447                   t = get_template_base (tparms, targs, parm, arg);
15448
15449                   if (!t)
15450                     return 1;
15451                 }
15452             }
15453           else if (CLASSTYPE_TEMPLATE_INFO (arg)
15454                    && (CLASSTYPE_TI_TEMPLATE (parm)
15455                        == CLASSTYPE_TI_TEMPLATE (arg)))
15456             /* Perhaps PARM is something like S<U> and ARG is S<int>.
15457                Then, we should unify `int' and `U'.  */
15458             t = arg;
15459           else
15460             /* There's no chance of unification succeeding.  */
15461             return 1;
15462
15463           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
15464                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
15465         }
15466       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
15467         return 1;
15468       return 0;
15469
15470     case METHOD_TYPE:
15471     case FUNCTION_TYPE:
15472       {
15473         unsigned int nargs;
15474         tree *args;
15475         tree a;
15476         unsigned int i;
15477
15478         if (TREE_CODE (arg) != TREE_CODE (parm))
15479           return 1;
15480
15481         /* CV qualifications for methods can never be deduced, they must
15482            match exactly.  We need to check them explicitly here,
15483            because type_unification_real treats them as any other
15484            cv-qualified parameter.  */
15485         if (TREE_CODE (parm) == METHOD_TYPE
15486             && (!check_cv_quals_for_unify
15487                 (UNIFY_ALLOW_NONE,
15488                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
15489                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
15490           return 1;
15491
15492         if (unify (tparms, targs, TREE_TYPE (parm),
15493                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
15494           return 1;
15495
15496         nargs = list_length (TYPE_ARG_TYPES (arg));
15497         args = XALLOCAVEC (tree, nargs);
15498         for (a = TYPE_ARG_TYPES (arg), i = 0;
15499              a != NULL_TREE && a != void_list_node;
15500              a = TREE_CHAIN (a), ++i)
15501           args[i] = TREE_VALUE (a);
15502         nargs = i;
15503
15504         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
15505                                       args, nargs, 1, DEDUCE_EXACT,
15506                                       LOOKUP_NORMAL);
15507       }
15508
15509     case OFFSET_TYPE:
15510       /* Unify a pointer to member with a pointer to member function, which
15511          deduces the type of the member as a function type. */
15512       if (TYPE_PTRMEMFUNC_P (arg))
15513         {
15514           tree method_type;
15515           tree fntype;
15516
15517           /* Check top-level cv qualifiers */
15518           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
15519             return 1;
15520
15521           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15522                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
15523             return 1;
15524
15525           /* Determine the type of the function we are unifying against. */
15526           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
15527           fntype =
15528             build_function_type (TREE_TYPE (method_type),
15529                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
15530
15531           /* Extract the cv-qualifiers of the member function from the
15532              implicit object parameter and place them on the function
15533              type to be restored later. */
15534           fntype = apply_memfn_quals (fntype, type_memfn_quals (method_type));
15535           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
15536         }
15537
15538       if (TREE_CODE (arg) != OFFSET_TYPE)
15539         return 1;
15540       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15541                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
15542         return 1;
15543       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15544                     strict);
15545
15546     case CONST_DECL:
15547       if (DECL_TEMPLATE_PARM_P (parm))
15548         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
15549       if (arg != integral_constant_value (parm))
15550         return 1;
15551       return 0;
15552
15553     case FIELD_DECL:
15554     case TEMPLATE_DECL:
15555       /* Matched cases are handled by the ARG == PARM test above.  */
15556       return 1;
15557
15558     case VAR_DECL:
15559       /* A non-type template parameter that is a variable should be a
15560          an integral constant, in which case, it whould have been
15561          folded into its (constant) value. So we should not be getting
15562          a variable here.  */
15563       gcc_unreachable ();
15564
15565     case TYPE_ARGUMENT_PACK:
15566     case NONTYPE_ARGUMENT_PACK:
15567       {
15568         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
15569         tree packed_args = ARGUMENT_PACK_ARGS (arg);
15570         int i, len = TREE_VEC_LENGTH (packed_parms);
15571         int argslen = TREE_VEC_LENGTH (packed_args);
15572         int parm_variadic_p = 0;
15573
15574         for (i = 0; i < len; ++i)
15575           {
15576             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
15577               {
15578                 if (i == len - 1)
15579                   /* We can unify against something with a trailing
15580                      parameter pack.  */
15581                   parm_variadic_p = 1;
15582                 else
15583                   /* Since there is something following the pack
15584                      expansion, we cannot unify this template argument
15585                      list.  */
15586                   return 0;
15587               }
15588           }
15589           
15590
15591         /* If we don't have enough arguments to satisfy the parameters
15592            (not counting the pack expression at the end), or we have
15593            too many arguments for a parameter list that doesn't end in
15594            a pack expression, we can't unify.  */
15595         if (argslen < (len - parm_variadic_p)
15596             || (argslen > len && !parm_variadic_p))
15597           return 1;
15598
15599         /* Unify all of the parameters that precede the (optional)
15600            pack expression.  */
15601         for (i = 0; i < len - parm_variadic_p; ++i)
15602           {
15603             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
15604                        TREE_VEC_ELT (packed_args, i), strict))
15605               return 1;
15606           }
15607
15608         if (parm_variadic_p)
15609           return unify_pack_expansion (tparms, targs, 
15610                                        packed_parms, packed_args,
15611                                        strict, /*call_args_p=*/false,
15612                                        /*subr=*/false);
15613         return 0;
15614       }
15615
15616       break;
15617
15618     case TYPEOF_TYPE:
15619     case DECLTYPE_TYPE:
15620       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
15621          nodes.  */
15622       return 0;
15623
15624     case ERROR_MARK:
15625       /* Unification fails if we hit an error node.  */
15626       return 1;
15627
15628     default:
15629       gcc_assert (EXPR_P (parm));
15630
15631       /* We must be looking at an expression.  This can happen with
15632          something like:
15633
15634            template <int I>
15635            void foo(S<I>, S<I + 2>);
15636
15637          This is a "nondeduced context":
15638
15639            [deduct.type]
15640
15641            The nondeduced contexts are:
15642
15643            --A type that is a template-id in which one or more of
15644              the template-arguments is an expression that references
15645              a template-parameter.
15646
15647          In these cases, we assume deduction succeeded, but don't
15648          actually infer any unifications.  */
15649
15650       if (!uses_template_parms (parm)
15651           && !template_args_equal (parm, arg))
15652         return 1;
15653       else
15654         return 0;
15655     }
15656 }
15657 \f
15658 /* Note that DECL can be defined in this translation unit, if
15659    required.  */
15660
15661 static void
15662 mark_definable (tree decl)
15663 {
15664   tree clone;
15665   DECL_NOT_REALLY_EXTERN (decl) = 1;
15666   FOR_EACH_CLONE (clone, decl)
15667     DECL_NOT_REALLY_EXTERN (clone) = 1;
15668 }
15669
15670 /* Called if RESULT is explicitly instantiated, or is a member of an
15671    explicitly instantiated class.  */
15672
15673 void
15674 mark_decl_instantiated (tree result, int extern_p)
15675 {
15676   SET_DECL_EXPLICIT_INSTANTIATION (result);
15677
15678   /* If this entity has already been written out, it's too late to
15679      make any modifications.  */
15680   if (TREE_ASM_WRITTEN (result))
15681     return;
15682
15683   if (TREE_CODE (result) != FUNCTION_DECL)
15684     /* The TREE_PUBLIC flag for function declarations will have been
15685        set correctly by tsubst.  */
15686     TREE_PUBLIC (result) = 1;
15687
15688   /* This might have been set by an earlier implicit instantiation.  */
15689   DECL_COMDAT (result) = 0;
15690
15691   if (extern_p)
15692     DECL_NOT_REALLY_EXTERN (result) = 0;
15693   else
15694     {
15695       mark_definable (result);
15696       /* Always make artificials weak.  */
15697       if (DECL_ARTIFICIAL (result) && flag_weak)
15698         comdat_linkage (result);
15699       /* For WIN32 we also want to put explicit instantiations in
15700          linkonce sections.  */
15701       else if (TREE_PUBLIC (result))
15702         maybe_make_one_only (result);
15703     }
15704
15705   /* If EXTERN_P, then this function will not be emitted -- unless
15706      followed by an explicit instantiation, at which point its linkage
15707      will be adjusted.  If !EXTERN_P, then this function will be
15708      emitted here.  In neither circumstance do we want
15709      import_export_decl to adjust the linkage.  */
15710   DECL_INTERFACE_KNOWN (result) = 1;
15711 }
15712
15713 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
15714    important template arguments.  If any are missing, we check whether
15715    they're important by using error_mark_node for substituting into any
15716    args that were used for partial ordering (the ones between ARGS and END)
15717    and seeing if it bubbles up.  */
15718
15719 static bool
15720 check_undeduced_parms (tree targs, tree args, tree end)
15721 {
15722   bool found = false;
15723   int i;
15724   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
15725     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
15726       {
15727         found = true;
15728         TREE_VEC_ELT (targs, i) = error_mark_node;
15729       }
15730   if (found)
15731     {
15732       for (; args != end; args = TREE_CHAIN (args))
15733         {
15734           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
15735           if (substed == error_mark_node)
15736             return true;
15737         }
15738     }
15739   return false;
15740 }
15741
15742 /* Given two function templates PAT1 and PAT2, return:
15743
15744    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
15745    -1 if PAT2 is more specialized than PAT1.
15746    0 if neither is more specialized.
15747
15748    LEN indicates the number of parameters we should consider
15749    (defaulted parameters should not be considered).
15750
15751    The 1998 std underspecified function template partial ordering, and
15752    DR214 addresses the issue.  We take pairs of arguments, one from
15753    each of the templates, and deduce them against each other.  One of
15754    the templates will be more specialized if all the *other*
15755    template's arguments deduce against its arguments and at least one
15756    of its arguments *does* *not* deduce against the other template's
15757    corresponding argument.  Deduction is done as for class templates.
15758    The arguments used in deduction have reference and top level cv
15759    qualifiers removed.  Iff both arguments were originally reference
15760    types *and* deduction succeeds in both directions, the template
15761    with the more cv-qualified argument wins for that pairing (if
15762    neither is more cv-qualified, they both are equal).  Unlike regular
15763    deduction, after all the arguments have been deduced in this way,
15764    we do *not* verify the deduced template argument values can be
15765    substituted into non-deduced contexts.
15766
15767    The logic can be a bit confusing here, because we look at deduce1 and
15768    targs1 to see if pat2 is at least as specialized, and vice versa; if we
15769    can find template arguments for pat1 to make arg1 look like arg2, that
15770    means that arg2 is at least as specialized as arg1.  */
15771
15772 int
15773 more_specialized_fn (tree pat1, tree pat2, int len)
15774 {
15775   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
15776   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
15777   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
15778   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
15779   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
15780   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
15781   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
15782   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
15783   tree origs1, origs2;
15784   bool lose1 = false;
15785   bool lose2 = false;
15786
15787   /* Remove the this parameter from non-static member functions.  If
15788      one is a non-static member function and the other is not a static
15789      member function, remove the first parameter from that function
15790      also.  This situation occurs for operator functions where we
15791      locate both a member function (with this pointer) and non-member
15792      operator (with explicit first operand).  */
15793   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
15794     {
15795       len--; /* LEN is the number of significant arguments for DECL1 */
15796       args1 = TREE_CHAIN (args1);
15797       if (!DECL_STATIC_FUNCTION_P (decl2))
15798         args2 = TREE_CHAIN (args2);
15799     }
15800   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
15801     {
15802       args2 = TREE_CHAIN (args2);
15803       if (!DECL_STATIC_FUNCTION_P (decl1))
15804         {
15805           len--;
15806           args1 = TREE_CHAIN (args1);
15807         }
15808     }
15809
15810   /* If only one is a conversion operator, they are unordered.  */
15811   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
15812     return 0;
15813
15814   /* Consider the return type for a conversion function */
15815   if (DECL_CONV_FN_P (decl1))
15816     {
15817       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
15818       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
15819       len++;
15820     }
15821
15822   processing_template_decl++;
15823
15824   origs1 = args1;
15825   origs2 = args2;
15826
15827   while (len--
15828          /* Stop when an ellipsis is seen.  */
15829          && args1 != NULL_TREE && args2 != NULL_TREE)
15830     {
15831       tree arg1 = TREE_VALUE (args1);
15832       tree arg2 = TREE_VALUE (args2);
15833       int deduce1, deduce2;
15834       int quals1 = -1;
15835       int quals2 = -1;
15836
15837       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15838           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15839         {
15840           /* When both arguments are pack expansions, we need only
15841              unify the patterns themselves.  */
15842           arg1 = PACK_EXPANSION_PATTERN (arg1);
15843           arg2 = PACK_EXPANSION_PATTERN (arg2);
15844
15845           /* This is the last comparison we need to do.  */
15846           len = 0;
15847         }
15848
15849       if (TREE_CODE (arg1) == REFERENCE_TYPE)
15850         {
15851           arg1 = TREE_TYPE (arg1);
15852           quals1 = cp_type_quals (arg1);
15853         }
15854
15855       if (TREE_CODE (arg2) == REFERENCE_TYPE)
15856         {
15857           arg2 = TREE_TYPE (arg2);
15858           quals2 = cp_type_quals (arg2);
15859         }
15860
15861       if ((quals1 < 0) != (quals2 < 0))
15862         {
15863           /* Only of the args is a reference, see if we should apply
15864              array/function pointer decay to it.  This is not part of
15865              DR214, but is, IMHO, consistent with the deduction rules
15866              for the function call itself, and with our earlier
15867              implementation of the underspecified partial ordering
15868              rules.  (nathan).  */
15869           if (quals1 >= 0)
15870             {
15871               switch (TREE_CODE (arg1))
15872                 {
15873                 case ARRAY_TYPE:
15874                   arg1 = TREE_TYPE (arg1);
15875                   /* FALLTHROUGH. */
15876                 case FUNCTION_TYPE:
15877                   arg1 = build_pointer_type (arg1);
15878                   break;
15879
15880                 default:
15881                   break;
15882                 }
15883             }
15884           else
15885             {
15886               switch (TREE_CODE (arg2))
15887                 {
15888                 case ARRAY_TYPE:
15889                   arg2 = TREE_TYPE (arg2);
15890                   /* FALLTHROUGH. */
15891                 case FUNCTION_TYPE:
15892                   arg2 = build_pointer_type (arg2);
15893                   break;
15894
15895                 default:
15896                   break;
15897                 }
15898             }
15899         }
15900
15901       arg1 = TYPE_MAIN_VARIANT (arg1);
15902       arg2 = TYPE_MAIN_VARIANT (arg2);
15903
15904       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
15905         {
15906           int i, len2 = list_length (args2);
15907           tree parmvec = make_tree_vec (1);
15908           tree argvec = make_tree_vec (len2);
15909           tree ta = args2;
15910
15911           /* Setup the parameter vector, which contains only ARG1.  */
15912           TREE_VEC_ELT (parmvec, 0) = arg1;
15913
15914           /* Setup the argument vector, which contains the remaining
15915              arguments.  */
15916           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
15917             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15918
15919           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
15920                                            argvec, UNIFY_ALLOW_NONE, 
15921                                            /*call_args_p=*/false, 
15922                                            /*subr=*/0);
15923
15924           /* We cannot deduce in the other direction, because ARG1 is
15925              a pack expansion but ARG2 is not.  */
15926           deduce2 = 0;
15927         }
15928       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15929         {
15930           int i, len1 = list_length (args1);
15931           tree parmvec = make_tree_vec (1);
15932           tree argvec = make_tree_vec (len1);
15933           tree ta = args1;
15934
15935           /* Setup the parameter vector, which contains only ARG1.  */
15936           TREE_VEC_ELT (parmvec, 0) = arg2;
15937
15938           /* Setup the argument vector, which contains the remaining
15939              arguments.  */
15940           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
15941             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15942
15943           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
15944                                            argvec, UNIFY_ALLOW_NONE, 
15945                                            /*call_args_p=*/false, 
15946                                            /*subr=*/0);
15947
15948           /* We cannot deduce in the other direction, because ARG2 is
15949              a pack expansion but ARG1 is not.*/
15950           deduce1 = 0;
15951         }
15952
15953       else
15954         {
15955           /* The normal case, where neither argument is a pack
15956              expansion.  */
15957           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
15958           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
15959         }
15960
15961       /* If we couldn't deduce arguments for tparms1 to make arg1 match
15962          arg2, then arg2 is not as specialized as arg1.  */
15963       if (!deduce1)
15964         lose2 = true;
15965       if (!deduce2)
15966         lose1 = true;
15967
15968       /* "If, for a given type, deduction succeeds in both directions
15969          (i.e., the types are identical after the transformations above)
15970          and if the type from the argument template is more cv-qualified
15971          than the type from the parameter template (as described above)
15972          that type is considered to be more specialized than the other. If
15973          neither type is more cv-qualified than the other then neither type
15974          is more specialized than the other."  */
15975
15976       if (deduce1 && deduce2
15977           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
15978         {
15979           if ((quals1 & quals2) == quals2)
15980             lose2 = true;
15981           if ((quals1 & quals2) == quals1)
15982             lose1 = true;
15983         }
15984
15985       if (lose1 && lose2)
15986         /* We've failed to deduce something in either direction.
15987            These must be unordered.  */
15988         break;
15989
15990       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15991           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15992         /* We have already processed all of the arguments in our
15993            handing of the pack expansion type.  */
15994         len = 0;
15995
15996       args1 = TREE_CHAIN (args1);
15997       args2 = TREE_CHAIN (args2);
15998     }
15999
16000   /* "In most cases, all template parameters must have values in order for
16001      deduction to succeed, but for partial ordering purposes a template
16002      parameter may remain without a value provided it is not used in the
16003      types being used for partial ordering."
16004
16005      Thus, if we are missing any of the targs1 we need to substitute into
16006      origs1, then pat2 is not as specialized as pat1.  This can happen when
16007      there is a nondeduced context.  */
16008   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
16009     lose2 = true;
16010   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
16011     lose1 = true;
16012
16013   processing_template_decl--;
16014
16015   /* All things being equal, if the next argument is a pack expansion
16016      for one function but not for the other, prefer the
16017      non-variadic function.  FIXME this is bogus; see c++/41958.  */
16018   if (lose1 == lose2
16019       && args1 && TREE_VALUE (args1)
16020       && args2 && TREE_VALUE (args2))
16021     {
16022       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
16023       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
16024     }
16025
16026   if (lose1 == lose2)
16027     return 0;
16028   else if (!lose1)
16029     return 1;
16030   else
16031     return -1;
16032 }
16033
16034 /* Determine which of two partial specializations is more specialized.
16035
16036    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
16037    to the first partial specialization.  The TREE_VALUE is the
16038    innermost set of template parameters for the partial
16039    specialization.  PAT2 is similar, but for the second template.
16040
16041    Return 1 if the first partial specialization is more specialized;
16042    -1 if the second is more specialized; 0 if neither is more
16043    specialized.
16044
16045    See [temp.class.order] for information about determining which of
16046    two templates is more specialized.  */
16047
16048 static int
16049 more_specialized_class (tree pat1, tree pat2)
16050 {
16051   tree targs;
16052   tree tmpl1, tmpl2;
16053   int winner = 0;
16054   bool any_deductions = false;
16055
16056   tmpl1 = TREE_TYPE (pat1);
16057   tmpl2 = TREE_TYPE (pat2);
16058
16059   /* Just like what happens for functions, if we are ordering between
16060      different class template specializations, we may encounter dependent
16061      types in the arguments, and we need our dependency check functions
16062      to behave correctly.  */
16063   ++processing_template_decl;
16064   targs = get_class_bindings (TREE_VALUE (pat1),
16065                               CLASSTYPE_TI_ARGS (tmpl1),
16066                               CLASSTYPE_TI_ARGS (tmpl2));
16067   if (targs)
16068     {
16069       --winner;
16070       any_deductions = true;
16071     }
16072
16073   targs = get_class_bindings (TREE_VALUE (pat2),
16074                               CLASSTYPE_TI_ARGS (tmpl2),
16075                               CLASSTYPE_TI_ARGS (tmpl1));
16076   if (targs)
16077     {
16078       ++winner;
16079       any_deductions = true;
16080     }
16081   --processing_template_decl;
16082
16083   /* In the case of a tie where at least one of the class templates
16084      has a parameter pack at the end, the template with the most
16085      non-packed parameters wins.  */
16086   if (winner == 0
16087       && any_deductions
16088       && (template_args_variadic_p (TREE_PURPOSE (pat1))
16089           || template_args_variadic_p (TREE_PURPOSE (pat2))))
16090     {
16091       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
16092       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
16093       int len1 = TREE_VEC_LENGTH (args1);
16094       int len2 = TREE_VEC_LENGTH (args2);
16095
16096       /* We don't count the pack expansion at the end.  */
16097       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
16098         --len1;
16099       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
16100         --len2;
16101
16102       if (len1 > len2)
16103         return 1;
16104       else if (len1 < len2)
16105         return -1;
16106     }
16107
16108   return winner;
16109 }
16110
16111 /* Return the template arguments that will produce the function signature
16112    DECL from the function template FN, with the explicit template
16113    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
16114    also match.  Return NULL_TREE if no satisfactory arguments could be
16115    found.  */
16116
16117 static tree
16118 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
16119 {
16120   int ntparms = DECL_NTPARMS (fn);
16121   tree targs = make_tree_vec (ntparms);
16122   tree decl_type;
16123   tree decl_arg_types;
16124   tree *args;
16125   unsigned int nargs, ix;
16126   tree arg;
16127
16128   /* Substitute the explicit template arguments into the type of DECL.
16129      The call to fn_type_unification will handle substitution into the
16130      FN.  */
16131   decl_type = TREE_TYPE (decl);
16132   if (explicit_args && uses_template_parms (decl_type))
16133     {
16134       tree tmpl;
16135       tree converted_args;
16136
16137       if (DECL_TEMPLATE_INFO (decl))
16138         tmpl = DECL_TI_TEMPLATE (decl);
16139       else
16140         /* We can get here for some invalid specializations.  */
16141         return NULL_TREE;
16142
16143       converted_args
16144         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
16145                                  explicit_args, NULL_TREE,
16146                                  tf_none,
16147                                  /*require_all_args=*/false,
16148                                  /*use_default_args=*/false);
16149       if (converted_args == error_mark_node)
16150         return NULL_TREE;
16151
16152       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
16153       if (decl_type == error_mark_node)
16154         return NULL_TREE;
16155     }
16156
16157   /* Never do unification on the 'this' parameter.  */
16158   decl_arg_types = skip_artificial_parms_for (decl, 
16159                                               TYPE_ARG_TYPES (decl_type));
16160
16161   nargs = list_length (decl_arg_types);
16162   args = XALLOCAVEC (tree, nargs);
16163   for (arg = decl_arg_types, ix = 0;
16164        arg != NULL_TREE && arg != void_list_node;
16165        arg = TREE_CHAIN (arg), ++ix)
16166     args[ix] = TREE_VALUE (arg);
16167
16168   if (fn_type_unification (fn, explicit_args, targs,
16169                            args, ix,
16170                            (check_rettype || DECL_CONV_FN_P (fn)
16171                             ? TREE_TYPE (decl_type) : NULL_TREE),
16172                            DEDUCE_EXACT, LOOKUP_NORMAL))
16173     return NULL_TREE;
16174
16175   return targs;
16176 }
16177
16178 /* Return the innermost template arguments that, when applied to a
16179    template specialization whose innermost template parameters are
16180    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
16181    ARGS.
16182
16183    For example, suppose we have:
16184
16185      template <class T, class U> struct S {};
16186      template <class T> struct S<T*, int> {};
16187
16188    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
16189    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
16190    int}.  The resulting vector will be {double}, indicating that `T'
16191    is bound to `double'.  */
16192
16193 static tree
16194 get_class_bindings (tree tparms, tree spec_args, tree args)
16195 {
16196   int i, ntparms = TREE_VEC_LENGTH (tparms);
16197   tree deduced_args;
16198   tree innermost_deduced_args;
16199
16200   innermost_deduced_args = make_tree_vec (ntparms);
16201   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
16202     {
16203       deduced_args = copy_node (args);
16204       SET_TMPL_ARGS_LEVEL (deduced_args,
16205                            TMPL_ARGS_DEPTH (deduced_args),
16206                            innermost_deduced_args);
16207     }
16208   else
16209     deduced_args = innermost_deduced_args;
16210
16211   if (unify (tparms, deduced_args,
16212              INNERMOST_TEMPLATE_ARGS (spec_args),
16213              INNERMOST_TEMPLATE_ARGS (args),
16214              UNIFY_ALLOW_NONE))
16215     return NULL_TREE;
16216
16217   for (i =  0; i < ntparms; ++i)
16218     if (! TREE_VEC_ELT (innermost_deduced_args, i))
16219       return NULL_TREE;
16220
16221   /* Verify that nondeduced template arguments agree with the type
16222      obtained from argument deduction.
16223
16224      For example:
16225
16226        struct A { typedef int X; };
16227        template <class T, class U> struct C {};
16228        template <class T> struct C<T, typename T::X> {};
16229
16230      Then with the instantiation `C<A, int>', we can deduce that
16231      `T' is `A' but unify () does not check whether `typename T::X'
16232      is `int'.  */
16233   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
16234   if (spec_args == error_mark_node
16235       /* We only need to check the innermost arguments; the other
16236          arguments will always agree.  */
16237       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
16238                               INNERMOST_TEMPLATE_ARGS (args)))
16239     return NULL_TREE;
16240
16241   /* Now that we have bindings for all of the template arguments,
16242      ensure that the arguments deduced for the template template
16243      parameters have compatible template parameter lists.  See the use
16244      of template_template_parm_bindings_ok_p in fn_type_unification
16245      for more information.  */
16246   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
16247     return NULL_TREE;
16248
16249   return deduced_args;
16250 }
16251
16252 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
16253    Return the TREE_LIST node with the most specialized template, if
16254    any.  If there is no most specialized template, the error_mark_node
16255    is returned.
16256
16257    Note that this function does not look at, or modify, the
16258    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
16259    returned is one of the elements of INSTANTIATIONS, callers may
16260    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
16261    and retrieve it from the value returned.  */
16262
16263 tree
16264 most_specialized_instantiation (tree templates)
16265 {
16266   tree fn, champ;
16267
16268   ++processing_template_decl;
16269
16270   champ = templates;
16271   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
16272     {
16273       int fate = 0;
16274
16275       if (get_bindings (TREE_VALUE (champ),
16276                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
16277                         NULL_TREE, /*check_ret=*/false))
16278         fate--;
16279
16280       if (get_bindings (TREE_VALUE (fn),
16281                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
16282                         NULL_TREE, /*check_ret=*/false))
16283         fate++;
16284
16285       if (fate == -1)
16286         champ = fn;
16287       else if (!fate)
16288         {
16289           /* Equally specialized, move to next function.  If there
16290              is no next function, nothing's most specialized.  */
16291           fn = TREE_CHAIN (fn);
16292           champ = fn;
16293           if (!fn)
16294             break;
16295         }
16296     }
16297
16298   if (champ)
16299     /* Now verify that champ is better than everything earlier in the
16300        instantiation list.  */
16301     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
16302       if (get_bindings (TREE_VALUE (champ),
16303                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
16304                         NULL_TREE, /*check_ret=*/false)
16305           || !get_bindings (TREE_VALUE (fn),
16306                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
16307                             NULL_TREE, /*check_ret=*/false))
16308         {
16309           champ = NULL_TREE;
16310           break;
16311         }
16312
16313   processing_template_decl--;
16314
16315   if (!champ)
16316     return error_mark_node;
16317
16318   return champ;
16319 }
16320
16321 /* If DECL is a specialization of some template, return the most
16322    general such template.  Otherwise, returns NULL_TREE.
16323
16324    For example, given:
16325
16326      template <class T> struct S { template <class U> void f(U); };
16327
16328    if TMPL is `template <class U> void S<int>::f(U)' this will return
16329    the full template.  This function will not trace past partial
16330    specializations, however.  For example, given in addition:
16331
16332      template <class T> struct S<T*> { template <class U> void f(U); };
16333
16334    if TMPL is `template <class U> void S<int*>::f(U)' this will return
16335    `template <class T> template <class U> S<T*>::f(U)'.  */
16336
16337 tree
16338 most_general_template (tree decl)
16339 {
16340   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
16341      an immediate specialization.  */
16342   if (TREE_CODE (decl) == FUNCTION_DECL)
16343     {
16344       if (DECL_TEMPLATE_INFO (decl)) {
16345         decl = DECL_TI_TEMPLATE (decl);
16346
16347         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
16348            template friend.  */
16349         if (TREE_CODE (decl) != TEMPLATE_DECL)
16350           return NULL_TREE;
16351       } else
16352         return NULL_TREE;
16353     }
16354
16355   /* Look for more and more general templates.  */
16356   while (DECL_TEMPLATE_INFO (decl))
16357     {
16358       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
16359          (See cp-tree.h for details.)  */
16360       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
16361         break;
16362
16363       if (CLASS_TYPE_P (TREE_TYPE (decl))
16364           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
16365         break;
16366
16367       /* Stop if we run into an explicitly specialized class template.  */
16368       if (!DECL_NAMESPACE_SCOPE_P (decl)
16369           && DECL_CONTEXT (decl)
16370           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
16371         break;
16372
16373       decl = DECL_TI_TEMPLATE (decl);
16374     }
16375
16376   return decl;
16377 }
16378
16379 /* Return the most specialized of the class template partial
16380    specializations of TMPL which can produce TYPE, a specialization of
16381    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
16382    a _TYPE node corresponding to the partial specialization, while the
16383    TREE_PURPOSE is the set of template arguments that must be
16384    substituted into the TREE_TYPE in order to generate TYPE.
16385
16386    If the choice of partial specialization is ambiguous, a diagnostic
16387    is issued, and the error_mark_node is returned.  If there are no
16388    partial specializations of TMPL matching TYPE, then NULL_TREE is
16389    returned.  */
16390
16391 static tree
16392 most_specialized_class (tree type, tree tmpl, tsubst_flags_t complain)
16393 {
16394   tree list = NULL_TREE;
16395   tree t;
16396   tree champ;
16397   int fate;
16398   bool ambiguous_p;
16399   tree args;
16400   tree outer_args = NULL_TREE;
16401
16402   tmpl = most_general_template (tmpl);
16403   args = CLASSTYPE_TI_ARGS (type);
16404
16405   /* For determining which partial specialization to use, only the
16406      innermost args are interesting.  */
16407   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
16408     {
16409       outer_args = strip_innermost_template_args (args, 1);
16410       args = INNERMOST_TEMPLATE_ARGS (args);
16411     }
16412
16413   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
16414     {
16415       tree partial_spec_args;
16416       tree spec_args;
16417       tree parms = TREE_VALUE (t);
16418
16419       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
16420
16421       ++processing_template_decl;
16422
16423       if (outer_args)
16424         {
16425           int i;
16426
16427           /* Discard the outer levels of args, and then substitute in the
16428              template args from the enclosing class.  */
16429           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
16430           partial_spec_args = tsubst_template_args
16431             (partial_spec_args, outer_args, tf_none, NULL_TREE);
16432
16433           /* PARMS already refers to just the innermost parms, but the
16434              template parms in partial_spec_args had their levels lowered
16435              by tsubst, so we need to do the same for the parm list.  We
16436              can't just tsubst the TREE_VEC itself, as tsubst wants to
16437              treat a TREE_VEC as an argument vector.  */
16438           parms = copy_node (parms);
16439           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
16440             TREE_VEC_ELT (parms, i) =
16441               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
16442
16443         }
16444
16445       partial_spec_args =
16446           coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
16447                                  add_to_template_args (outer_args,
16448                                                        partial_spec_args),
16449                                  tmpl, tf_none,
16450                                  /*require_all_args=*/true,
16451                                  /*use_default_args=*/true);
16452
16453       --processing_template_decl;
16454
16455       if (partial_spec_args == error_mark_node)
16456         return error_mark_node;
16457
16458       spec_args = get_class_bindings (parms,
16459                                       partial_spec_args,
16460                                       args);
16461       if (spec_args)
16462         {
16463           if (outer_args)
16464             spec_args = add_to_template_args (outer_args, spec_args);
16465           list = tree_cons (spec_args, TREE_VALUE (t), list);
16466           TREE_TYPE (list) = TREE_TYPE (t);
16467         }
16468     }
16469
16470   if (! list)
16471     return NULL_TREE;
16472
16473   ambiguous_p = false;
16474   t = list;
16475   champ = t;
16476   t = TREE_CHAIN (t);
16477   for (; t; t = TREE_CHAIN (t))
16478     {
16479       fate = more_specialized_class (champ, t);
16480       if (fate == 1)
16481         ;
16482       else
16483         {
16484           if (fate == 0)
16485             {
16486               t = TREE_CHAIN (t);
16487               if (! t)
16488                 {
16489                   ambiguous_p = true;
16490                   break;
16491                 }
16492             }
16493           champ = t;
16494         }
16495     }
16496
16497   if (!ambiguous_p)
16498     for (t = list; t && t != champ; t = TREE_CHAIN (t))
16499       {
16500         fate = more_specialized_class (champ, t);
16501         if (fate != 1)
16502           {
16503             ambiguous_p = true;
16504             break;
16505           }
16506       }
16507
16508   if (ambiguous_p)
16509     {
16510       const char *str;
16511       char *spaces = NULL;
16512       if (!(complain & tf_error))
16513         return error_mark_node;
16514       error ("ambiguous class template instantiation for %q#T", type);
16515       str = TREE_CHAIN (list) ? _("candidates are:") : _("candidate is:");
16516       for (t = list; t; t = TREE_CHAIN (t))
16517         {
16518           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
16519           spaces = spaces ? spaces : get_spaces (str);
16520         }
16521       free (spaces);
16522       return error_mark_node;
16523     }
16524
16525   return champ;
16526 }
16527
16528 /* Explicitly instantiate DECL.  */
16529
16530 void
16531 do_decl_instantiation (tree decl, tree storage)
16532 {
16533   tree result = NULL_TREE;
16534   int extern_p = 0;
16535
16536   if (!decl || decl == error_mark_node)
16537     /* An error occurred, for which grokdeclarator has already issued
16538        an appropriate message.  */
16539     return;
16540   else if (! DECL_LANG_SPECIFIC (decl))
16541     {
16542       error ("explicit instantiation of non-template %q#D", decl);
16543       return;
16544     }
16545   else if (TREE_CODE (decl) == VAR_DECL)
16546     {
16547       /* There is an asymmetry here in the way VAR_DECLs and
16548          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
16549          the latter, the DECL we get back will be marked as a
16550          template instantiation, and the appropriate
16551          DECL_TEMPLATE_INFO will be set up.  This does not happen for
16552          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
16553          should handle VAR_DECLs as it currently handles
16554          FUNCTION_DECLs.  */
16555       if (!DECL_CLASS_SCOPE_P (decl))
16556         {
16557           error ("%qD is not a static data member of a class template", decl);
16558           return;
16559         }
16560       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
16561       if (!result || TREE_CODE (result) != VAR_DECL)
16562         {
16563           error ("no matching template for %qD found", decl);
16564           return;
16565         }
16566       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
16567         {
16568           error ("type %qT for explicit instantiation %qD does not match "
16569                  "declared type %qT", TREE_TYPE (result), decl,
16570                  TREE_TYPE (decl));
16571           return;
16572         }
16573     }
16574   else if (TREE_CODE (decl) != FUNCTION_DECL)
16575     {
16576       error ("explicit instantiation of %q#D", decl);
16577       return;
16578     }
16579   else
16580     result = decl;
16581
16582   /* Check for various error cases.  Note that if the explicit
16583      instantiation is valid the RESULT will currently be marked as an
16584      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
16585      until we get here.  */
16586
16587   if (DECL_TEMPLATE_SPECIALIZATION (result))
16588     {
16589       /* DR 259 [temp.spec].
16590
16591          Both an explicit instantiation and a declaration of an explicit
16592          specialization shall not appear in a program unless the explicit
16593          instantiation follows a declaration of the explicit specialization.
16594
16595          For a given set of template parameters, if an explicit
16596          instantiation of a template appears after a declaration of an
16597          explicit specialization for that template, the explicit
16598          instantiation has no effect.  */
16599       return;
16600     }
16601   else if (DECL_EXPLICIT_INSTANTIATION (result))
16602     {
16603       /* [temp.spec]
16604
16605          No program shall explicitly instantiate any template more
16606          than once.
16607
16608          We check DECL_NOT_REALLY_EXTERN so as not to complain when
16609          the first instantiation was `extern' and the second is not,
16610          and EXTERN_P for the opposite case.  */
16611       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
16612         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
16613       /* If an "extern" explicit instantiation follows an ordinary
16614          explicit instantiation, the template is instantiated.  */
16615       if (extern_p)
16616         return;
16617     }
16618   else if (!DECL_IMPLICIT_INSTANTIATION (result))
16619     {
16620       error ("no matching template for %qD found", result);
16621       return;
16622     }
16623   else if (!DECL_TEMPLATE_INFO (result))
16624     {
16625       permerror (input_location, "explicit instantiation of non-template %q#D", result);
16626       return;
16627     }
16628
16629   if (storage == NULL_TREE)
16630     ;
16631   else if (storage == ridpointers[(int) RID_EXTERN])
16632     {
16633       if (!in_system_header && (cxx_dialect == cxx98))
16634         pedwarn (input_location, OPT_pedantic, 
16635                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
16636                  "instantiations");
16637       extern_p = 1;
16638     }
16639   else
16640     error ("storage class %qD applied to template instantiation", storage);
16641
16642   check_explicit_instantiation_namespace (result);
16643   mark_decl_instantiated (result, extern_p);
16644   if (! extern_p)
16645     instantiate_decl (result, /*defer_ok=*/1,
16646                       /*expl_inst_class_mem_p=*/false);
16647 }
16648
16649 static void
16650 mark_class_instantiated (tree t, int extern_p)
16651 {
16652   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
16653   SET_CLASSTYPE_INTERFACE_KNOWN (t);
16654   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
16655   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
16656   if (! extern_p)
16657     {
16658       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
16659       rest_of_type_compilation (t, 1);
16660     }
16661 }
16662
16663 /* Called from do_type_instantiation through binding_table_foreach to
16664    do recursive instantiation for the type bound in ENTRY.  */
16665 static void
16666 bt_instantiate_type_proc (binding_entry entry, void *data)
16667 {
16668   tree storage = *(tree *) data;
16669
16670   if (MAYBE_CLASS_TYPE_P (entry->type)
16671       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
16672     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
16673 }
16674
16675 /* Called from do_type_instantiation to instantiate a member
16676    (a member function or a static member variable) of an
16677    explicitly instantiated class template.  */
16678 static void
16679 instantiate_class_member (tree decl, int extern_p)
16680 {
16681   mark_decl_instantiated (decl, extern_p);
16682   if (! extern_p)
16683     instantiate_decl (decl, /*defer_ok=*/1,
16684                       /*expl_inst_class_mem_p=*/true);
16685 }
16686
16687 /* Perform an explicit instantiation of template class T.  STORAGE, if
16688    non-null, is the RID for extern, inline or static.  COMPLAIN is
16689    nonzero if this is called from the parser, zero if called recursively,
16690    since the standard is unclear (as detailed below).  */
16691
16692 void
16693 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
16694 {
16695   int extern_p = 0;
16696   int nomem_p = 0;
16697   int static_p = 0;
16698   int previous_instantiation_extern_p = 0;
16699
16700   if (TREE_CODE (t) == TYPE_DECL)
16701     t = TREE_TYPE (t);
16702
16703   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
16704     {
16705       error ("explicit instantiation of non-template type %qT", t);
16706       return;
16707     }
16708
16709   complete_type (t);
16710
16711   if (!COMPLETE_TYPE_P (t))
16712     {
16713       if (complain & tf_error)
16714         error ("explicit instantiation of %q#T before definition of template",
16715                t);
16716       return;
16717     }
16718
16719   if (storage != NULL_TREE)
16720     {
16721       if (!in_system_header)
16722         {
16723           if (storage == ridpointers[(int) RID_EXTERN])
16724             {
16725               if (cxx_dialect == cxx98)
16726                 pedwarn (input_location, OPT_pedantic, 
16727                          "ISO C++ 1998 forbids the use of %<extern%> on "
16728                          "explicit instantiations");
16729             }
16730           else
16731             pedwarn (input_location, OPT_pedantic, 
16732                      "ISO C++ forbids the use of %qE"
16733                      " on explicit instantiations", storage);
16734         }
16735
16736       if (storage == ridpointers[(int) RID_INLINE])
16737         nomem_p = 1;
16738       else if (storage == ridpointers[(int) RID_EXTERN])
16739         extern_p = 1;
16740       else if (storage == ridpointers[(int) RID_STATIC])
16741         static_p = 1;
16742       else
16743         {
16744           error ("storage class %qD applied to template instantiation",
16745                  storage);
16746           extern_p = 0;
16747         }
16748     }
16749
16750   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
16751     {
16752       /* DR 259 [temp.spec].
16753
16754          Both an explicit instantiation and a declaration of an explicit
16755          specialization shall not appear in a program unless the explicit
16756          instantiation follows a declaration of the explicit specialization.
16757
16758          For a given set of template parameters, if an explicit
16759          instantiation of a template appears after a declaration of an
16760          explicit specialization for that template, the explicit
16761          instantiation has no effect.  */
16762       return;
16763     }
16764   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
16765     {
16766       /* [temp.spec]
16767
16768          No program shall explicitly instantiate any template more
16769          than once.
16770
16771          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
16772          instantiation was `extern'.  If EXTERN_P then the second is.
16773          These cases are OK.  */
16774       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
16775
16776       if (!previous_instantiation_extern_p && !extern_p
16777           && (complain & tf_error))
16778         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
16779
16780       /* If we've already instantiated the template, just return now.  */
16781       if (!CLASSTYPE_INTERFACE_ONLY (t))
16782         return;
16783     }
16784
16785   check_explicit_instantiation_namespace (TYPE_NAME (t));
16786   mark_class_instantiated (t, extern_p);
16787
16788   if (nomem_p)
16789     return;
16790
16791   {
16792     tree tmp;
16793
16794     /* In contrast to implicit instantiation, where only the
16795        declarations, and not the definitions, of members are
16796        instantiated, we have here:
16797
16798          [temp.explicit]
16799
16800          The explicit instantiation of a class template specialization
16801          implies the instantiation of all of its members not
16802          previously explicitly specialized in the translation unit
16803          containing the explicit instantiation.
16804
16805        Of course, we can't instantiate member template classes, since
16806        we don't have any arguments for them.  Note that the standard
16807        is unclear on whether the instantiation of the members are
16808        *explicit* instantiations or not.  However, the most natural
16809        interpretation is that it should be an explicit instantiation.  */
16810
16811     if (! static_p)
16812       for (tmp = TYPE_METHODS (t); tmp; tmp = DECL_CHAIN (tmp))
16813         if (TREE_CODE (tmp) == FUNCTION_DECL
16814             && DECL_TEMPLATE_INSTANTIATION (tmp))
16815           instantiate_class_member (tmp, extern_p);
16816
16817     for (tmp = TYPE_FIELDS (t); tmp; tmp = DECL_CHAIN (tmp))
16818       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
16819         instantiate_class_member (tmp, extern_p);
16820
16821     if (CLASSTYPE_NESTED_UTDS (t))
16822       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
16823                              bt_instantiate_type_proc, &storage);
16824   }
16825 }
16826
16827 /* Given a function DECL, which is a specialization of TMPL, modify
16828    DECL to be a re-instantiation of TMPL with the same template
16829    arguments.  TMPL should be the template into which tsubst'ing
16830    should occur for DECL, not the most general template.
16831
16832    One reason for doing this is a scenario like this:
16833
16834      template <class T>
16835      void f(const T&, int i);
16836
16837      void g() { f(3, 7); }
16838
16839      template <class T>
16840      void f(const T& t, const int i) { }
16841
16842    Note that when the template is first instantiated, with
16843    instantiate_template, the resulting DECL will have no name for the
16844    first parameter, and the wrong type for the second.  So, when we go
16845    to instantiate the DECL, we regenerate it.  */
16846
16847 static void
16848 regenerate_decl_from_template (tree decl, tree tmpl)
16849 {
16850   /* The arguments used to instantiate DECL, from the most general
16851      template.  */
16852   tree args;
16853   tree code_pattern;
16854
16855   args = DECL_TI_ARGS (decl);
16856   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
16857
16858   /* Make sure that we can see identifiers, and compute access
16859      correctly.  */
16860   push_access_scope (decl);
16861
16862   if (TREE_CODE (decl) == FUNCTION_DECL)
16863     {
16864       tree decl_parm;
16865       tree pattern_parm;
16866       tree specs;
16867       int args_depth;
16868       int parms_depth;
16869
16870       args_depth = TMPL_ARGS_DEPTH (args);
16871       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
16872       if (args_depth > parms_depth)
16873         args = get_innermost_template_args (args, parms_depth);
16874
16875       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
16876                                               args, tf_error, NULL_TREE);
16877       if (specs)
16878         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
16879                                                     specs);
16880
16881       /* Merge parameter declarations.  */
16882       decl_parm = skip_artificial_parms_for (decl,
16883                                              DECL_ARGUMENTS (decl));
16884       pattern_parm
16885         = skip_artificial_parms_for (code_pattern,
16886                                      DECL_ARGUMENTS (code_pattern));
16887       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
16888         {
16889           tree parm_type;
16890           tree attributes;
16891           
16892           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16893             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
16894           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
16895                               NULL_TREE);
16896           parm_type = type_decays_to (parm_type);
16897           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16898             TREE_TYPE (decl_parm) = parm_type;
16899           attributes = DECL_ATTRIBUTES (pattern_parm);
16900           if (DECL_ATTRIBUTES (decl_parm) != attributes)
16901             {
16902               DECL_ATTRIBUTES (decl_parm) = attributes;
16903               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16904             }
16905           decl_parm = DECL_CHAIN (decl_parm);
16906           pattern_parm = DECL_CHAIN (pattern_parm);
16907         }
16908       /* Merge any parameters that match with the function parameter
16909          pack.  */
16910       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
16911         {
16912           int i, len;
16913           tree expanded_types;
16914           /* Expand the TYPE_PACK_EXPANSION that provides the types for
16915              the parameters in this function parameter pack.  */
16916           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
16917                                                  args, tf_error, NULL_TREE);
16918           len = TREE_VEC_LENGTH (expanded_types);
16919           for (i = 0; i < len; i++)
16920             {
16921               tree parm_type;
16922               tree attributes;
16923           
16924               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16925                 /* Rename the parameter to include the index.  */
16926                 DECL_NAME (decl_parm) = 
16927                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
16928               parm_type = TREE_VEC_ELT (expanded_types, i);
16929               parm_type = type_decays_to (parm_type);
16930               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16931                 TREE_TYPE (decl_parm) = parm_type;
16932               attributes = DECL_ATTRIBUTES (pattern_parm);
16933               if (DECL_ATTRIBUTES (decl_parm) != attributes)
16934                 {
16935                   DECL_ATTRIBUTES (decl_parm) = attributes;
16936                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16937                 }
16938               decl_parm = DECL_CHAIN (decl_parm);
16939             }
16940         }
16941       /* Merge additional specifiers from the CODE_PATTERN.  */
16942       if (DECL_DECLARED_INLINE_P (code_pattern)
16943           && !DECL_DECLARED_INLINE_P (decl))
16944         DECL_DECLARED_INLINE_P (decl) = 1;
16945     }
16946   else if (TREE_CODE (decl) == VAR_DECL)
16947     {
16948       DECL_INITIAL (decl) =
16949         tsubst_expr (DECL_INITIAL (code_pattern), args,
16950                      tf_error, DECL_TI_TEMPLATE (decl),
16951                      /*integral_constant_expression_p=*/false);
16952       if (VAR_HAD_UNKNOWN_BOUND (decl))
16953         TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
16954                                    tf_error, DECL_TI_TEMPLATE (decl));
16955     }
16956   else
16957     gcc_unreachable ();
16958
16959   pop_access_scope (decl);
16960 }
16961
16962 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
16963    substituted to get DECL.  */
16964
16965 tree
16966 template_for_substitution (tree decl)
16967 {
16968   tree tmpl = DECL_TI_TEMPLATE (decl);
16969
16970   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
16971      for the instantiation.  This is not always the most general
16972      template.  Consider, for example:
16973
16974         template <class T>
16975         struct S { template <class U> void f();
16976                    template <> void f<int>(); };
16977
16978      and an instantiation of S<double>::f<int>.  We want TD to be the
16979      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
16980   while (/* An instantiation cannot have a definition, so we need a
16981             more general template.  */
16982          DECL_TEMPLATE_INSTANTIATION (tmpl)
16983            /* We must also deal with friend templates.  Given:
16984
16985                 template <class T> struct S {
16986                   template <class U> friend void f() {};
16987                 };
16988
16989               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
16990               so far as the language is concerned, but that's still
16991               where we get the pattern for the instantiation from.  On
16992               other hand, if the definition comes outside the class, say:
16993
16994                 template <class T> struct S {
16995                   template <class U> friend void f();
16996                 };
16997                 template <class U> friend void f() {}
16998
16999               we don't need to look any further.  That's what the check for
17000               DECL_INITIAL is for.  */
17001           || (TREE_CODE (decl) == FUNCTION_DECL
17002               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
17003               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
17004     {
17005       /* The present template, TD, should not be a definition.  If it
17006          were a definition, we should be using it!  Note that we
17007          cannot restructure the loop to just keep going until we find
17008          a template with a definition, since that might go too far if
17009          a specialization was declared, but not defined.  */
17010       gcc_assert (TREE_CODE (decl) != VAR_DECL
17011                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
17012
17013       /* Fetch the more general template.  */
17014       tmpl = DECL_TI_TEMPLATE (tmpl);
17015     }
17016
17017   return tmpl;
17018 }
17019
17020 /* Returns true if we need to instantiate this template instance even if we
17021    know we aren't going to emit it..  */
17022
17023 bool
17024 always_instantiate_p (tree decl)
17025 {
17026   /* We always instantiate inline functions so that we can inline them.  An
17027      explicit instantiation declaration prohibits implicit instantiation of
17028      non-inline functions.  With high levels of optimization, we would
17029      normally inline non-inline functions -- but we're not allowed to do
17030      that for "extern template" functions.  Therefore, we check
17031      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
17032   return ((TREE_CODE (decl) == FUNCTION_DECL
17033            && DECL_DECLARED_INLINE_P (decl))
17034           /* And we need to instantiate static data members so that
17035              their initializers are available in integral constant
17036              expressions.  */
17037           || (TREE_CODE (decl) == VAR_DECL
17038               && decl_maybe_constant_var_p (decl)));
17039 }
17040
17041 /* Produce the definition of D, a _DECL generated from a template.  If
17042    DEFER_OK is nonzero, then we don't have to actually do the
17043    instantiation now; we just have to do it sometime.  Normally it is
17044    an error if this is an explicit instantiation but D is undefined.
17045    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
17046    explicitly instantiated class template.  */
17047
17048 tree
17049 instantiate_decl (tree d, int defer_ok,
17050                   bool expl_inst_class_mem_p)
17051 {
17052   tree tmpl = DECL_TI_TEMPLATE (d);
17053   tree gen_args;
17054   tree args;
17055   tree td;
17056   tree code_pattern;
17057   tree spec;
17058   tree gen_tmpl;
17059   bool pattern_defined;
17060   int need_push;
17061   location_t saved_loc = input_location;
17062   bool external_p;
17063
17064   /* This function should only be used to instantiate templates for
17065      functions and static member variables.  */
17066   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
17067               || TREE_CODE (d) == VAR_DECL);
17068
17069   /* Variables are never deferred; if instantiation is required, they
17070      are instantiated right away.  That allows for better code in the
17071      case that an expression refers to the value of the variable --
17072      if the variable has a constant value the referring expression can
17073      take advantage of that fact.  */
17074   if (TREE_CODE (d) == VAR_DECL
17075       || DECL_DECLARED_CONSTEXPR_P (d))
17076     defer_ok = 0;
17077
17078   /* Don't instantiate cloned functions.  Instead, instantiate the
17079      functions they cloned.  */
17080   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
17081     d = DECL_CLONED_FUNCTION (d);
17082
17083   if (DECL_TEMPLATE_INSTANTIATED (d)
17084       || DECL_TEMPLATE_SPECIALIZATION (d))
17085     /* D has already been instantiated or explicitly specialized, so
17086        there's nothing for us to do here.
17087
17088        It might seem reasonable to check whether or not D is an explicit
17089        instantiation, and, if so, stop here.  But when an explicit
17090        instantiation is deferred until the end of the compilation,
17091        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
17092        the instantiation.  */
17093     return d;
17094
17095   /* Check to see whether we know that this template will be
17096      instantiated in some other file, as with "extern template"
17097      extension.  */
17098   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
17099
17100   /* In general, we do not instantiate such templates.  */
17101   if (external_p && !always_instantiate_p (d))
17102     return d;
17103
17104   gen_tmpl = most_general_template (tmpl);
17105   gen_args = DECL_TI_ARGS (d);
17106
17107   if (tmpl != gen_tmpl)
17108     /* We should already have the extra args.  */
17109     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
17110                 == TMPL_ARGS_DEPTH (gen_args));
17111   /* And what's in the hash table should match D.  */
17112   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
17113               || spec == NULL_TREE);
17114
17115   /* This needs to happen before any tsubsting.  */
17116   if (! push_tinst_level (d))
17117     return d;
17118
17119   timevar_push (TV_PARSE);
17120
17121   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
17122      for the instantiation.  */
17123   td = template_for_substitution (d);
17124   code_pattern = DECL_TEMPLATE_RESULT (td);
17125
17126   /* We should never be trying to instantiate a member of a class
17127      template or partial specialization.  */
17128   gcc_assert (d != code_pattern);
17129
17130   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
17131       || DECL_TEMPLATE_SPECIALIZATION (td))
17132     /* In the case of a friend template whose definition is provided
17133        outside the class, we may have too many arguments.  Drop the
17134        ones we don't need.  The same is true for specializations.  */
17135     args = get_innermost_template_args
17136       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
17137   else
17138     args = gen_args;
17139
17140   if (TREE_CODE (d) == FUNCTION_DECL)
17141     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
17142   else
17143     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
17144
17145   /* We may be in the middle of deferred access check.  Disable it now.  */
17146   push_deferring_access_checks (dk_no_deferred);
17147
17148   /* Unless an explicit instantiation directive has already determined
17149      the linkage of D, remember that a definition is available for
17150      this entity.  */
17151   if (pattern_defined
17152       && !DECL_INTERFACE_KNOWN (d)
17153       && !DECL_NOT_REALLY_EXTERN (d))
17154     mark_definable (d);
17155
17156   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
17157   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
17158   input_location = DECL_SOURCE_LOCATION (d);
17159
17160   /* If D is a member of an explicitly instantiated class template,
17161      and no definition is available, treat it like an implicit
17162      instantiation.  */
17163   if (!pattern_defined && expl_inst_class_mem_p
17164       && DECL_EXPLICIT_INSTANTIATION (d))
17165     {
17166       DECL_NOT_REALLY_EXTERN (d) = 0;
17167       DECL_INTERFACE_KNOWN (d) = 0;
17168       SET_DECL_IMPLICIT_INSTANTIATION (d);
17169     }
17170
17171   /* Recheck the substitutions to obtain any warning messages
17172      about ignoring cv qualifiers.  Don't do this for artificial decls,
17173      as it breaks the context-sensitive substitution for lambda op(). */
17174   if (!defer_ok && !DECL_ARTIFICIAL (d))
17175     {
17176       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
17177       tree type = TREE_TYPE (gen);
17178
17179       /* Make sure that we can see identifiers, and compute access
17180          correctly.  D is already the target FUNCTION_DECL with the
17181          right context.  */
17182       push_access_scope (d);
17183
17184       if (TREE_CODE (gen) == FUNCTION_DECL)
17185         {
17186           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
17187           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
17188                                           d);
17189           /* Don't simply tsubst the function type, as that will give
17190              duplicate warnings about poor parameter qualifications.
17191              The function arguments are the same as the decl_arguments
17192              without the top level cv qualifiers.  */
17193           type = TREE_TYPE (type);
17194         }
17195       tsubst (type, gen_args, tf_warning_or_error, d);
17196
17197       pop_access_scope (d);
17198     }
17199
17200   /* Defer all other templates, unless we have been explicitly
17201      forbidden from doing so.  */
17202   if (/* If there is no definition, we cannot instantiate the
17203          template.  */
17204       ! pattern_defined
17205       /* If it's OK to postpone instantiation, do so.  */
17206       || defer_ok
17207       /* If this is a static data member that will be defined
17208          elsewhere, we don't want to instantiate the entire data
17209          member, but we do want to instantiate the initializer so that
17210          we can substitute that elsewhere.  */
17211       || (external_p && TREE_CODE (d) == VAR_DECL))
17212     {
17213       /* The definition of the static data member is now required so
17214          we must substitute the initializer.  */
17215       if (TREE_CODE (d) == VAR_DECL
17216           && !DECL_INITIAL (d)
17217           && DECL_INITIAL (code_pattern))
17218         {
17219           tree ns;
17220           tree init;
17221           bool const_init = false;
17222
17223           ns = decl_namespace_context (d);
17224           push_nested_namespace (ns);
17225           push_nested_class (DECL_CONTEXT (d));
17226           init = tsubst_expr (DECL_INITIAL (code_pattern),
17227                               args,
17228                               tf_warning_or_error, NULL_TREE,
17229                               /*integral_constant_expression_p=*/false);
17230           /* Make sure the initializer is still constant, in case of
17231              circular dependency (template/instantiate6.C). */
17232           const_init
17233             = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
17234           cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
17235                           /*asmspec_tree=*/NULL_TREE,
17236                           LOOKUP_ONLYCONVERTING);
17237           pop_nested_class ();
17238           pop_nested_namespace (ns);
17239         }
17240
17241       /* We restore the source position here because it's used by
17242          add_pending_template.  */
17243       input_location = saved_loc;
17244
17245       if (at_eof && !pattern_defined
17246           && DECL_EXPLICIT_INSTANTIATION (d)
17247           && DECL_NOT_REALLY_EXTERN (d))
17248         /* [temp.explicit]
17249
17250            The definition of a non-exported function template, a
17251            non-exported member function template, or a non-exported
17252            member function or static data member of a class template
17253            shall be present in every translation unit in which it is
17254            explicitly instantiated.  */
17255         permerror (input_location,  "explicit instantiation of %qD "
17256                    "but no definition available", d);
17257
17258       /* If we're in unevaluated context, we just wanted to get the
17259          constant value; this isn't an odr use, so don't queue
17260          a full instantiation.  */
17261       if (cp_unevaluated_operand != 0)
17262         goto out;
17263       /* ??? Historically, we have instantiated inline functions, even
17264          when marked as "extern template".  */
17265       if (!(external_p && TREE_CODE (d) == VAR_DECL))
17266         add_pending_template (d);
17267       goto out;
17268     }
17269   /* Tell the repository that D is available in this translation unit
17270      -- and see if it is supposed to be instantiated here.  */
17271   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
17272     {
17273       /* In a PCH file, despite the fact that the repository hasn't
17274          requested instantiation in the PCH it is still possible that
17275          an instantiation will be required in a file that includes the
17276          PCH.  */
17277       if (pch_file)
17278         add_pending_template (d);
17279       /* Instantiate inline functions so that the inliner can do its
17280          job, even though we'll not be emitting a copy of this
17281          function.  */
17282       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
17283         goto out;
17284     }
17285
17286   need_push = !cfun || !global_bindings_p ();
17287   if (need_push)
17288     push_to_top_level ();
17289
17290   /* Mark D as instantiated so that recursive calls to
17291      instantiate_decl do not try to instantiate it again.  */
17292   DECL_TEMPLATE_INSTANTIATED (d) = 1;
17293
17294   /* Regenerate the declaration in case the template has been modified
17295      by a subsequent redeclaration.  */
17296   regenerate_decl_from_template (d, td);
17297
17298   /* We already set the file and line above.  Reset them now in case
17299      they changed as a result of calling regenerate_decl_from_template.  */
17300   input_location = DECL_SOURCE_LOCATION (d);
17301
17302   if (TREE_CODE (d) == VAR_DECL)
17303     {
17304       tree init;
17305       bool const_init = false;
17306
17307       /* Clear out DECL_RTL; whatever was there before may not be right
17308          since we've reset the type of the declaration.  */
17309       SET_DECL_RTL (d, NULL);
17310       DECL_IN_AGGR_P (d) = 0;
17311
17312       /* The initializer is placed in DECL_INITIAL by
17313          regenerate_decl_from_template so we don't need to
17314          push/pop_access_scope again here.  Pull it out so that
17315          cp_finish_decl can process it.  */
17316       init = DECL_INITIAL (d);
17317       DECL_INITIAL (d) = NULL_TREE;
17318       DECL_INITIALIZED_P (d) = 0;
17319
17320       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
17321          initializer.  That function will defer actual emission until
17322          we have a chance to determine linkage.  */
17323       DECL_EXTERNAL (d) = 0;
17324
17325       /* Enter the scope of D so that access-checking works correctly.  */
17326       push_nested_class (DECL_CONTEXT (d));
17327       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
17328       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
17329       pop_nested_class ();
17330     }
17331   else if (TREE_CODE (d) == FUNCTION_DECL)
17332     {
17333       htab_t saved_local_specializations;
17334       tree subst_decl;
17335       tree tmpl_parm;
17336       tree spec_parm;
17337
17338       /* Save away the current list, in case we are instantiating one
17339          template from within the body of another.  */
17340       saved_local_specializations = local_specializations;
17341
17342       /* Set up the list of local specializations.  */
17343       local_specializations = htab_create (37,
17344                                            hash_local_specialization,
17345                                            eq_local_specializations,
17346                                            NULL);
17347
17348       /* Set up context.  */
17349       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
17350
17351       /* Create substitution entries for the parameters.  */
17352       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
17353       tmpl_parm = DECL_ARGUMENTS (subst_decl);
17354       spec_parm = DECL_ARGUMENTS (d);
17355       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
17356         {
17357           register_local_specialization (spec_parm, tmpl_parm);
17358           spec_parm = skip_artificial_parms_for (d, spec_parm);
17359           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
17360         }
17361       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
17362         {
17363           register_local_specialization (spec_parm, tmpl_parm);
17364           tmpl_parm = DECL_CHAIN (tmpl_parm);
17365           spec_parm = DECL_CHAIN (spec_parm);
17366         }
17367       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
17368         {
17369           /* Register the (value) argument pack as a specialization of
17370              TMPL_PARM, then move on.  */
17371           tree argpack = make_fnparm_pack (spec_parm);
17372           register_local_specialization (argpack, tmpl_parm);
17373           tmpl_parm = DECL_CHAIN (tmpl_parm);
17374           spec_parm = NULL_TREE;
17375         }
17376       gcc_assert (!spec_parm);
17377
17378       /* Substitute into the body of the function.  */
17379       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
17380                    tf_warning_or_error, tmpl,
17381                    /*integral_constant_expression_p=*/false);
17382
17383       /* Set the current input_location to the end of the function
17384          so that finish_function knows where we are.  */
17385       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
17386
17387       /* We don't need the local specializations any more.  */
17388       htab_delete (local_specializations);
17389       local_specializations = saved_local_specializations;
17390
17391       /* Finish the function.  */
17392       d = finish_function (0);
17393       expand_or_defer_fn (d);
17394     }
17395
17396   /* We're not deferring instantiation any more.  */
17397   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
17398
17399   if (need_push)
17400     pop_from_top_level ();
17401
17402 out:
17403   input_location = saved_loc;
17404   pop_deferring_access_checks ();
17405   pop_tinst_level ();
17406
17407   timevar_pop (TV_PARSE);
17408
17409   return d;
17410 }
17411
17412 /* Run through the list of templates that we wish we could
17413    instantiate, and instantiate any we can.  RETRIES is the
17414    number of times we retry pending template instantiation.  */
17415
17416 void
17417 instantiate_pending_templates (int retries)
17418 {
17419   int reconsider;
17420   location_t saved_loc = input_location;
17421
17422   /* Instantiating templates may trigger vtable generation.  This in turn
17423      may require further template instantiations.  We place a limit here
17424      to avoid infinite loop.  */
17425   if (pending_templates && retries >= max_tinst_depth)
17426     {
17427       tree decl = pending_templates->tinst->decl;
17428
17429       error ("template instantiation depth exceeds maximum of %d"
17430              " instantiating %q+D, possibly from virtual table generation"
17431              " (use -ftemplate-depth= to increase the maximum)",
17432              max_tinst_depth, decl);
17433       if (TREE_CODE (decl) == FUNCTION_DECL)
17434         /* Pretend that we defined it.  */
17435         DECL_INITIAL (decl) = error_mark_node;
17436       return;
17437     }
17438
17439   do
17440     {
17441       struct pending_template **t = &pending_templates;
17442       struct pending_template *last = NULL;
17443       reconsider = 0;
17444       while (*t)
17445         {
17446           tree instantiation = reopen_tinst_level ((*t)->tinst);
17447           bool complete = false;
17448
17449           if (TYPE_P (instantiation))
17450             {
17451               tree fn;
17452
17453               if (!COMPLETE_TYPE_P (instantiation))
17454                 {
17455                   instantiate_class_template (instantiation);
17456                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
17457                     for (fn = TYPE_METHODS (instantiation);
17458                          fn;
17459                          fn = TREE_CHAIN (fn))
17460                       if (! DECL_ARTIFICIAL (fn))
17461                         instantiate_decl (fn,
17462                                           /*defer_ok=*/0,
17463                                           /*expl_inst_class_mem_p=*/false);
17464                   if (COMPLETE_TYPE_P (instantiation))
17465                     reconsider = 1;
17466                 }
17467
17468               complete = COMPLETE_TYPE_P (instantiation);
17469             }
17470           else
17471             {
17472               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
17473                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
17474                 {
17475                   instantiation
17476                     = instantiate_decl (instantiation,
17477                                         /*defer_ok=*/0,
17478                                         /*expl_inst_class_mem_p=*/false);
17479                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
17480                     reconsider = 1;
17481                 }
17482
17483               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
17484                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
17485             }
17486
17487           if (complete)
17488             /* If INSTANTIATION has been instantiated, then we don't
17489                need to consider it again in the future.  */
17490             *t = (*t)->next;
17491           else
17492             {
17493               last = *t;
17494               t = &(*t)->next;
17495             }
17496           tinst_depth = 0;
17497           current_tinst_level = NULL;
17498         }
17499       last_pending_template = last;
17500     }
17501   while (reconsider);
17502
17503   input_location = saved_loc;
17504 }
17505
17506 /* Substitute ARGVEC into T, which is a list of initializers for
17507    either base class or a non-static data member.  The TREE_PURPOSEs
17508    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
17509    instantiate_decl.  */
17510
17511 static tree
17512 tsubst_initializer_list (tree t, tree argvec)
17513 {
17514   tree inits = NULL_TREE;
17515
17516   for (; t; t = TREE_CHAIN (t))
17517     {
17518       tree decl;
17519       tree init;
17520       tree expanded_bases = NULL_TREE;
17521       tree expanded_arguments = NULL_TREE;
17522       int i, len = 1;
17523
17524       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
17525         {
17526           tree expr;
17527           tree arg;
17528
17529           /* Expand the base class expansion type into separate base
17530              classes.  */
17531           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
17532                                                  tf_warning_or_error,
17533                                                  NULL_TREE);
17534           if (expanded_bases == error_mark_node)
17535             continue;
17536           
17537           /* We'll be building separate TREE_LISTs of arguments for
17538              each base.  */
17539           len = TREE_VEC_LENGTH (expanded_bases);
17540           expanded_arguments = make_tree_vec (len);
17541           for (i = 0; i < len; i++)
17542             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
17543
17544           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
17545              expand each argument in the TREE_VALUE of t.  */
17546           expr = make_node (EXPR_PACK_EXPANSION);
17547           PACK_EXPANSION_PARAMETER_PACKS (expr) =
17548             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
17549
17550           if (TREE_VALUE (t) == void_type_node)
17551             /* VOID_TYPE_NODE is used to indicate
17552                value-initialization.  */
17553             {
17554               for (i = 0; i < len; i++)
17555                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
17556             }
17557           else
17558             {
17559               /* Substitute parameter packs into each argument in the
17560                  TREE_LIST.  */
17561               in_base_initializer = 1;
17562               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
17563                 {
17564                   tree expanded_exprs;
17565
17566                   /* Expand the argument.  */
17567                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
17568                   expanded_exprs 
17569                     = tsubst_pack_expansion (expr, argvec,
17570                                              tf_warning_or_error,
17571                                              NULL_TREE);
17572                   if (expanded_exprs == error_mark_node)
17573                     continue;
17574
17575                   /* Prepend each of the expanded expressions to the
17576                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
17577                   for (i = 0; i < len; i++)
17578                     {
17579                       TREE_VEC_ELT (expanded_arguments, i) = 
17580                         tree_cons (NULL_TREE, 
17581                                    TREE_VEC_ELT (expanded_exprs, i),
17582                                    TREE_VEC_ELT (expanded_arguments, i));
17583                     }
17584                 }
17585               in_base_initializer = 0;
17586
17587               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
17588                  since we built them backwards.  */
17589               for (i = 0; i < len; i++)
17590                 {
17591                   TREE_VEC_ELT (expanded_arguments, i) = 
17592                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
17593                 }
17594             }
17595         }
17596
17597       for (i = 0; i < len; ++i)
17598         {
17599           if (expanded_bases)
17600             {
17601               decl = TREE_VEC_ELT (expanded_bases, i);
17602               decl = expand_member_init (decl);
17603               init = TREE_VEC_ELT (expanded_arguments, i);
17604             }
17605           else
17606             {
17607               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
17608                                   tf_warning_or_error, NULL_TREE);
17609
17610               decl = expand_member_init (decl);
17611               if (decl && !DECL_P (decl))
17612                 in_base_initializer = 1;
17613
17614               init = TREE_VALUE (t);
17615               if (init != void_type_node)
17616                 init = tsubst_expr (init, argvec,
17617                                     tf_warning_or_error, NULL_TREE,
17618                                     /*integral_constant_expression_p=*/false);
17619               in_base_initializer = 0;
17620             }
17621
17622           if (decl)
17623             {
17624               init = build_tree_list (decl, init);
17625               TREE_CHAIN (init) = inits;
17626               inits = init;
17627             }
17628         }
17629     }
17630   return inits;
17631 }
17632
17633 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
17634
17635 static void
17636 set_current_access_from_decl (tree decl)
17637 {
17638   if (TREE_PRIVATE (decl))
17639     current_access_specifier = access_private_node;
17640   else if (TREE_PROTECTED (decl))
17641     current_access_specifier = access_protected_node;
17642   else
17643     current_access_specifier = access_public_node;
17644 }
17645
17646 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
17647    is the instantiation (which should have been created with
17648    start_enum) and ARGS are the template arguments to use.  */
17649
17650 static void
17651 tsubst_enum (tree tag, tree newtag, tree args)
17652 {
17653   tree e;
17654
17655   if (SCOPED_ENUM_P (newtag))
17656     begin_scope (sk_scoped_enum, newtag);
17657
17658   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
17659     {
17660       tree value;
17661       tree decl;
17662
17663       decl = TREE_VALUE (e);
17664       /* Note that in a template enum, the TREE_VALUE is the
17665          CONST_DECL, not the corresponding INTEGER_CST.  */
17666       value = tsubst_expr (DECL_INITIAL (decl),
17667                            args, tf_warning_or_error, NULL_TREE,
17668                            /*integral_constant_expression_p=*/true);
17669
17670       /* Give this enumeration constant the correct access.  */
17671       set_current_access_from_decl (decl);
17672
17673       /* Actually build the enumerator itself.  */
17674       build_enumerator
17675         (DECL_NAME (decl), value, newtag, DECL_SOURCE_LOCATION (decl));
17676     }
17677
17678   if (SCOPED_ENUM_P (newtag))
17679     finish_scope ();
17680
17681   finish_enum_value_list (newtag);
17682   finish_enum (newtag);
17683
17684   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
17685     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
17686 }
17687
17688 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
17689    its type -- but without substituting the innermost set of template
17690    arguments.  So, innermost set of template parameters will appear in
17691    the type.  */
17692
17693 tree
17694 get_mostly_instantiated_function_type (tree decl)
17695 {
17696   tree fn_type;
17697   tree tmpl;
17698   tree targs;
17699   tree tparms;
17700   int parm_depth;
17701
17702   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
17703   targs = DECL_TI_ARGS (decl);
17704   tparms = DECL_TEMPLATE_PARMS (tmpl);
17705   parm_depth = TMPL_PARMS_DEPTH (tparms);
17706
17707   /* There should be as many levels of arguments as there are levels
17708      of parameters.  */
17709   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
17710
17711   fn_type = TREE_TYPE (tmpl);
17712
17713   if (parm_depth == 1)
17714     /* No substitution is necessary.  */
17715     ;
17716   else
17717     {
17718       int i, save_access_control;
17719       tree partial_args;
17720
17721       /* Replace the innermost level of the TARGS with NULL_TREEs to
17722          let tsubst know not to substitute for those parameters.  */
17723       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
17724       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
17725         SET_TMPL_ARGS_LEVEL (partial_args, i,
17726                              TMPL_ARGS_LEVEL (targs, i));
17727       SET_TMPL_ARGS_LEVEL (partial_args,
17728                            TMPL_ARGS_DEPTH (targs),
17729                            make_tree_vec (DECL_NTPARMS (tmpl)));
17730
17731       /* Disable access control as this function is used only during
17732          name-mangling.  */
17733       save_access_control = flag_access_control;
17734       flag_access_control = 0;
17735
17736       ++processing_template_decl;
17737       /* Now, do the (partial) substitution to figure out the
17738          appropriate function type.  */
17739       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
17740       --processing_template_decl;
17741
17742       /* Substitute into the template parameters to obtain the real
17743          innermost set of parameters.  This step is important if the
17744          innermost set of template parameters contains value
17745          parameters whose types depend on outer template parameters.  */
17746       TREE_VEC_LENGTH (partial_args)--;
17747       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
17748
17749       flag_access_control = save_access_control;
17750     }
17751
17752   return fn_type;
17753 }
17754
17755 /* Return truthvalue if we're processing a template different from
17756    the last one involved in diagnostics.  */
17757 int
17758 problematic_instantiation_changed (void)
17759 {
17760   return last_template_error_tick != tinst_level_tick;
17761 }
17762
17763 /* Remember current template involved in diagnostics.  */
17764 void
17765 record_last_problematic_instantiation (void)
17766 {
17767   last_template_error_tick = tinst_level_tick;
17768 }
17769
17770 struct tinst_level *
17771 current_instantiation (void)
17772 {
17773   return current_tinst_level;
17774 }
17775
17776 /* [temp.param] Check that template non-type parm TYPE is of an allowable
17777    type. Return zero for ok, nonzero for disallowed. Issue error and
17778    warning messages under control of COMPLAIN.  */
17779
17780 static int
17781 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
17782 {
17783   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
17784     return 0;
17785   else if (POINTER_TYPE_P (type))
17786     return 0;
17787   else if (TYPE_PTR_TO_MEMBER_P (type))
17788     return 0;
17789   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
17790     return 0;
17791   else if (TREE_CODE (type) == TYPENAME_TYPE)
17792     return 0;
17793
17794   if (complain & tf_error)
17795     error ("%q#T is not a valid type for a template constant parameter", type);
17796   return 1;
17797 }
17798
17799 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
17800    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
17801
17802 static bool
17803 dependent_type_p_r (tree type)
17804 {
17805   tree scope;
17806
17807   /* [temp.dep.type]
17808
17809      A type is dependent if it is:
17810
17811      -- a template parameter. Template template parameters are types
17812         for us (since TYPE_P holds true for them) so we handle
17813         them here.  */
17814   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17815       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
17816     return true;
17817   /* -- a qualified-id with a nested-name-specifier which contains a
17818         class-name that names a dependent type or whose unqualified-id
17819         names a dependent type.  */
17820   if (TREE_CODE (type) == TYPENAME_TYPE)
17821     return true;
17822   /* -- a cv-qualified type where the cv-unqualified type is
17823         dependent.  */
17824   type = TYPE_MAIN_VARIANT (type);
17825   /* -- a compound type constructed from any dependent type.  */
17826   if (TYPE_PTR_TO_MEMBER_P (type))
17827     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
17828             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
17829                                            (type)));
17830   else if (TREE_CODE (type) == POINTER_TYPE
17831            || TREE_CODE (type) == REFERENCE_TYPE)
17832     return dependent_type_p (TREE_TYPE (type));
17833   else if (TREE_CODE (type) == FUNCTION_TYPE
17834            || TREE_CODE (type) == METHOD_TYPE)
17835     {
17836       tree arg_type;
17837
17838       if (dependent_type_p (TREE_TYPE (type)))
17839         return true;
17840       for (arg_type = TYPE_ARG_TYPES (type);
17841            arg_type;
17842            arg_type = TREE_CHAIN (arg_type))
17843         if (dependent_type_p (TREE_VALUE (arg_type)))
17844           return true;
17845       return false;
17846     }
17847   /* -- an array type constructed from any dependent type or whose
17848         size is specified by a constant expression that is
17849         value-dependent.
17850
17851         We checked for type- and value-dependence of the bounds in
17852         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
17853   if (TREE_CODE (type) == ARRAY_TYPE)
17854     {
17855       if (TYPE_DOMAIN (type)
17856           && dependent_type_p (TYPE_DOMAIN (type)))
17857         return true;
17858       return dependent_type_p (TREE_TYPE (type));
17859     }
17860
17861   /* -- a template-id in which either the template name is a template
17862      parameter ...  */
17863   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
17864     return true;
17865   /* ... or any of the template arguments is a dependent type or
17866         an expression that is type-dependent or value-dependent.  */
17867   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
17868            && (any_dependent_template_arguments_p
17869                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
17870     return true;
17871
17872   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
17873      argument of the `typeof' expression is not type-dependent, then
17874      it should already been have resolved.  */
17875   if (TREE_CODE (type) == TYPEOF_TYPE
17876       || TREE_CODE (type) == DECLTYPE_TYPE)
17877     return true;
17878
17879   /* A template argument pack is dependent if any of its packed
17880      arguments are.  */
17881   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
17882     {
17883       tree args = ARGUMENT_PACK_ARGS (type);
17884       int i, len = TREE_VEC_LENGTH (args);
17885       for (i = 0; i < len; ++i)
17886         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17887           return true;
17888     }
17889
17890   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
17891      be template parameters.  */
17892   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
17893     return true;
17894
17895   /* The standard does not specifically mention types that are local
17896      to template functions or local classes, but they should be
17897      considered dependent too.  For example:
17898
17899        template <int I> void f() {
17900          enum E { a = I };
17901          S<sizeof (E)> s;
17902        }
17903
17904      The size of `E' cannot be known until the value of `I' has been
17905      determined.  Therefore, `E' must be considered dependent.  */
17906   scope = TYPE_CONTEXT (type);
17907   if (scope && TYPE_P (scope))
17908     return dependent_type_p (scope);
17909   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
17910     return type_dependent_expression_p (scope);
17911
17912   /* Other types are non-dependent.  */
17913   return false;
17914 }
17915
17916 /* Returns TRUE if TYPE is dependent, in the sense of
17917    [temp.dep.type].  */
17918
17919 bool
17920 dependent_type_p (tree type)
17921 {
17922   /* If there are no template parameters in scope, then there can't be
17923      any dependent types.  */
17924   if (!processing_template_decl)
17925     {
17926       /* If we are not processing a template, then nobody should be
17927          providing us with a dependent type.  */
17928       gcc_assert (type);
17929       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
17930       return false;
17931     }
17932
17933   /* If the type is NULL, we have not computed a type for the entity
17934      in question; in that case, the type is dependent.  */
17935   if (!type)
17936     return true;
17937
17938   /* Erroneous types can be considered non-dependent.  */
17939   if (type == error_mark_node)
17940     return false;
17941
17942   /* If we have not already computed the appropriate value for TYPE,
17943      do so now.  */
17944   if (!TYPE_DEPENDENT_P_VALID (type))
17945     {
17946       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
17947       TYPE_DEPENDENT_P_VALID (type) = 1;
17948     }
17949
17950   return TYPE_DEPENDENT_P (type);
17951 }
17952
17953 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
17954    lookup.  In other words, a dependent type that is not the current
17955    instantiation.  */
17956
17957 bool
17958 dependent_scope_p (tree scope)
17959 {
17960   return (scope && TYPE_P (scope) && dependent_type_p (scope)
17961           && !currently_open_class (scope));
17962 }
17963
17964 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
17965    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
17966    expression.  */
17967
17968 /* FIXME this predicate is not appropriate for general expressions; the
17969    predicates we want instead are "valid constant expression, value
17970    dependent or not?", "really constant expression, not value dependent?"
17971    and "instantiation-dependent?".  Try to integrate with
17972    potential_constant_expression?
17973
17974    fold_non_dependent_expr: fold if constant and not type-dependent and not value-dependent.
17975      (what about instantiation-dependent constant-expressions?)
17976    is_late_template_attribute: defer if instantiation-dependent.
17977    compute_array_index_type: proceed if constant and not t- or v-dependent
17978      if instantiation-dependent, need to remember full expression
17979    uses_template_parms: FIXME - need to audit callers
17980    tsubst_decl [function_decl]: Why is this using value_dependent_expression_p?
17981    dependent_type_p [array_type]: dependent if index type is dependent
17982      (or non-constant?)
17983    static_assert - instantiation-dependent */
17984
17985 bool
17986 value_dependent_expression_p (tree expression)
17987 {
17988   if (!processing_template_decl)
17989     return false;
17990
17991   /* A name declared with a dependent type.  */
17992   if (DECL_P (expression) && type_dependent_expression_p (expression))
17993     return true;
17994
17995   switch (TREE_CODE (expression))
17996     {
17997     case IDENTIFIER_NODE:
17998       /* A name that has not been looked up -- must be dependent.  */
17999       return true;
18000
18001     case TEMPLATE_PARM_INDEX:
18002       /* A non-type template parm.  */
18003       return true;
18004
18005     case CONST_DECL:
18006       /* A non-type template parm.  */
18007       if (DECL_TEMPLATE_PARM_P (expression))
18008         return true;
18009       return value_dependent_expression_p (DECL_INITIAL (expression));
18010
18011     case VAR_DECL:
18012        /* A constant with integral or enumeration type and is initialized
18013           with an expression that is value-dependent.  */
18014       if (DECL_INITIAL (expression)
18015           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
18016           && value_dependent_expression_p (DECL_INITIAL (expression)))
18017         return true;
18018       return false;
18019
18020     case DYNAMIC_CAST_EXPR:
18021     case STATIC_CAST_EXPR:
18022     case CONST_CAST_EXPR:
18023     case REINTERPRET_CAST_EXPR:
18024     case CAST_EXPR:
18025       /* These expressions are value-dependent if the type to which
18026          the cast occurs is dependent or the expression being casted
18027          is value-dependent.  */
18028       {
18029         tree type = TREE_TYPE (expression);
18030
18031         if (dependent_type_p (type))
18032           return true;
18033
18034         /* A functional cast has a list of operands.  */
18035         expression = TREE_OPERAND (expression, 0);
18036         if (!expression)
18037           {
18038             /* If there are no operands, it must be an expression such
18039                as "int()". This should not happen for aggregate types
18040                because it would form non-constant expressions.  */
18041             gcc_assert (cxx_dialect >= cxx0x
18042                         || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
18043
18044             return false;
18045           }
18046
18047         if (TREE_CODE (expression) == TREE_LIST)
18048           return any_value_dependent_elements_p (expression);
18049
18050         return value_dependent_expression_p (expression);
18051       }
18052
18053     case SIZEOF_EXPR:
18054     case ALIGNOF_EXPR:
18055       /* A `sizeof' expression is value-dependent if the operand is
18056          type-dependent or is a pack expansion.  */
18057       expression = TREE_OPERAND (expression, 0);
18058       if (PACK_EXPANSION_P (expression))
18059         return true;
18060       else if (TYPE_P (expression))
18061         return dependent_type_p (expression);
18062       return type_dependent_expression_p (expression);
18063
18064     case AT_ENCODE_EXPR:
18065       /* An 'encode' expression is value-dependent if the operand is
18066          type-dependent.  */
18067       expression = TREE_OPERAND (expression, 0);
18068       return dependent_type_p (expression);
18069
18070     case NOEXCEPT_EXPR:
18071       expression = TREE_OPERAND (expression, 0);
18072       /* FIXME why check value-dependency?  */
18073       return (type_dependent_expression_p (expression)
18074               || value_dependent_expression_p (expression));
18075
18076     case SCOPE_REF:
18077       {
18078         tree name = TREE_OPERAND (expression, 1);
18079         return value_dependent_expression_p (name);
18080       }
18081
18082     case COMPONENT_REF:
18083       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
18084               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
18085
18086     case NONTYPE_ARGUMENT_PACK:
18087       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
18088          is value-dependent.  */
18089       {
18090         tree values = ARGUMENT_PACK_ARGS (expression);
18091         int i, len = TREE_VEC_LENGTH (values);
18092         
18093         for (i = 0; i < len; ++i)
18094           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
18095             return true;
18096         
18097         return false;
18098       }
18099
18100     case TRAIT_EXPR:
18101       {
18102         tree type2 = TRAIT_EXPR_TYPE2 (expression);
18103         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
18104                 || (type2 ? dependent_type_p (type2) : false));
18105       }
18106
18107     case MODOP_EXPR:
18108       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
18109               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
18110
18111     case ADDR_EXPR:
18112       {
18113         tree op = TREE_OPERAND (expression, 0);
18114         return (value_dependent_expression_p (op)
18115                 || has_value_dependent_address (op));
18116       }
18117
18118     case CALL_EXPR:
18119       {
18120         tree fn = get_callee_fndecl (expression);
18121         int i, nargs;
18122         if (!fn && value_dependent_expression_p (CALL_EXPR_FN (expression)))
18123           return true;
18124         nargs = call_expr_nargs (expression);
18125         for (i = 0; i < nargs; ++i)
18126           {
18127             tree op = CALL_EXPR_ARG (expression, i);
18128             /* In a call to a constexpr member function, look through the
18129                implicit ADDR_EXPR on the object argument so that it doesn't
18130                cause the call to be considered value-dependent.  We also
18131                look through it in potential_constant_expression.  */
18132             if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
18133                 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
18134                 && TREE_CODE (op) == ADDR_EXPR)
18135               op = TREE_OPERAND (op, 0);
18136             if (value_dependent_expression_p (op))
18137               return true;
18138           }
18139         return false;
18140       }
18141
18142     default:
18143       /* A constant expression is value-dependent if any subexpression is
18144          value-dependent.  */
18145       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
18146         {
18147         case tcc_reference:
18148         case tcc_unary:
18149           return (value_dependent_expression_p
18150                   (TREE_OPERAND (expression, 0)));
18151
18152         case tcc_comparison:
18153         case tcc_binary:
18154           return ((value_dependent_expression_p
18155                    (TREE_OPERAND (expression, 0)))
18156                   || (value_dependent_expression_p
18157                       (TREE_OPERAND (expression, 1))));
18158
18159         case tcc_expression:
18160         case tcc_vl_exp:
18161           {
18162             int i;
18163             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
18164               /* In some cases, some of the operands may be missing.
18165                  (For example, in the case of PREDECREMENT_EXPR, the
18166                  amount to increment by may be missing.)  That doesn't
18167                  make the expression dependent.  */
18168               if (TREE_OPERAND (expression, i)
18169                   && (value_dependent_expression_p
18170                       (TREE_OPERAND (expression, i))))
18171                 return true;
18172             return false;
18173           }
18174
18175         default:
18176           break;
18177         }
18178     }
18179
18180   /* The expression is not value-dependent.  */
18181   return false;
18182 }
18183
18184 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
18185    [temp.dep.expr].  */
18186
18187 bool
18188 type_dependent_expression_p (tree expression)
18189 {
18190   if (!processing_template_decl)
18191     return false;
18192
18193   if (expression == error_mark_node)
18194     return false;
18195
18196   /* An unresolved name is always dependent.  */
18197   if (TREE_CODE (expression) == IDENTIFIER_NODE
18198       || TREE_CODE (expression) == USING_DECL)
18199     return true;
18200
18201   /* Some expression forms are never type-dependent.  */
18202   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
18203       || TREE_CODE (expression) == SIZEOF_EXPR
18204       || TREE_CODE (expression) == ALIGNOF_EXPR
18205       || TREE_CODE (expression) == AT_ENCODE_EXPR
18206       || TREE_CODE (expression) == NOEXCEPT_EXPR
18207       || TREE_CODE (expression) == TRAIT_EXPR
18208       || TREE_CODE (expression) == TYPEID_EXPR
18209       || TREE_CODE (expression) == DELETE_EXPR
18210       || TREE_CODE (expression) == VEC_DELETE_EXPR
18211       || TREE_CODE (expression) == THROW_EXPR)
18212     return false;
18213
18214   /* The types of these expressions depends only on the type to which
18215      the cast occurs.  */
18216   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
18217       || TREE_CODE (expression) == STATIC_CAST_EXPR
18218       || TREE_CODE (expression) == CONST_CAST_EXPR
18219       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
18220       || TREE_CODE (expression) == CAST_EXPR)
18221     return dependent_type_p (TREE_TYPE (expression));
18222
18223   /* The types of these expressions depends only on the type created
18224      by the expression.  */
18225   if (TREE_CODE (expression) == NEW_EXPR
18226       || TREE_CODE (expression) == VEC_NEW_EXPR)
18227     {
18228       /* For NEW_EXPR tree nodes created inside a template, either
18229          the object type itself or a TREE_LIST may appear as the
18230          operand 1.  */
18231       tree type = TREE_OPERAND (expression, 1);
18232       if (TREE_CODE (type) == TREE_LIST)
18233         /* This is an array type.  We need to check array dimensions
18234            as well.  */
18235         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
18236                || value_dependent_expression_p
18237                     (TREE_OPERAND (TREE_VALUE (type), 1));
18238       else
18239         return dependent_type_p (type);
18240     }
18241
18242   if (TREE_CODE (expression) == SCOPE_REF)
18243     {
18244       tree scope = TREE_OPERAND (expression, 0);
18245       tree name = TREE_OPERAND (expression, 1);
18246
18247       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
18248          contains an identifier associated by name lookup with one or more
18249          declarations declared with a dependent type, or...a
18250          nested-name-specifier or qualified-id that names a member of an
18251          unknown specialization.  */
18252       return (type_dependent_expression_p (name)
18253               || dependent_scope_p (scope));
18254     }
18255
18256   if (TREE_CODE (expression) == FUNCTION_DECL
18257       && DECL_LANG_SPECIFIC (expression)
18258       && DECL_TEMPLATE_INFO (expression)
18259       && (any_dependent_template_arguments_p
18260           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
18261     return true;
18262
18263   if (TREE_CODE (expression) == TEMPLATE_DECL
18264       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
18265     return false;
18266
18267   if (TREE_CODE (expression) == STMT_EXPR)
18268     expression = stmt_expr_value_expr (expression);
18269
18270   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
18271     {
18272       tree elt;
18273       unsigned i;
18274
18275       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
18276         {
18277           if (type_dependent_expression_p (elt))
18278             return true;
18279         }
18280       return false;
18281     }
18282
18283   /* A static data member of the current instantiation with incomplete
18284      array type is type-dependent, as the definition and specializations
18285      can have different bounds.  */
18286   if (TREE_CODE (expression) == VAR_DECL
18287       && DECL_CLASS_SCOPE_P (expression)
18288       && dependent_type_p (DECL_CONTEXT (expression))
18289       && VAR_HAD_UNKNOWN_BOUND (expression))
18290     return true;
18291
18292   if (TREE_TYPE (expression) == unknown_type_node)
18293     {
18294       if (TREE_CODE (expression) == ADDR_EXPR)
18295         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
18296       if (TREE_CODE (expression) == COMPONENT_REF
18297           || TREE_CODE (expression) == OFFSET_REF)
18298         {
18299           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
18300             return true;
18301           expression = TREE_OPERAND (expression, 1);
18302           if (TREE_CODE (expression) == IDENTIFIER_NODE)
18303             return false;
18304         }
18305       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
18306       if (TREE_CODE (expression) == SCOPE_REF)
18307         return false;
18308
18309       if (TREE_CODE (expression) == BASELINK)
18310         expression = BASELINK_FUNCTIONS (expression);
18311
18312       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
18313         {
18314           if (any_dependent_template_arguments_p
18315               (TREE_OPERAND (expression, 1)))
18316             return true;
18317           expression = TREE_OPERAND (expression, 0);
18318         }
18319       gcc_assert (TREE_CODE (expression) == OVERLOAD
18320                   || TREE_CODE (expression) == FUNCTION_DECL);
18321
18322       while (expression)
18323         {
18324           if (type_dependent_expression_p (OVL_CURRENT (expression)))
18325             return true;
18326           expression = OVL_NEXT (expression);
18327         }
18328       return false;
18329     }
18330
18331   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
18332
18333   return (dependent_type_p (TREE_TYPE (expression)));
18334 }
18335
18336 /* Like type_dependent_expression_p, but it also works while not processing
18337    a template definition, i.e. during substitution or mangling.  */
18338
18339 bool
18340 type_dependent_expression_p_push (tree expr)
18341 {
18342   bool b;
18343   ++processing_template_decl;
18344   b = type_dependent_expression_p (expr);
18345   --processing_template_decl;
18346   return b;
18347 }
18348
18349 /* Returns TRUE if ARGS contains a type-dependent expression.  */
18350
18351 bool
18352 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
18353 {
18354   unsigned int i;
18355   tree arg;
18356
18357   FOR_EACH_VEC_ELT (tree, args, i, arg)
18358     {
18359       if (type_dependent_expression_p (arg))
18360         return true;
18361     }
18362   return false;
18363 }
18364
18365 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
18366    expressions) contains any value-dependent expressions.  */
18367
18368 bool
18369 any_value_dependent_elements_p (const_tree list)
18370 {
18371   for (; list; list = TREE_CHAIN (list))
18372     if (value_dependent_expression_p (TREE_VALUE (list)))
18373       return true;
18374
18375   return false;
18376 }
18377
18378 /* Returns TRUE if the ARG (a template argument) is dependent.  */
18379
18380 bool
18381 dependent_template_arg_p (tree arg)
18382 {
18383   if (!processing_template_decl)
18384     return false;
18385
18386   /* Assume a template argument that was wrongly written by the user
18387      is dependent. This is consistent with what
18388      any_dependent_template_arguments_p [that calls this function]
18389      does.  */
18390   if (arg == error_mark_node)
18391     return true;
18392
18393   if (TREE_CODE (arg) == TEMPLATE_DECL
18394       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
18395     return dependent_template_p (arg);
18396   else if (ARGUMENT_PACK_P (arg))
18397     {
18398       tree args = ARGUMENT_PACK_ARGS (arg);
18399       int i, len = TREE_VEC_LENGTH (args);
18400       for (i = 0; i < len; ++i)
18401         {
18402           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
18403             return true;
18404         }
18405
18406       return false;
18407     }
18408   else if (TYPE_P (arg))
18409     return dependent_type_p (arg);
18410   else
18411     return (type_dependent_expression_p (arg)
18412             || value_dependent_expression_p (arg));
18413 }
18414
18415 /* Returns true if ARGS (a collection of template arguments) contains
18416    any types that require structural equality testing.  */
18417
18418 bool
18419 any_template_arguments_need_structural_equality_p (tree args)
18420 {
18421   int i;
18422   int j;
18423
18424   if (!args)
18425     return false;
18426   if (args == error_mark_node)
18427     return true;
18428
18429   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
18430     {
18431       tree level = TMPL_ARGS_LEVEL (args, i + 1);
18432       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
18433         {
18434           tree arg = TREE_VEC_ELT (level, j);
18435           tree packed_args = NULL_TREE;
18436           int k, len = 1;
18437
18438           if (ARGUMENT_PACK_P (arg))
18439             {
18440               /* Look inside the argument pack.  */
18441               packed_args = ARGUMENT_PACK_ARGS (arg);
18442               len = TREE_VEC_LENGTH (packed_args);
18443             }
18444
18445           for (k = 0; k < len; ++k)
18446             {
18447               if (packed_args)
18448                 arg = TREE_VEC_ELT (packed_args, k);
18449
18450               if (error_operand_p (arg))
18451                 return true;
18452               else if (TREE_CODE (arg) == TEMPLATE_DECL
18453                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
18454                 continue;
18455               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
18456                 return true;
18457               else if (!TYPE_P (arg) && TREE_TYPE (arg)
18458                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
18459                 return true;
18460             }
18461         }
18462     }
18463
18464   return false;
18465 }
18466
18467 /* Returns true if ARGS (a collection of template arguments) contains
18468    any dependent arguments.  */
18469
18470 bool
18471 any_dependent_template_arguments_p (const_tree args)
18472 {
18473   int i;
18474   int j;
18475
18476   if (!args)
18477     return false;
18478   if (args == error_mark_node)
18479     return true;
18480
18481   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
18482     {
18483       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
18484       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
18485         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
18486           return true;
18487     }
18488
18489   return false;
18490 }
18491
18492 /* Returns TRUE if the template TMPL is dependent.  */
18493
18494 bool
18495 dependent_template_p (tree tmpl)
18496 {
18497   if (TREE_CODE (tmpl) == OVERLOAD)
18498     {
18499       while (tmpl)
18500         {
18501           if (dependent_template_p (OVL_FUNCTION (tmpl)))
18502             return true;
18503           tmpl = OVL_CHAIN (tmpl);
18504         }
18505       return false;
18506     }
18507
18508   /* Template template parameters are dependent.  */
18509   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
18510       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
18511     return true;
18512   /* So are names that have not been looked up.  */
18513   if (TREE_CODE (tmpl) == SCOPE_REF
18514       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
18515     return true;
18516   /* So are member templates of dependent classes.  */
18517   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
18518     return dependent_type_p (DECL_CONTEXT (tmpl));
18519   return false;
18520 }
18521
18522 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
18523
18524 bool
18525 dependent_template_id_p (tree tmpl, tree args)
18526 {
18527   return (dependent_template_p (tmpl)
18528           || any_dependent_template_arguments_p (args));
18529 }
18530
18531 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
18532    is dependent.  */
18533
18534 bool
18535 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
18536 {
18537   int i;
18538
18539   if (!processing_template_decl)
18540     return false;
18541
18542   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
18543     {
18544       tree decl = TREE_VEC_ELT (declv, i);
18545       tree init = TREE_VEC_ELT (initv, i);
18546       tree cond = TREE_VEC_ELT (condv, i);
18547       tree incr = TREE_VEC_ELT (incrv, i);
18548
18549       if (type_dependent_expression_p (decl))
18550         return true;
18551
18552       if (init && type_dependent_expression_p (init))
18553         return true;
18554
18555       if (type_dependent_expression_p (cond))
18556         return true;
18557
18558       if (COMPARISON_CLASS_P (cond)
18559           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
18560               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
18561         return true;
18562
18563       if (TREE_CODE (incr) == MODOP_EXPR)
18564         {
18565           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
18566               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
18567             return true;
18568         }
18569       else if (type_dependent_expression_p (incr))
18570         return true;
18571       else if (TREE_CODE (incr) == MODIFY_EXPR)
18572         {
18573           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
18574             return true;
18575           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
18576             {
18577               tree t = TREE_OPERAND (incr, 1);
18578               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
18579                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
18580                 return true;
18581             }
18582         }
18583     }
18584
18585   return false;
18586 }
18587
18588 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
18589    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
18590    no such TYPE can be found.  Note that this function peers inside
18591    uninstantiated templates and therefore should be used only in
18592    extremely limited situations.  ONLY_CURRENT_P restricts this
18593    peering to the currently open classes hierarchy (which is required
18594    when comparing types).  */
18595
18596 tree
18597 resolve_typename_type (tree type, bool only_current_p)
18598 {
18599   tree scope;
18600   tree name;
18601   tree decl;
18602   int quals;
18603   tree pushed_scope;
18604   tree result;
18605
18606   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
18607
18608   scope = TYPE_CONTEXT (type);
18609   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
18610      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
18611      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
18612      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
18613      identifier  of the TYPENAME_TYPE anymore.
18614      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
18615      TYPENAME_TYPE instead, we avoid messing up with a possible
18616      typedef variant case.  */
18617   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
18618
18619   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
18620      it first before we can figure out what NAME refers to.  */
18621   if (TREE_CODE (scope) == TYPENAME_TYPE)
18622     scope = resolve_typename_type (scope, only_current_p);
18623   /* If we don't know what SCOPE refers to, then we cannot resolve the
18624      TYPENAME_TYPE.  */
18625   if (TREE_CODE (scope) == TYPENAME_TYPE)
18626     return type;
18627   /* If the SCOPE is a template type parameter, we have no way of
18628      resolving the name.  */
18629   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
18630     return type;
18631   /* If the SCOPE is not the current instantiation, there's no reason
18632      to look inside it.  */
18633   if (only_current_p && !currently_open_class (scope))
18634     return type;
18635   /* If this is a typedef, we don't want to look inside (c++/11987).  */
18636   if (typedef_variant_p (type))
18637     return type;
18638   /* If SCOPE isn't the template itself, it will not have a valid
18639      TYPE_FIELDS list.  */
18640   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
18641     /* scope is either the template itself or a compatible instantiation
18642        like X<T>, so look up the name in the original template.  */
18643     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
18644   else
18645     /* scope is a partial instantiation, so we can't do the lookup or we
18646        will lose the template arguments.  */
18647     return type;
18648   /* Enter the SCOPE so that name lookup will be resolved as if we
18649      were in the class definition.  In particular, SCOPE will no
18650      longer be considered a dependent type.  */
18651   pushed_scope = push_scope (scope);
18652   /* Look up the declaration.  */
18653   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
18654
18655   result = NULL_TREE;
18656   
18657   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
18658      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
18659   if (!decl)
18660     /*nop*/;
18661   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
18662            && TREE_CODE (decl) == TYPE_DECL)
18663     {
18664       result = TREE_TYPE (decl);
18665       if (result == error_mark_node)
18666         result = NULL_TREE;
18667     }
18668   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
18669            && DECL_CLASS_TEMPLATE_P (decl))
18670     {
18671       tree tmpl;
18672       tree args;
18673       /* Obtain the template and the arguments.  */
18674       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
18675       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
18676       /* Instantiate the template.  */
18677       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
18678                                       /*entering_scope=*/0,
18679                                       tf_error | tf_user);
18680       if (result == error_mark_node)
18681         result = NULL_TREE;
18682     }
18683   
18684   /* Leave the SCOPE.  */
18685   if (pushed_scope)
18686     pop_scope (pushed_scope);
18687
18688   /* If we failed to resolve it, return the original typename.  */
18689   if (!result)
18690     return type;
18691   
18692   /* If lookup found a typename type, resolve that too.  */
18693   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
18694     {
18695       /* Ill-formed programs can cause infinite recursion here, so we
18696          must catch that.  */
18697       TYPENAME_IS_RESOLVING_P (type) = 1;
18698       result = resolve_typename_type (result, only_current_p);
18699       TYPENAME_IS_RESOLVING_P (type) = 0;
18700     }
18701   
18702   /* Qualify the resulting type.  */
18703   quals = cp_type_quals (type);
18704   if (quals)
18705     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
18706
18707   return result;
18708 }
18709
18710 /* EXPR is an expression which is not type-dependent.  Return a proxy
18711    for EXPR that can be used to compute the types of larger
18712    expressions containing EXPR.  */
18713
18714 tree
18715 build_non_dependent_expr (tree expr)
18716 {
18717   tree inner_expr;
18718
18719   /* Preserve null pointer constants so that the type of things like
18720      "p == 0" where "p" is a pointer can be determined.  */
18721   if (null_ptr_cst_p (expr))
18722     return expr;
18723   /* Preserve OVERLOADs; the functions must be available to resolve
18724      types.  */
18725   inner_expr = expr;
18726   if (TREE_CODE (inner_expr) == STMT_EXPR)
18727     inner_expr = stmt_expr_value_expr (inner_expr);
18728   if (TREE_CODE (inner_expr) == ADDR_EXPR)
18729     inner_expr = TREE_OPERAND (inner_expr, 0);
18730   if (TREE_CODE (inner_expr) == COMPONENT_REF)
18731     inner_expr = TREE_OPERAND (inner_expr, 1);
18732   if (is_overloaded_fn (inner_expr)
18733       || TREE_CODE (inner_expr) == OFFSET_REF)
18734     return expr;
18735   /* There is no need to return a proxy for a variable.  */
18736   if (TREE_CODE (expr) == VAR_DECL)
18737     return expr;
18738   /* Preserve string constants; conversions from string constants to
18739      "char *" are allowed, even though normally a "const char *"
18740      cannot be used to initialize a "char *".  */
18741   if (TREE_CODE (expr) == STRING_CST)
18742     return expr;
18743   /* Preserve arithmetic constants, as an optimization -- there is no
18744      reason to create a new node.  */
18745   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
18746     return expr;
18747   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
18748      There is at least one place where we want to know that a
18749      particular expression is a throw-expression: when checking a ?:
18750      expression, there are special rules if the second or third
18751      argument is a throw-expression.  */
18752   if (TREE_CODE (expr) == THROW_EXPR)
18753     return expr;
18754
18755   if (TREE_CODE (expr) == COND_EXPR)
18756     return build3 (COND_EXPR,
18757                    TREE_TYPE (expr),
18758                    TREE_OPERAND (expr, 0),
18759                    (TREE_OPERAND (expr, 1)
18760                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
18761                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
18762                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
18763   if (TREE_CODE (expr) == COMPOUND_EXPR
18764       && !COMPOUND_EXPR_OVERLOADED (expr))
18765     return build2 (COMPOUND_EXPR,
18766                    TREE_TYPE (expr),
18767                    TREE_OPERAND (expr, 0),
18768                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
18769
18770   /* If the type is unknown, it can't really be non-dependent */
18771   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
18772
18773   /* Otherwise, build a NON_DEPENDENT_EXPR.
18774
18775      REFERENCE_TYPEs are not stripped for expressions in templates
18776      because doing so would play havoc with mangling.  Consider, for
18777      example:
18778
18779        template <typename T> void f<T& g>() { g(); }
18780
18781      In the body of "f", the expression for "g" will have
18782      REFERENCE_TYPE, even though the standard says that it should
18783      not.  The reason is that we must preserve the syntactic form of
18784      the expression so that mangling (say) "f<g>" inside the body of
18785      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
18786      stripped here.  */
18787   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
18788 }
18789
18790 /* ARGS is a vector of expressions as arguments to a function call.
18791    Replace the arguments with equivalent non-dependent expressions.
18792    This modifies ARGS in place.  */
18793
18794 void
18795 make_args_non_dependent (VEC(tree,gc) *args)
18796 {
18797   unsigned int ix;
18798   tree arg;
18799
18800   FOR_EACH_VEC_ELT (tree, args, ix, arg)
18801     {
18802       tree newarg = build_non_dependent_expr (arg);
18803       if (newarg != arg)
18804         VEC_replace (tree, args, ix, newarg);
18805     }
18806 }
18807
18808 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
18809    with a level one deeper than the actual template parms.  */
18810
18811 tree
18812 make_auto (void)
18813 {
18814   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
18815   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
18816                                TYPE_DECL, get_identifier ("auto"), au);
18817   TYPE_STUB_DECL (au) = TYPE_NAME (au);
18818   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
18819     (0, processing_template_decl + 1, processing_template_decl + 1,
18820      0, TYPE_NAME (au), NULL_TREE);
18821   TYPE_CANONICAL (au) = canonical_type_parameter (au);
18822   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
18823   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
18824
18825   return au;
18826 }
18827
18828 /* Given type ARG, return std::initializer_list<ARG>.  */
18829
18830 static tree
18831 listify (tree arg)
18832 {
18833   tree std_init_list = namespace_binding
18834     (get_identifier ("initializer_list"), std_node);
18835   tree argvec;
18836   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
18837     {    
18838       error ("deducing from brace-enclosed initializer list requires "
18839              "#include <initializer_list>");
18840       return error_mark_node;
18841     }
18842   argvec = make_tree_vec (1);
18843   TREE_VEC_ELT (argvec, 0) = arg;
18844   return lookup_template_class (std_init_list, argvec, NULL_TREE,
18845                                 NULL_TREE, 0, tf_warning_or_error);
18846 }
18847
18848 /* Replace auto in TYPE with std::initializer_list<auto>.  */
18849
18850 static tree
18851 listify_autos (tree type, tree auto_node)
18852 {
18853   tree init_auto = listify (auto_node);
18854   tree argvec = make_tree_vec (1);
18855   TREE_VEC_ELT (argvec, 0) = init_auto;
18856   if (processing_template_decl)
18857     argvec = add_to_template_args (current_template_args (), argvec);
18858   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18859 }
18860
18861 /* walk_tree helper for do_auto_deduction.  */
18862
18863 static tree
18864 contains_auto_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
18865                  void *type)
18866 {
18867   /* Is this a variable with the type we're looking for?  */
18868   if (DECL_P (*tp)
18869       && TREE_TYPE (*tp) == type)
18870     return *tp;
18871   else
18872     return NULL_TREE;
18873 }
18874
18875 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
18876    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
18877
18878 tree
18879 do_auto_deduction (tree type, tree init, tree auto_node)
18880 {
18881   tree parms, tparms, targs;
18882   tree args[1];
18883   tree decl;
18884   int val;
18885
18886   /* The name of the object being declared shall not appear in the
18887      initializer expression.  */
18888   decl = cp_walk_tree_without_duplicates (&init, contains_auto_r, type);
18889   if (decl)
18890     {
18891       error ("variable %q#D with %<auto%> type used in its own "
18892              "initializer", decl);
18893       return error_mark_node;
18894     }
18895
18896   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
18897      with either a new invented type template parameter U or, if the
18898      initializer is a braced-init-list (8.5.4), with
18899      std::initializer_list<U>.  */
18900   if (BRACE_ENCLOSED_INITIALIZER_P (init))
18901     type = listify_autos (type, auto_node);
18902
18903   init = resolve_nondeduced_context (init);
18904
18905   parms = build_tree_list (NULL_TREE, type);
18906   args[0] = init;
18907   tparms = make_tree_vec (1);
18908   targs = make_tree_vec (1);
18909   TREE_VEC_ELT (tparms, 0)
18910     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
18911   val = type_unification_real (tparms, targs, parms, args, 1, 0,
18912                                DEDUCE_CALL, LOOKUP_NORMAL);
18913   if (val > 0)
18914     {
18915       error ("unable to deduce %qT from %qE", type, init);
18916       return error_mark_node;
18917     }
18918
18919   /* If the list of declarators contains more than one declarator, the type
18920      of each declared variable is determined as described above. If the
18921      type deduced for the template parameter U is not the same in each
18922      deduction, the program is ill-formed.  */
18923   if (TREE_TYPE (auto_node)
18924       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
18925     {
18926       error ("inconsistent deduction for %qT: %qT and then %qT",
18927              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
18928       return error_mark_node;
18929     }
18930   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
18931
18932   if (processing_template_decl)
18933     targs = add_to_template_args (current_template_args (), targs);
18934   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
18935 }
18936
18937 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
18938    result.  */
18939
18940 tree
18941 splice_late_return_type (tree type, tree late_return_type)
18942 {
18943   tree argvec;
18944
18945   if (late_return_type == NULL_TREE)
18946     return type;
18947   argvec = make_tree_vec (1);
18948   TREE_VEC_ELT (argvec, 0) = late_return_type;
18949   if (processing_template_decl)
18950     argvec = add_to_template_args (current_template_args (), argvec);
18951   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18952 }
18953
18954 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
18955
18956 bool
18957 is_auto (const_tree type)
18958 {
18959   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18960       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
18961     return true;
18962   else
18963     return false;
18964 }
18965
18966 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
18967    appear as a type-specifier for the declaration in question, we don't
18968    have to look through the whole type.  */
18969
18970 tree
18971 type_uses_auto (tree type)
18972 {
18973   enum tree_code code;
18974   if (is_auto (type))
18975     return type;
18976
18977   code = TREE_CODE (type);
18978
18979   if (code == POINTER_TYPE || code == REFERENCE_TYPE
18980       || code == OFFSET_TYPE || code == FUNCTION_TYPE
18981       || code == METHOD_TYPE || code == ARRAY_TYPE)
18982     return type_uses_auto (TREE_TYPE (type));
18983
18984   if (TYPE_PTRMEMFUNC_P (type))
18985     return type_uses_auto (TREE_TYPE (TREE_TYPE
18986                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
18987
18988   return NULL_TREE;
18989 }
18990
18991 /* For a given template T, return the vector of typedefs referenced
18992    in T for which access check is needed at T instantiation time.
18993    T is either  a FUNCTION_DECL or a RECORD_TYPE.
18994    Those typedefs were added to T by the function
18995    append_type_to_template_for_access_check.  */
18996
18997 VEC(qualified_typedef_usage_t,gc)*
18998 get_types_needing_access_check (tree t)
18999 {
19000   tree ti;
19001   VEC(qualified_typedef_usage_t,gc) *result = NULL;
19002
19003   if (!t || t == error_mark_node)
19004     return NULL;
19005
19006   if (!(ti = get_template_info (t)))
19007     return NULL;
19008
19009   if (CLASS_TYPE_P (t)
19010       || TREE_CODE (t) == FUNCTION_DECL)
19011     {
19012       if (!TI_TEMPLATE (ti))
19013         return NULL;
19014
19015       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
19016     }
19017
19018   return result;
19019 }
19020
19021 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
19022    tied to T. That list of typedefs will be access checked at
19023    T instantiation time.
19024    T is either a FUNCTION_DECL or a RECORD_TYPE.
19025    TYPE_DECL is a TYPE_DECL node representing a typedef.
19026    SCOPE is the scope through which TYPE_DECL is accessed.
19027    LOCATION is the location of the usage point of TYPE_DECL.
19028
19029    This function is a subroutine of
19030    append_type_to_template_for_access_check.  */
19031
19032 static void
19033 append_type_to_template_for_access_check_1 (tree t,
19034                                             tree type_decl,
19035                                             tree scope,
19036                                             location_t location)
19037 {
19038   qualified_typedef_usage_t typedef_usage;
19039   tree ti;
19040
19041   if (!t || t == error_mark_node)
19042     return;
19043
19044   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
19045                || CLASS_TYPE_P (t))
19046               && type_decl
19047               && TREE_CODE (type_decl) == TYPE_DECL
19048               && scope);
19049
19050   if (!(ti = get_template_info (t)))
19051     return;
19052
19053   gcc_assert (TI_TEMPLATE (ti));
19054
19055   typedef_usage.typedef_decl = type_decl;
19056   typedef_usage.context = scope;
19057   typedef_usage.locus = location;
19058
19059   VEC_safe_push (qualified_typedef_usage_t, gc,
19060                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
19061                  &typedef_usage);
19062 }
19063
19064 /* Append TYPE_DECL to the template TEMPL.
19065    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
19066    At TEMPL instanciation time, TYPE_DECL will be checked to see
19067    if it can be accessed through SCOPE.
19068    LOCATION is the location of the usage point of TYPE_DECL.
19069
19070    e.g. consider the following code snippet:
19071
19072      class C
19073      {
19074        typedef int myint;
19075      };
19076
19077      template<class U> struct S
19078      {
19079        C::myint mi; // <-- usage point of the typedef C::myint
19080      };
19081
19082      S<char> s;
19083
19084    At S<char> instantiation time, we need to check the access of C::myint
19085    In other words, we need to check the access of the myint typedef through
19086    the C scope. For that purpose, this function will add the myint typedef
19087    and the scope C through which its being accessed to a list of typedefs
19088    tied to the template S. That list will be walked at template instantiation
19089    time and access check performed on each typedefs it contains.
19090    Note that this particular code snippet should yield an error because
19091    myint is private to C.  */
19092
19093 void
19094 append_type_to_template_for_access_check (tree templ,
19095                                           tree type_decl,
19096                                           tree scope,
19097                                           location_t location)
19098 {
19099   qualified_typedef_usage_t *iter;
19100   int i;
19101
19102   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
19103
19104   /* Make sure we don't append the type to the template twice.  */
19105   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
19106                     get_types_needing_access_check (templ),
19107                     i, iter)
19108     if (iter->typedef_decl == type_decl && scope == iter->context)
19109       return;
19110
19111   append_type_to_template_for_access_check_1 (templ, type_decl,
19112                                               scope, location);
19113 }
19114
19115 /* Set up the hash tables for template instantiations.  */
19116
19117 void
19118 init_template_processing (void)
19119 {
19120   decl_specializations = htab_create_ggc (37,
19121                                           hash_specialization,
19122                                           eq_specializations,
19123                                           ggc_free);
19124   type_specializations = htab_create_ggc (37,
19125                                           hash_specialization,
19126                                           eq_specializations,
19127                                           ggc_free);
19128 }
19129
19130 /* Print stats about the template hash tables for -fstats.  */
19131
19132 void
19133 print_template_statistics (void)
19134 {
19135   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
19136            "%f collisions\n", (long) htab_size (decl_specializations),
19137            (long) htab_elements (decl_specializations),
19138            htab_collisions (decl_specializations));
19139   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
19140            "%f collisions\n", (long) htab_size (type_specializations),
19141            (long) htab_elements (type_specializations),
19142            htab_collisions (type_specializations));
19143 }
19144
19145 #include "gt-cp-pt.h"