OSDN Git Service

PR c++/50614
[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, 2011
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 ((chain_next ("%h.next"))) 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 enum template_base_result {
113   tbr_incomplete_type,
114   tbr_ambiguous_baseclass,
115   tbr_success
116 };
117
118 static void push_access_scope (tree);
119 static void pop_access_scope (tree);
120 static void push_deduction_access_scope (tree);
121 static void pop_deduction_access_scope (tree);
122 static bool resolve_overloaded_unification (tree, tree, tree, tree,
123                                             unification_kind_t, int,
124                                             bool);
125 static int try_one_overload (tree, tree, tree, tree, tree,
126                              unification_kind_t, int, bool, bool);
127 static int unify (tree, tree, tree, tree, int, bool);
128 static void add_pending_template (tree);
129 static tree reopen_tinst_level (struct tinst_level *);
130 static tree tsubst_initializer_list (tree, tree);
131 static tree get_class_bindings (tree, tree, tree);
132 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
133                                    bool, bool);
134 static void tsubst_enum (tree, tree, tree);
135 static tree add_to_template_args (tree, tree);
136 static tree add_outermost_template_args (tree, tree);
137 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
138 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
139                                              tree);
140 static int type_unification_real (tree, tree, tree, const tree *,
141                                   unsigned int, int, unification_kind_t, int,
142                                   bool);
143 static void note_template_header (int);
144 static tree convert_nontype_argument_function (tree, tree);
145 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
146 static tree convert_template_argument (tree, tree, tree,
147                                        tsubst_flags_t, int, tree);
148 static int for_each_template_parm (tree, tree_fn_t, void*,
149                                    struct pointer_set_t*, bool);
150 static tree expand_template_argument_pack (tree);
151 static tree build_template_parm_index (int, int, int, int, tree, tree);
152 static bool inline_needs_template_parms (tree);
153 static void push_inline_template_parms_recursive (tree, int);
154 static tree retrieve_local_specialization (tree);
155 static void register_local_specialization (tree, tree);
156 static hashval_t hash_specialization (const void *p);
157 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
158 static int mark_template_parm (tree, void *);
159 static int template_parm_this_level_p (tree, void *);
160 static tree tsubst_friend_function (tree, tree);
161 static tree tsubst_friend_class (tree, tree);
162 static int can_complete_type_without_circularity (tree);
163 static tree get_bindings (tree, tree, tree, bool);
164 static int template_decl_level (tree);
165 static int check_cv_quals_for_unify (int, tree, tree);
166 static void template_parm_level_and_index (tree, int*, int*);
167 static int unify_pack_expansion (tree, tree, tree,
168                                  tree, unification_kind_t, bool, bool);
169 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
170 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
171 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
172 static void regenerate_decl_from_template (tree, tree);
173 static tree most_specialized_class (tree, tree, tsubst_flags_t);
174 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
175 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
176 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
177 static bool check_specialization_scope (void);
178 static tree process_partial_specialization (tree);
179 static void set_current_access_from_decl (tree);
180 static enum template_base_result get_template_base (tree, tree, tree, tree,
181                                                     bool , tree *);
182 static tree try_class_unification (tree, tree, tree, tree, bool);
183 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
184                                            tree, tree);
185 static bool template_template_parm_bindings_ok_p (tree, tree);
186 static int template_args_equal (tree, tree);
187 static void tsubst_default_arguments (tree);
188 static tree for_each_template_parm_r (tree *, int *, void *);
189 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
190 static void copy_default_args_to_explicit_spec (tree);
191 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
192 static int eq_local_specializations (const void *, const void *);
193 static bool dependent_template_arg_p (tree);
194 static bool any_template_arguments_need_structural_equality_p (tree);
195 static bool dependent_type_p_r (tree);
196 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
197 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
198 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
199 static tree tsubst_decl (tree, tree, tsubst_flags_t);
200 static void perform_typedefs_access_check (tree tmpl, tree targs);
201 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
202                                                         location_t);
203 static tree listify (tree);
204 static tree listify_autos (tree, tree);
205 static tree template_parm_to_arg (tree t);
206 static bool arg_from_parm_pack_p (tree, tree);
207 static tree current_template_args (void);
208 static tree fixup_template_type_parm_type (tree, int);
209 static tree fixup_template_parm_index (tree, tree, int);
210 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
211
212 /* Make the current scope suitable for access checking when we are
213    processing T.  T can be FUNCTION_DECL for instantiated function
214    template, or VAR_DECL for static member variable (need by
215    instantiate_decl).  */
216
217 static void
218 push_access_scope (tree t)
219 {
220   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
221               || TREE_CODE (t) == VAR_DECL);
222
223   if (DECL_FRIEND_CONTEXT (t))
224     push_nested_class (DECL_FRIEND_CONTEXT (t));
225   else if (DECL_CLASS_SCOPE_P (t))
226     push_nested_class (DECL_CONTEXT (t));
227   else
228     push_to_top_level ();
229
230   if (TREE_CODE (t) == FUNCTION_DECL)
231     {
232       saved_access_scope = tree_cons
233         (NULL_TREE, current_function_decl, saved_access_scope);
234       current_function_decl = t;
235     }
236 }
237
238 /* Restore the scope set up by push_access_scope.  T is the node we
239    are processing.  */
240
241 static void
242 pop_access_scope (tree t)
243 {
244   if (TREE_CODE (t) == FUNCTION_DECL)
245     {
246       current_function_decl = TREE_VALUE (saved_access_scope);
247       saved_access_scope = TREE_CHAIN (saved_access_scope);
248     }
249
250   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
251     pop_nested_class ();
252   else
253     pop_from_top_level ();
254 }
255
256 /* Do any processing required when DECL (a member template
257    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
258    to DECL, unless it is a specialization, in which case the DECL
259    itself is returned.  */
260
261 tree
262 finish_member_template_decl (tree decl)
263 {
264   if (decl == error_mark_node)
265     return error_mark_node;
266
267   gcc_assert (DECL_P (decl));
268
269   if (TREE_CODE (decl) == TYPE_DECL)
270     {
271       tree type;
272
273       type = TREE_TYPE (decl);
274       if (type == error_mark_node)
275         return error_mark_node;
276       if (MAYBE_CLASS_TYPE_P (type)
277           && CLASSTYPE_TEMPLATE_INFO (type)
278           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
279         {
280           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
281           check_member_template (tmpl);
282           return tmpl;
283         }
284       return NULL_TREE;
285     }
286   else if (TREE_CODE (decl) == FIELD_DECL)
287     error ("data member %qD cannot be a member template", decl);
288   else if (DECL_TEMPLATE_INFO (decl))
289     {
290       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
291         {
292           check_member_template (DECL_TI_TEMPLATE (decl));
293           return DECL_TI_TEMPLATE (decl);
294         }
295       else
296         return decl;
297     }
298   else
299     error ("invalid member template declaration %qD", decl);
300
301   return error_mark_node;
302 }
303
304 /* Create a template info node.  */
305
306 tree
307 build_template_info (tree template_decl, tree template_args)
308 {
309   tree result = make_node (TEMPLATE_INFO);
310   TI_TEMPLATE (result) = template_decl;
311   TI_ARGS (result) = template_args;
312   return result;
313 }
314
315 /* Return the template info node corresponding to T, whatever T is.  */
316
317 tree
318 get_template_info (const_tree t)
319 {
320   tree tinfo = NULL_TREE;
321
322   if (!t || t == error_mark_node)
323     return NULL;
324
325   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
326     tinfo = DECL_TEMPLATE_INFO (t);
327
328   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
329     t = TREE_TYPE (t);
330
331   if (TAGGED_TYPE_P (t))
332     tinfo = TYPE_TEMPLATE_INFO (t);
333   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
334     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
335
336   return tinfo;
337 }
338
339 /* Returns the template nesting level of the indicated class TYPE.
340
341    For example, in:
342      template <class T>
343      struct A
344      {
345        template <class U>
346        struct B {};
347      };
348
349    A<T>::B<U> has depth two, while A<T> has depth one.
350    Both A<T>::B<int> and A<int>::B<U> have depth one, if
351    they are instantiations, not specializations.
352
353    This function is guaranteed to return 0 if passed NULL_TREE so
354    that, for example, `template_class_depth (current_class_type)' is
355    always safe.  */
356
357 int
358 template_class_depth (tree type)
359 {
360   int depth;
361
362   for (depth = 0;
363        type && TREE_CODE (type) != NAMESPACE_DECL;
364        type = (TREE_CODE (type) == FUNCTION_DECL)
365          ? CP_DECL_CONTEXT (type) : CP_TYPE_CONTEXT (type))
366     {
367       tree tinfo = get_template_info (type);
368
369       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
370           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
371         ++depth;
372     }
373
374   return depth;
375 }
376
377 /* Subroutine of maybe_begin_member_template_processing.
378    Returns true if processing DECL needs us to push template parms.  */
379
380 static bool
381 inline_needs_template_parms (tree decl)
382 {
383   if (! DECL_TEMPLATE_INFO (decl))
384     return false;
385
386   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
387           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
388 }
389
390 /* Subroutine of maybe_begin_member_template_processing.
391    Push the template parms in PARMS, starting from LEVELS steps into the
392    chain, and ending at the beginning, since template parms are listed
393    innermost first.  */
394
395 static void
396 push_inline_template_parms_recursive (tree parmlist, int levels)
397 {
398   tree parms = TREE_VALUE (parmlist);
399   int i;
400
401   if (levels > 1)
402     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
403
404   ++processing_template_decl;
405   current_template_parms
406     = tree_cons (size_int (processing_template_decl),
407                  parms, current_template_parms);
408   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
409
410   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
411                NULL);
412   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
413     {
414       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
415
416       if (parm == error_mark_node)
417         continue;
418
419       gcc_assert (DECL_P (parm));
420
421       switch (TREE_CODE (parm))
422         {
423         case TYPE_DECL:
424         case TEMPLATE_DECL:
425           pushdecl (parm);
426           break;
427
428         case PARM_DECL:
429           {
430             /* Make a CONST_DECL as is done in process_template_parm.
431                It is ugly that we recreate this here; the original
432                version built in process_template_parm is no longer
433                available.  */
434             tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
435                                     CONST_DECL, DECL_NAME (parm),
436                                     TREE_TYPE (parm));
437             DECL_ARTIFICIAL (decl) = 1;
438             TREE_CONSTANT (decl) = 1;
439             TREE_READONLY (decl) = 1;
440             DECL_INITIAL (decl) = DECL_INITIAL (parm);
441             SET_DECL_TEMPLATE_PARM_P (decl);
442             pushdecl (decl);
443           }
444           break;
445
446         default:
447           gcc_unreachable ();
448         }
449     }
450 }
451
452 /* Restore the template parameter context for a member template or
453    a friend template defined in a class definition.  */
454
455 void
456 maybe_begin_member_template_processing (tree decl)
457 {
458   tree parms;
459   int levels = 0;
460
461   if (inline_needs_template_parms (decl))
462     {
463       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
464       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
465
466       if (DECL_TEMPLATE_SPECIALIZATION (decl))
467         {
468           --levels;
469           parms = TREE_CHAIN (parms);
470         }
471
472       push_inline_template_parms_recursive (parms, levels);
473     }
474
475   /* Remember how many levels of template parameters we pushed so that
476      we can pop them later.  */
477   VEC_safe_push (int, heap, inline_parm_levels, levels);
478 }
479
480 /* Undo the effects of maybe_begin_member_template_processing.  */
481
482 void
483 maybe_end_member_template_processing (void)
484 {
485   int i;
486   int last;
487
488   if (VEC_length (int, inline_parm_levels) == 0)
489     return;
490
491   last = VEC_pop (int, inline_parm_levels);
492   for (i = 0; i < last; ++i)
493     {
494       --processing_template_decl;
495       current_template_parms = TREE_CHAIN (current_template_parms);
496       poplevel (0, 0, 0);
497     }
498 }
499
500 /* Return a new template argument vector which contains all of ARGS,
501    but has as its innermost set of arguments the EXTRA_ARGS.  */
502
503 static tree
504 add_to_template_args (tree args, tree extra_args)
505 {
506   tree new_args;
507   int extra_depth;
508   int i;
509   int j;
510
511   if (args == NULL_TREE || extra_args == error_mark_node)
512     return extra_args;
513
514   extra_depth = TMPL_ARGS_DEPTH (extra_args);
515   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
516
517   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
518     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
519
520   for (j = 1; j <= extra_depth; ++j, ++i)
521     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
522
523   return new_args;
524 }
525
526 /* Like add_to_template_args, but only the outermost ARGS are added to
527    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
528    (EXTRA_ARGS) levels are added.  This function is used to combine
529    the template arguments from a partial instantiation with the
530    template arguments used to attain the full instantiation from the
531    partial instantiation.  */
532
533 static tree
534 add_outermost_template_args (tree args, tree extra_args)
535 {
536   tree new_args;
537
538   /* If there are more levels of EXTRA_ARGS than there are ARGS,
539      something very fishy is going on.  */
540   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
541
542   /* If *all* the new arguments will be the EXTRA_ARGS, just return
543      them.  */
544   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
545     return extra_args;
546
547   /* For the moment, we make ARGS look like it contains fewer levels.  */
548   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
549
550   new_args = add_to_template_args (args, extra_args);
551
552   /* Now, we restore ARGS to its full dimensions.  */
553   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
554
555   return new_args;
556 }
557
558 /* Return the N levels of innermost template arguments from the ARGS.  */
559
560 tree
561 get_innermost_template_args (tree args, int n)
562 {
563   tree new_args;
564   int extra_levels;
565   int i;
566
567   gcc_assert (n >= 0);
568
569   /* If N is 1, just return the innermost set of template arguments.  */
570   if (n == 1)
571     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
572
573   /* If we're not removing anything, just return the arguments we were
574      given.  */
575   extra_levels = TMPL_ARGS_DEPTH (args) - n;
576   gcc_assert (extra_levels >= 0);
577   if (extra_levels == 0)
578     return args;
579
580   /* Make a new set of arguments, not containing the outer arguments.  */
581   new_args = make_tree_vec (n);
582   for (i = 1; i <= n; ++i)
583     SET_TMPL_ARGS_LEVEL (new_args, i,
584                          TMPL_ARGS_LEVEL (args, i + extra_levels));
585
586   return new_args;
587 }
588
589 /* The inverse of get_innermost_template_args: Return all but the innermost
590    EXTRA_LEVELS levels of template arguments from the ARGS.  */
591
592 static tree
593 strip_innermost_template_args (tree args, int extra_levels)
594 {
595   tree new_args;
596   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
597   int i;
598
599   gcc_assert (n >= 0);
600
601   /* If N is 1, just return the outermost set of template arguments.  */
602   if (n == 1)
603     return TMPL_ARGS_LEVEL (args, 1);
604
605   /* If we're not removing anything, just return the arguments we were
606      given.  */
607   gcc_assert (extra_levels >= 0);
608   if (extra_levels == 0)
609     return args;
610
611   /* Make a new set of arguments, not containing the inner arguments.  */
612   new_args = make_tree_vec (n);
613   for (i = 1; i <= n; ++i)
614     SET_TMPL_ARGS_LEVEL (new_args, i,
615                          TMPL_ARGS_LEVEL (args, i));
616
617   return new_args;
618 }
619
620 /* We've got a template header coming up; push to a new level for storing
621    the parms.  */
622
623 void
624 begin_template_parm_list (void)
625 {
626   /* We use a non-tag-transparent scope here, which causes pushtag to
627      put tags in this scope, rather than in the enclosing class or
628      namespace scope.  This is the right thing, since we want
629      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
630      global template class, push_template_decl handles putting the
631      TEMPLATE_DECL into top-level scope.  For a nested template class,
632      e.g.:
633
634        template <class T> struct S1 {
635          template <class T> struct S2 {};
636        };
637
638      pushtag contains special code to call pushdecl_with_scope on the
639      TEMPLATE_DECL for S2.  */
640   begin_scope (sk_template_parms, NULL);
641   ++processing_template_decl;
642   ++processing_template_parmlist;
643   note_template_header (0);
644 }
645
646 /* This routine is called when a specialization is declared.  If it is
647    invalid to declare a specialization here, an error is reported and
648    false is returned, otherwise this routine will return true.  */
649
650 static bool
651 check_specialization_scope (void)
652 {
653   tree scope = current_scope ();
654
655   /* [temp.expl.spec]
656
657      An explicit specialization shall be declared in the namespace of
658      which the template is a member, or, for member templates, in the
659      namespace of which the enclosing class or enclosing class
660      template is a member.  An explicit specialization of a member
661      function, member class or static data member of a class template
662      shall be declared in the namespace of which the class template
663      is a member.  */
664   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
665     {
666       error ("explicit specialization in non-namespace scope %qD", scope);
667       return false;
668     }
669
670   /* [temp.expl.spec]
671
672      In an explicit specialization declaration for a member of a class
673      template or a member template that appears in namespace scope,
674      the member template and some of its enclosing class templates may
675      remain unspecialized, except that the declaration shall not
676      explicitly specialize a class member template if its enclosing
677      class templates are not explicitly specialized as well.  */
678   if (current_template_parms)
679     {
680       error ("enclosing class templates are not explicitly specialized");
681       return false;
682     }
683
684   return true;
685 }
686
687 /* We've just seen template <>.  */
688
689 bool
690 begin_specialization (void)
691 {
692   begin_scope (sk_template_spec, NULL);
693   note_template_header (1);
694   return check_specialization_scope ();
695 }
696
697 /* Called at then end of processing a declaration preceded by
698    template<>.  */
699
700 void
701 end_specialization (void)
702 {
703   finish_scope ();
704   reset_specialization ();
705 }
706
707 /* Any template <>'s that we have seen thus far are not referring to a
708    function specialization.  */
709
710 void
711 reset_specialization (void)
712 {
713   processing_specialization = 0;
714   template_header_count = 0;
715 }
716
717 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
718    it was of the form template <>.  */
719
720 static void
721 note_template_header (int specialization)
722 {
723   processing_specialization = specialization;
724   template_header_count++;
725 }
726
727 /* We're beginning an explicit instantiation.  */
728
729 void
730 begin_explicit_instantiation (void)
731 {
732   gcc_assert (!processing_explicit_instantiation);
733   processing_explicit_instantiation = true;
734 }
735
736
737 void
738 end_explicit_instantiation (void)
739 {
740   gcc_assert (processing_explicit_instantiation);
741   processing_explicit_instantiation = false;
742 }
743
744 /* An explicit specialization or partial specialization TMPL is being
745    declared.  Check that the namespace in which the specialization is
746    occurring is permissible.  Returns false iff it is invalid to
747    specialize TMPL in the current namespace.  */
748
749 static bool
750 check_specialization_namespace (tree tmpl)
751 {
752   tree tpl_ns = decl_namespace_context (tmpl);
753
754   /* [tmpl.expl.spec]
755
756      An explicit specialization shall be declared in the namespace of
757      which the template is a member, or, for member templates, in the
758      namespace of which the enclosing class or enclosing class
759      template is a member.  An explicit specialization of a member
760      function, member class or static data member of a class template
761      shall be declared in the namespace of which the class template is
762      a member.  */
763   if (current_scope() != DECL_CONTEXT (tmpl)
764       && !at_namespace_scope_p ())
765     {
766       error ("specialization of %qD must appear at namespace scope", tmpl);
767       return false;
768     }
769   if (is_associated_namespace (current_namespace, tpl_ns))
770     /* Same or super-using namespace.  */
771     return true;
772   else
773     {
774       permerror (input_location, "specialization of %qD in different namespace", tmpl);
775       permerror (input_location, "  from definition of %q+#D", tmpl);
776       return false;
777     }
778 }
779
780 /* SPEC is an explicit instantiation.  Check that it is valid to
781    perform this explicit instantiation in the current namespace.  */
782
783 static void
784 check_explicit_instantiation_namespace (tree spec)
785 {
786   tree ns;
787
788   /* DR 275: An explicit instantiation shall appear in an enclosing
789      namespace of its template.  */
790   ns = decl_namespace_context (spec);
791   if (!is_ancestor (current_namespace, ns))
792     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
793                "(which does not enclose namespace %qD)",
794                spec, current_namespace, ns);
795 }
796
797 /* The TYPE is being declared.  If it is a template type, that means it
798    is a partial specialization.  Do appropriate error-checking.  */
799
800 tree
801 maybe_process_partial_specialization (tree type)
802 {
803   tree context;
804
805   if (type == error_mark_node)
806     return error_mark_node;
807
808   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
809     {
810       error ("name of class shadows template template parameter %qD",
811              TYPE_NAME (type));
812       return error_mark_node;
813     }
814
815   context = TYPE_CONTEXT (type);
816
817   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
818     {
819       /* This is for ordinary explicit specialization and partial
820          specialization of a template class such as:
821
822            template <> class C<int>;
823
824          or:
825
826            template <class T> class C<T*>;
827
828          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
829
830       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
831           && !COMPLETE_TYPE_P (type))
832         {
833           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
834           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
835           if (processing_template_decl)
836             {
837               if (push_template_decl (TYPE_MAIN_DECL (type))
838                   == error_mark_node)
839                 return error_mark_node;
840             }
841         }
842       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
843         error ("specialization of %qT after instantiation", type);
844     }
845   else if (CLASS_TYPE_P (type)
846            && !CLASSTYPE_USE_TEMPLATE (type)
847            && CLASSTYPE_TEMPLATE_INFO (type)
848            && context && CLASS_TYPE_P (context)
849            && CLASSTYPE_TEMPLATE_INFO (context))
850     {
851       /* This is for an explicit specialization of member class
852          template according to [temp.expl.spec/18]:
853
854            template <> template <class U> class C<int>::D;
855
856          The context `C<int>' must be an implicit instantiation.
857          Otherwise this is just a member class template declared
858          earlier like:
859
860            template <> class C<int> { template <class U> class D; };
861            template <> template <class U> class C<int>::D;
862
863          In the first case, `C<int>::D' is a specialization of `C<T>::D'
864          while in the second case, `C<int>::D' is a primary template
865          and `C<T>::D' may not exist.  */
866
867       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
868           && !COMPLETE_TYPE_P (type))
869         {
870           tree t;
871           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
872
873           if (current_namespace
874               != decl_namespace_context (tmpl))
875             {
876               permerror (input_location, "specializing %q#T in different namespace", type);
877               permerror (input_location, "  from definition of %q+#D", tmpl);
878             }
879
880           /* Check for invalid specialization after instantiation:
881
882                template <> template <> class C<int>::D<int>;
883                template <> template <class U> class C<int>::D;  */
884
885           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
886                t; t = TREE_CHAIN (t))
887             {
888               tree inst = TREE_VALUE (t);
889               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst))
890                 {
891                   /* We already have a full specialization of this partial
892                      instantiation.  Reassign it to the new member
893                      specialization template.  */
894                   spec_entry elt;
895                   spec_entry *entry;
896                   void **slot;
897
898                   elt.tmpl = most_general_template (tmpl);
899                   elt.args = CLASSTYPE_TI_ARGS (inst);
900                   elt.spec = inst;
901
902                   htab_remove_elt (type_specializations, &elt);
903
904                   elt.tmpl = tmpl;
905                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
906
907                   slot = htab_find_slot (type_specializations, &elt, INSERT);
908                   entry = ggc_alloc_spec_entry ();
909                   *entry = elt;
910                   *slot = entry;
911                 }
912               else if (COMPLETE_OR_OPEN_TYPE_P (inst))
913                 /* But if we've had an implicit instantiation, that's a
914                    problem ([temp.expl.spec]/6).  */
915                 error ("specialization %qT after instantiation %qT",
916                        type, inst);
917             }
918
919           /* Mark TYPE as a specialization.  And as a result, we only
920              have one level of template argument for the innermost
921              class template.  */
922           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
923           CLASSTYPE_TI_ARGS (type)
924             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
925         }
926     }
927   else if (processing_specialization)
928     {
929        /* Someday C++0x may allow for enum template specialization.  */
930       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
931           && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
932         pedwarn (input_location, OPT_pedantic, "template specialization "
933                  "of %qD not allowed by ISO C++", type);
934       else
935         {
936           error ("explicit specialization of non-template %qT", type);
937           return error_mark_node;
938         }
939     }
940
941   return type;
942 }
943
944 /* Returns nonzero if we can optimize the retrieval of specializations
945    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
946    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
947
948 static inline bool
949 optimize_specialization_lookup_p (tree tmpl)
950 {
951   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
952           && DECL_CLASS_SCOPE_P (tmpl)
953           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
954              parameter.  */
955           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
956           /* The optimized lookup depends on the fact that the
957              template arguments for the member function template apply
958              purely to the containing class, which is not true if the
959              containing class is an explicit or partial
960              specialization.  */
961           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
962           && !DECL_MEMBER_TEMPLATE_P (tmpl)
963           && !DECL_CONV_FN_P (tmpl)
964           /* It is possible to have a template that is not a member
965              template and is not a member of a template class:
966
967              template <typename T>
968              struct S { friend A::f(); };
969
970              Here, the friend function is a template, but the context does
971              not have template information.  The optimized lookup relies
972              on having ARGS be the template arguments for both the class
973              and the function template.  */
974           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
975 }
976
977 /* Retrieve the specialization (in the sense of [temp.spec] - a
978    specialization is either an instantiation or an explicit
979    specialization) of TMPL for the given template ARGS.  If there is
980    no such specialization, return NULL_TREE.  The ARGS are a vector of
981    arguments, or a vector of vectors of arguments, in the case of
982    templates with more than one level of parameters.
983
984    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
985    then we search for a partial specialization matching ARGS.  This
986    parameter is ignored if TMPL is not a class template.  */
987
988 static tree
989 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
990 {
991   if (args == error_mark_node)
992     return NULL_TREE;
993
994   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
995
996   /* There should be as many levels of arguments as there are
997      levels of parameters.  */
998   gcc_assert (TMPL_ARGS_DEPTH (args)
999               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
1000
1001   if (optimize_specialization_lookup_p (tmpl))
1002     {
1003       tree class_template;
1004       tree class_specialization;
1005       VEC(tree,gc) *methods;
1006       tree fns;
1007       int idx;
1008
1009       /* The template arguments actually apply to the containing
1010          class.  Find the class specialization with those
1011          arguments.  */
1012       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1013       class_specialization
1014         = retrieve_specialization (class_template, args, 0);
1015       if (!class_specialization)
1016         return NULL_TREE;
1017       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
1018          for the specialization.  */
1019       idx = class_method_index_for_fn (class_specialization, tmpl);
1020       if (idx == -1)
1021         return NULL_TREE;
1022       /* Iterate through the methods with the indicated name, looking
1023          for the one that has an instance of TMPL.  */
1024       methods = CLASSTYPE_METHOD_VEC (class_specialization);
1025       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
1026         {
1027           tree fn = OVL_CURRENT (fns);
1028           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1029               /* using-declarations can add base methods to the method vec,
1030                  and we don't want those here.  */
1031               && DECL_CONTEXT (fn) == class_specialization)
1032             return fn;
1033         }
1034       return NULL_TREE;
1035     }
1036   else
1037     {
1038       spec_entry *found;
1039       spec_entry elt;
1040       htab_t specializations;
1041
1042       elt.tmpl = tmpl;
1043       elt.args = args;
1044       elt.spec = NULL_TREE;
1045
1046       if (DECL_CLASS_TEMPLATE_P (tmpl))
1047         specializations = type_specializations;
1048       else
1049         specializations = decl_specializations;
1050
1051       if (hash == 0)
1052         hash = hash_specialization (&elt);
1053       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1054       if (found)
1055         return found->spec;
1056     }
1057
1058   return NULL_TREE;
1059 }
1060
1061 /* Like retrieve_specialization, but for local declarations.  */
1062
1063 static tree
1064 retrieve_local_specialization (tree tmpl)
1065 {
1066   tree spec;
1067
1068   if (local_specializations == NULL)
1069     return NULL_TREE;
1070
1071   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1072                                      htab_hash_pointer (tmpl));
1073   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1074 }
1075
1076 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1077
1078 int
1079 is_specialization_of (tree decl, tree tmpl)
1080 {
1081   tree t;
1082
1083   if (TREE_CODE (decl) == FUNCTION_DECL)
1084     {
1085       for (t = decl;
1086            t != NULL_TREE;
1087            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1088         if (t == tmpl)
1089           return 1;
1090     }
1091   else
1092     {
1093       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1094
1095       for (t = TREE_TYPE (decl);
1096            t != NULL_TREE;
1097            t = CLASSTYPE_USE_TEMPLATE (t)
1098              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1099         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1100           return 1;
1101     }
1102
1103   return 0;
1104 }
1105
1106 /* Returns nonzero iff DECL is a specialization of friend declaration
1107    FRIEND_DECL according to [temp.friend].  */
1108
1109 bool
1110 is_specialization_of_friend (tree decl, tree friend_decl)
1111 {
1112   bool need_template = true;
1113   int template_depth;
1114
1115   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1116               || TREE_CODE (decl) == TYPE_DECL);
1117
1118   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1119      of a template class, we want to check if DECL is a specialization
1120      if this.  */
1121   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1122       && DECL_TEMPLATE_INFO (friend_decl)
1123       && !DECL_USE_TEMPLATE (friend_decl))
1124     {
1125       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1126       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1127       need_template = false;
1128     }
1129   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1130            && !PRIMARY_TEMPLATE_P (friend_decl))
1131     need_template = false;
1132
1133   /* There is nothing to do if this is not a template friend.  */
1134   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1135     return false;
1136
1137   if (is_specialization_of (decl, friend_decl))
1138     return true;
1139
1140   /* [temp.friend/6]
1141      A member of a class template may be declared to be a friend of a
1142      non-template class.  In this case, the corresponding member of
1143      every specialization of the class template is a friend of the
1144      class granting friendship.
1145
1146      For example, given a template friend declaration
1147
1148        template <class T> friend void A<T>::f();
1149
1150      the member function below is considered a friend
1151
1152        template <> struct A<int> {
1153          void f();
1154        };
1155
1156      For this type of template friend, TEMPLATE_DEPTH below will be
1157      nonzero.  To determine if DECL is a friend of FRIEND, we first
1158      check if the enclosing class is a specialization of another.  */
1159
1160   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1161   if (template_depth
1162       && DECL_CLASS_SCOPE_P (decl)
1163       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1164                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1165     {
1166       /* Next, we check the members themselves.  In order to handle
1167          a few tricky cases, such as when FRIEND_DECL's are
1168
1169            template <class T> friend void A<T>::g(T t);
1170            template <class T> template <T t> friend void A<T>::h();
1171
1172          and DECL's are
1173
1174            void A<int>::g(int);
1175            template <int> void A<int>::h();
1176
1177          we need to figure out ARGS, the template arguments from
1178          the context of DECL.  This is required for template substitution
1179          of `T' in the function parameter of `g' and template parameter
1180          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1181
1182       tree context = DECL_CONTEXT (decl);
1183       tree args = NULL_TREE;
1184       int current_depth = 0;
1185
1186       while (current_depth < template_depth)
1187         {
1188           if (CLASSTYPE_TEMPLATE_INFO (context))
1189             {
1190               if (current_depth == 0)
1191                 args = TYPE_TI_ARGS (context);
1192               else
1193                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1194               current_depth++;
1195             }
1196           context = TYPE_CONTEXT (context);
1197         }
1198
1199       if (TREE_CODE (decl) == FUNCTION_DECL)
1200         {
1201           bool is_template;
1202           tree friend_type;
1203           tree decl_type;
1204           tree friend_args_type;
1205           tree decl_args_type;
1206
1207           /* Make sure that both DECL and FRIEND_DECL are templates or
1208              non-templates.  */
1209           is_template = DECL_TEMPLATE_INFO (decl)
1210                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1211           if (need_template ^ is_template)
1212             return false;
1213           else if (is_template)
1214             {
1215               /* If both are templates, check template parameter list.  */
1216               tree friend_parms
1217                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1218                                          args, tf_none);
1219               if (!comp_template_parms
1220                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1221                       friend_parms))
1222                 return false;
1223
1224               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1225             }
1226           else
1227             decl_type = TREE_TYPE (decl);
1228
1229           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1230                                               tf_none, NULL_TREE);
1231           if (friend_type == error_mark_node)
1232             return false;
1233
1234           /* Check if return types match.  */
1235           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1236             return false;
1237
1238           /* Check if function parameter types match, ignoring the
1239              `this' parameter.  */
1240           friend_args_type = TYPE_ARG_TYPES (friend_type);
1241           decl_args_type = TYPE_ARG_TYPES (decl_type);
1242           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1243             friend_args_type = TREE_CHAIN (friend_args_type);
1244           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1245             decl_args_type = TREE_CHAIN (decl_args_type);
1246
1247           return compparms (decl_args_type, friend_args_type);
1248         }
1249       else
1250         {
1251           /* DECL is a TYPE_DECL */
1252           bool is_template;
1253           tree decl_type = TREE_TYPE (decl);
1254
1255           /* Make sure that both DECL and FRIEND_DECL are templates or
1256              non-templates.  */
1257           is_template
1258             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1259               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1260
1261           if (need_template ^ is_template)
1262             return false;
1263           else if (is_template)
1264             {
1265               tree friend_parms;
1266               /* If both are templates, check the name of the two
1267                  TEMPLATE_DECL's first because is_friend didn't.  */
1268               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1269                   != DECL_NAME (friend_decl))
1270                 return false;
1271
1272               /* Now check template parameter list.  */
1273               friend_parms
1274                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1275                                          args, tf_none);
1276               return comp_template_parms
1277                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1278                  friend_parms);
1279             }
1280           else
1281             return (DECL_NAME (decl)
1282                     == DECL_NAME (friend_decl));
1283         }
1284     }
1285   return false;
1286 }
1287
1288 /* Register the specialization SPEC as a specialization of TMPL with
1289    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1290    is actually just a friend declaration.  Returns SPEC, or an
1291    equivalent prior declaration, if available.  */
1292
1293 static tree
1294 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1295                          hashval_t hash)
1296 {
1297   tree fn;
1298   void **slot = NULL;
1299   spec_entry elt;
1300
1301   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1302
1303   if (TREE_CODE (spec) == FUNCTION_DECL
1304       && uses_template_parms (DECL_TI_ARGS (spec)))
1305     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1306        register it; we want the corresponding TEMPLATE_DECL instead.
1307        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1308        the more obvious `uses_template_parms (spec)' to avoid problems
1309        with default function arguments.  In particular, given
1310        something like this:
1311
1312           template <class T> void f(T t1, T t = T())
1313
1314        the default argument expression is not substituted for in an
1315        instantiation unless and until it is actually needed.  */
1316     return spec;
1317
1318   if (optimize_specialization_lookup_p (tmpl))
1319     /* We don't put these specializations in the hash table, but we might
1320        want to give an error about a mismatch.  */
1321     fn = retrieve_specialization (tmpl, args, 0);
1322   else
1323     {
1324       elt.tmpl = tmpl;
1325       elt.args = args;
1326       elt.spec = spec;
1327
1328       if (hash == 0)
1329         hash = hash_specialization (&elt);
1330
1331       slot =
1332         htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1333       if (*slot)
1334         fn = ((spec_entry *) *slot)->spec;
1335       else
1336         fn = NULL_TREE;
1337     }
1338
1339   /* We can sometimes try to re-register a specialization that we've
1340      already got.  In particular, regenerate_decl_from_template calls
1341      duplicate_decls which will update the specialization list.  But,
1342      we'll still get called again here anyhow.  It's more convenient
1343      to simply allow this than to try to prevent it.  */
1344   if (fn == spec)
1345     return spec;
1346   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1347     {
1348       if (DECL_TEMPLATE_INSTANTIATION (fn))
1349         {
1350           if (DECL_ODR_USED (fn)
1351               || DECL_EXPLICIT_INSTANTIATION (fn))
1352             {
1353               error ("specialization of %qD after instantiation",
1354                      fn);
1355               return error_mark_node;
1356             }
1357           else
1358             {
1359               tree clone;
1360               /* This situation should occur only if the first
1361                  specialization is an implicit instantiation, the
1362                  second is an explicit specialization, and the
1363                  implicit instantiation has not yet been used.  That
1364                  situation can occur if we have implicitly
1365                  instantiated a member function and then specialized
1366                  it later.
1367
1368                  We can also wind up here if a friend declaration that
1369                  looked like an instantiation turns out to be a
1370                  specialization:
1371
1372                    template <class T> void foo(T);
1373                    class S { friend void foo<>(int) };
1374                    template <> void foo(int);
1375
1376                  We transform the existing DECL in place so that any
1377                  pointers to it become pointers to the updated
1378                  declaration.
1379
1380                  If there was a definition for the template, but not
1381                  for the specialization, we want this to look as if
1382                  there were no definition, and vice versa.  */
1383               DECL_INITIAL (fn) = NULL_TREE;
1384               duplicate_decls (spec, fn, is_friend);
1385               /* The call to duplicate_decls will have applied
1386                  [temp.expl.spec]:
1387
1388                    An explicit specialization of a function template
1389                    is inline only if it is explicitly declared to be,
1390                    and independently of whether its function template
1391                    is.
1392
1393                 to the primary function; now copy the inline bits to
1394                 the various clones.  */
1395               FOR_EACH_CLONE (clone, fn)
1396                 {
1397                   DECL_DECLARED_INLINE_P (clone)
1398                     = DECL_DECLARED_INLINE_P (fn);
1399                   DECL_SOURCE_LOCATION (clone)
1400                     = DECL_SOURCE_LOCATION (fn);
1401                 }
1402               check_specialization_namespace (fn);
1403
1404               return fn;
1405             }
1406         }
1407       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1408         {
1409           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1410             /* Dup decl failed, but this is a new definition. Set the
1411                line number so any errors match this new
1412                definition.  */
1413             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1414
1415           return fn;
1416         }
1417     }
1418   else if (fn)
1419     return duplicate_decls (spec, fn, is_friend);
1420
1421   /* A specialization must be declared in the same namespace as the
1422      template it is specializing.  */
1423   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1424       && !check_specialization_namespace (tmpl))
1425     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1426
1427   if (slot != NULL /* !optimize_specialization_lookup_p (tmpl) */)
1428     {
1429       spec_entry *entry = ggc_alloc_spec_entry ();
1430       gcc_assert (tmpl && args && spec);
1431       *entry = elt;
1432       *slot = entry;
1433       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1434           && PRIMARY_TEMPLATE_P (tmpl)
1435           && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1436         /* TMPL is a forward declaration of a template function; keep a list
1437            of all specializations in case we need to reassign them to a friend
1438            template later in tsubst_friend_function.  */
1439         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1440           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1441     }
1442
1443   return spec;
1444 }
1445
1446 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1447    TMPL and ARGS members, ignores SPEC.  */
1448
1449 static int
1450 eq_specializations (const void *p1, const void *p2)
1451 {
1452   const spec_entry *e1 = (const spec_entry *)p1;
1453   const spec_entry *e2 = (const spec_entry *)p2;
1454
1455   return (e1->tmpl == e2->tmpl
1456           && comp_template_args (e1->args, e2->args));
1457 }
1458
1459 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1460
1461 static hashval_t
1462 hash_tmpl_and_args (tree tmpl, tree args)
1463 {
1464   hashval_t val = DECL_UID (tmpl);
1465   return iterative_hash_template_arg (args, val);
1466 }
1467
1468 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1469    ignoring SPEC.  */
1470
1471 static hashval_t
1472 hash_specialization (const void *p)
1473 {
1474   const spec_entry *e = (const spec_entry *)p;
1475   return hash_tmpl_and_args (e->tmpl, e->args);
1476 }
1477
1478 /* Recursively calculate a hash value for a template argument ARG, for use
1479    in the hash tables of template specializations.  */
1480
1481 hashval_t
1482 iterative_hash_template_arg (tree arg, hashval_t val)
1483 {
1484   unsigned HOST_WIDE_INT i;
1485   enum tree_code code;
1486   char tclass;
1487
1488   if (arg == NULL_TREE)
1489     return iterative_hash_object (arg, val);
1490
1491   if (!TYPE_P (arg))
1492     STRIP_NOPS (arg);
1493
1494   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1495     /* We can get one of these when re-hashing a previous entry in the middle
1496        of substituting into a pack expansion.  Just look through it.  */
1497     arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1498
1499   code = TREE_CODE (arg);
1500   tclass = TREE_CODE_CLASS (code);
1501
1502   val = iterative_hash_object (code, val);
1503
1504   switch (code)
1505     {
1506     case ERROR_MARK:
1507       return val;
1508
1509     case IDENTIFIER_NODE:
1510       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1511
1512     case TREE_VEC:
1513       {
1514         int i, len = TREE_VEC_LENGTH (arg);
1515         for (i = 0; i < len; ++i)
1516           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1517         return val;
1518       }
1519
1520     case TYPE_PACK_EXPANSION:
1521     case EXPR_PACK_EXPANSION:
1522       return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1523
1524     case TYPE_ARGUMENT_PACK:
1525     case NONTYPE_ARGUMENT_PACK:
1526       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1527
1528     case TREE_LIST:
1529       for (; arg; arg = TREE_CHAIN (arg))
1530         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1531       return val;
1532
1533     case OVERLOAD:
1534       for (; arg; arg = OVL_NEXT (arg))
1535         val = iterative_hash_template_arg (OVL_CURRENT (arg), val);
1536       return val;
1537
1538     case CONSTRUCTOR:
1539       {
1540         tree field, value;
1541         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1542           {
1543             val = iterative_hash_template_arg (field, val);
1544             val = iterative_hash_template_arg (value, val);
1545           }
1546         return val;
1547       }
1548
1549     case PARM_DECL:
1550       if (!DECL_ARTIFICIAL (arg))
1551         {
1552           val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1553           val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1554         }
1555       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1556
1557     case TARGET_EXPR:
1558       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1559
1560     case PTRMEM_CST:
1561       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1562       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1563
1564     case TEMPLATE_PARM_INDEX:
1565       val = iterative_hash_template_arg
1566         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1567       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1568       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1569
1570     case TRAIT_EXPR:
1571       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1572       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1573       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1574
1575     case BASELINK:
1576       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1577                                          val);
1578       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1579                                           val);
1580
1581     case MODOP_EXPR:
1582       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1583       code = TREE_CODE (TREE_OPERAND (arg, 1));
1584       val = iterative_hash_object (code, val);
1585       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1586
1587     case LAMBDA_EXPR:
1588       /* A lambda can't appear in a template arg, but don't crash on
1589          erroneous input.  */
1590       gcc_assert (seen_error ());
1591       return val;
1592
1593     case CAST_EXPR:
1594     case IMPLICIT_CONV_EXPR:
1595     case STATIC_CAST_EXPR:
1596     case REINTERPRET_CAST_EXPR:
1597     case CONST_CAST_EXPR:
1598     case DYNAMIC_CAST_EXPR:
1599     case NEW_EXPR:
1600       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1601       /* Now hash operands as usual.  */
1602       break;
1603
1604     default:
1605       break;
1606     }
1607
1608   switch (tclass)
1609     {
1610     case tcc_type:
1611       if (TYPE_CANONICAL (arg))
1612         return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1613                                       val);
1614       else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1615         return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1616       /* Otherwise just compare the types during lookup.  */
1617       return val;
1618
1619     case tcc_declaration:
1620     case tcc_constant:
1621       return iterative_hash_expr (arg, val);
1622
1623     default:
1624       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1625       {
1626         unsigned n = cp_tree_operand_length (arg);
1627         for (i = 0; i < n; ++i)
1628           val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1629         return val;
1630       }
1631     }
1632   gcc_unreachable ();
1633   return 0;
1634 }
1635
1636 /* Unregister the specialization SPEC as a specialization of TMPL.
1637    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1638    if the SPEC was listed as a specialization of TMPL.
1639
1640    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1641
1642 bool
1643 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1644 {
1645   spec_entry *entry;
1646   spec_entry elt;
1647
1648   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1649   elt.args = TI_ARGS (tinfo);
1650   elt.spec = NULL_TREE;
1651
1652   entry = (spec_entry *) htab_find (decl_specializations, &elt);
1653   if (entry != NULL)
1654     {
1655       gcc_assert (entry->spec == spec || entry->spec == new_spec);
1656       gcc_assert (new_spec != NULL_TREE);
1657       entry->spec = new_spec;
1658       return 1;
1659     }
1660
1661   return 0;
1662 }
1663
1664 /* Compare an entry in the local specializations hash table P1 (which
1665    is really a pointer to a TREE_LIST) with P2 (which is really a
1666    DECL).  */
1667
1668 static int
1669 eq_local_specializations (const void *p1, const void *p2)
1670 {
1671   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1672 }
1673
1674 /* Hash P1, an entry in the local specializations table.  */
1675
1676 static hashval_t
1677 hash_local_specialization (const void* p1)
1678 {
1679   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1680 }
1681
1682 /* Like register_specialization, but for local declarations.  We are
1683    registering SPEC, an instantiation of TMPL.  */
1684
1685 static void
1686 register_local_specialization (tree spec, tree tmpl)
1687 {
1688   void **slot;
1689
1690   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1691                                    htab_hash_pointer (tmpl), INSERT);
1692   *slot = build_tree_list (spec, tmpl);
1693 }
1694
1695 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1696    specialized class.  */
1697
1698 bool
1699 explicit_class_specialization_p (tree type)
1700 {
1701   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1702     return false;
1703   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1704 }
1705
1706 /* Print the list of functions at FNS, going through all the overloads
1707    for each element of the list.  Alternatively, FNS can not be a
1708    TREE_LIST, in which case it will be printed together with all the
1709    overloads.
1710
1711    MORE and *STR should respectively be FALSE and NULL when the function
1712    is called from the outside.  They are used internally on recursive
1713    calls.  print_candidates manages the two parameters and leaves NULL
1714    in *STR when it ends.  */
1715
1716 static void
1717 print_candidates_1 (tree fns, bool more, const char **str)
1718 {
1719   tree fn, fn2;
1720   char *spaces = NULL;
1721
1722   for (fn = fns; fn; fn = OVL_NEXT (fn))
1723     if (TREE_CODE (fn) == TREE_LIST)
1724       {
1725         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1726           print_candidates_1 (TREE_VALUE (fn2),
1727                               TREE_CHAIN (fn2) || more, str);
1728       }
1729     else
1730       {
1731         if (!*str)
1732           {
1733             /* Pick the prefix string.  */
1734             if (!more && !OVL_NEXT (fns))
1735               {
1736                 error ("candidate is: %+#D", OVL_CURRENT (fn));
1737                 continue;
1738               }
1739
1740             *str = _("candidates are:");
1741             spaces = get_spaces (*str);
1742           }
1743         error ("%s %+#D", *str, OVL_CURRENT (fn));
1744         *str = spaces ? spaces : *str;
1745       }
1746
1747   if (!more)
1748     {
1749       free (spaces);
1750       *str = NULL;
1751     }
1752 }
1753
1754 /* Print the list of candidate FNS in an error message.  FNS can also
1755    be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
1756
1757 void
1758 print_candidates (tree fns)
1759 {
1760   const char *str = NULL;
1761   print_candidates_1 (fns, false, &str);
1762   gcc_assert (str == NULL);
1763 }
1764
1765 /* Returns the template (one of the functions given by TEMPLATE_ID)
1766    which can be specialized to match the indicated DECL with the
1767    explicit template args given in TEMPLATE_ID.  The DECL may be
1768    NULL_TREE if none is available.  In that case, the functions in
1769    TEMPLATE_ID are non-members.
1770
1771    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1772    specialization of a member template.
1773
1774    The TEMPLATE_COUNT is the number of references to qualifying
1775    template classes that appeared in the name of the function. See
1776    check_explicit_specialization for a more accurate description.
1777
1778    TSK indicates what kind of template declaration (if any) is being
1779    declared.  TSK_TEMPLATE indicates that the declaration given by
1780    DECL, though a FUNCTION_DECL, has template parameters, and is
1781    therefore a template function.
1782
1783    The template args (those explicitly specified and those deduced)
1784    are output in a newly created vector *TARGS_OUT.
1785
1786    If it is impossible to determine the result, an error message is
1787    issued.  The error_mark_node is returned to indicate failure.  */
1788
1789 static tree
1790 determine_specialization (tree template_id,
1791                           tree decl,
1792                           tree* targs_out,
1793                           int need_member_template,
1794                           int template_count,
1795                           tmpl_spec_kind tsk)
1796 {
1797   tree fns;
1798   tree targs;
1799   tree explicit_targs;
1800   tree candidates = NULL_TREE;
1801   /* A TREE_LIST of templates of which DECL may be a specialization.
1802      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1803      corresponding TREE_PURPOSE is the set of template arguments that,
1804      when used to instantiate the template, would produce a function
1805      with the signature of DECL.  */
1806   tree templates = NULL_TREE;
1807   int header_count;
1808   cp_binding_level *b;
1809
1810   *targs_out = NULL_TREE;
1811
1812   if (template_id == error_mark_node || decl == error_mark_node)
1813     return error_mark_node;
1814
1815   fns = TREE_OPERAND (template_id, 0);
1816   explicit_targs = TREE_OPERAND (template_id, 1);
1817
1818   if (fns == error_mark_node)
1819     return error_mark_node;
1820
1821   /* Check for baselinks.  */
1822   if (BASELINK_P (fns))
1823     fns = BASELINK_FUNCTIONS (fns);
1824
1825   if (!is_overloaded_fn (fns))
1826     {
1827       error ("%qD is not a function template", fns);
1828       return error_mark_node;
1829     }
1830
1831   /* Count the number of template headers specified for this
1832      specialization.  */
1833   header_count = 0;
1834   for (b = current_binding_level;
1835        b->kind == sk_template_parms;
1836        b = b->level_chain)
1837     ++header_count;
1838
1839   for (; fns; fns = OVL_NEXT (fns))
1840     {
1841       tree fn = OVL_CURRENT (fns);
1842
1843       if (TREE_CODE (fn) == TEMPLATE_DECL)
1844         {
1845           tree decl_arg_types;
1846           tree fn_arg_types;
1847
1848           /* In case of explicit specialization, we need to check if
1849              the number of template headers appearing in the specialization
1850              is correct. This is usually done in check_explicit_specialization,
1851              but the check done there cannot be exhaustive when specializing
1852              member functions. Consider the following code:
1853
1854              template <> void A<int>::f(int);
1855              template <> template <> void A<int>::f(int);
1856
1857              Assuming that A<int> is not itself an explicit specialization
1858              already, the first line specializes "f" which is a non-template
1859              member function, whilst the second line specializes "f" which
1860              is a template member function. So both lines are syntactically
1861              correct, and check_explicit_specialization does not reject
1862              them.
1863
1864              Here, we can do better, as we are matching the specialization
1865              against the declarations. We count the number of template
1866              headers, and we check if they match TEMPLATE_COUNT + 1
1867              (TEMPLATE_COUNT is the number of qualifying template classes,
1868              plus there must be another header for the member template
1869              itself).
1870
1871              Notice that if header_count is zero, this is not a
1872              specialization but rather a template instantiation, so there
1873              is no check we can perform here.  */
1874           if (header_count && header_count != template_count + 1)
1875             continue;
1876
1877           /* Check that the number of template arguments at the
1878              innermost level for DECL is the same as for FN.  */
1879           if (current_binding_level->kind == sk_template_parms
1880               && !current_binding_level->explicit_spec_p
1881               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1882                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1883                                       (current_template_parms))))
1884             continue;
1885
1886           /* DECL might be a specialization of FN.  */
1887           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1888           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1889
1890           /* For a non-static member function, we need to make sure
1891              that the const qualification is the same.  Since
1892              get_bindings does not try to merge the "this" parameter,
1893              we must do the comparison explicitly.  */
1894           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1895               && !same_type_p (TREE_VALUE (fn_arg_types),
1896                                TREE_VALUE (decl_arg_types)))
1897             continue;
1898
1899           /* Skip the "this" parameter and, for constructors of
1900              classes with virtual bases, the VTT parameter.  A
1901              full specialization of a constructor will have a VTT
1902              parameter, but a template never will.  */ 
1903           decl_arg_types 
1904             = skip_artificial_parms_for (decl, decl_arg_types);
1905           fn_arg_types 
1906             = skip_artificial_parms_for (fn, fn_arg_types);
1907
1908           /* Check that the number of function parameters matches.
1909              For example,
1910                template <class T> void f(int i = 0);
1911                template <> void f<int>();
1912              The specialization f<int> is invalid but is not caught
1913              by get_bindings below.  */
1914           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1915             continue;
1916
1917           /* Function templates cannot be specializations; there are
1918              no partial specializations of functions.  Therefore, if
1919              the type of DECL does not match FN, there is no
1920              match.  */
1921           if (tsk == tsk_template)
1922             {
1923               if (compparms (fn_arg_types, decl_arg_types))
1924                 candidates = tree_cons (NULL_TREE, fn, candidates);
1925               continue;
1926             }
1927
1928           /* See whether this function might be a specialization of this
1929              template.  */
1930           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1931
1932           if (!targs)
1933             /* We cannot deduce template arguments that when used to
1934                specialize TMPL will produce DECL.  */
1935             continue;
1936
1937           /* Save this template, and the arguments deduced.  */
1938           templates = tree_cons (targs, fn, templates);
1939         }
1940       else if (need_member_template)
1941         /* FN is an ordinary member function, and we need a
1942            specialization of a member template.  */
1943         ;
1944       else if (TREE_CODE (fn) != FUNCTION_DECL)
1945         /* We can get IDENTIFIER_NODEs here in certain erroneous
1946            cases.  */
1947         ;
1948       else if (!DECL_FUNCTION_MEMBER_P (fn))
1949         /* This is just an ordinary non-member function.  Nothing can
1950            be a specialization of that.  */
1951         ;
1952       else if (DECL_ARTIFICIAL (fn))
1953         /* Cannot specialize functions that are created implicitly.  */
1954         ;
1955       else
1956         {
1957           tree decl_arg_types;
1958
1959           /* This is an ordinary member function.  However, since
1960              we're here, we can assume it's enclosing class is a
1961              template class.  For example,
1962
1963                template <typename T> struct S { void f(); };
1964                template <> void S<int>::f() {}
1965
1966              Here, S<int>::f is a non-template, but S<int> is a
1967              template class.  If FN has the same type as DECL, we
1968              might be in business.  */
1969
1970           if (!DECL_TEMPLATE_INFO (fn))
1971             /* Its enclosing class is an explicit specialization
1972                of a template class.  This is not a candidate.  */
1973             continue;
1974
1975           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1976                             TREE_TYPE (TREE_TYPE (fn))))
1977             /* The return types differ.  */
1978             continue;
1979
1980           /* Adjust the type of DECL in case FN is a static member.  */
1981           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1982           if (DECL_STATIC_FUNCTION_P (fn)
1983               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1984             decl_arg_types = TREE_CHAIN (decl_arg_types);
1985
1986           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1987                          decl_arg_types))
1988             /* They match!  */
1989             candidates = tree_cons (NULL_TREE, fn, candidates);
1990         }
1991     }
1992
1993   if (templates && TREE_CHAIN (templates))
1994     {
1995       /* We have:
1996
1997            [temp.expl.spec]
1998
1999            It is possible for a specialization with a given function
2000            signature to be instantiated from more than one function
2001            template.  In such cases, explicit specification of the
2002            template arguments must be used to uniquely identify the
2003            function template specialization being specialized.
2004
2005          Note that here, there's no suggestion that we're supposed to
2006          determine which of the candidate templates is most
2007          specialized.  However, we, also have:
2008
2009            [temp.func.order]
2010
2011            Partial ordering of overloaded function template
2012            declarations is used in the following contexts to select
2013            the function template to which a function template
2014            specialization refers:
2015
2016            -- when an explicit specialization refers to a function
2017               template.
2018
2019          So, we do use the partial ordering rules, at least for now.
2020          This extension can only serve to make invalid programs valid,
2021          so it's safe.  And, there is strong anecdotal evidence that
2022          the committee intended the partial ordering rules to apply;
2023          the EDG front end has that behavior, and John Spicer claims
2024          that the committee simply forgot to delete the wording in
2025          [temp.expl.spec].  */
2026       tree tmpl = most_specialized_instantiation (templates);
2027       if (tmpl != error_mark_node)
2028         {
2029           templates = tmpl;
2030           TREE_CHAIN (templates) = NULL_TREE;
2031         }
2032     }
2033
2034   if (templates == NULL_TREE && candidates == NULL_TREE)
2035     {
2036       error ("template-id %qD for %q+D does not match any template "
2037              "declaration", template_id, decl);
2038       if (header_count && header_count != template_count + 1)
2039         inform (input_location, "saw %d %<template<>%>, need %d for "
2040                 "specializing a member function template",
2041                 header_count, template_count + 1);
2042       return error_mark_node;
2043     }
2044   else if ((templates && TREE_CHAIN (templates))
2045            || (candidates && TREE_CHAIN (candidates))
2046            || (templates && candidates))
2047     {
2048       error ("ambiguous template specialization %qD for %q+D",
2049              template_id, decl);
2050       candidates = chainon (candidates, templates);
2051       print_candidates (candidates);
2052       return error_mark_node;
2053     }
2054
2055   /* We have one, and exactly one, match.  */
2056   if (candidates)
2057     {
2058       tree fn = TREE_VALUE (candidates);
2059       *targs_out = copy_node (DECL_TI_ARGS (fn));
2060       /* DECL is a re-declaration or partial instantiation of a template
2061          function.  */
2062       if (TREE_CODE (fn) == TEMPLATE_DECL)
2063         return fn;
2064       /* It was a specialization of an ordinary member function in a
2065          template class.  */
2066       return DECL_TI_TEMPLATE (fn);
2067     }
2068
2069   /* It was a specialization of a template.  */
2070   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2071   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2072     {
2073       *targs_out = copy_node (targs);
2074       SET_TMPL_ARGS_LEVEL (*targs_out,
2075                            TMPL_ARGS_DEPTH (*targs_out),
2076                            TREE_PURPOSE (templates));
2077     }
2078   else
2079     *targs_out = TREE_PURPOSE (templates);
2080   return TREE_VALUE (templates);
2081 }
2082
2083 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2084    but with the default argument values filled in from those in the
2085    TMPL_TYPES.  */
2086
2087 static tree
2088 copy_default_args_to_explicit_spec_1 (tree spec_types,
2089                                       tree tmpl_types)
2090 {
2091   tree new_spec_types;
2092
2093   if (!spec_types)
2094     return NULL_TREE;
2095
2096   if (spec_types == void_list_node)
2097     return void_list_node;
2098
2099   /* Substitute into the rest of the list.  */
2100   new_spec_types =
2101     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2102                                           TREE_CHAIN (tmpl_types));
2103
2104   /* Add the default argument for this parameter.  */
2105   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2106                          TREE_VALUE (spec_types),
2107                          new_spec_types);
2108 }
2109
2110 /* DECL is an explicit specialization.  Replicate default arguments
2111    from the template it specializes.  (That way, code like:
2112
2113      template <class T> void f(T = 3);
2114      template <> void f(double);
2115      void g () { f (); }
2116
2117    works, as required.)  An alternative approach would be to look up
2118    the correct default arguments at the call-site, but this approach
2119    is consistent with how implicit instantiations are handled.  */
2120
2121 static void
2122 copy_default_args_to_explicit_spec (tree decl)
2123 {
2124   tree tmpl;
2125   tree spec_types;
2126   tree tmpl_types;
2127   tree new_spec_types;
2128   tree old_type;
2129   tree new_type;
2130   tree t;
2131   tree object_type = NULL_TREE;
2132   tree in_charge = NULL_TREE;
2133   tree vtt = NULL_TREE;
2134
2135   /* See if there's anything we need to do.  */
2136   tmpl = DECL_TI_TEMPLATE (decl);
2137   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2138   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2139     if (TREE_PURPOSE (t))
2140       break;
2141   if (!t)
2142     return;
2143
2144   old_type = TREE_TYPE (decl);
2145   spec_types = TYPE_ARG_TYPES (old_type);
2146
2147   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2148     {
2149       /* Remove the this pointer, but remember the object's type for
2150          CV quals.  */
2151       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2152       spec_types = TREE_CHAIN (spec_types);
2153       tmpl_types = TREE_CHAIN (tmpl_types);
2154
2155       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2156         {
2157           /* DECL may contain more parameters than TMPL due to the extra
2158              in-charge parameter in constructors and destructors.  */
2159           in_charge = spec_types;
2160           spec_types = TREE_CHAIN (spec_types);
2161         }
2162       if (DECL_HAS_VTT_PARM_P (decl))
2163         {
2164           vtt = spec_types;
2165           spec_types = TREE_CHAIN (spec_types);
2166         }
2167     }
2168
2169   /* Compute the merged default arguments.  */
2170   new_spec_types =
2171     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2172
2173   /* Compute the new FUNCTION_TYPE.  */
2174   if (object_type)
2175     {
2176       if (vtt)
2177         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2178                                          TREE_VALUE (vtt),
2179                                          new_spec_types);
2180
2181       if (in_charge)
2182         /* Put the in-charge parameter back.  */
2183         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2184                                          TREE_VALUE (in_charge),
2185                                          new_spec_types);
2186
2187       new_type = build_method_type_directly (object_type,
2188                                              TREE_TYPE (old_type),
2189                                              new_spec_types);
2190     }
2191   else
2192     new_type = build_function_type (TREE_TYPE (old_type),
2193                                     new_spec_types);
2194   new_type = cp_build_type_attribute_variant (new_type,
2195                                               TYPE_ATTRIBUTES (old_type));
2196   new_type = build_exception_variant (new_type,
2197                                       TYPE_RAISES_EXCEPTIONS (old_type));
2198   TREE_TYPE (decl) = new_type;
2199 }
2200
2201 /* Check to see if the function just declared, as indicated in
2202    DECLARATOR, and in DECL, is a specialization of a function
2203    template.  We may also discover that the declaration is an explicit
2204    instantiation at this point.
2205
2206    Returns DECL, or an equivalent declaration that should be used
2207    instead if all goes well.  Issues an error message if something is
2208    amiss.  Returns error_mark_node if the error is not easily
2209    recoverable.
2210
2211    FLAGS is a bitmask consisting of the following flags:
2212
2213    2: The function has a definition.
2214    4: The function is a friend.
2215
2216    The TEMPLATE_COUNT is the number of references to qualifying
2217    template classes that appeared in the name of the function.  For
2218    example, in
2219
2220      template <class T> struct S { void f(); };
2221      void S<int>::f();
2222
2223    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2224    classes are not counted in the TEMPLATE_COUNT, so that in
2225
2226      template <class T> struct S {};
2227      template <> struct S<int> { void f(); }
2228      template <> void S<int>::f();
2229
2230    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2231    invalid; there should be no template <>.)
2232
2233    If the function is a specialization, it is marked as such via
2234    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2235    is set up correctly, and it is added to the list of specializations
2236    for that template.  */
2237
2238 tree
2239 check_explicit_specialization (tree declarator,
2240                                tree decl,
2241                                int template_count,
2242                                int flags)
2243 {
2244   int have_def = flags & 2;
2245   int is_friend = flags & 4;
2246   int specialization = 0;
2247   int explicit_instantiation = 0;
2248   int member_specialization = 0;
2249   tree ctype = DECL_CLASS_CONTEXT (decl);
2250   tree dname = DECL_NAME (decl);
2251   tmpl_spec_kind tsk;
2252
2253   if (is_friend)
2254     {
2255       if (!processing_specialization)
2256         tsk = tsk_none;
2257       else
2258         tsk = tsk_excessive_parms;
2259     }
2260   else
2261     tsk = current_tmpl_spec_kind (template_count);
2262
2263   switch (tsk)
2264     {
2265     case tsk_none:
2266       if (processing_specialization)
2267         {
2268           specialization = 1;
2269           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2270         }
2271       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2272         {
2273           if (is_friend)
2274             /* This could be something like:
2275
2276                template <class T> void f(T);
2277                class S { friend void f<>(int); }  */
2278             specialization = 1;
2279           else
2280             {
2281               /* This case handles bogus declarations like template <>
2282                  template <class T> void f<int>(); */
2283
2284               error ("template-id %qD in declaration of primary template",
2285                      declarator);
2286               return decl;
2287             }
2288         }
2289       break;
2290
2291     case tsk_invalid_member_spec:
2292       /* The error has already been reported in
2293          check_specialization_scope.  */
2294       return error_mark_node;
2295
2296     case tsk_invalid_expl_inst:
2297       error ("template parameter list used in explicit instantiation");
2298
2299       /* Fall through.  */
2300
2301     case tsk_expl_inst:
2302       if (have_def)
2303         error ("definition provided for explicit instantiation");
2304
2305       explicit_instantiation = 1;
2306       break;
2307
2308     case tsk_excessive_parms:
2309     case tsk_insufficient_parms:
2310       if (tsk == tsk_excessive_parms)
2311         error ("too many template parameter lists in declaration of %qD",
2312                decl);
2313       else if (template_header_count)
2314         error("too few template parameter lists in declaration of %qD", decl);
2315       else
2316         error("explicit specialization of %qD must be introduced by "
2317               "%<template <>%>", decl);
2318
2319       /* Fall through.  */
2320     case tsk_expl_spec:
2321       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2322       if (ctype)
2323         member_specialization = 1;
2324       else
2325         specialization = 1;
2326       break;
2327
2328     case tsk_template:
2329       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2330         {
2331           /* This case handles bogus declarations like template <>
2332              template <class T> void f<int>(); */
2333
2334           if (uses_template_parms (declarator))
2335             error ("function template partial specialization %qD "
2336                    "is not allowed", declarator);
2337           else
2338             error ("template-id %qD in declaration of primary template",
2339                    declarator);
2340           return decl;
2341         }
2342
2343       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2344         /* This is a specialization of a member template, without
2345            specialization the containing class.  Something like:
2346
2347              template <class T> struct S {
2348                template <class U> void f (U);
2349              };
2350              template <> template <class U> void S<int>::f(U) {}
2351
2352            That's a specialization -- but of the entire template.  */
2353         specialization = 1;
2354       break;
2355
2356     default:
2357       gcc_unreachable ();
2358     }
2359
2360   if (specialization || member_specialization)
2361     {
2362       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2363       for (; t; t = TREE_CHAIN (t))
2364         if (TREE_PURPOSE (t))
2365           {
2366             permerror (input_location, 
2367                        "default argument specified in explicit specialization");
2368             break;
2369           }
2370     }
2371
2372   if (specialization || member_specialization || explicit_instantiation)
2373     {
2374       tree tmpl = NULL_TREE;
2375       tree targs = NULL_TREE;
2376
2377       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2378       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2379         {
2380           tree fns;
2381
2382           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2383           if (ctype)
2384             fns = dname;
2385           else
2386             {
2387               /* If there is no class context, the explicit instantiation
2388                  must be at namespace scope.  */
2389               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2390
2391               /* Find the namespace binding, using the declaration
2392                  context.  */
2393               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2394                                            false, true);
2395               if (fns == error_mark_node || !is_overloaded_fn (fns))
2396                 {
2397                   error ("%qD is not a template function", dname);
2398                   fns = error_mark_node;
2399                 }
2400               else
2401                 {
2402                   tree fn = OVL_CURRENT (fns);
2403                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2404                                                 CP_DECL_CONTEXT (fn)))
2405                     error ("%qD is not declared in %qD",
2406                            decl, current_namespace);
2407                 }
2408             }
2409
2410           declarator = lookup_template_function (fns, NULL_TREE);
2411         }
2412
2413       if (declarator == error_mark_node)
2414         return error_mark_node;
2415
2416       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2417         {
2418           if (!explicit_instantiation)
2419             /* A specialization in class scope.  This is invalid,
2420                but the error will already have been flagged by
2421                check_specialization_scope.  */
2422             return error_mark_node;
2423           else
2424             {
2425               /* It's not valid to write an explicit instantiation in
2426                  class scope, e.g.:
2427
2428                    class C { template void f(); }
2429
2430                    This case is caught by the parser.  However, on
2431                    something like:
2432
2433                    template class C { void f(); };
2434
2435                    (which is invalid) we can get here.  The error will be
2436                    issued later.  */
2437               ;
2438             }
2439
2440           return decl;
2441         }
2442       else if (ctype != NULL_TREE
2443                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2444                    IDENTIFIER_NODE))
2445         {
2446           /* Find the list of functions in ctype that have the same
2447              name as the declared function.  */
2448           tree name = TREE_OPERAND (declarator, 0);
2449           tree fns = NULL_TREE;
2450           int idx;
2451
2452           if (constructor_name_p (name, ctype))
2453             {
2454               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2455
2456               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2457                   : !CLASSTYPE_DESTRUCTORS (ctype))
2458                 {
2459                   /* From [temp.expl.spec]:
2460
2461                      If such an explicit specialization for the member
2462                      of a class template names an implicitly-declared
2463                      special member function (clause _special_), the
2464                      program is ill-formed.
2465
2466                      Similar language is found in [temp.explicit].  */
2467                   error ("specialization of implicitly-declared special member function");
2468                   return error_mark_node;
2469                 }
2470
2471               name = is_constructor ? ctor_identifier : dtor_identifier;
2472             }
2473
2474           if (!DECL_CONV_FN_P (decl))
2475             {
2476               idx = lookup_fnfields_1 (ctype, name);
2477               if (idx >= 0)
2478                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2479             }
2480           else
2481             {
2482               VEC(tree,gc) *methods;
2483               tree ovl;
2484
2485               /* For a type-conversion operator, we cannot do a
2486                  name-based lookup.  We might be looking for `operator
2487                  int' which will be a specialization of `operator T'.
2488                  So, we find *all* the conversion operators, and then
2489                  select from them.  */
2490               fns = NULL_TREE;
2491
2492               methods = CLASSTYPE_METHOD_VEC (ctype);
2493               if (methods)
2494                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2495                      VEC_iterate (tree, methods, idx, ovl);
2496                      ++idx)
2497                   {
2498                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2499                       /* There are no more conversion functions.  */
2500                       break;
2501
2502                     /* Glue all these conversion functions together
2503                        with those we already have.  */
2504                     for (; ovl; ovl = OVL_NEXT (ovl))
2505                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2506                   }
2507             }
2508
2509           if (fns == NULL_TREE)
2510             {
2511               error ("no member function %qD declared in %qT", name, ctype);
2512               return error_mark_node;
2513             }
2514           else
2515             TREE_OPERAND (declarator, 0) = fns;
2516         }
2517
2518       /* Figure out what exactly is being specialized at this point.
2519          Note that for an explicit instantiation, even one for a
2520          member function, we cannot tell apriori whether the
2521          instantiation is for a member template, or just a member
2522          function of a template class.  Even if a member template is
2523          being instantiated, the member template arguments may be
2524          elided if they can be deduced from the rest of the
2525          declaration.  */
2526       tmpl = determine_specialization (declarator, decl,
2527                                        &targs,
2528                                        member_specialization,
2529                                        template_count,
2530                                        tsk);
2531
2532       if (!tmpl || tmpl == error_mark_node)
2533         /* We couldn't figure out what this declaration was
2534            specializing.  */
2535         return error_mark_node;
2536       else
2537         {
2538           tree gen_tmpl = most_general_template (tmpl);
2539
2540           if (explicit_instantiation)
2541             {
2542               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2543                  is done by do_decl_instantiation later.  */
2544
2545               int arg_depth = TMPL_ARGS_DEPTH (targs);
2546               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2547
2548               if (arg_depth > parm_depth)
2549                 {
2550                   /* If TMPL is not the most general template (for
2551                      example, if TMPL is a friend template that is
2552                      injected into namespace scope), then there will
2553                      be too many levels of TARGS.  Remove some of them
2554                      here.  */
2555                   int i;
2556                   tree new_targs;
2557
2558                   new_targs = make_tree_vec (parm_depth);
2559                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2560                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2561                       = TREE_VEC_ELT (targs, i);
2562                   targs = new_targs;
2563                 }
2564
2565               return instantiate_template (tmpl, targs, tf_error);
2566             }
2567
2568           /* If we thought that the DECL was a member function, but it
2569              turns out to be specializing a static member function,
2570              make DECL a static member function as well.  */
2571           if (DECL_STATIC_FUNCTION_P (tmpl)
2572               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2573             revert_static_member_fn (decl);
2574
2575           /* If this is a specialization of a member template of a
2576              template class, we want to return the TEMPLATE_DECL, not
2577              the specialization of it.  */
2578           if (tsk == tsk_template)
2579             {
2580               tree result = DECL_TEMPLATE_RESULT (tmpl);
2581               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2582               DECL_INITIAL (result) = NULL_TREE;
2583               if (have_def)
2584                 {
2585                   tree parm;
2586                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2587                   DECL_SOURCE_LOCATION (result)
2588                     = DECL_SOURCE_LOCATION (decl);
2589                   /* We want to use the argument list specified in the
2590                      definition, not in the original declaration.  */
2591                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2592                   for (parm = DECL_ARGUMENTS (result); parm;
2593                        parm = DECL_CHAIN (parm))
2594                     DECL_CONTEXT (parm) = result;
2595                 }
2596               return register_specialization (tmpl, gen_tmpl, targs,
2597                                               is_friend, 0);
2598             }
2599
2600           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2601           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2602
2603           /* Inherit default function arguments from the template
2604              DECL is specializing.  */
2605           copy_default_args_to_explicit_spec (decl);
2606
2607           /* This specialization has the same protection as the
2608              template it specializes.  */
2609           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2610           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2611
2612           /* 7.1.1-1 [dcl.stc]
2613
2614              A storage-class-specifier shall not be specified in an
2615              explicit specialization...
2616
2617              The parser rejects these, so unless action is taken here,
2618              explicit function specializations will always appear with
2619              global linkage.
2620
2621              The action recommended by the C++ CWG in response to C++
2622              defect report 605 is to make the storage class and linkage
2623              of the explicit specialization match the templated function:
2624
2625              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2626            */
2627           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2628             {
2629               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2630               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2631
2632               /* This specialization has the same linkage and visibility as
2633                  the function template it specializes.  */
2634               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2635               if (! TREE_PUBLIC (decl))
2636                 {
2637                   DECL_INTERFACE_KNOWN (decl) = 1;
2638                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2639                 }
2640               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2641               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2642                 {
2643                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2644                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2645                 }
2646             }
2647
2648           /* If DECL is a friend declaration, declared using an
2649              unqualified name, the namespace associated with DECL may
2650              have been set incorrectly.  For example, in:
2651
2652                template <typename T> void f(T);
2653                namespace N {
2654                  struct S { friend void f<int>(int); }
2655                }
2656
2657              we will have set the DECL_CONTEXT for the friend
2658              declaration to N, rather than to the global namespace.  */
2659           if (DECL_NAMESPACE_SCOPE_P (decl))
2660             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2661
2662           if (is_friend && !have_def)
2663             /* This is not really a declaration of a specialization.
2664                It's just the name of an instantiation.  But, it's not
2665                a request for an instantiation, either.  */
2666             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2667           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2668             /* This is indeed a specialization.  In case of constructors
2669                and destructors, we need in-charge and not-in-charge
2670                versions in V3 ABI.  */
2671             clone_function_decl (decl, /*update_method_vec_p=*/0);
2672
2673           /* Register this specialization so that we can find it
2674              again.  */
2675           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2676         }
2677     }
2678
2679   return decl;
2680 }
2681
2682 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2683    parameters.  These are represented in the same format used for
2684    DECL_TEMPLATE_PARMS.  */
2685
2686 int
2687 comp_template_parms (const_tree parms1, const_tree parms2)
2688 {
2689   const_tree p1;
2690   const_tree p2;
2691
2692   if (parms1 == parms2)
2693     return 1;
2694
2695   for (p1 = parms1, p2 = parms2;
2696        p1 != NULL_TREE && p2 != NULL_TREE;
2697        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2698     {
2699       tree t1 = TREE_VALUE (p1);
2700       tree t2 = TREE_VALUE (p2);
2701       int i;
2702
2703       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2704       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2705
2706       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2707         return 0;
2708
2709       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2710         {
2711           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2712           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2713
2714           /* If either of the template parameters are invalid, assume
2715              they match for the sake of error recovery. */
2716           if (parm1 == error_mark_node || parm2 == error_mark_node)
2717             return 1;
2718
2719           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2720             return 0;
2721
2722           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2723               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2724                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2725             continue;
2726           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2727             return 0;
2728         }
2729     }
2730
2731   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2732     /* One set of parameters has more parameters lists than the
2733        other.  */
2734     return 0;
2735
2736   return 1;
2737 }
2738
2739 /* Determine whether PARM is a parameter pack.  */
2740
2741 bool 
2742 template_parameter_pack_p (const_tree parm)
2743 {
2744   /* Determine if we have a non-type template parameter pack.  */
2745   if (TREE_CODE (parm) == PARM_DECL)
2746     return (DECL_TEMPLATE_PARM_P (parm) 
2747             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2748   if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
2749     return TEMPLATE_PARM_PARAMETER_PACK (parm);
2750
2751   /* If this is a list of template parameters, we could get a
2752      TYPE_DECL or a TEMPLATE_DECL.  */ 
2753   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2754     parm = TREE_TYPE (parm);
2755
2756   /* Otherwise it must be a type template parameter.  */
2757   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2758            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2759           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2760 }
2761
2762 /* Determine if T is a function parameter pack.  */
2763
2764 bool
2765 function_parameter_pack_p (const_tree t)
2766 {
2767   if (t && TREE_CODE (t) == PARM_DECL)
2768     return FUNCTION_PARAMETER_PACK_P (t);
2769   return false;
2770 }
2771
2772 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2773    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2774
2775 tree
2776 get_function_template_decl (const_tree primary_func_tmpl_inst)
2777 {
2778   if (! primary_func_tmpl_inst
2779       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2780       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2781     return NULL;
2782
2783   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2784 }
2785
2786 /* Return true iff the function parameter PARAM_DECL was expanded
2787    from the function parameter pack PACK.  */
2788
2789 bool
2790 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2791 {
2792   if (DECL_ARTIFICIAL (param_decl)
2793       || !function_parameter_pack_p (pack))
2794     return false;
2795
2796   /* The parameter pack and its pack arguments have the same
2797      DECL_PARM_INDEX.  */
2798   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2799 }
2800
2801 /* Determine whether ARGS describes a variadic template args list,
2802    i.e., one that is terminated by a template argument pack.  */
2803
2804 static bool 
2805 template_args_variadic_p (tree args)
2806 {
2807   int nargs;
2808   tree last_parm;
2809
2810   if (args == NULL_TREE)
2811     return false;
2812
2813   args = INNERMOST_TEMPLATE_ARGS (args);
2814   nargs = TREE_VEC_LENGTH (args);
2815
2816   if (nargs == 0)
2817     return false;
2818
2819   last_parm = TREE_VEC_ELT (args, nargs - 1);
2820
2821   return ARGUMENT_PACK_P (last_parm);
2822 }
2823
2824 /* Generate a new name for the parameter pack name NAME (an
2825    IDENTIFIER_NODE) that incorporates its */
2826
2827 static tree
2828 make_ith_pack_parameter_name (tree name, int i)
2829 {
2830   /* Munge the name to include the parameter index.  */
2831 #define NUMBUF_LEN 128
2832   char numbuf[NUMBUF_LEN];
2833   char* newname;
2834   int newname_len;
2835
2836   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2837   newname_len = IDENTIFIER_LENGTH (name)
2838                 + strlen (numbuf) + 2;
2839   newname = (char*)alloca (newname_len);
2840   snprintf (newname, newname_len,
2841             "%s#%i", IDENTIFIER_POINTER (name), i);
2842   return get_identifier (newname);
2843 }
2844
2845 /* Return true if T is a primary function
2846    or class template instantiation.  */
2847
2848 bool
2849 primary_template_instantiation_p (const_tree t)
2850 {
2851   if (!t)
2852     return false;
2853
2854   if (TREE_CODE (t) == FUNCTION_DECL)
2855     return DECL_LANG_SPECIFIC (t)
2856            && DECL_TEMPLATE_INSTANTIATION (t)
2857            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2858   else if (CLASS_TYPE_P (t))
2859     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2860            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2861   return false;
2862 }
2863
2864 /* Return true if PARM is a template template parameter.  */
2865
2866 bool
2867 template_template_parameter_p (const_tree parm)
2868 {
2869   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2870 }
2871
2872 /* Return the template parameters of T if T is a
2873    primary template instantiation, NULL otherwise.  */
2874
2875 tree
2876 get_primary_template_innermost_parameters (const_tree t)
2877 {
2878   tree parms = NULL, template_info = NULL;
2879
2880   if ((template_info = get_template_info (t))
2881       && primary_template_instantiation_p (t))
2882     parms = INNERMOST_TEMPLATE_PARMS
2883         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2884
2885   return parms;
2886 }
2887
2888 /* Return the template parameters of the LEVELth level from the full list
2889    of template parameters PARMS.  */
2890
2891 tree
2892 get_template_parms_at_level (tree parms, int level)
2893 {
2894   tree p;
2895   if (!parms
2896       || TREE_CODE (parms) != TREE_LIST
2897       || level > TMPL_PARMS_DEPTH (parms))
2898     return NULL_TREE;
2899
2900   for (p = parms; p; p = TREE_CHAIN (p))
2901     if (TMPL_PARMS_DEPTH (p) == level)
2902       return p;
2903
2904   return NULL_TREE;
2905 }
2906
2907 /* Returns the template arguments of T if T is a template instantiation,
2908    NULL otherwise.  */
2909
2910 tree
2911 get_template_innermost_arguments (const_tree t)
2912 {
2913   tree args = NULL, template_info = NULL;
2914
2915   if ((template_info = get_template_info (t))
2916       && TI_ARGS (template_info))
2917     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2918
2919   return args;
2920 }
2921
2922 /* Return the argument pack elements of T if T is a template argument pack,
2923    NULL otherwise.  */
2924
2925 tree
2926 get_template_argument_pack_elems (const_tree t)
2927 {
2928   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2929       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2930     return NULL;
2931
2932   return ARGUMENT_PACK_ARGS (t);
2933 }
2934
2935 /* Structure used to track the progress of find_parameter_packs_r.  */
2936 struct find_parameter_pack_data 
2937 {
2938   /* TREE_LIST that will contain all of the parameter packs found by
2939      the traversal.  */
2940   tree* parameter_packs;
2941
2942   /* Set of AST nodes that have been visited by the traversal.  */
2943   struct pointer_set_t *visited;
2944 };
2945
2946 /* Identifies all of the argument packs that occur in a template
2947    argument and appends them to the TREE_LIST inside DATA, which is a
2948    find_parameter_pack_data structure. This is a subroutine of
2949    make_pack_expansion and uses_parameter_packs.  */
2950 static tree
2951 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2952 {
2953   tree t = *tp;
2954   struct find_parameter_pack_data* ppd = 
2955     (struct find_parameter_pack_data*)data;
2956   bool parameter_pack_p = false;
2957
2958   /* Identify whether this is a parameter pack or not.  */
2959   switch (TREE_CODE (t))
2960     {
2961     case TEMPLATE_PARM_INDEX:
2962       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2963         parameter_pack_p = true;
2964       break;
2965
2966     case TEMPLATE_TYPE_PARM:
2967       t = TYPE_MAIN_VARIANT (t);
2968     case TEMPLATE_TEMPLATE_PARM:
2969       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2970         parameter_pack_p = true;
2971       break;
2972
2973     case PARM_DECL:
2974       if (FUNCTION_PARAMETER_PACK_P (t))
2975         {
2976           /* We don't want to walk into the type of a PARM_DECL,
2977              because we don't want to see the type parameter pack.  */
2978           *walk_subtrees = 0;
2979           parameter_pack_p = true;
2980         }
2981       break;
2982
2983     default:
2984       /* Not a parameter pack.  */
2985       break;
2986     }
2987
2988   if (parameter_pack_p)
2989     {
2990       /* Add this parameter pack to the list.  */
2991       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2992     }
2993
2994   if (TYPE_P (t))
2995     cp_walk_tree (&TYPE_CONTEXT (t), 
2996                   &find_parameter_packs_r, ppd, ppd->visited);
2997
2998   /* This switch statement will return immediately if we don't find a
2999      parameter pack.  */
3000   switch (TREE_CODE (t)) 
3001     {
3002     case TEMPLATE_PARM_INDEX:
3003       return NULL_TREE;
3004
3005     case BOUND_TEMPLATE_TEMPLATE_PARM:
3006       /* Check the template itself.  */
3007       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
3008                     &find_parameter_packs_r, ppd, ppd->visited);
3009       /* Check the template arguments.  */
3010       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
3011                     ppd->visited);
3012       *walk_subtrees = 0;
3013       return NULL_TREE;
3014
3015     case TEMPLATE_TYPE_PARM:
3016     case TEMPLATE_TEMPLATE_PARM:
3017       return NULL_TREE;
3018
3019     case PARM_DECL:
3020       return NULL_TREE;
3021
3022     case RECORD_TYPE:
3023       if (TYPE_PTRMEMFUNC_P (t))
3024         return NULL_TREE;
3025       /* Fall through.  */
3026
3027     case UNION_TYPE:
3028     case ENUMERAL_TYPE:
3029       if (TYPE_TEMPLATE_INFO (t))
3030         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
3031                       &find_parameter_packs_r, ppd, ppd->visited);
3032
3033       *walk_subtrees = 0;
3034       return NULL_TREE;
3035
3036     case CONSTRUCTOR:
3037     case TEMPLATE_DECL:
3038       cp_walk_tree (&TREE_TYPE (t),
3039                     &find_parameter_packs_r, ppd, ppd->visited);
3040       return NULL_TREE;
3041  
3042     case TYPENAME_TYPE:
3043       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3044                    ppd, ppd->visited);
3045       *walk_subtrees = 0;
3046       return NULL_TREE;
3047       
3048     case TYPE_PACK_EXPANSION:
3049     case EXPR_PACK_EXPANSION:
3050       *walk_subtrees = 0;
3051       return NULL_TREE;
3052
3053     case INTEGER_TYPE:
3054       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
3055                     ppd, ppd->visited);
3056       *walk_subtrees = 0;
3057       return NULL_TREE;
3058
3059     case IDENTIFIER_NODE:
3060       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
3061                     ppd->visited);
3062       *walk_subtrees = 0;
3063       return NULL_TREE;
3064
3065     default:
3066       return NULL_TREE;
3067     }
3068
3069   return NULL_TREE;
3070 }
3071
3072 /* Determines if the expression or type T uses any parameter packs.  */
3073 bool
3074 uses_parameter_packs (tree t)
3075 {
3076   tree parameter_packs = NULL_TREE;
3077   struct find_parameter_pack_data ppd;
3078   ppd.parameter_packs = &parameter_packs;
3079   ppd.visited = pointer_set_create ();
3080   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3081   pointer_set_destroy (ppd.visited);
3082   return parameter_packs != NULL_TREE;
3083 }
3084
3085 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3086    representation a base-class initializer into a parameter pack
3087    expansion. If all goes well, the resulting node will be an
3088    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3089    respectively.  */
3090 tree 
3091 make_pack_expansion (tree arg)
3092 {
3093   tree result;
3094   tree parameter_packs = NULL_TREE;
3095   bool for_types = false;
3096   struct find_parameter_pack_data ppd;
3097
3098   if (!arg || arg == error_mark_node)
3099     return arg;
3100
3101   if (TREE_CODE (arg) == TREE_LIST)
3102     {
3103       /* The only time we will see a TREE_LIST here is for a base
3104          class initializer.  In this case, the TREE_PURPOSE will be a
3105          _TYPE node (representing the base class expansion we're
3106          initializing) and the TREE_VALUE will be a TREE_LIST
3107          containing the initialization arguments. 
3108
3109          The resulting expansion looks somewhat different from most
3110          expansions. Rather than returning just one _EXPANSION, we
3111          return a TREE_LIST whose TREE_PURPOSE is a
3112          TYPE_PACK_EXPANSION containing the bases that will be
3113          initialized.  The TREE_VALUE will be identical to the
3114          original TREE_VALUE, which is a list of arguments that will
3115          be passed to each base.  We do not introduce any new pack
3116          expansion nodes into the TREE_VALUE (although it is possible
3117          that some already exist), because the TREE_PURPOSE and
3118          TREE_VALUE all need to be expanded together with the same
3119          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3120          resulting TREE_PURPOSE will mention the parameter packs in
3121          both the bases and the arguments to the bases.  */
3122       tree purpose;
3123       tree value;
3124       tree parameter_packs = NULL_TREE;
3125
3126       /* Determine which parameter packs will be used by the base
3127          class expansion.  */
3128       ppd.visited = pointer_set_create ();
3129       ppd.parameter_packs = &parameter_packs;
3130       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3131                     &ppd, ppd.visited);
3132
3133       if (parameter_packs == NULL_TREE)
3134         {
3135           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3136           pointer_set_destroy (ppd.visited);
3137           return error_mark_node;
3138         }
3139
3140       if (TREE_VALUE (arg) != void_type_node)
3141         {
3142           /* Collect the sets of parameter packs used in each of the
3143              initialization arguments.  */
3144           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3145             {
3146               /* Determine which parameter packs will be expanded in this
3147                  argument.  */
3148               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3149                             &ppd, ppd.visited);
3150             }
3151         }
3152
3153       pointer_set_destroy (ppd.visited);
3154
3155       /* Create the pack expansion type for the base type.  */
3156       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3157       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3158       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3159
3160       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3161          they will rarely be compared to anything.  */
3162       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3163
3164       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3165     }
3166
3167   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3168     for_types = true;
3169
3170   /* Build the PACK_EXPANSION_* node.  */
3171   result = for_types
3172      ? cxx_make_type (TYPE_PACK_EXPANSION)
3173      : make_node (EXPR_PACK_EXPANSION);
3174   SET_PACK_EXPANSION_PATTERN (result, arg);
3175   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3176     {
3177       /* Propagate type and const-expression information.  */
3178       TREE_TYPE (result) = TREE_TYPE (arg);
3179       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3180     }
3181   else
3182     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3183        they will rarely be compared to anything.  */
3184     SET_TYPE_STRUCTURAL_EQUALITY (result);
3185
3186   /* Determine which parameter packs will be expanded.  */
3187   ppd.parameter_packs = &parameter_packs;
3188   ppd.visited = pointer_set_create ();
3189   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3190   pointer_set_destroy (ppd.visited);
3191
3192   /* Make sure we found some parameter packs.  */
3193   if (parameter_packs == NULL_TREE)
3194     {
3195       if (TYPE_P (arg))
3196         error ("expansion pattern %<%T%> contains no argument packs", arg);
3197       else
3198         error ("expansion pattern %<%E%> contains no argument packs", arg);
3199       return error_mark_node;
3200     }
3201   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3202
3203   return result;
3204 }
3205
3206 /* Checks T for any "bare" parameter packs, which have not yet been
3207    expanded, and issues an error if any are found. This operation can
3208    only be done on full expressions or types (e.g., an expression
3209    statement, "if" condition, etc.), because we could have expressions like:
3210
3211      foo(f(g(h(args)))...)
3212
3213    where "args" is a parameter pack. check_for_bare_parameter_packs
3214    should not be called for the subexpressions args, h(args),
3215    g(h(args)), or f(g(h(args))), because we would produce erroneous
3216    error messages. 
3217
3218    Returns TRUE and emits an error if there were bare parameter packs,
3219    returns FALSE otherwise.  */
3220 bool 
3221 check_for_bare_parameter_packs (tree t)
3222 {
3223   tree parameter_packs = NULL_TREE;
3224   struct find_parameter_pack_data ppd;
3225
3226   if (!processing_template_decl || !t || t == error_mark_node)
3227     return false;
3228
3229   if (TREE_CODE (t) == TYPE_DECL)
3230     t = TREE_TYPE (t);
3231
3232   ppd.parameter_packs = &parameter_packs;
3233   ppd.visited = pointer_set_create ();
3234   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3235   pointer_set_destroy (ppd.visited);
3236
3237   if (parameter_packs) 
3238     {
3239       error ("parameter packs not expanded with %<...%>:");
3240       while (parameter_packs)
3241         {
3242           tree pack = TREE_VALUE (parameter_packs);
3243           tree name = NULL_TREE;
3244
3245           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3246               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3247             name = TYPE_NAME (pack);
3248           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3249             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3250           else
3251             name = DECL_NAME (pack);
3252
3253           if (name)
3254             inform (input_location, "        %qD", name);
3255           else
3256             inform (input_location, "        <anonymous>");
3257
3258           parameter_packs = TREE_CHAIN (parameter_packs);
3259         }
3260
3261       return true;
3262     }
3263
3264   return false;
3265 }
3266
3267 /* Expand any parameter packs that occur in the template arguments in
3268    ARGS.  */
3269 tree
3270 expand_template_argument_pack (tree args)
3271 {
3272   tree result_args = NULL_TREE;
3273   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3274   int num_result_args = -1;
3275   int non_default_args_count = -1;
3276
3277   /* First, determine if we need to expand anything, and the number of
3278      slots we'll need.  */
3279   for (in_arg = 0; in_arg < nargs; ++in_arg)
3280     {
3281       tree arg = TREE_VEC_ELT (args, in_arg);
3282       if (arg == NULL_TREE)
3283         return args;
3284       if (ARGUMENT_PACK_P (arg))
3285         {
3286           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3287           if (num_result_args < 0)
3288             num_result_args = in_arg + num_packed;
3289           else
3290             num_result_args += num_packed;
3291         }
3292       else
3293         {
3294           if (num_result_args >= 0)
3295             num_result_args++;
3296         }
3297     }
3298
3299   /* If no expansion is necessary, we're done.  */
3300   if (num_result_args < 0)
3301     return args;
3302
3303   /* Expand arguments.  */
3304   result_args = make_tree_vec (num_result_args);
3305   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3306     non_default_args_count =
3307       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3308   for (in_arg = 0; in_arg < nargs; ++in_arg)
3309     {
3310       tree arg = TREE_VEC_ELT (args, in_arg);
3311       if (ARGUMENT_PACK_P (arg))
3312         {
3313           tree packed = ARGUMENT_PACK_ARGS (arg);
3314           int i, num_packed = TREE_VEC_LENGTH (packed);
3315           for (i = 0; i < num_packed; ++i, ++out_arg)
3316             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3317           if (non_default_args_count > 0)
3318             non_default_args_count += num_packed;
3319         }
3320       else
3321         {
3322           TREE_VEC_ELT (result_args, out_arg) = arg;
3323           ++out_arg;
3324         }
3325     }
3326   if (non_default_args_count >= 0)
3327     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3328   return result_args;
3329 }
3330
3331 /* Checks if DECL shadows a template parameter.
3332
3333    [temp.local]: A template-parameter shall not be redeclared within its
3334    scope (including nested scopes).
3335
3336    Emits an error and returns TRUE if the DECL shadows a parameter,
3337    returns FALSE otherwise.  */
3338
3339 bool
3340 check_template_shadow (tree decl)
3341 {
3342   tree olddecl;
3343
3344   /* If we're not in a template, we can't possibly shadow a template
3345      parameter.  */
3346   if (!current_template_parms)
3347     return true;
3348
3349   /* Figure out what we're shadowing.  */
3350   if (TREE_CODE (decl) == OVERLOAD)
3351     decl = OVL_CURRENT (decl);
3352   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3353
3354   /* If there's no previous binding for this name, we're not shadowing
3355      anything, let alone a template parameter.  */
3356   if (!olddecl)
3357     return true;
3358
3359   /* If we're not shadowing a template parameter, we're done.  Note
3360      that OLDDECL might be an OVERLOAD (or perhaps even an
3361      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3362      node.  */
3363   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3364     return true;
3365
3366   /* We check for decl != olddecl to avoid bogus errors for using a
3367      name inside a class.  We check TPFI to avoid duplicate errors for
3368      inline member templates.  */
3369   if (decl == olddecl
3370       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3371     return true;
3372
3373   error ("declaration of %q+#D", decl);
3374   error (" shadows template parm %q+#D", olddecl);
3375   return false;
3376 }
3377
3378 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3379    ORIG_LEVEL, DECL, and TYPE.  NUM_SIBLINGS is the total number of
3380    template parameters.  */
3381
3382 static tree
3383 build_template_parm_index (int index,
3384                            int level,
3385                            int orig_level,
3386                            int num_siblings,
3387                            tree decl,
3388                            tree type)
3389 {
3390   tree t = make_node (TEMPLATE_PARM_INDEX);
3391   TEMPLATE_PARM_IDX (t) = index;
3392   TEMPLATE_PARM_LEVEL (t) = level;
3393   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3394   TEMPLATE_PARM_NUM_SIBLINGS (t) = num_siblings;
3395   TEMPLATE_PARM_DECL (t) = decl;
3396   TREE_TYPE (t) = type;
3397   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3398   TREE_READONLY (t) = TREE_READONLY (decl);
3399
3400   return t;
3401 }
3402
3403 /* Find the canonical type parameter for the given template type
3404    parameter.  Returns the canonical type parameter, which may be TYPE
3405    if no such parameter existed.  */
3406
3407 static tree
3408 canonical_type_parameter (tree type)
3409 {
3410   tree list;
3411   int idx = TEMPLATE_TYPE_IDX (type);
3412   if (!canonical_template_parms)
3413     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3414
3415   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3416     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3417
3418   list = VEC_index (tree, canonical_template_parms, idx);
3419   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3420     list = TREE_CHAIN (list);
3421
3422   if (list)
3423     return TREE_VALUE (list);
3424   else
3425     {
3426       VEC_replace(tree, canonical_template_parms, idx,
3427                   tree_cons (NULL_TREE, type, 
3428                              VEC_index (tree, canonical_template_parms, idx)));
3429       return type;
3430     }
3431 }
3432
3433 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3434    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3435    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3436    new one is created.  */
3437
3438 static tree
3439 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3440                             tsubst_flags_t complain)
3441 {
3442   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3443       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3444           != TEMPLATE_PARM_LEVEL (index) - levels)
3445       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3446     {
3447       tree orig_decl = TEMPLATE_PARM_DECL (index);
3448       tree decl, t;
3449
3450       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3451                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3452       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3453       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3454       DECL_ARTIFICIAL (decl) = 1;
3455       SET_DECL_TEMPLATE_PARM_P (decl);
3456
3457       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3458                                      TEMPLATE_PARM_LEVEL (index) - levels,
3459                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3460                                      TEMPLATE_PARM_NUM_SIBLINGS (index),
3461                                      decl, type);
3462       TEMPLATE_PARM_DESCENDANTS (index) = t;
3463       TEMPLATE_PARM_PARAMETER_PACK (t) 
3464         = TEMPLATE_PARM_PARAMETER_PACK (index);
3465
3466         /* Template template parameters need this.  */
3467       if (TREE_CODE (decl) == TEMPLATE_DECL)
3468         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3469           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3470            args, complain);
3471     }
3472
3473   return TEMPLATE_PARM_DESCENDANTS (index);
3474 }
3475
3476 /* Process information from new template parameter PARM and append it
3477    to the LIST being built.  This new parameter is a non-type
3478    parameter iff IS_NON_TYPE is true. This new parameter is a
3479    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
3480    is in PARM_LOC. NUM_TEMPLATE_PARMS is the size of the template
3481    parameter list PARM belongs to. This is used used to create a
3482    proper canonical type for the type of PARM that is to be created,
3483    iff PARM is a type.  If the size is not known, this parameter shall
3484    be set to 0.  */
3485
3486 tree
3487 process_template_parm (tree list, location_t parm_loc, tree parm,
3488                        bool is_non_type, bool is_parameter_pack,
3489                        unsigned num_template_parms)
3490 {
3491   tree decl = 0;
3492   tree defval;
3493   tree err_parm_list;
3494   int idx = 0;
3495
3496   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3497   defval = TREE_PURPOSE (parm);
3498
3499   if (list)
3500     {
3501       tree p = tree_last (list);
3502
3503       if (p && TREE_VALUE (p) != error_mark_node)
3504         {
3505           p = TREE_VALUE (p);
3506           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3507             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3508           else
3509             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3510         }
3511
3512       ++idx;
3513     }
3514   else
3515     idx = 0;
3516
3517   if (is_non_type)
3518     {
3519       parm = TREE_VALUE (parm);
3520
3521       SET_DECL_TEMPLATE_PARM_P (parm);
3522
3523       if (TREE_TYPE (parm) == error_mark_node)
3524         {
3525           err_parm_list = build_tree_list (defval, parm);
3526           TREE_VALUE (err_parm_list) = error_mark_node;
3527            return chainon (list, err_parm_list);
3528         }
3529       else
3530       {
3531         /* [temp.param]
3532
3533            The top-level cv-qualifiers on the template-parameter are
3534            ignored when determining its type.  */
3535         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3536         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3537           {
3538             err_parm_list = build_tree_list (defval, parm);
3539             TREE_VALUE (err_parm_list) = error_mark_node;
3540              return chainon (list, err_parm_list);
3541           }
3542
3543         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3544           {
3545             /* This template parameter is not a parameter pack, but it
3546                should be. Complain about "bare" parameter packs.  */
3547             check_for_bare_parameter_packs (TREE_TYPE (parm));
3548             
3549             /* Recover by calling this a parameter pack.  */
3550             is_parameter_pack = true;
3551           }
3552       }
3553
3554       /* A template parameter is not modifiable.  */
3555       TREE_CONSTANT (parm) = 1;
3556       TREE_READONLY (parm) = 1;
3557       decl = build_decl (parm_loc,
3558                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3559       TREE_CONSTANT (decl) = 1;
3560       TREE_READONLY (decl) = 1;
3561       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3562         = build_template_parm_index (idx, processing_template_decl,
3563                                      processing_template_decl,
3564                                      num_template_parms,
3565                                      decl, TREE_TYPE (parm));
3566
3567       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3568         = is_parameter_pack;
3569     }
3570   else
3571     {
3572       tree t;
3573       parm = TREE_VALUE (TREE_VALUE (parm));
3574
3575       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3576         {
3577           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3578           /* This is for distinguishing between real templates and template
3579              template parameters */
3580           TREE_TYPE (parm) = t;
3581           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3582           decl = parm;
3583         }
3584       else
3585         {
3586           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3587           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3588           decl = build_decl (parm_loc,
3589                              TYPE_DECL, parm, t);
3590         }
3591
3592       TYPE_NAME (t) = decl;
3593       TYPE_STUB_DECL (t) = decl;
3594       parm = decl;
3595       TEMPLATE_TYPE_PARM_INDEX (t)
3596         = build_template_parm_index (idx, processing_template_decl,
3597                                      processing_template_decl,
3598                                      num_template_parms,
3599                                      decl, TREE_TYPE (parm));
3600       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3601       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3602     }
3603   DECL_ARTIFICIAL (decl) = 1;
3604   SET_DECL_TEMPLATE_PARM_P (decl);
3605   pushdecl (decl);
3606   parm = build_tree_list (defval, parm);
3607   return chainon (list, parm);
3608 }
3609
3610 /* The end of a template parameter list has been reached.  Process the
3611    tree list into a parameter vector, converting each parameter into a more
3612    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3613    as PARM_DECLs.  */
3614
3615 tree
3616 end_template_parm_list (tree parms)
3617 {
3618   int nparms;
3619   tree parm, next;
3620   tree saved_parmlist = make_tree_vec (list_length (parms));
3621
3622   current_template_parms
3623     = tree_cons (size_int (processing_template_decl),
3624                  saved_parmlist, current_template_parms);
3625
3626   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3627     {
3628       next = TREE_CHAIN (parm);
3629       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3630       TREE_CHAIN (parm) = NULL_TREE;
3631     }
3632
3633   --processing_template_parmlist;
3634
3635   return saved_parmlist;
3636 }
3637
3638 /* Create a new type almost identical to TYPE but which has the
3639    following differences:
3640
3641      1/ T has a new TEMPLATE_PARM_INDEX that carries the new number of
3642      template sibling parameters of T.
3643
3644      2/ T has a new canonical type that matches the new number
3645      of sibling parms.
3646
3647      3/ From now on, T is going to be what lookups referring to the
3648      name of TYPE will return. No lookup should return TYPE anymore.
3649
3650    NUM_PARMS is the new number of sibling parms TYPE belongs to.
3651
3652    This is a subroutine of fixup_template_parms.  */
3653
3654 static tree
3655 fixup_template_type_parm_type (tree type, int num_parms)
3656 {
3657   tree orig_idx = TEMPLATE_TYPE_PARM_INDEX (type), idx;
3658   tree t;
3659   /* This is the decl which name is inserted into the symbol table for
3660      the template parm type. So whenever we lookup the type name, this
3661      is the DECL we get.  */
3662   tree decl;
3663
3664   /* Do not fix up the type twice.  */
3665   if (orig_idx && TEMPLATE_PARM_NUM_SIBLINGS (orig_idx) != 0)
3666     return type;
3667
3668   t = copy_type (type);
3669   decl = TYPE_NAME (t);
3670
3671   TYPE_MAIN_VARIANT (t) = t;
3672   TYPE_NEXT_VARIANT (t)= NULL_TREE;
3673   TYPE_POINTER_TO (t) = 0;
3674   TYPE_REFERENCE_TO (t) = 0;
3675
3676   idx = build_template_parm_index (TEMPLATE_PARM_IDX (orig_idx),
3677                                    TEMPLATE_PARM_LEVEL (orig_idx),
3678                                    TEMPLATE_PARM_ORIG_LEVEL (orig_idx),
3679                                    num_parms,
3680                                    decl, t);
3681   TEMPLATE_PARM_DESCENDANTS (idx) = TEMPLATE_PARM_DESCENDANTS (orig_idx);
3682   TEMPLATE_PARM_PARAMETER_PACK (idx) = TEMPLATE_PARM_PARAMETER_PACK (orig_idx);
3683   TEMPLATE_TYPE_PARM_INDEX (t) = idx;
3684
3685   TYPE_STUB_DECL (t) = decl;
3686   TEMPLATE_TYPE_DECL (t) = decl;
3687   if (TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
3688     TREE_TYPE (DECL_TEMPLATE_RESULT  (decl)) = t;
3689
3690   /* Update the type associated to the type name stored in the symbol
3691      table. Now, whenever the type name is looked up, the resulting
3692      type is properly fixed up.  */
3693   TREE_TYPE (decl) = t;
3694
3695   TYPE_CANONICAL (t) = canonical_type_parameter (t);
3696
3697   return t;
3698 }
3699
3700 /* Create and return a new TEMPLATE_PARM_INDEX that is almost
3701    identical to I, but that is fixed up as to:
3702
3703    1/ carry the number of sibling parms (NUM_PARMS) of the template
3704    parm represented by I.
3705
3706    2/ replace all references to template parm types declared before I
3707    (in the same template parm list as I) by references to template
3708    parm types contained in ARGS. ARGS should contain the list of
3709    template parms that have been fixed up so far, in a form suitable
3710    to be passed to tsubst.
3711
3712    This is a subroutine of fixup_template_parms.  */
3713
3714 static tree
3715 fixup_template_parm_index (tree i, tree args, int num_parms)
3716 {
3717   tree index, decl, type;
3718
3719   if (i == NULL_TREE
3720       || TREE_CODE (i) != TEMPLATE_PARM_INDEX
3721       /* Do not fix up the index twice.  */
3722       || (TEMPLATE_PARM_NUM_SIBLINGS (i) != 0))
3723     return i;
3724
3725   decl = TEMPLATE_PARM_DECL (i);
3726   type = TREE_TYPE (decl);
3727
3728   index = build_template_parm_index (TEMPLATE_PARM_IDX (i),
3729                                      TEMPLATE_PARM_LEVEL (i),
3730                                      TEMPLATE_PARM_ORIG_LEVEL (i),
3731                                      num_parms,
3732                                      decl, type);
3733
3734   TEMPLATE_PARM_DESCENDANTS (index) = TEMPLATE_PARM_DESCENDANTS (i);
3735   TEMPLATE_PARM_PARAMETER_PACK (index) = TEMPLATE_PARM_PARAMETER_PACK (i);
3736
3737   type = tsubst (type, args, tf_none, NULL_TREE);
3738   
3739   TREE_TYPE (decl) = type;
3740   TREE_TYPE (index) = type;
3741
3742   return index;
3743 }
3744
3745 /* 
3746    This is a subroutine of fixup_template_parms.
3747
3748    It computes the canonical type of the type of the template
3749    parameter PARM_DESC and update all references to that type so that
3750    they use the newly computed canonical type. No access check is
3751    performed during the fixup. PARM_DESC is a TREE_LIST which
3752    TREE_VALUE is the template parameter and its TREE_PURPOSE is the
3753    default argument of the template parm if any. IDX is the index of
3754    the template parameter, starting at 0. NUM_PARMS is the number of
3755    template parameters in the set PARM_DESC belongs to. ARGLIST is a
3756    TREE_VEC containing the full set of template parameters in a form
3757    suitable to be passed to substs functions as their ARGS
3758    argument. This is what current_template_args returns for a given
3759    template. The innermost vector of args in ARGLIST is the set of
3760    template parms that have been fixed up so far. This function adds
3761    the fixed up parameter into that vector.  */
3762
3763 static void
3764 fixup_template_parm (tree parm_desc,
3765                      int idx,
3766                      int num_parms,
3767                      tree arglist)
3768 {
3769   tree parm = TREE_VALUE (parm_desc);
3770   tree fixedup_args = INNERMOST_TEMPLATE_ARGS (arglist);
3771
3772   push_deferring_access_checks (dk_no_check);
3773
3774   if (TREE_CODE (parm) == TYPE_DECL)
3775     {
3776       /* PARM is a template type parameter. Fix up its type, add
3777          the fixed-up template parm to the vector of fixed-up
3778          template parms so far, and substitute the fixed-up
3779          template parms into the default argument of this
3780          parameter.  */
3781       tree t =
3782         fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
3783       TREE_TYPE (parm) = t;
3784
3785       TREE_VEC_ELT (fixedup_args, idx) = template_parm_to_arg (parm_desc);
3786     }
3787   else if (TREE_CODE (parm) == TEMPLATE_DECL)
3788     {
3789       /* PARM is a template template parameter. This is going to
3790          be interesting.  */
3791       tree tparms, targs, innermost_args, t;
3792       int j;
3793
3794       /* First, fix up the parms of the template template parm
3795          because the parms are involved in defining the new canonical
3796          type of the template template parm.  */
3797
3798       /* So we need to substitute the template parm types that have
3799          been fixed up so far into the template parms of this template
3800          template parm. E.g, consider this:
3801
3802          template<class T, template<T u> class TT> class S;
3803
3804          In this case we want to substitute T into the
3805          template parameters of TT.
3806
3807          So let's walk the template parms of PARM here, and
3808          tsubst ARGLIST into into each of the template
3809          parms.   */
3810
3811       /* For this substitution we need to build the full set of
3812          template parameters and use that as arguments for the
3813          tsubsting function.  */
3814       tparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
3815
3816       /* This will contain the innermost parms of PARM into which
3817          we have substituted so far.  */
3818       innermost_args = make_tree_vec (TREE_VEC_LENGTH (tparms));
3819       targs = add_to_template_args (arglist, innermost_args);
3820       for (j = 0; j < TREE_VEC_LENGTH (tparms); ++j)
3821         {
3822           tree parameter;
3823
3824           parameter = TREE_VEC_ELT (tparms, j);
3825
3826           /* INNERMOST_ARGS needs to have at least the same number
3827              of elements as the index PARAMETER, ortherwise
3828              tsubsting into PARAMETER will result in partially
3829              instantiating it, reducing its tempate parm
3830              level. Let's tactically fill INNERMOST_ARGS for that
3831              purpose.  */
3832           TREE_VEC_ELT (innermost_args, j) =
3833             template_parm_to_arg (parameter);
3834
3835           fixup_template_parm (parameter, j,
3836                                TREE_VEC_LENGTH (tparms),
3837                                targs);
3838         }
3839
3840       /* Now fix up the type of the template template parm.  */
3841
3842       t = fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
3843       TREE_TYPE (parm) = t;
3844
3845       TREE_VEC_ELT (fixedup_args, idx) =
3846         template_parm_to_arg (parm_desc);
3847     }
3848   else if (TREE_CODE (parm) == PARM_DECL)
3849     {
3850       /* PARM is a non-type template parameter. We need to:
3851
3852        * Fix up its TEMPLATE_PARM_INDEX to make it carry the
3853        proper number of sibling parameters.
3854
3855        * Make lookups of the template parameter return a reference
3856        to the fixed-up index. No lookup should return references
3857        to the former index anymore.
3858
3859        * Substitute the template parms that got fixed up so far
3860
3861        * into the type of PARM.  */
3862
3863       tree index = DECL_INITIAL (parm);
3864
3865       /* PUSHED_DECL is the decl added to the symbol table with
3866          the name of the parameter. E,g:
3867              
3868          template<class T, T u> //#0
3869          auto my_function(T t) -> decltype(u); //#1
3870
3871          Here, when looking up u at //#1, we get the decl of u
3872          resulting from the declaration in #0. This is what
3873          PUSHED_DECL is. We need to replace the reference to the
3874          old TEMPLATE_PARM_INDEX carried by PUSHED_DECL by the
3875          fixed-up TEMPLATE_PARM_INDEX.  */
3876       tree pushed_decl = TEMPLATE_PARM_DECL (index);
3877
3878       /* Let's fix up the TEMPLATE_PARM_INDEX then. Note that we must
3879          fixup the type of PUSHED_DECL as well and luckily
3880          fixup_template_parm_index does it for us too.  */
3881       tree fixed_up_index =
3882         fixup_template_parm_index (index, arglist, num_parms);
3883
3884       DECL_INITIAL (pushed_decl) = DECL_INITIAL (parm) = fixed_up_index;
3885
3886       /* Add this fixed up PARM to the template parms we've fixed
3887          up so far and use that to substitute the fixed-up
3888          template parms into the type of PARM.  */
3889       TREE_VEC_ELT (fixedup_args, idx) =
3890         template_parm_to_arg (parm_desc);
3891       TREE_TYPE (parm) = tsubst (TREE_TYPE (parm), arglist,
3892                                  tf_none, NULL_TREE);
3893     }
3894
3895   TREE_PURPOSE (parm_desc) =
3896     tsubst_template_arg (TREE_PURPOSE (parm_desc),
3897                          arglist, tf_none, parm);
3898
3899   pop_deferring_access_checks ();
3900 }
3901
3902 /* Walk the current template parms and properly compute the canonical
3903    types of the dependent types created during
3904    cp_parser_template_parameter_list.  */
3905
3906 void
3907 fixup_template_parms (void)
3908 {
3909   tree arglist;
3910   tree parameter_vec;
3911   tree fixedup_args;
3912   int i, num_parms;
3913
3914   parameter_vec = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3915   if (parameter_vec == NULL_TREE)
3916     return;
3917
3918   num_parms = TREE_VEC_LENGTH (parameter_vec);
3919
3920   /* This vector contains the current innermost template parms that
3921      have been fixed up so far.  The form of FIXEDUP_ARGS is suitable
3922      to be passed to tsubst* functions as their ARGS argument.  */
3923   fixedup_args = make_tree_vec (num_parms);
3924
3925   /* This vector contains the full set of template parms in a form
3926      suitable to be passed to substs functions as their ARGS
3927      argument.  */
3928   arglist = current_template_args ();
3929   arglist = add_outermost_template_args (arglist, fixedup_args);
3930
3931   /* Let's do the proper fixup now.  */
3932   for (i = 0; i < num_parms; ++i)
3933     fixup_template_parm (TREE_VEC_ELT (parameter_vec, i),
3934                          i, num_parms, arglist);
3935 }
3936
3937 /* end_template_decl is called after a template declaration is seen.  */
3938
3939 void
3940 end_template_decl (void)
3941 {
3942   reset_specialization ();
3943
3944   if (! processing_template_decl)
3945     return;
3946
3947   /* This matches the pushlevel in begin_template_parm_list.  */
3948   finish_scope ();
3949
3950   --processing_template_decl;
3951   current_template_parms = TREE_CHAIN (current_template_parms);
3952 }
3953
3954 /* Takes a TREE_LIST representing a template parameter and convert it
3955    into an argument suitable to be passed to the type substitution
3956    functions.  Note that If the TREE_LIST contains an error_mark
3957    node, the returned argument is error_mark_node.  */
3958
3959 static tree
3960 template_parm_to_arg (tree t)
3961 {
3962
3963   if (t == NULL_TREE
3964       || TREE_CODE (t) != TREE_LIST)
3965     return t;
3966
3967   if (error_operand_p (TREE_VALUE (t)))
3968     return error_mark_node;
3969
3970   t = TREE_VALUE (t);
3971
3972   if (TREE_CODE (t) == TYPE_DECL
3973       || TREE_CODE (t) == TEMPLATE_DECL)
3974     {
3975       t = TREE_TYPE (t);
3976
3977       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3978         {
3979           /* Turn this argument into a TYPE_ARGUMENT_PACK
3980              with a single element, which expands T.  */
3981           tree vec = make_tree_vec (1);
3982 #ifdef ENABLE_CHECKING
3983           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3984             (vec, TREE_VEC_LENGTH (vec));
3985 #endif
3986           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3987
3988           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3989           SET_ARGUMENT_PACK_ARGS (t, vec);
3990         }
3991     }
3992   else
3993     {
3994       t = DECL_INITIAL (t);
3995
3996       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3997         {
3998           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3999              with a single element, which expands T.  */
4000           tree vec = make_tree_vec (1);
4001           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
4002 #ifdef ENABLE_CHECKING
4003           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
4004             (vec, TREE_VEC_LENGTH (vec));
4005 #endif
4006           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4007
4008           t  = make_node (NONTYPE_ARGUMENT_PACK);
4009           SET_ARGUMENT_PACK_ARGS (t, vec);
4010           TREE_TYPE (t) = type;
4011         }
4012     }
4013   return t;
4014 }
4015
4016 /* This function returns TRUE if PARM_PACK is a template parameter
4017    pack and if ARG_PACK is what template_parm_to_arg returned when
4018    passed PARM_PACK.  */
4019
4020 static bool
4021 arg_from_parm_pack_p (tree arg_pack, tree parm_pack)
4022 {
4023   /* For clarity in the comments below let's use the representation
4024      argument_pack<elements>' to denote an argument pack and its
4025      elements.
4026
4027      In the 'if' block below, we want to detect cases where
4028      ARG_PACK is argument_pack<PARM_PACK...>.  I.e, we want to
4029      check if ARG_PACK is an argument pack which sole element is
4030      the expansion of PARM_PACK.  That argument pack is typically
4031      created by template_parm_to_arg when passed a parameter
4032      pack.  */
4033
4034   if (arg_pack
4035       && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
4036       && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
4037     {
4038       tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
4039       tree pattern = PACK_EXPANSION_PATTERN (expansion);
4040       /* So we have an argument_pack<P...>.  We want to test if P
4041          is actually PARM_PACK.  We will not use cp_tree_equal to
4042          test P and PARM_PACK because during type fixup (by
4043          fixup_template_parm) P can be a pre-fixup version of a
4044          type and PARM_PACK be its post-fixup version.
4045          cp_tree_equal would consider them as different even
4046          though we would want to consider them compatible for our
4047          precise purpose here.
4048
4049          Thus we are going to consider that P and PARM_PACK are
4050          compatible if they have the same DECL.  */
4051       if ((/* If ARG_PACK is a type parameter pack named by the
4052               same DECL as parm_pack ...  */
4053            (TYPE_P (pattern)
4054             && TYPE_P (parm_pack)
4055             && TYPE_NAME (pattern) == TYPE_NAME (parm_pack))
4056            /* ... or if PARM_PACK is a non-type parameter named by the
4057               same DECL as ARG_PACK.  Note that PARM_PACK being a
4058               non-type parameter means it's either a PARM_DECL or a
4059               TEMPLATE_PARM_INDEX.  */
4060            || (TREE_CODE (pattern) == TEMPLATE_PARM_INDEX
4061                && ((TREE_CODE (parm_pack) == PARM_DECL
4062                     && (TEMPLATE_PARM_DECL (pattern)
4063                         == TEMPLATE_PARM_DECL (DECL_INITIAL (parm_pack))))
4064                    || (TREE_CODE (parm_pack) == TEMPLATE_PARM_INDEX
4065                        && (TEMPLATE_PARM_DECL (pattern)
4066                            == TEMPLATE_PARM_DECL (parm_pack))))))
4067           && template_parameter_pack_p (pattern))
4068         return true;
4069     }
4070   return false;
4071 }
4072
4073 /* Within the declaration of a template, return all levels of template
4074    parameters that apply.  The template parameters are represented as
4075    a TREE_VEC, in the form documented in cp-tree.h for template
4076    arguments.  */
4077
4078 static tree
4079 current_template_args (void)
4080 {
4081   tree header;
4082   tree args = NULL_TREE;
4083   int length = TMPL_PARMS_DEPTH (current_template_parms);
4084   int l = length;
4085
4086   /* If there is only one level of template parameters, we do not
4087      create a TREE_VEC of TREE_VECs.  Instead, we return a single
4088      TREE_VEC containing the arguments.  */
4089   if (length > 1)
4090     args = make_tree_vec (length);
4091
4092   for (header = current_template_parms; header; header = TREE_CHAIN (header))
4093     {
4094       tree a = copy_node (TREE_VALUE (header));
4095       int i;
4096
4097       TREE_TYPE (a) = NULL_TREE;
4098       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4099         TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4100
4101 #ifdef ENABLE_CHECKING
4102       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4103 #endif
4104
4105       if (length > 1)
4106         TREE_VEC_ELT (args, --l) = a;
4107       else
4108         args = a;
4109     }
4110
4111     if (length > 1 && TREE_VEC_ELT (args, 0) == NULL_TREE)
4112       /* This can happen for template parms of a template template
4113          parameter, e.g:
4114
4115          template<template<class T, class U> class TT> struct S;
4116
4117          Consider the level of the parms of TT; T and U both have
4118          level 2; TT has no template parm of level 1. So in this case
4119          the first element of full_template_args is NULL_TREE. If we
4120          leave it like this TMPL_ARG_DEPTH on args returns 1 instead
4121          of 2. This will make tsubst wrongly consider that T and U
4122          have level 1. Instead, let's create a dummy vector as the
4123          first element of full_template_args so that TMPL_ARG_DEPTH
4124          returns the correct depth for args.  */
4125       TREE_VEC_ELT (args, 0) = make_tree_vec (1);
4126   return args;
4127 }
4128
4129 /* Update the declared TYPE by doing any lookups which were thought to be
4130    dependent, but are not now that we know the SCOPE of the declarator.  */
4131
4132 tree
4133 maybe_update_decl_type (tree orig_type, tree scope)
4134 {
4135   tree type = orig_type;
4136
4137   if (type == NULL_TREE)
4138     return type;
4139
4140   if (TREE_CODE (orig_type) == TYPE_DECL)
4141     type = TREE_TYPE (type);
4142
4143   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4144       && dependent_type_p (type)
4145       /* Don't bother building up the args in this case.  */
4146       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4147     {
4148       /* tsubst in the args corresponding to the template parameters,
4149          including auto if present.  Most things will be unchanged, but
4150          make_typename_type and tsubst_qualified_id will resolve
4151          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4152       tree args = current_template_args ();
4153       tree auto_node = type_uses_auto (type);
4154       tree pushed;
4155       if (auto_node)
4156         {
4157           tree auto_vec = make_tree_vec (1);
4158           TREE_VEC_ELT (auto_vec, 0) = auto_node;
4159           args = add_to_template_args (args, auto_vec);
4160         }
4161       pushed = push_scope (scope);
4162       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4163       if (pushed)
4164         pop_scope (scope);
4165     }
4166
4167   if (type == error_mark_node)
4168     return orig_type;
4169
4170   if (TREE_CODE (orig_type) == TYPE_DECL)
4171     {
4172       if (same_type_p (type, TREE_TYPE (orig_type)))
4173         type = orig_type;
4174       else
4175         type = TYPE_NAME (type);
4176     }
4177   return type;
4178 }
4179
4180 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4181    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
4182    a member template.  Used by push_template_decl below.  */
4183
4184 static tree
4185 build_template_decl (tree decl, tree parms, bool member_template_p)
4186 {
4187   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4188   DECL_TEMPLATE_PARMS (tmpl) = parms;
4189   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4190   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
4191   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4192
4193   return tmpl;
4194 }
4195
4196 struct template_parm_data
4197 {
4198   /* The level of the template parameters we are currently
4199      processing.  */
4200   int level;
4201
4202   /* The index of the specialization argument we are currently
4203      processing.  */
4204   int current_arg;
4205
4206   /* An array whose size is the number of template parameters.  The
4207      elements are nonzero if the parameter has been used in any one
4208      of the arguments processed so far.  */
4209   int* parms;
4210
4211   /* An array whose size is the number of template arguments.  The
4212      elements are nonzero if the argument makes use of template
4213      parameters of this level.  */
4214   int* arg_uses_template_parms;
4215 };
4216
4217 /* Subroutine of push_template_decl used to see if each template
4218    parameter in a partial specialization is used in the explicit
4219    argument list.  If T is of the LEVEL given in DATA (which is
4220    treated as a template_parm_data*), then DATA->PARMS is marked
4221    appropriately.  */
4222
4223 static int
4224 mark_template_parm (tree t, void* data)
4225 {
4226   int level;
4227   int idx;
4228   struct template_parm_data* tpd = (struct template_parm_data*) data;
4229
4230   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4231     {
4232       level = TEMPLATE_PARM_LEVEL (t);
4233       idx = TEMPLATE_PARM_IDX (t);
4234     }
4235   else
4236     {
4237       level = TEMPLATE_TYPE_LEVEL (t);
4238       idx = TEMPLATE_TYPE_IDX (t);
4239     }
4240
4241   if (level == tpd->level)
4242     {
4243       tpd->parms[idx] = 1;
4244       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4245     }
4246
4247   /* Return zero so that for_each_template_parm will continue the
4248      traversal of the tree; we want to mark *every* template parm.  */
4249   return 0;
4250 }
4251
4252 /* Process the partial specialization DECL.  */
4253
4254 static tree
4255 process_partial_specialization (tree decl)
4256 {
4257   tree type = TREE_TYPE (decl);
4258   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
4259   tree specargs = CLASSTYPE_TI_ARGS (type);
4260   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4261   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4262   tree inner_parms;
4263   tree inst;
4264   int nargs = TREE_VEC_LENGTH (inner_args);
4265   int ntparms;
4266   int  i;
4267   bool did_error_intro = false;
4268   struct template_parm_data tpd;
4269   struct template_parm_data tpd2;
4270
4271   gcc_assert (current_template_parms);
4272
4273   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4274   ntparms = TREE_VEC_LENGTH (inner_parms);
4275
4276   /* We check that each of the template parameters given in the
4277      partial specialization is used in the argument list to the
4278      specialization.  For example:
4279
4280        template <class T> struct S;
4281        template <class T> struct S<T*>;
4282
4283      The second declaration is OK because `T*' uses the template
4284      parameter T, whereas
4285
4286        template <class T> struct S<int>;
4287
4288      is no good.  Even trickier is:
4289
4290        template <class T>
4291        struct S1
4292        {
4293           template <class U>
4294           struct S2;
4295           template <class U>
4296           struct S2<T>;
4297        };
4298
4299      The S2<T> declaration is actually invalid; it is a
4300      full-specialization.  Of course,
4301
4302           template <class U>
4303           struct S2<T (*)(U)>;
4304
4305      or some such would have been OK.  */
4306   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4307   tpd.parms = XALLOCAVEC (int, ntparms);
4308   memset (tpd.parms, 0, sizeof (int) * ntparms);
4309
4310   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4311   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4312   for (i = 0; i < nargs; ++i)
4313     {
4314       tpd.current_arg = i;
4315       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4316                               &mark_template_parm,
4317                               &tpd,
4318                               NULL,
4319                               /*include_nondeduced_p=*/false);
4320     }
4321   for (i = 0; i < ntparms; ++i)
4322     if (tpd.parms[i] == 0)
4323       {
4324         /* One of the template parms was not used in the
4325            specialization.  */
4326         if (!did_error_intro)
4327           {
4328             error ("template parameters not used in partial specialization:");
4329             did_error_intro = true;
4330           }
4331
4332         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
4333       }
4334
4335   if (did_error_intro)
4336     return error_mark_node;
4337
4338   /* [temp.class.spec]
4339
4340      The argument list of the specialization shall not be identical to
4341      the implicit argument list of the primary template.  */
4342   if (comp_template_args
4343       (inner_args,
4344        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
4345                                                    (maintmpl)))))
4346     error ("partial specialization %qT does not specialize any template arguments", type);
4347
4348   /* [temp.class.spec]
4349
4350      A partially specialized non-type argument expression shall not
4351      involve template parameters of the partial specialization except
4352      when the argument expression is a simple identifier.
4353
4354      The type of a template parameter corresponding to a specialized
4355      non-type argument shall not be dependent on a parameter of the
4356      specialization. 
4357
4358      Also, we verify that pack expansions only occur at the
4359      end of the argument list.  */
4360   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
4361   tpd2.parms = 0;
4362   for (i = 0; i < nargs; ++i)
4363     {
4364       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
4365       tree arg = TREE_VEC_ELT (inner_args, i);
4366       tree packed_args = NULL_TREE;
4367       int j, len = 1;
4368
4369       if (ARGUMENT_PACK_P (arg))
4370         {
4371           /* Extract the arguments from the argument pack. We'll be
4372              iterating over these in the following loop.  */
4373           packed_args = ARGUMENT_PACK_ARGS (arg);
4374           len = TREE_VEC_LENGTH (packed_args);
4375         }
4376
4377       for (j = 0; j < len; j++)
4378         {
4379           if (packed_args)
4380             /* Get the Jth argument in the parameter pack.  */
4381             arg = TREE_VEC_ELT (packed_args, j);
4382
4383           if (PACK_EXPANSION_P (arg))
4384             {
4385               /* Pack expansions must come at the end of the
4386                  argument list.  */
4387               if ((packed_args && j < len - 1)
4388                   || (!packed_args && i < nargs - 1))
4389                 {
4390                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4391                     error ("parameter pack argument %qE must be at the "
4392                            "end of the template argument list", arg);
4393                   else
4394                     error ("parameter pack argument %qT must be at the "
4395                            "end of the template argument list", arg);
4396                 }
4397             }
4398
4399           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4400             /* We only care about the pattern.  */
4401             arg = PACK_EXPANSION_PATTERN (arg);
4402
4403           if (/* These first two lines are the `non-type' bit.  */
4404               !TYPE_P (arg)
4405               && TREE_CODE (arg) != TEMPLATE_DECL
4406               /* This next line is the `argument expression is not just a
4407                  simple identifier' condition and also the `specialized
4408                  non-type argument' bit.  */
4409               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
4410             {
4411               if ((!packed_args && tpd.arg_uses_template_parms[i])
4412                   || (packed_args && uses_template_parms (arg)))
4413                 error ("template argument %qE involves template parameter(s)",
4414                        arg);
4415               else 
4416                 {
4417                   /* Look at the corresponding template parameter,
4418                      marking which template parameters its type depends
4419                      upon.  */
4420                   tree type = TREE_TYPE (parm);
4421
4422                   if (!tpd2.parms)
4423                     {
4424                       /* We haven't yet initialized TPD2.  Do so now.  */
4425                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4426                       /* The number of parameters here is the number in the
4427                          main template, which, as checked in the assertion
4428                          above, is NARGS.  */
4429                       tpd2.parms = XALLOCAVEC (int, nargs);
4430                       tpd2.level = 
4431                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4432                     }
4433
4434                   /* Mark the template parameters.  But this time, we're
4435                      looking for the template parameters of the main
4436                      template, not in the specialization.  */
4437                   tpd2.current_arg = i;
4438                   tpd2.arg_uses_template_parms[i] = 0;
4439                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4440                   for_each_template_parm (type,
4441                                           &mark_template_parm,
4442                                           &tpd2,
4443                                           NULL,
4444                                           /*include_nondeduced_p=*/false);
4445
4446                   if (tpd2.arg_uses_template_parms [i])
4447                     {
4448                       /* The type depended on some template parameters.
4449                          If they are fully specialized in the
4450                          specialization, that's OK.  */
4451                       int j;
4452                       int count = 0;
4453                       for (j = 0; j < nargs; ++j)
4454                         if (tpd2.parms[j] != 0
4455                             && tpd.arg_uses_template_parms [j])
4456                           ++count;
4457                       if (count != 0)
4458                         error_n (input_location, count,
4459                                  "type %qT of template argument %qE depends "
4460                                  "on a template parameter",
4461                                  "type %qT of template argument %qE depends "
4462                                  "on template parameters",
4463                                  type,
4464                                  arg);
4465                     }
4466                 }
4467             }
4468         }
4469     }
4470
4471   /* We should only get here once.  */
4472   gcc_assert (!COMPLETE_TYPE_P (type));
4473
4474   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4475     = tree_cons (specargs, inner_parms,
4476                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4477   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4478
4479   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
4480        inst = TREE_CHAIN (inst))
4481     {
4482       tree inst_type = TREE_VALUE (inst);
4483       if (COMPLETE_TYPE_P (inst_type)
4484           && CLASSTYPE_IMPLICIT_INSTANTIATION (inst_type))
4485         {
4486           tree spec = most_specialized_class (inst_type, maintmpl, tf_none);
4487           if (spec && TREE_TYPE (spec) == type)
4488             permerror (input_location,
4489                        "partial specialization of %qT after instantiation "
4490                        "of %qT", type, inst_type);
4491         }
4492     }
4493
4494   return decl;
4495 }
4496
4497 /* Check that a template declaration's use of default arguments and
4498    parameter packs is not invalid.  Here, PARMS are the template
4499    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
4500    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
4501    specialization.
4502    
4503
4504    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4505    declaration (but not a definition); 1 indicates a declaration, 2
4506    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4507    emitted for extraneous default arguments.
4508
4509    Returns TRUE if there were no errors found, FALSE otherwise. */
4510
4511 bool
4512 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
4513                          int is_partial, int is_friend_decl)
4514 {
4515   const char *msg;
4516   int last_level_to_check;
4517   tree parm_level;
4518   bool no_errors = true;
4519
4520   /* [temp.param]
4521
4522      A default template-argument shall not be specified in a
4523      function template declaration or a function template definition, nor
4524      in the template-parameter-list of the definition of a member of a
4525      class template.  */
4526
4527   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
4528     /* You can't have a function template declaration in a local
4529        scope, nor you can you define a member of a class template in a
4530        local scope.  */
4531     return true;
4532
4533   if (current_class_type
4534       && !TYPE_BEING_DEFINED (current_class_type)
4535       && DECL_LANG_SPECIFIC (decl)
4536       && DECL_DECLARES_FUNCTION_P (decl)
4537       /* If this is either a friend defined in the scope of the class
4538          or a member function.  */
4539       && (DECL_FUNCTION_MEMBER_P (decl)
4540           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4541           : DECL_FRIEND_CONTEXT (decl)
4542           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4543           : false)
4544       /* And, if it was a member function, it really was defined in
4545          the scope of the class.  */
4546       && (!DECL_FUNCTION_MEMBER_P (decl)
4547           || DECL_INITIALIZED_IN_CLASS_P (decl)))
4548     /* We already checked these parameters when the template was
4549        declared, so there's no need to do it again now.  This function
4550        was defined in class scope, but we're processing it's body now
4551        that the class is complete.  */
4552     return true;
4553
4554   /* Core issue 226 (C++0x only): the following only applies to class
4555      templates.  */
4556   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
4557     {
4558       /* [temp.param]
4559
4560          If a template-parameter has a default template-argument, all
4561          subsequent template-parameters shall have a default
4562          template-argument supplied.  */
4563       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4564         {
4565           tree inner_parms = TREE_VALUE (parm_level);
4566           int ntparms = TREE_VEC_LENGTH (inner_parms);
4567           int seen_def_arg_p = 0;
4568           int i;
4569
4570           for (i = 0; i < ntparms; ++i)
4571             {
4572               tree parm = TREE_VEC_ELT (inner_parms, i);
4573
4574               if (parm == error_mark_node)
4575                 continue;
4576
4577               if (TREE_PURPOSE (parm))
4578                 seen_def_arg_p = 1;
4579               else if (seen_def_arg_p
4580                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4581                 {
4582                   error ("no default argument for %qD", TREE_VALUE (parm));
4583                   /* For better subsequent error-recovery, we indicate that
4584                      there should have been a default argument.  */
4585                   TREE_PURPOSE (parm) = error_mark_node;
4586                   no_errors = false;
4587                 }
4588               else if (is_primary
4589                        && !is_partial
4590                        && !is_friend_decl
4591                        /* Don't complain about an enclosing partial
4592                           specialization.  */
4593                        && parm_level == parms
4594                        && TREE_CODE (decl) == TYPE_DECL
4595                        && i < ntparms - 1
4596                        && template_parameter_pack_p (TREE_VALUE (parm)))
4597                 {
4598                   /* A primary class template can only have one
4599                      parameter pack, at the end of the template
4600                      parameter list.  */
4601
4602                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4603                     error ("parameter pack %qE must be at the end of the"
4604                            " template parameter list", TREE_VALUE (parm));
4605                   else
4606                     error ("parameter pack %qT must be at the end of the"
4607                            " template parameter list", 
4608                            TREE_TYPE (TREE_VALUE (parm)));
4609
4610                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4611                     = error_mark_node;
4612                   no_errors = false;
4613                 }
4614             }
4615         }
4616     }
4617
4618   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4619       || is_partial 
4620       || !is_primary
4621       || is_friend_decl)
4622     /* For an ordinary class template, default template arguments are
4623        allowed at the innermost level, e.g.:
4624          template <class T = int>
4625          struct S {};
4626        but, in a partial specialization, they're not allowed even
4627        there, as we have in [temp.class.spec]:
4628
4629          The template parameter list of a specialization shall not
4630          contain default template argument values.
4631
4632        So, for a partial specialization, or for a function template
4633        (in C++98/C++03), we look at all of them.  */
4634     ;
4635   else
4636     /* But, for a primary class template that is not a partial
4637        specialization we look at all template parameters except the
4638        innermost ones.  */
4639     parms = TREE_CHAIN (parms);
4640
4641   /* Figure out what error message to issue.  */
4642   if (is_friend_decl == 2)
4643     msg = G_("default template arguments may not be used in function template "
4644              "friend re-declaration");
4645   else if (is_friend_decl)
4646     msg = G_("default template arguments may not be used in function template "
4647              "friend declarations");
4648   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4649     msg = G_("default template arguments may not be used in function templates "
4650              "without -std=c++0x or -std=gnu++0x");
4651   else if (is_partial)
4652     msg = G_("default template arguments may not be used in "
4653              "partial specializations");
4654   else
4655     msg = G_("default argument for template parameter for class enclosing %qD");
4656
4657   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4658     /* If we're inside a class definition, there's no need to
4659        examine the parameters to the class itself.  On the one
4660        hand, they will be checked when the class is defined, and,
4661        on the other, default arguments are valid in things like:
4662          template <class T = double>
4663          struct S { template <class U> void f(U); };
4664        Here the default argument for `S' has no bearing on the
4665        declaration of `f'.  */
4666     last_level_to_check = template_class_depth (current_class_type) + 1;
4667   else
4668     /* Check everything.  */
4669     last_level_to_check = 0;
4670
4671   for (parm_level = parms;
4672        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4673        parm_level = TREE_CHAIN (parm_level))
4674     {
4675       tree inner_parms = TREE_VALUE (parm_level);
4676       int i;
4677       int ntparms;
4678
4679       ntparms = TREE_VEC_LENGTH (inner_parms);
4680       for (i = 0; i < ntparms; ++i)
4681         {
4682           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4683             continue;
4684
4685           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4686             {
4687               if (msg)
4688                 {
4689                   no_errors = false;
4690                   if (is_friend_decl == 2)
4691                     return no_errors;
4692
4693                   error (msg, decl);
4694                   msg = 0;
4695                 }
4696
4697               /* Clear out the default argument so that we are not
4698                  confused later.  */
4699               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4700             }
4701         }
4702
4703       /* At this point, if we're still interested in issuing messages,
4704          they must apply to classes surrounding the object declared.  */
4705       if (msg)
4706         msg = G_("default argument for template parameter for class "
4707                  "enclosing %qD");
4708     }
4709
4710   return no_errors;
4711 }
4712
4713 /* Worker for push_template_decl_real, called via
4714    for_each_template_parm.  DATA is really an int, indicating the
4715    level of the parameters we are interested in.  If T is a template
4716    parameter of that level, return nonzero.  */
4717
4718 static int
4719 template_parm_this_level_p (tree t, void* data)
4720 {
4721   int this_level = *(int *)data;
4722   int level;
4723
4724   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4725     level = TEMPLATE_PARM_LEVEL (t);
4726   else
4727     level = TEMPLATE_TYPE_LEVEL (t);
4728   return level == this_level;
4729 }
4730
4731 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4732    parameters given by current_template_args, or reuses a
4733    previously existing one, if appropriate.  Returns the DECL, or an
4734    equivalent one, if it is replaced via a call to duplicate_decls.
4735
4736    If IS_FRIEND is true, DECL is a friend declaration.  */
4737
4738 tree
4739 push_template_decl_real (tree decl, bool is_friend)
4740 {
4741   tree tmpl;
4742   tree args;
4743   tree info;
4744   tree ctx;
4745   int primary;
4746   int is_partial;
4747   int new_template_p = 0;
4748   /* True if the template is a member template, in the sense of
4749      [temp.mem].  */
4750   bool member_template_p = false;
4751
4752   if (decl == error_mark_node || !current_template_parms)
4753     return error_mark_node;
4754
4755   /* See if this is a partial specialization.  */
4756   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4757                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4758                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4759
4760   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4761     is_friend = true;
4762
4763   if (is_friend)
4764     /* For a friend, we want the context of the friend function, not
4765        the type of which it is a friend.  */
4766     ctx = CP_DECL_CONTEXT (decl);
4767   else if (CP_DECL_CONTEXT (decl)
4768            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4769     /* In the case of a virtual function, we want the class in which
4770        it is defined.  */
4771     ctx = CP_DECL_CONTEXT (decl);
4772   else
4773     /* Otherwise, if we're currently defining some class, the DECL
4774        is assumed to be a member of the class.  */
4775     ctx = current_scope ();
4776
4777   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4778     ctx = NULL_TREE;
4779
4780   if (!DECL_CONTEXT (decl))
4781     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4782
4783   /* See if this is a primary template.  */
4784   if (is_friend && ctx)
4785     /* A friend template that specifies a class context, i.e.
4786          template <typename T> friend void A<T>::f();
4787        is not primary.  */
4788     primary = 0;
4789   else
4790     primary = template_parm_scope_p ();
4791
4792   if (primary)
4793     {
4794       if (DECL_CLASS_SCOPE_P (decl))
4795         member_template_p = true;
4796       if (TREE_CODE (decl) == TYPE_DECL
4797           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4798         {
4799           error ("template class without a name");
4800           return error_mark_node;
4801         }
4802       else if (TREE_CODE (decl) == FUNCTION_DECL)
4803         {
4804           if (DECL_DESTRUCTOR_P (decl))
4805             {
4806               /* [temp.mem]
4807
4808                  A destructor shall not be a member template.  */
4809               error ("destructor %qD declared as member template", decl);
4810               return error_mark_node;
4811             }
4812           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4813               && (!prototype_p (TREE_TYPE (decl))
4814                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4815                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4816                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4817                       == void_list_node)))
4818             {
4819               /* [basic.stc.dynamic.allocation]
4820
4821                  An allocation function can be a function
4822                  template. ... Template allocation functions shall
4823                  have two or more parameters.  */
4824               error ("invalid template declaration of %qD", decl);
4825               return error_mark_node;
4826             }
4827         }
4828       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4829                && CLASS_TYPE_P (TREE_TYPE (decl)))
4830         /* OK */;
4831       else
4832         {
4833           error ("template declaration of %q#D", decl);
4834           return error_mark_node;
4835         }
4836     }
4837
4838   /* Check to see that the rules regarding the use of default
4839      arguments are not being violated.  */
4840   check_default_tmpl_args (decl, current_template_parms,
4841                            primary, is_partial, /*is_friend_decl=*/0);
4842
4843   /* Ensure that there are no parameter packs in the type of this
4844      declaration that have not been expanded.  */
4845   if (TREE_CODE (decl) == FUNCTION_DECL)
4846     {
4847       /* Check each of the arguments individually to see if there are
4848          any bare parameter packs.  */
4849       tree type = TREE_TYPE (decl);
4850       tree arg = DECL_ARGUMENTS (decl);
4851       tree argtype = TYPE_ARG_TYPES (type);
4852
4853       while (arg && argtype)
4854         {
4855           if (!FUNCTION_PARAMETER_PACK_P (arg)
4856               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4857             {
4858             /* This is a PARM_DECL that contains unexpanded parameter
4859                packs. We have already complained about this in the
4860                check_for_bare_parameter_packs call, so just replace
4861                these types with ERROR_MARK_NODE.  */
4862               TREE_TYPE (arg) = error_mark_node;
4863               TREE_VALUE (argtype) = error_mark_node;
4864             }
4865
4866           arg = DECL_CHAIN (arg);
4867           argtype = TREE_CHAIN (argtype);
4868         }
4869
4870       /* Check for bare parameter packs in the return type and the
4871          exception specifiers.  */
4872       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4873         /* Errors were already issued, set return type to int
4874            as the frontend doesn't expect error_mark_node as
4875            the return type.  */
4876         TREE_TYPE (type) = integer_type_node;
4877       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4878         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4879     }
4880   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4881     {
4882       TREE_TYPE (decl) = error_mark_node;
4883       return error_mark_node;
4884     }
4885
4886   if (is_partial)
4887     return process_partial_specialization (decl);
4888
4889   args = current_template_args ();
4890
4891   if (!ctx
4892       || TREE_CODE (ctx) == FUNCTION_DECL
4893       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4894       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4895     {
4896       if (DECL_LANG_SPECIFIC (decl)
4897           && DECL_TEMPLATE_INFO (decl)
4898           && DECL_TI_TEMPLATE (decl))
4899         tmpl = DECL_TI_TEMPLATE (decl);
4900       /* If DECL is a TYPE_DECL for a class-template, then there won't
4901          be DECL_LANG_SPECIFIC.  The information equivalent to
4902          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4903       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4904                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4905                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4906         {
4907           /* Since a template declaration already existed for this
4908              class-type, we must be redeclaring it here.  Make sure
4909              that the redeclaration is valid.  */
4910           redeclare_class_template (TREE_TYPE (decl),
4911                                     current_template_parms);
4912           /* We don't need to create a new TEMPLATE_DECL; just use the
4913              one we already had.  */
4914           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4915         }
4916       else
4917         {
4918           tmpl = build_template_decl (decl, current_template_parms,
4919                                       member_template_p);
4920           new_template_p = 1;
4921
4922           if (DECL_LANG_SPECIFIC (decl)
4923               && DECL_TEMPLATE_SPECIALIZATION (decl))
4924             {
4925               /* A specialization of a member template of a template
4926                  class.  */
4927               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4928               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4929               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4930             }
4931         }
4932     }
4933   else
4934     {
4935       tree a, t, current, parms;
4936       int i;
4937       tree tinfo = get_template_info (decl);
4938
4939       if (!tinfo)
4940         {
4941           error ("template definition of non-template %q#D", decl);
4942           return error_mark_node;
4943         }
4944
4945       tmpl = TI_TEMPLATE (tinfo);
4946
4947       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4948           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4949           && DECL_TEMPLATE_SPECIALIZATION (decl)
4950           && DECL_MEMBER_TEMPLATE_P (tmpl))
4951         {
4952           tree new_tmpl;
4953
4954           /* The declaration is a specialization of a member
4955              template, declared outside the class.  Therefore, the
4956              innermost template arguments will be NULL, so we
4957              replace them with the arguments determined by the
4958              earlier call to check_explicit_specialization.  */
4959           args = DECL_TI_ARGS (decl);
4960
4961           new_tmpl
4962             = build_template_decl (decl, current_template_parms,
4963                                    member_template_p);
4964           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4965           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4966           DECL_TI_TEMPLATE (decl) = new_tmpl;
4967           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4968           DECL_TEMPLATE_INFO (new_tmpl)
4969             = build_template_info (tmpl, args);
4970
4971           register_specialization (new_tmpl,
4972                                    most_general_template (tmpl),
4973                                    args,
4974                                    is_friend, 0);
4975           return decl;
4976         }
4977
4978       /* Make sure the template headers we got make sense.  */
4979
4980       parms = DECL_TEMPLATE_PARMS (tmpl);
4981       i = TMPL_PARMS_DEPTH (parms);
4982       if (TMPL_ARGS_DEPTH (args) != i)
4983         {
4984           error ("expected %d levels of template parms for %q#D, got %d",
4985                  i, decl, TMPL_ARGS_DEPTH (args));
4986         }
4987       else
4988         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4989           {
4990             a = TMPL_ARGS_LEVEL (args, i);
4991             t = INNERMOST_TEMPLATE_PARMS (parms);
4992
4993             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4994               {
4995                 if (current == decl)
4996                   error ("got %d template parameters for %q#D",
4997                          TREE_VEC_LENGTH (a), decl);
4998                 else
4999                   error ("got %d template parameters for %q#T",
5000                          TREE_VEC_LENGTH (a), current);
5001                 error ("  but %d required", TREE_VEC_LENGTH (t));
5002                 return error_mark_node;
5003               }
5004
5005             if (current == decl)
5006               current = ctx;
5007             else if (current == NULL_TREE)
5008               /* Can happen in erroneous input.  */
5009               break;
5010             else
5011               current = (TYPE_P (current)
5012                          ? TYPE_CONTEXT (current)
5013                          : DECL_CONTEXT (current));
5014           }
5015
5016       /* Check that the parms are used in the appropriate qualifying scopes
5017          in the declarator.  */
5018       if (!comp_template_args
5019           (TI_ARGS (tinfo),
5020            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
5021         {
5022           error ("\
5023 template arguments to %qD do not match original template %qD",
5024                  decl, DECL_TEMPLATE_RESULT (tmpl));
5025           if (!uses_template_parms (TI_ARGS (tinfo)))
5026             inform (input_location, "use template<> for an explicit specialization");
5027           /* Avoid crash in import_export_decl.  */
5028           DECL_INTERFACE_KNOWN (decl) = 1;
5029           return error_mark_node;
5030         }
5031     }
5032
5033   DECL_TEMPLATE_RESULT (tmpl) = decl;
5034   TREE_TYPE (tmpl) = TREE_TYPE (decl);
5035
5036   /* Push template declarations for global functions and types.  Note
5037      that we do not try to push a global template friend declared in a
5038      template class; such a thing may well depend on the template
5039      parameters of the class.  */
5040   if (new_template_p && !ctx
5041       && !(is_friend && template_class_depth (current_class_type) > 0))
5042     {
5043       tmpl = pushdecl_namespace_level (tmpl, is_friend);
5044       if (tmpl == error_mark_node)
5045         return error_mark_node;
5046
5047       /* Hide template friend classes that haven't been declared yet.  */
5048       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
5049         {
5050           DECL_ANTICIPATED (tmpl) = 1;
5051           DECL_FRIEND_P (tmpl) = 1;
5052         }
5053     }
5054
5055   if (primary)
5056     {
5057       tree parms = DECL_TEMPLATE_PARMS (tmpl);
5058       int i;
5059
5060       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
5061       if (DECL_CONV_FN_P (tmpl))
5062         {
5063           int depth = TMPL_PARMS_DEPTH (parms);
5064
5065           /* It is a conversion operator. See if the type converted to
5066              depends on innermost template operands.  */
5067
5068           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
5069                                          depth))
5070             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
5071         }
5072
5073       /* Give template template parms a DECL_CONTEXT of the template
5074          for which they are a parameter.  */
5075       parms = INNERMOST_TEMPLATE_PARMS (parms);
5076       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
5077         {
5078           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5079           if (TREE_CODE (parm) == TEMPLATE_DECL)
5080             DECL_CONTEXT (parm) = tmpl;
5081         }
5082     }
5083
5084   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
5085      back to its most general template.  If TMPL is a specialization,
5086      ARGS may only have the innermost set of arguments.  Add the missing
5087      argument levels if necessary.  */
5088   if (DECL_TEMPLATE_INFO (tmpl))
5089     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
5090
5091   info = build_template_info (tmpl, args);
5092
5093   if (DECL_IMPLICIT_TYPEDEF_P (decl))
5094     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
5095   else if (DECL_LANG_SPECIFIC (decl))
5096     DECL_TEMPLATE_INFO (decl) = info;
5097
5098   return DECL_TEMPLATE_RESULT (tmpl);
5099 }
5100
5101 tree
5102 push_template_decl (tree decl)
5103 {
5104   return push_template_decl_real (decl, false);
5105 }
5106
5107 /* Called when a class template TYPE is redeclared with the indicated
5108    template PARMS, e.g.:
5109
5110      template <class T> struct S;
5111      template <class T> struct S {};  */
5112
5113 bool
5114 redeclare_class_template (tree type, tree parms)
5115 {
5116   tree tmpl;
5117   tree tmpl_parms;
5118   int i;
5119
5120   if (!TYPE_TEMPLATE_INFO (type))
5121     {
5122       error ("%qT is not a template type", type);
5123       return false;
5124     }
5125
5126   tmpl = TYPE_TI_TEMPLATE (type);
5127   if (!PRIMARY_TEMPLATE_P (tmpl))
5128     /* The type is nested in some template class.  Nothing to worry
5129        about here; there are no new template parameters for the nested
5130        type.  */
5131     return true;
5132
5133   if (!parms)
5134     {
5135       error ("template specifiers not specified in declaration of %qD",
5136              tmpl);
5137       return false;
5138     }
5139
5140   parms = INNERMOST_TEMPLATE_PARMS (parms);
5141   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
5142
5143   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
5144     {
5145       error_n (input_location, TREE_VEC_LENGTH (parms),
5146                "redeclared with %d template parameter",
5147                "redeclared with %d template parameters",
5148                TREE_VEC_LENGTH (parms));
5149       inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
5150                 "previous declaration %q+D used %d template parameter",
5151                 "previous declaration %q+D used %d template parameters",
5152                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
5153       return false;
5154     }
5155
5156   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
5157     {
5158       tree tmpl_parm;
5159       tree parm;
5160       tree tmpl_default;
5161       tree parm_default;
5162
5163       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
5164           || TREE_VEC_ELT (parms, i) == error_mark_node)
5165         continue;
5166
5167       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
5168       if (tmpl_parm == error_mark_node)
5169         return false;
5170
5171       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5172       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
5173       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
5174
5175       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
5176          TEMPLATE_DECL.  */
5177       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
5178           || (TREE_CODE (tmpl_parm) != TYPE_DECL
5179               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
5180           || (TREE_CODE (tmpl_parm) != PARM_DECL
5181               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
5182                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
5183           || (TREE_CODE (tmpl_parm) == PARM_DECL
5184               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
5185                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
5186         {
5187           error ("template parameter %q+#D", tmpl_parm);
5188           error ("redeclared here as %q#D", parm);
5189           return false;
5190         }
5191
5192       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
5193         {
5194           /* We have in [temp.param]:
5195
5196              A template-parameter may not be given default arguments
5197              by two different declarations in the same scope.  */
5198           error_at (input_location, "redefinition of default argument for %q#D", parm);
5199           inform (DECL_SOURCE_LOCATION (tmpl_parm),
5200                   "original definition appeared here");
5201           return false;
5202         }
5203
5204       if (parm_default != NULL_TREE)
5205         /* Update the previous template parameters (which are the ones
5206            that will really count) with the new default value.  */
5207         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
5208       else if (tmpl_default != NULL_TREE)
5209         /* Update the new parameters, too; they'll be used as the
5210            parameters for any members.  */
5211         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
5212     }
5213
5214     return true;
5215 }
5216
5217 /* Simplify EXPR if it is a non-dependent expression.  Returns the
5218    (possibly simplified) expression.  */
5219
5220 static tree
5221 fold_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
5222 {
5223   if (expr == NULL_TREE)
5224     return NULL_TREE;
5225
5226   /* If we're in a template, but EXPR isn't value dependent, simplify
5227      it.  We're supposed to treat:
5228
5229        template <typename T> void f(T[1 + 1]);
5230        template <typename T> void f(T[2]);
5231
5232      as two declarations of the same function, for example.  */
5233   if (processing_template_decl
5234       && !type_dependent_expression_p (expr)
5235       && potential_constant_expression (expr)
5236       && !value_dependent_expression_p (expr))
5237     {
5238       HOST_WIDE_INT saved_processing_template_decl;
5239
5240       saved_processing_template_decl = processing_template_decl;
5241       processing_template_decl = 0;
5242       expr = tsubst_copy_and_build (expr,
5243                                     /*args=*/NULL_TREE,
5244                                     complain,
5245                                     /*in_decl=*/NULL_TREE,
5246                                     /*function_p=*/false,
5247                                     /*integral_constant_expression_p=*/true);
5248       processing_template_decl = saved_processing_template_decl;
5249     }
5250   return expr;
5251 }
5252
5253 tree
5254 fold_non_dependent_expr (tree expr)
5255 {
5256   return fold_non_dependent_expr_sfinae (expr, tf_error);
5257 }
5258
5259 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
5260    must be a function or a pointer-to-function type, as specified
5261    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
5262    and check that the resulting function has external linkage.  */
5263
5264 static tree
5265 convert_nontype_argument_function (tree type, tree expr)
5266 {
5267   tree fns = expr;
5268   tree fn, fn_no_ptr;
5269
5270   fn = instantiate_type (type, fns, tf_none);
5271   if (fn == error_mark_node)
5272     return error_mark_node;
5273
5274   fn_no_ptr = fn;
5275   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
5276     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
5277   if (TREE_CODE (fn_no_ptr) == BASELINK)
5278     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
5279  
5280   /* [temp.arg.nontype]/1
5281
5282      A template-argument for a non-type, non-template template-parameter
5283      shall be one of:
5284      [...]
5285      -- the address of an object or function with external linkage.  */
5286   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
5287     {
5288       error ("%qE is not a valid template argument for type %qT "
5289              "because function %qD has not external linkage",
5290              expr, type, fn_no_ptr);
5291       return NULL_TREE;
5292     }
5293
5294   return fn;
5295 }
5296
5297 /* Subroutine of convert_nontype_argument.
5298    Check if EXPR of type TYPE is a valid pointer-to-member constant.
5299    Emit an error otherwise.  */
5300
5301 static bool
5302 check_valid_ptrmem_cst_expr (tree type, tree expr,
5303                              tsubst_flags_t complain)
5304 {
5305   STRIP_NOPS (expr);
5306   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
5307     return true;
5308   if (cxx_dialect >= cxx0x && null_member_pointer_value_p (expr))
5309     return true;
5310   if (complain & tf_error)
5311     {
5312       error ("%qE is not a valid template argument for type %qT",
5313              expr, type);
5314       error ("it must be a pointer-to-member of the form %<&X::Y%>");
5315     }
5316   return false;
5317 }
5318
5319 /* Returns TRUE iff the address of OP is value-dependent.
5320
5321    14.6.2.4 [temp.dep.temp]:
5322    A non-integral non-type template-argument is dependent if its type is
5323    dependent or it has either of the following forms
5324      qualified-id
5325      & qualified-id
5326    and contains a nested-name-specifier which specifies a class-name that
5327    names a dependent type.
5328
5329    We generalize this to just say that the address of a member of a
5330    dependent class is value-dependent; the above doesn't cover the
5331    address of a static data member named with an unqualified-id.  */
5332
5333 static bool
5334 has_value_dependent_address (tree op)
5335 {
5336   /* We could use get_inner_reference here, but there's no need;
5337      this is only relevant for template non-type arguments, which
5338      can only be expressed as &id-expression.  */
5339   if (DECL_P (op))
5340     {
5341       tree ctx = CP_DECL_CONTEXT (op);
5342       if (TYPE_P (ctx) && dependent_type_p (ctx))
5343         return true;
5344     }
5345
5346   return false;
5347 }
5348
5349 /* The next set of functions are used for providing helpful explanatory
5350    diagnostics for failed overload resolution.  Their messages should be
5351    indented by two spaces for consistency with the messages in
5352    call.c  */
5353
5354 static int
5355 unify_success (bool explain_p ATTRIBUTE_UNUSED)
5356 {
5357   return 0;
5358 }
5359
5360 static int
5361 unify_parameter_deduction_failure (bool explain_p, tree parm)
5362 {
5363   if (explain_p)
5364     inform (input_location,
5365             "  couldn't deduce template parameter %qD", parm);
5366   return 1;
5367 }
5368
5369 static int
5370 unify_invalid (bool explain_p ATTRIBUTE_UNUSED)
5371 {
5372   return 1;
5373 }
5374
5375 static int
5376 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
5377 {
5378   if (explain_p)
5379     inform (input_location,
5380             "  types %qT and %qT have incompatible cv-qualifiers",
5381             parm, arg);
5382   return 1;
5383 }
5384
5385 static int
5386 unify_type_mismatch (bool explain_p, tree parm, tree arg)
5387 {
5388   if (explain_p)
5389     inform (input_location, "  mismatched types %qT and %qT", parm, arg);
5390   return 1;
5391 }
5392
5393 static int
5394 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
5395 {
5396   if (explain_p)
5397     inform (input_location,
5398             "  template parameter %qD is not a parameter pack, but "
5399             "argument %qD is",
5400             parm, arg);
5401   return 1;
5402 }
5403
5404 static int
5405 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
5406 {
5407   if (explain_p)
5408     inform (input_location,
5409             "  template argument %qE does not match "
5410             "pointer-to-member constant %qE",
5411             arg, parm);
5412   return 1;
5413 }
5414
5415 static int
5416 unify_expression_unequal (bool explain_p, tree parm, tree arg)
5417 {
5418   if (explain_p)
5419     inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
5420   return 1;
5421 }
5422
5423 static int
5424 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
5425 {
5426   if (explain_p)
5427     inform (input_location,
5428             "  inconsistent parameter pack deduction with %qT and %qT",
5429             old_arg, new_arg);
5430   return 1;
5431 }
5432
5433 static int
5434 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
5435 {
5436   if (explain_p)
5437     inform (input_location,
5438             "  deduced conflicting types for parameter %qT (%qT and %qT)",
5439             parm, first, second);
5440   return 1;
5441 }
5442
5443 static int
5444 unify_vla_arg (bool explain_p, tree arg)
5445 {
5446   if (explain_p)
5447     inform (input_location,
5448             "  variable-sized array type %qT is not "
5449             "a valid template argument",
5450             arg);
5451   return 1;
5452 }
5453
5454 static int
5455 unify_method_type_error (bool explain_p, tree arg)
5456 {
5457   if (explain_p)
5458     inform (input_location,
5459             "  member function type %qT is not a valid template argument",
5460             arg);
5461   return 1;
5462 }
5463
5464 static int
5465 unify_arity (bool explain_p, int have, int wanted)
5466 {
5467   if (explain_p)
5468     inform_n (input_location, wanted,
5469               "  candidate expects %d argument, %d provided",
5470               "  candidate expects %d arguments, %d provided",
5471               wanted, have);
5472   return 1;
5473 }
5474
5475 static int
5476 unify_too_many_arguments (bool explain_p, int have, int wanted)
5477 {
5478   return unify_arity (explain_p, have, wanted);
5479 }
5480
5481 static int
5482 unify_too_few_arguments (bool explain_p, int have, int wanted)
5483 {
5484   return unify_arity (explain_p, have, wanted);
5485 }
5486
5487 static int
5488 unify_arg_conversion (bool explain_p, tree to_type,
5489                       tree from_type, tree arg)
5490 {
5491   if (explain_p)
5492     inform (input_location, "  cannot convert %qE (type %qT) to type %qT",
5493             arg, from_type, to_type);
5494   return 1;
5495 }
5496
5497 static int
5498 unify_no_common_base (bool explain_p, enum template_base_result r,
5499                       tree parm, tree arg)
5500 {
5501   if (explain_p)
5502     switch (r)
5503       {
5504       case tbr_ambiguous_baseclass:
5505         inform (input_location, "  %qT is an ambiguous base class of %qT",
5506                 arg, parm);
5507         break;
5508       default:
5509         inform (input_location, "  %qT is not derived from %qT", arg, parm);
5510         break;
5511       }
5512   return 1;
5513 }
5514
5515 static int
5516 unify_inconsistent_template_template_parameters (bool explain_p)
5517 {
5518   if (explain_p)
5519     inform (input_location,
5520             "  template parameters of a template template argument are "
5521             "inconsistent with other deduced template arguments");
5522   return 1;
5523 }
5524
5525 static int
5526 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
5527 {
5528   if (explain_p)
5529     inform (input_location,
5530             "  can't deduce a template for %qT from non-template type %qT",
5531             parm, arg);
5532   return 1;
5533 }
5534
5535 static int
5536 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
5537 {
5538   if (explain_p)
5539     inform (input_location,
5540             "  template argument %qE does not match %qD", arg, parm);
5541   return 1;
5542 }
5543
5544 static int
5545 unify_overload_resolution_failure (bool explain_p, tree arg)
5546 {
5547   if (explain_p)
5548     inform (input_location,
5549             "  could not resolve address from overloaded function %qE",
5550             arg);
5551   return 1;
5552 }
5553
5554 /* Attempt to convert the non-type template parameter EXPR to the
5555    indicated TYPE.  If the conversion is successful, return the
5556    converted value.  If the conversion is unsuccessful, return
5557    NULL_TREE if we issued an error message, or error_mark_node if we
5558    did not.  We issue error messages for out-and-out bad template
5559    parameters, but not simply because the conversion failed, since we
5560    might be just trying to do argument deduction.  Both TYPE and EXPR
5561    must be non-dependent.
5562
5563    The conversion follows the special rules described in
5564    [temp.arg.nontype], and it is much more strict than an implicit
5565    conversion.
5566
5567    This function is called twice for each template argument (see
5568    lookup_template_class for a more accurate description of this
5569    problem). This means that we need to handle expressions which
5570    are not valid in a C++ source, but can be created from the
5571    first call (for instance, casts to perform conversions). These
5572    hacks can go away after we fix the double coercion problem.  */
5573
5574 static tree
5575 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
5576 {
5577   tree expr_type;
5578
5579   /* Detect immediately string literals as invalid non-type argument.
5580      This special-case is not needed for correctness (we would easily
5581      catch this later), but only to provide better diagnostic for this
5582      common user mistake. As suggested by DR 100, we do not mention
5583      linkage issues in the diagnostic as this is not the point.  */
5584   /* FIXME we're making this OK.  */
5585   if (TREE_CODE (expr) == STRING_CST)
5586     {
5587       if (complain & tf_error)
5588         error ("%qE is not a valid template argument for type %qT "
5589                "because string literals can never be used in this context",
5590                expr, type);
5591       return NULL_TREE;
5592     }
5593
5594   /* Add the ADDR_EXPR now for the benefit of
5595      value_dependent_expression_p.  */
5596   if (TYPE_PTROBV_P (type)
5597       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
5598     expr = decay_conversion (expr);
5599
5600   /* If we are in a template, EXPR may be non-dependent, but still
5601      have a syntactic, rather than semantic, form.  For example, EXPR
5602      might be a SCOPE_REF, rather than the VAR_DECL to which the
5603      SCOPE_REF refers.  Preserving the qualifying scope is necessary
5604      so that access checking can be performed when the template is
5605      instantiated -- but here we need the resolved form so that we can
5606      convert the argument.  */
5607   if (TYPE_REF_OBJ_P (type)
5608       && has_value_dependent_address (expr))
5609     /* If we want the address and it's value-dependent, don't fold.  */;
5610   else if (!type_unknown_p (expr))
5611     expr = fold_non_dependent_expr_sfinae (expr, complain);
5612   if (error_operand_p (expr))
5613     return error_mark_node;
5614   expr_type = TREE_TYPE (expr);
5615   if (TREE_CODE (type) == REFERENCE_TYPE)
5616     expr = mark_lvalue_use (expr);
5617   else
5618     expr = mark_rvalue_use (expr);
5619
5620   /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
5621      to a non-type argument of "nullptr".  */
5622   if (expr == nullptr_node
5623       && (TYPE_PTR_P (type) || TYPE_PTR_TO_MEMBER_P (type)))
5624     expr = convert (type, expr);
5625
5626   /* In C++11, non-type template arguments can be arbitrary constant
5627      expressions.  But don't fold a PTRMEM_CST to a CONSTRUCTOR yet.  */
5628   if (cxx_dialect >= cxx0x && TREE_CODE (expr) != PTRMEM_CST)
5629     expr = maybe_constant_value (expr);
5630
5631   /* HACK: Due to double coercion, we can get a
5632      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
5633      which is the tree that we built on the first call (see
5634      below when coercing to reference to object or to reference to
5635      function). We just strip everything and get to the arg.
5636      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
5637      for examples.  */
5638   if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
5639     {
5640       tree probe_type, probe = expr;
5641       if (REFERENCE_REF_P (probe))
5642         probe = TREE_OPERAND (probe, 0);
5643       probe_type = TREE_TYPE (probe);
5644       if (TREE_CODE (probe) == NOP_EXPR)
5645         {
5646           /* ??? Maybe we could use convert_from_reference here, but we
5647              would need to relax its constraints because the NOP_EXPR
5648              could actually change the type to something more cv-qualified,
5649              and this is not folded by convert_from_reference.  */
5650           tree addr = TREE_OPERAND (probe, 0);
5651           gcc_assert (TREE_CODE (probe_type) == REFERENCE_TYPE);
5652           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
5653           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
5654           gcc_assert (same_type_ignoring_top_level_qualifiers_p
5655                       (TREE_TYPE (probe_type),
5656                        TREE_TYPE (TREE_TYPE (addr))));
5657
5658           expr = TREE_OPERAND (addr, 0);
5659           expr_type = TREE_TYPE (expr);
5660         }
5661     }
5662
5663   /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
5664      parameter is a pointer to object, through decay and
5665      qualification conversion. Let's strip everything.  */
5666   else if (TREE_CODE (expr) == NOP_EXPR && TYPE_PTROBV_P (type))
5667     {
5668       STRIP_NOPS (expr);
5669       gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
5670       gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
5671       /* Skip the ADDR_EXPR only if it is part of the decay for
5672          an array. Otherwise, it is part of the original argument
5673          in the source code.  */
5674       if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
5675         expr = TREE_OPERAND (expr, 0);
5676       expr_type = TREE_TYPE (expr);
5677     }
5678
5679   /* [temp.arg.nontype]/5, bullet 1
5680
5681      For a non-type template-parameter of integral or enumeration type,
5682      integral promotions (_conv.prom_) and integral conversions
5683      (_conv.integral_) are applied.  */
5684   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5685     {
5686       tree t = build_integral_nontype_arg_conv (type, expr, complain);
5687       t = maybe_constant_value (t);
5688       if (t != error_mark_node)
5689         expr = t;
5690
5691       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
5692         return error_mark_node;
5693
5694       /* Notice that there are constant expressions like '4 % 0' which
5695          do not fold into integer constants.  */
5696       if (TREE_CODE (expr) != INTEGER_CST)
5697         {
5698           if (complain & tf_error)
5699             {
5700               int errs = errorcount, warns = warningcount;
5701               expr = cxx_constant_value (expr);
5702               if (errorcount > errs || warningcount > warns)
5703                 inform (EXPR_LOC_OR_HERE (expr),
5704                         "in template argument for type %qT ", type);
5705               if (expr == error_mark_node)
5706                 return NULL_TREE;
5707               /* else cxx_constant_value complained but gave us
5708                  a real constant, so go ahead.  */
5709               gcc_assert (TREE_CODE (expr) == INTEGER_CST);
5710             }
5711           else
5712             return NULL_TREE;
5713         }
5714     }
5715   /* [temp.arg.nontype]/5, bullet 2
5716
5717      For a non-type template-parameter of type pointer to object,
5718      qualification conversions (_conv.qual_) and the array-to-pointer
5719      conversion (_conv.array_) are applied.  */
5720   else if (TYPE_PTROBV_P (type))
5721     {
5722       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
5723
5724          A template-argument for a non-type, non-template template-parameter
5725          shall be one of: [...]
5726
5727          -- the name of a non-type template-parameter;
5728          -- the address of an object or function with external linkage, [...]
5729             expressed as "& id-expression" where the & is optional if the name
5730             refers to a function or array, or if the corresponding
5731             template-parameter is a reference.
5732
5733         Here, we do not care about functions, as they are invalid anyway
5734         for a parameter of type pointer-to-object.  */
5735
5736       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
5737         /* Non-type template parameters are OK.  */
5738         ;
5739       else if (cxx_dialect >= cxx0x && integer_zerop (expr))
5740         /* Null pointer values are OK in C++11.  */;
5741       else if (TREE_CODE (expr) != ADDR_EXPR
5742                && TREE_CODE (expr_type) != ARRAY_TYPE)
5743         {
5744           if (TREE_CODE (expr) == VAR_DECL)
5745             {
5746               error ("%qD is not a valid template argument "
5747                      "because %qD is a variable, not the address of "
5748                      "a variable",
5749                      expr, expr);
5750               return NULL_TREE;
5751             }
5752           /* Other values, like integer constants, might be valid
5753              non-type arguments of some other type.  */
5754           return error_mark_node;
5755         }
5756       else
5757         {
5758           tree decl;
5759
5760           decl = ((TREE_CODE (expr) == ADDR_EXPR)
5761                   ? TREE_OPERAND (expr, 0) : expr);
5762           if (TREE_CODE (decl) != VAR_DECL)
5763             {
5764               error ("%qE is not a valid template argument of type %qT "
5765                      "because %qE is not a variable",
5766                      expr, type, decl);
5767               return NULL_TREE;
5768             }
5769           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
5770             {
5771               error ("%qE is not a valid template argument of type %qT "
5772                      "because %qD does not have external linkage",
5773                      expr, type, decl);
5774               return NULL_TREE;
5775             }
5776         }
5777
5778       expr = decay_conversion (expr);
5779       if (expr == error_mark_node)
5780         return error_mark_node;
5781
5782       expr = perform_qualification_conversions (type, expr);
5783       if (expr == error_mark_node)
5784         return error_mark_node;
5785     }
5786   /* [temp.arg.nontype]/5, bullet 3
5787
5788      For a non-type template-parameter of type reference to object, no
5789      conversions apply. The type referred to by the reference may be more
5790      cv-qualified than the (otherwise identical) type of the
5791      template-argument. The template-parameter is bound directly to the
5792      template-argument, which must be an lvalue.  */
5793   else if (TYPE_REF_OBJ_P (type))
5794     {
5795       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5796                                                       expr_type))
5797         return error_mark_node;
5798
5799       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5800         {
5801           error ("%qE is not a valid template argument for type %qT "
5802                  "because of conflicts in cv-qualification", expr, type);
5803           return NULL_TREE;
5804         }
5805
5806       if (!real_lvalue_p (expr))
5807         {
5808           error ("%qE is not a valid template argument for type %qT "
5809                  "because it is not an lvalue", expr, type);
5810           return NULL_TREE;
5811         }
5812
5813       /* [temp.arg.nontype]/1
5814
5815          A template-argument for a non-type, non-template template-parameter
5816          shall be one of: [...]
5817
5818          -- the address of an object or function with external linkage.  */
5819       if (TREE_CODE (expr) == INDIRECT_REF
5820           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5821         {
5822           expr = TREE_OPERAND (expr, 0);
5823           if (DECL_P (expr))
5824             {
5825               error ("%q#D is not a valid template argument for type %qT "
5826                      "because a reference variable does not have a constant "
5827                      "address", expr, type);
5828               return NULL_TREE;
5829             }
5830         }
5831
5832       if (!DECL_P (expr))
5833         {
5834           error ("%qE is not a valid template argument for type %qT "
5835                  "because it is not an object with external linkage",
5836                  expr, type);
5837           return NULL_TREE;
5838         }
5839
5840       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5841         {
5842           error ("%qE is not a valid template argument for type %qT "
5843                  "because object %qD has not external linkage",
5844                  expr, type, expr);
5845           return NULL_TREE;
5846         }
5847
5848       expr = build_nop (type, build_address (expr));
5849     }
5850   /* [temp.arg.nontype]/5, bullet 4
5851
5852      For a non-type template-parameter of type pointer to function, only
5853      the function-to-pointer conversion (_conv.func_) is applied. If the
5854      template-argument represents a set of overloaded functions (or a
5855      pointer to such), the matching function is selected from the set
5856      (_over.over_).  */
5857   else if (TYPE_PTRFN_P (type))
5858     {
5859       /* If the argument is a template-id, we might not have enough
5860          context information to decay the pointer.  */
5861       if (!type_unknown_p (expr_type))
5862         {
5863           expr = decay_conversion (expr);
5864           if (expr == error_mark_node)
5865             return error_mark_node;
5866         }
5867
5868       if (cxx_dialect >= cxx0x && integer_zerop (expr))
5869         /* Null pointer values are OK in C++11.  */
5870         return perform_qualification_conversions (type, expr);
5871
5872       expr = convert_nontype_argument_function (type, expr);
5873       if (!expr || expr == error_mark_node)
5874         return expr;
5875
5876       if (TREE_CODE (expr) != ADDR_EXPR)
5877         {
5878           error ("%qE is not a valid template argument for type %qT", expr, type);
5879           error ("it must be the address of a function with external linkage");
5880           return NULL_TREE;
5881         }
5882     }
5883   /* [temp.arg.nontype]/5, bullet 5
5884
5885      For a non-type template-parameter of type reference to function, no
5886      conversions apply. If the template-argument represents a set of
5887      overloaded functions, the matching function is selected from the set
5888      (_over.over_).  */
5889   else if (TYPE_REFFN_P (type))
5890     {
5891       if (TREE_CODE (expr) == ADDR_EXPR)
5892         {
5893           error ("%qE is not a valid template argument for type %qT "
5894                  "because it is a pointer", expr, type);
5895           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5896           return NULL_TREE;
5897         }
5898
5899       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5900       if (!expr || expr == error_mark_node)
5901         return expr;
5902
5903       expr = build_nop (type, build_address (expr));
5904     }
5905   /* [temp.arg.nontype]/5, bullet 6
5906
5907      For a non-type template-parameter of type pointer to member function,
5908      no conversions apply. If the template-argument represents a set of
5909      overloaded member functions, the matching member function is selected
5910      from the set (_over.over_).  */
5911   else if (TYPE_PTRMEMFUNC_P (type))
5912     {
5913       expr = instantiate_type (type, expr, tf_none);
5914       if (expr == error_mark_node)
5915         return error_mark_node;
5916
5917       /* [temp.arg.nontype] bullet 1 says the pointer to member
5918          expression must be a pointer-to-member constant.  */
5919       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5920         return error_mark_node;
5921
5922       /* There is no way to disable standard conversions in
5923          resolve_address_of_overloaded_function (called by
5924          instantiate_type). It is possible that the call succeeded by
5925          converting &B::I to &D::I (where B is a base of D), so we need
5926          to reject this conversion here.
5927
5928          Actually, even if there was a way to disable standard conversions,
5929          it would still be better to reject them here so that we can
5930          provide a superior diagnostic.  */
5931       if (!same_type_p (TREE_TYPE (expr), type))
5932         {
5933           error ("%qE is not a valid template argument for type %qT "
5934                  "because it is of type %qT", expr, type,
5935                  TREE_TYPE (expr));
5936           /* If we are just one standard conversion off, explain.  */
5937           if (can_convert (type, TREE_TYPE (expr)))
5938             inform (input_location,
5939                     "standard conversions are not allowed in this context");
5940           return NULL_TREE;
5941         }
5942     }
5943   /* [temp.arg.nontype]/5, bullet 7
5944
5945      For a non-type template-parameter of type pointer to data member,
5946      qualification conversions (_conv.qual_) are applied.  */
5947   else if (TYPE_PTRMEM_P (type))
5948     {
5949       /* [temp.arg.nontype] bullet 1 says the pointer to member
5950          expression must be a pointer-to-member constant.  */
5951       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5952         return error_mark_node;
5953
5954       expr = perform_qualification_conversions (type, expr);
5955       if (expr == error_mark_node)
5956         return expr;
5957     }
5958   else if (NULLPTR_TYPE_P (type))
5959     {
5960       if (expr != nullptr_node)
5961         {
5962           error ("%qE is not a valid template argument for type %qT "
5963                  "because it is of type %qT", expr, type, TREE_TYPE (expr));
5964           return NULL_TREE;
5965         }
5966       return expr;
5967     }
5968   /* A template non-type parameter must be one of the above.  */
5969   else
5970     gcc_unreachable ();
5971
5972   /* Sanity check: did we actually convert the argument to the
5973      right type?  */
5974   gcc_assert (same_type_ignoring_top_level_qualifiers_p
5975               (type, TREE_TYPE (expr)));
5976   return expr;
5977 }
5978
5979 /* Subroutine of coerce_template_template_parms, which returns 1 if
5980    PARM_PARM and ARG_PARM match using the rule for the template
5981    parameters of template template parameters. Both PARM and ARG are
5982    template parameters; the rest of the arguments are the same as for
5983    coerce_template_template_parms.
5984  */
5985 static int
5986 coerce_template_template_parm (tree parm,
5987                               tree arg,
5988                               tsubst_flags_t complain,
5989                               tree in_decl,
5990                               tree outer_args)
5991 {
5992   if (arg == NULL_TREE || arg == error_mark_node
5993       || parm == NULL_TREE || parm == error_mark_node)
5994     return 0;
5995   
5996   if (TREE_CODE (arg) != TREE_CODE (parm))
5997     return 0;
5998   
5999   switch (TREE_CODE (parm))
6000     {
6001     case TEMPLATE_DECL:
6002       /* We encounter instantiations of templates like
6003          template <template <template <class> class> class TT>
6004          class C;  */
6005       {
6006         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
6007         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
6008         
6009         if (!coerce_template_template_parms
6010             (parmparm, argparm, complain, in_decl, outer_args))
6011           return 0;
6012       }
6013       /* Fall through.  */
6014       
6015     case TYPE_DECL:
6016       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
6017           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
6018         /* Argument is a parameter pack but parameter is not.  */
6019         return 0;
6020       break;
6021       
6022     case PARM_DECL:
6023       /* The tsubst call is used to handle cases such as
6024          
6025            template <int> class C {};
6026            template <class T, template <T> class TT> class D {};
6027            D<int, C> d;
6028
6029          i.e. the parameter list of TT depends on earlier parameters.  */
6030       if (!uses_template_parms (TREE_TYPE (arg))
6031           && !same_type_p
6032                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
6033                  TREE_TYPE (arg)))
6034         return 0;
6035       
6036       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
6037           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
6038         /* Argument is a parameter pack but parameter is not.  */
6039         return 0;
6040       
6041       break;
6042
6043     default:
6044       gcc_unreachable ();
6045     }
6046
6047   return 1;
6048 }
6049
6050
6051 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
6052    template template parameters.  Both PARM_PARMS and ARG_PARMS are
6053    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
6054    or PARM_DECL.
6055
6056    Consider the example:
6057      template <class T> class A;
6058      template<template <class U> class TT> class B;
6059
6060    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
6061    the parameters to A, and OUTER_ARGS contains A.  */
6062
6063 static int
6064 coerce_template_template_parms (tree parm_parms,
6065                                 tree arg_parms,
6066                                 tsubst_flags_t complain,
6067                                 tree in_decl,
6068                                 tree outer_args)
6069 {
6070   int nparms, nargs, i;
6071   tree parm, arg;
6072   int variadic_p = 0;
6073
6074   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
6075   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
6076
6077   nparms = TREE_VEC_LENGTH (parm_parms);
6078   nargs = TREE_VEC_LENGTH (arg_parms);
6079
6080   /* Determine whether we have a parameter pack at the end of the
6081      template template parameter's template parameter list.  */
6082   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
6083     {
6084       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
6085       
6086       if (parm == error_mark_node)
6087         return 0;
6088
6089       switch (TREE_CODE (parm))
6090         {
6091         case TEMPLATE_DECL:
6092         case TYPE_DECL:
6093           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
6094             variadic_p = 1;
6095           break;
6096           
6097         case PARM_DECL:
6098           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
6099             variadic_p = 1;
6100           break;
6101           
6102         default:
6103           gcc_unreachable ();
6104         }
6105     }
6106  
6107   if (nargs != nparms
6108       && !(variadic_p && nargs >= nparms - 1))
6109     return 0;
6110
6111   /* Check all of the template parameters except the parameter pack at
6112      the end (if any).  */
6113   for (i = 0; i < nparms - variadic_p; ++i)
6114     {
6115       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
6116           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
6117         continue;
6118
6119       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
6120       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
6121
6122       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
6123                                           outer_args))
6124         return 0;
6125
6126     }
6127
6128   if (variadic_p)
6129     {
6130       /* Check each of the template parameters in the template
6131          argument against the template parameter pack at the end of
6132          the template template parameter.  */
6133       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
6134         return 0;
6135
6136       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
6137
6138       for (; i < nargs; ++i)
6139         {
6140           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
6141             continue;
6142  
6143           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
6144  
6145           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
6146                                               outer_args))
6147             return 0;
6148         }
6149     }
6150
6151   return 1;
6152 }
6153
6154 /* Verifies that the deduced template arguments (in TARGS) for the
6155    template template parameters (in TPARMS) represent valid bindings,
6156    by comparing the template parameter list of each template argument
6157    to the template parameter list of its corresponding template
6158    template parameter, in accordance with DR150. This
6159    routine can only be called after all template arguments have been
6160    deduced. It will return TRUE if all of the template template
6161    parameter bindings are okay, FALSE otherwise.  */
6162 bool 
6163 template_template_parm_bindings_ok_p (tree tparms, tree targs)
6164 {
6165   int i, ntparms = TREE_VEC_LENGTH (tparms);
6166   bool ret = true;
6167
6168   /* We're dealing with template parms in this process.  */
6169   ++processing_template_decl;
6170
6171   targs = INNERMOST_TEMPLATE_ARGS (targs);
6172
6173   for (i = 0; i < ntparms; ++i)
6174     {
6175       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
6176       tree targ = TREE_VEC_ELT (targs, i);
6177
6178       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
6179         {
6180           tree packed_args = NULL_TREE;
6181           int idx, len = 1;
6182
6183           if (ARGUMENT_PACK_P (targ))
6184             {
6185               /* Look inside the argument pack.  */
6186               packed_args = ARGUMENT_PACK_ARGS (targ);
6187               len = TREE_VEC_LENGTH (packed_args);
6188             }
6189
6190           for (idx = 0; idx < len; ++idx)
6191             {
6192               tree targ_parms = NULL_TREE;
6193
6194               if (packed_args)
6195                 /* Extract the next argument from the argument
6196                    pack.  */
6197                 targ = TREE_VEC_ELT (packed_args, idx);
6198
6199               if (PACK_EXPANSION_P (targ))
6200                 /* Look at the pattern of the pack expansion.  */
6201                 targ = PACK_EXPANSION_PATTERN (targ);
6202
6203               /* Extract the template parameters from the template
6204                  argument.  */
6205               if (TREE_CODE (targ) == TEMPLATE_DECL)
6206                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
6207               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
6208                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
6209
6210               /* Verify that we can coerce the template template
6211                  parameters from the template argument to the template
6212                  parameter.  This requires an exact match.  */
6213               if (targ_parms
6214                   && !coerce_template_template_parms
6215                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
6216                         targ_parms,
6217                         tf_none,
6218                         tparm,
6219                         targs))
6220                 {
6221                   ret = false;
6222                   goto out;
6223                 }
6224             }
6225         }
6226     }
6227
6228  out:
6229
6230   --processing_template_decl;
6231   return ret;
6232 }
6233
6234 /* Since type attributes aren't mangled, we need to strip them from
6235    template type arguments.  */
6236
6237 static tree
6238 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
6239 {
6240   tree mv;
6241   if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
6242     return arg;
6243   mv = TYPE_MAIN_VARIANT (arg);
6244   arg = strip_typedefs (arg);
6245   if (TYPE_ALIGN (arg) != TYPE_ALIGN (mv)
6246       || TYPE_ATTRIBUTES (arg) != TYPE_ATTRIBUTES (mv))
6247     {
6248       if (complain & tf_warning)
6249         warning (0, "ignoring attributes on template argument %qT", arg);
6250       arg = build_aligned_type (arg, TYPE_ALIGN (mv));
6251       arg = cp_build_type_attribute_variant (arg, TYPE_ATTRIBUTES (mv));
6252     }
6253   return arg;
6254 }
6255
6256 /* Convert the indicated template ARG as necessary to match the
6257    indicated template PARM.  Returns the converted ARG, or
6258    error_mark_node if the conversion was unsuccessful.  Error and
6259    warning messages are issued under control of COMPLAIN.  This
6260    conversion is for the Ith parameter in the parameter list.  ARGS is
6261    the full set of template arguments deduced so far.  */
6262
6263 static tree
6264 convert_template_argument (tree parm,
6265                            tree arg,
6266                            tree args,
6267                            tsubst_flags_t complain,
6268                            int i,
6269                            tree in_decl)
6270 {
6271   tree orig_arg;
6272   tree val;
6273   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
6274
6275   if (TREE_CODE (arg) == TREE_LIST
6276       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
6277     {
6278       /* The template argument was the name of some
6279          member function.  That's usually
6280          invalid, but static members are OK.  In any
6281          case, grab the underlying fields/functions
6282          and issue an error later if required.  */
6283       orig_arg = TREE_VALUE (arg);
6284       TREE_TYPE (arg) = unknown_type_node;
6285     }
6286
6287   orig_arg = arg;
6288
6289   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
6290   requires_type = (TREE_CODE (parm) == TYPE_DECL
6291                    || requires_tmpl_type);
6292
6293   /* When determining whether an argument pack expansion is a template,
6294      look at the pattern.  */
6295   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
6296     arg = PACK_EXPANSION_PATTERN (arg);
6297
6298   /* Deal with an injected-class-name used as a template template arg.  */
6299   if (requires_tmpl_type && CLASS_TYPE_P (arg))
6300     {
6301       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
6302       if (TREE_CODE (t) == TEMPLATE_DECL)
6303         {
6304           if (cxx_dialect >= cxx0x)
6305             /* OK under DR 1004.  */;
6306           else if (complain & tf_warning_or_error)
6307             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
6308                      " used as template template argument", TYPE_NAME (arg));
6309           else if (flag_pedantic_errors)
6310             t = arg;
6311
6312           arg = t;
6313         }
6314     }
6315
6316   is_tmpl_type = 
6317     ((TREE_CODE (arg) == TEMPLATE_DECL
6318       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
6319      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
6320      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
6321
6322   if (is_tmpl_type
6323       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
6324           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
6325     arg = TYPE_STUB_DECL (arg);
6326
6327   is_type = TYPE_P (arg) || is_tmpl_type;
6328
6329   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
6330       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
6331     {
6332       permerror (input_location, "to refer to a type member of a template parameter, "
6333                  "use %<typename %E%>", orig_arg);
6334
6335       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
6336                                      TREE_OPERAND (arg, 1),
6337                                      typename_type,
6338                                      complain & tf_error);
6339       arg = orig_arg;
6340       is_type = 1;
6341     }
6342   if (is_type != requires_type)
6343     {
6344       if (in_decl)
6345         {
6346           if (complain & tf_error)
6347             {
6348               error ("type/value mismatch at argument %d in template "
6349                      "parameter list for %qD",
6350                      i + 1, in_decl);
6351               if (is_type)
6352                 error ("  expected a constant of type %qT, got %qT",
6353                        TREE_TYPE (parm),
6354                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
6355               else if (requires_tmpl_type)
6356                 error ("  expected a class template, got %qE", orig_arg);
6357               else
6358                 error ("  expected a type, got %qE", orig_arg);
6359             }
6360         }
6361       return error_mark_node;
6362     }
6363   if (is_tmpl_type ^ requires_tmpl_type)
6364     {
6365       if (in_decl && (complain & tf_error))
6366         {
6367           error ("type/value mismatch at argument %d in template "
6368                  "parameter list for %qD",
6369                  i + 1, in_decl);
6370           if (is_tmpl_type)
6371             error ("  expected a type, got %qT", DECL_NAME (arg));
6372           else
6373             error ("  expected a class template, got %qT", orig_arg);
6374         }
6375       return error_mark_node;
6376     }
6377
6378   if (is_type)
6379     {
6380       if (requires_tmpl_type)
6381         {
6382           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
6383             /* The number of argument required is not known yet.
6384                Just accept it for now.  */
6385             val = TREE_TYPE (arg);
6386           else
6387             {
6388               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
6389               tree argparm;
6390
6391               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
6392
6393               if (coerce_template_template_parms (parmparm, argparm,
6394                                                   complain, in_decl,
6395                                                   args))
6396                 {
6397                   val = arg;
6398
6399                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
6400                      TEMPLATE_DECL.  */
6401                   if (val != error_mark_node)
6402                     {
6403                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
6404                         val = TREE_TYPE (val);
6405                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
6406                         val = make_pack_expansion (val);
6407                     }
6408                 }
6409               else
6410                 {
6411                   if (in_decl && (complain & tf_error))
6412                     {
6413                       error ("type/value mismatch at argument %d in "
6414                              "template parameter list for %qD",
6415                              i + 1, in_decl);
6416                       error ("  expected a template of type %qD, got %qT",
6417                              parm, orig_arg);
6418                     }
6419
6420                   val = error_mark_node;
6421                 }
6422             }
6423         }
6424       else
6425         val = orig_arg;
6426       /* We only form one instance of each template specialization.
6427          Therefore, if we use a non-canonical variant (i.e., a
6428          typedef), any future messages referring to the type will use
6429          the typedef, which is confusing if those future uses do not
6430          themselves also use the typedef.  */
6431       if (TYPE_P (val))
6432         val = canonicalize_type_argument (val, complain);
6433     }
6434   else
6435     {
6436       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
6437
6438       if (invalid_nontype_parm_type_p (t, complain))
6439         return error_mark_node;
6440
6441       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
6442         {
6443           if (same_type_p (t, TREE_TYPE (orig_arg)))
6444             val = orig_arg;
6445           else
6446             {
6447               /* Not sure if this is reachable, but it doesn't hurt
6448                  to be robust.  */
6449               error ("type mismatch in nontype parameter pack");
6450               val = error_mark_node;
6451             }
6452         }
6453       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
6454         /* We used to call digest_init here.  However, digest_init
6455            will report errors, which we don't want when complain
6456            is zero.  More importantly, digest_init will try too
6457            hard to convert things: for example, `0' should not be
6458            converted to pointer type at this point according to
6459            the standard.  Accepting this is not merely an
6460            extension, since deciding whether or not these
6461            conversions can occur is part of determining which
6462            function template to call, or whether a given explicit
6463            argument specification is valid.  */
6464         val = convert_nontype_argument (t, orig_arg, complain);
6465       else
6466         val = orig_arg;
6467
6468       if (val == NULL_TREE)
6469         val = error_mark_node;
6470       else if (val == error_mark_node && (complain & tf_error))
6471         error ("could not convert template argument %qE to %qT",  orig_arg, t);
6472
6473       if (TREE_CODE (val) == SCOPE_REF)
6474         {
6475           /* Strip typedefs from the SCOPE_REF.  */
6476           tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
6477           tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
6478                                                    complain);
6479           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
6480                                       QUALIFIED_NAME_IS_TEMPLATE (val));
6481         }
6482     }
6483
6484   return val;
6485 }
6486
6487 /* Coerces the remaining template arguments in INNER_ARGS (from
6488    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
6489    Returns the coerced argument pack. PARM_IDX is the position of this
6490    parameter in the template parameter list. ARGS is the original
6491    template argument list.  */
6492 static tree
6493 coerce_template_parameter_pack (tree parms,
6494                                 int parm_idx,
6495                                 tree args,
6496                                 tree inner_args,
6497                                 int arg_idx,
6498                                 tree new_args,
6499                                 int* lost,
6500                                 tree in_decl,
6501                                 tsubst_flags_t complain)
6502 {
6503   tree parm = TREE_VEC_ELT (parms, parm_idx);
6504   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6505   tree packed_args;
6506   tree argument_pack;
6507   tree packed_types = NULL_TREE;
6508
6509   if (arg_idx > nargs)
6510     arg_idx = nargs;
6511
6512   packed_args = make_tree_vec (nargs - arg_idx);
6513
6514   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
6515       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
6516     {
6517       /* When the template parameter is a non-type template
6518          parameter pack whose type uses parameter packs, we need
6519          to look at each of the template arguments
6520          separately. Build a vector of the types for these
6521          non-type template parameters in PACKED_TYPES.  */
6522       tree expansion 
6523         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
6524       packed_types = tsubst_pack_expansion (expansion, args,
6525                                             complain, in_decl);
6526
6527       if (packed_types == error_mark_node)
6528         return error_mark_node;
6529
6530       /* Check that we have the right number of arguments.  */
6531       if (arg_idx < nargs
6532           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
6533           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
6534         {
6535           int needed_parms 
6536             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
6537           error ("wrong number of template arguments (%d, should be %d)",
6538                  nargs, needed_parms);
6539           return error_mark_node;
6540         }
6541
6542       /* If we aren't able to check the actual arguments now
6543          (because they haven't been expanded yet), we can at least
6544          verify that all of the types used for the non-type
6545          template parameter pack are, in fact, valid for non-type
6546          template parameters.  */
6547       if (arg_idx < nargs 
6548           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
6549         {
6550           int j, len = TREE_VEC_LENGTH (packed_types);
6551           for (j = 0; j < len; ++j)
6552             {
6553               tree t = TREE_VEC_ELT (packed_types, j);
6554               if (invalid_nontype_parm_type_p (t, complain))
6555                 return error_mark_node;
6556             }
6557         }
6558     }
6559
6560   /* Convert the remaining arguments, which will be a part of the
6561      parameter pack "parm".  */
6562   for (; arg_idx < nargs; ++arg_idx)
6563     {
6564       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
6565       tree actual_parm = TREE_VALUE (parm);
6566
6567       if (packed_types && !PACK_EXPANSION_P (arg))
6568         {
6569           /* When we have a vector of types (corresponding to the
6570              non-type template parameter pack that uses parameter
6571              packs in its type, as mention above), and the
6572              argument is not an expansion (which expands to a
6573              currently unknown number of arguments), clone the
6574              parm and give it the next type in PACKED_TYPES.  */
6575           actual_parm = copy_node (actual_parm);
6576           TREE_TYPE (actual_parm) = 
6577             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
6578         }
6579
6580       if (arg != error_mark_node)
6581         arg = convert_template_argument (actual_parm, 
6582                                          arg, new_args, complain, parm_idx,
6583                                          in_decl);
6584       if (arg == error_mark_node)
6585         (*lost)++;
6586       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
6587     }
6588
6589   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
6590       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
6591     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
6592   else
6593     {
6594       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
6595       TREE_TYPE (argument_pack) 
6596         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
6597       TREE_CONSTANT (argument_pack) = 1;
6598     }
6599
6600   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
6601 #ifdef ENABLE_CHECKING
6602   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
6603                                        TREE_VEC_LENGTH (packed_args));
6604 #endif
6605   return argument_pack;
6606 }
6607
6608 /* Convert all template arguments to their appropriate types, and
6609    return a vector containing the innermost resulting template
6610    arguments.  If any error occurs, return error_mark_node. Error and
6611    warning messages are issued under control of COMPLAIN.
6612
6613    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
6614    for arguments not specified in ARGS.  Otherwise, if
6615    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
6616    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
6617    USE_DEFAULT_ARGS is false, then all arguments must be specified in
6618    ARGS.  */
6619
6620 static tree
6621 coerce_template_parms (tree parms,
6622                        tree args,
6623                        tree in_decl,
6624                        tsubst_flags_t complain,
6625                        bool require_all_args,
6626                        bool use_default_args)
6627 {
6628   int nparms, nargs, parm_idx, arg_idx, lost = 0;
6629   tree inner_args;
6630   tree new_args;
6631   tree new_inner_args;
6632   int saved_unevaluated_operand;
6633   int saved_inhibit_evaluation_warnings;
6634
6635   /* When used as a boolean value, indicates whether this is a
6636      variadic template parameter list. Since it's an int, we can also
6637      subtract it from nparms to get the number of non-variadic
6638      parameters.  */
6639   int variadic_p = 0;
6640   int post_variadic_parms = 0;
6641
6642   if (args == error_mark_node)
6643     return error_mark_node;
6644
6645   nparms = TREE_VEC_LENGTH (parms);
6646
6647   /* Determine if there are any parameter packs.  */
6648   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
6649     {
6650       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
6651       if (variadic_p)
6652         ++post_variadic_parms;
6653       if (template_parameter_pack_p (tparm))
6654         ++variadic_p;
6655     }
6656
6657   inner_args = INNERMOST_TEMPLATE_ARGS (args);
6658   /* If there are no parameters that follow a parameter pack, we need to
6659      expand any argument packs so that we can deduce a parameter pack from
6660      some non-packed args followed by an argument pack, as in variadic85.C.
6661      If there are such parameters, we need to leave argument packs intact
6662      so the arguments are assigned properly.  This can happen when dealing
6663      with a nested class inside a partial specialization of a class
6664      template, as in variadic92.C, or when deducing a template parameter pack
6665      from a sub-declarator, as in variadic114.C.  */
6666   if (!post_variadic_parms)
6667     inner_args = expand_template_argument_pack (inner_args);
6668
6669   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6670   if ((nargs > nparms && !variadic_p)
6671       || (nargs < nparms - variadic_p
6672           && require_all_args
6673           && (!use_default_args
6674               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
6675                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
6676     {
6677       if (complain & tf_error)
6678         {
6679           if (variadic_p)
6680             {
6681               nparms -= variadic_p;
6682               error ("wrong number of template arguments "
6683                      "(%d, should be %d or more)", nargs, nparms);
6684             }
6685           else
6686              error ("wrong number of template arguments "
6687                     "(%d, should be %d)", nargs, nparms);
6688
6689           if (in_decl)
6690             error ("provided for %q+D", in_decl);
6691         }
6692
6693       return error_mark_node;
6694     }
6695
6696   /* We need to evaluate the template arguments, even though this
6697      template-id may be nested within a "sizeof".  */
6698   saved_unevaluated_operand = cp_unevaluated_operand;
6699   cp_unevaluated_operand = 0;
6700   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
6701   c_inhibit_evaluation_warnings = 0;
6702   new_inner_args = make_tree_vec (nparms);
6703   new_args = add_outermost_template_args (args, new_inner_args);
6704   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
6705     {
6706       tree arg;
6707       tree parm;
6708
6709       /* Get the Ith template parameter.  */
6710       parm = TREE_VEC_ELT (parms, parm_idx);
6711  
6712       if (parm == error_mark_node)
6713       {
6714         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
6715         continue;
6716       }
6717
6718       /* Calculate the next argument.  */
6719       if (arg_idx < nargs)
6720         arg = TREE_VEC_ELT (inner_args, arg_idx);
6721       else
6722         arg = NULL_TREE;
6723
6724       if (template_parameter_pack_p (TREE_VALUE (parm))
6725           && !(arg && ARGUMENT_PACK_P (arg)))
6726         {
6727           /* All remaining arguments will be placed in the
6728              template parameter pack PARM.  */
6729           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
6730                                                 inner_args, arg_idx,
6731                                                 new_args, &lost,
6732                                                 in_decl, complain);
6733
6734           /* Store this argument.  */
6735           if (arg == error_mark_node)
6736             lost++;
6737           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
6738
6739           /* We are done with all of the arguments.  */
6740           arg_idx = nargs;
6741           
6742           continue;
6743         }
6744       else if (arg)
6745         {
6746           if (PACK_EXPANSION_P (arg))
6747             {
6748               /* We don't know how many args we have yet, just
6749                  use the unconverted ones for now.  */
6750               new_inner_args = args;
6751               break;
6752             }
6753         }
6754       else if (require_all_args)
6755         {
6756           /* There must be a default arg in this case.  */
6757           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
6758                                      complain, in_decl);
6759           /* The position of the first default template argument,
6760              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
6761              Record that.  */
6762           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6763             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
6764         }
6765       else
6766         break;
6767
6768       if (arg == error_mark_node)
6769         {
6770           if (complain & tf_error)
6771             error ("template argument %d is invalid", arg_idx + 1);
6772         }
6773       else if (!arg)
6774         /* This only occurs if there was an error in the template
6775            parameter list itself (which we would already have
6776            reported) that we are trying to recover from, e.g., a class
6777            template with a parameter list such as
6778            template<typename..., typename>.  */
6779         ++lost;
6780       else
6781         arg = convert_template_argument (TREE_VALUE (parm),
6782                                          arg, new_args, complain, 
6783                                          parm_idx, in_decl);
6784
6785       if (arg == error_mark_node)
6786         lost++;
6787       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6788     }
6789   cp_unevaluated_operand = saved_unevaluated_operand;
6790   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6791
6792   if (lost)
6793     return error_mark_node;
6794
6795 #ifdef ENABLE_CHECKING
6796   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6797     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6798                                          TREE_VEC_LENGTH (new_inner_args));
6799 #endif
6800
6801   return new_inner_args;
6802 }
6803
6804 /* Returns 1 if template args OT and NT are equivalent.  */
6805
6806 static int
6807 template_args_equal (tree ot, tree nt)
6808 {
6809   if (nt == ot)
6810     return 1;
6811   if (nt == NULL_TREE || ot == NULL_TREE)
6812     return false;
6813
6814   if (TREE_CODE (nt) == TREE_VEC)
6815     /* For member templates */
6816     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6817   else if (PACK_EXPANSION_P (ot))
6818     return PACK_EXPANSION_P (nt) 
6819       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6820                               PACK_EXPANSION_PATTERN (nt));
6821   else if (ARGUMENT_PACK_P (ot))
6822     {
6823       int i, len;
6824       tree opack, npack;
6825
6826       if (!ARGUMENT_PACK_P (nt))
6827         return 0;
6828
6829       opack = ARGUMENT_PACK_ARGS (ot);
6830       npack = ARGUMENT_PACK_ARGS (nt);
6831       len = TREE_VEC_LENGTH (opack);
6832       if (TREE_VEC_LENGTH (npack) != len)
6833         return 0;
6834       for (i = 0; i < len; ++i)
6835         if (!template_args_equal (TREE_VEC_ELT (opack, i),
6836                                   TREE_VEC_ELT (npack, i)))
6837           return 0;
6838       return 1;
6839     }
6840   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6841     {
6842       /* We get here probably because we are in the middle of substituting
6843          into the pattern of a pack expansion. In that case the
6844          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6845          interested in. So we want to use the initial pack argument for
6846          the comparison.  */
6847       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6848       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6849         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6850       return template_args_equal (ot, nt);
6851     }
6852   else if (TYPE_P (nt))
6853     return TYPE_P (ot) && same_type_p (ot, nt);
6854   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6855     return 0;
6856   else
6857     return cp_tree_equal (ot, nt);
6858 }
6859
6860 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
6861    template arguments.  Returns 0 otherwise, and updates OLDARG_PTR and
6862    NEWARG_PTR with the offending arguments if they are non-NULL.  */
6863
6864 static int
6865 comp_template_args_with_info (tree oldargs, tree newargs,
6866                               tree *oldarg_ptr, tree *newarg_ptr)
6867 {
6868   int i;
6869
6870   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6871     return 0;
6872
6873   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6874     {
6875       tree nt = TREE_VEC_ELT (newargs, i);
6876       tree ot = TREE_VEC_ELT (oldargs, i);
6877
6878       if (! template_args_equal (ot, nt))
6879         {
6880           if (oldarg_ptr != NULL)
6881             *oldarg_ptr = ot;
6882           if (newarg_ptr != NULL)
6883             *newarg_ptr = nt;
6884           return 0;
6885         }
6886     }
6887   return 1;
6888 }
6889
6890 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6891    of template arguments.  Returns 0 otherwise.  */
6892
6893 int
6894 comp_template_args (tree oldargs, tree newargs)
6895 {
6896   return comp_template_args_with_info (oldargs, newargs, NULL, NULL);
6897 }
6898
6899 static void
6900 add_pending_template (tree d)
6901 {
6902   tree ti = (TYPE_P (d)
6903              ? CLASSTYPE_TEMPLATE_INFO (d)
6904              : DECL_TEMPLATE_INFO (d));
6905   struct pending_template *pt;
6906   int level;
6907
6908   if (TI_PENDING_TEMPLATE_FLAG (ti))
6909     return;
6910
6911   /* We are called both from instantiate_decl, where we've already had a
6912      tinst_level pushed, and instantiate_template, where we haven't.
6913      Compensate.  */
6914   level = !current_tinst_level || current_tinst_level->decl != d;
6915
6916   if (level)
6917     push_tinst_level (d);
6918
6919   pt = ggc_alloc_pending_template ();
6920   pt->next = NULL;
6921   pt->tinst = current_tinst_level;
6922   if (last_pending_template)
6923     last_pending_template->next = pt;
6924   else
6925     pending_templates = pt;
6926
6927   last_pending_template = pt;
6928
6929   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6930
6931   if (level)
6932     pop_tinst_level ();
6933 }
6934
6935
6936 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6937    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6938    documentation for TEMPLATE_ID_EXPR.  */
6939
6940 tree
6941 lookup_template_function (tree fns, tree arglist)
6942 {
6943   tree type;
6944
6945   if (fns == error_mark_node || arglist == error_mark_node)
6946     return error_mark_node;
6947
6948   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6949
6950   if (!is_overloaded_fn (fns) && TREE_CODE (fns) != IDENTIFIER_NODE)
6951     {
6952       error ("%q#D is not a function template", fns);
6953       return error_mark_node;
6954     }
6955
6956   if (BASELINK_P (fns))
6957     {
6958       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6959                                          unknown_type_node,
6960                                          BASELINK_FUNCTIONS (fns),
6961                                          arglist);
6962       return fns;
6963     }
6964
6965   type = TREE_TYPE (fns);
6966   if (TREE_CODE (fns) == OVERLOAD || !type)
6967     type = unknown_type_node;
6968
6969   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6970 }
6971
6972 /* Within the scope of a template class S<T>, the name S gets bound
6973    (in build_self_reference) to a TYPE_DECL for the class, not a
6974    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6975    or one of its enclosing classes, and that type is a template,
6976    return the associated TEMPLATE_DECL.  Otherwise, the original
6977    DECL is returned.
6978
6979    Also handle the case when DECL is a TREE_LIST of ambiguous
6980    injected-class-names from different bases.  */
6981
6982 tree
6983 maybe_get_template_decl_from_type_decl (tree decl)
6984 {
6985   if (decl == NULL_TREE)
6986     return decl;
6987
6988   /* DR 176: A lookup that finds an injected-class-name (10.2
6989      [class.member.lookup]) can result in an ambiguity in certain cases
6990      (for example, if it is found in more than one base class). If all of
6991      the injected-class-names that are found refer to specializations of
6992      the same class template, and if the name is followed by a
6993      template-argument-list, the reference refers to the class template
6994      itself and not a specialization thereof, and is not ambiguous.  */
6995   if (TREE_CODE (decl) == TREE_LIST)
6996     {
6997       tree t, tmpl = NULL_TREE;
6998       for (t = decl; t; t = TREE_CHAIN (t))
6999         {
7000           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
7001           if (!tmpl)
7002             tmpl = elt;
7003           else if (tmpl != elt)
7004             break;
7005         }
7006       if (tmpl && t == NULL_TREE)
7007         return tmpl;
7008       else
7009         return decl;
7010     }
7011
7012   return (decl != NULL_TREE
7013           && DECL_SELF_REFERENCE_P (decl)
7014           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
7015     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
7016 }
7017
7018 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
7019    parameters, find the desired type.
7020
7021    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
7022
7023    IN_DECL, if non-NULL, is the template declaration we are trying to
7024    instantiate.
7025
7026    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
7027    the class we are looking up.
7028
7029    Issue error and warning messages under control of COMPLAIN.
7030
7031    If the template class is really a local class in a template
7032    function, then the FUNCTION_CONTEXT is the function in which it is
7033    being instantiated.
7034
7035    ??? Note that this function is currently called *twice* for each
7036    template-id: the first time from the parser, while creating the
7037    incomplete type (finish_template_type), and the second type during the
7038    real instantiation (instantiate_template_class). This is surely something
7039    that we want to avoid. It also causes some problems with argument
7040    coercion (see convert_nontype_argument for more information on this).  */
7041
7042 static tree
7043 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
7044                          int entering_scope, tsubst_flags_t complain)
7045 {
7046   tree templ = NULL_TREE, parmlist;
7047   tree t;
7048   void **slot;
7049   spec_entry *entry;
7050   spec_entry elt;
7051   hashval_t hash;
7052
7053   if (TREE_CODE (d1) == IDENTIFIER_NODE)
7054     {
7055       tree value = innermost_non_namespace_value (d1);
7056       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
7057         templ = value;
7058       else
7059         {
7060           if (context)
7061             push_decl_namespace (context);
7062           templ = lookup_name (d1);
7063           templ = maybe_get_template_decl_from_type_decl (templ);
7064           if (context)
7065             pop_decl_namespace ();
7066         }
7067       if (templ)
7068         context = DECL_CONTEXT (templ);
7069     }
7070   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
7071     {
7072       tree type = TREE_TYPE (d1);
7073
7074       /* If we are declaring a constructor, say A<T>::A<T>, we will get
7075          an implicit typename for the second A.  Deal with it.  */
7076       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
7077         type = TREE_TYPE (type);
7078
7079       if (CLASSTYPE_TEMPLATE_INFO (type))
7080         {
7081           templ = CLASSTYPE_TI_TEMPLATE (type);
7082           d1 = DECL_NAME (templ);
7083         }
7084     }
7085   else if (TREE_CODE (d1) == ENUMERAL_TYPE
7086            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
7087     {
7088       templ = TYPE_TI_TEMPLATE (d1);
7089       d1 = DECL_NAME (templ);
7090     }
7091   else if (TREE_CODE (d1) == TEMPLATE_DECL
7092            && DECL_TEMPLATE_RESULT (d1)
7093            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
7094     {
7095       templ = d1;
7096       d1 = DECL_NAME (templ);
7097       context = DECL_CONTEXT (templ);
7098     }
7099
7100   /* Issue an error message if we didn't find a template.  */
7101   if (! templ)
7102     {
7103       if (complain & tf_error)
7104         error ("%qT is not a template", d1);
7105       return error_mark_node;
7106     }
7107
7108   if (TREE_CODE (templ) != TEMPLATE_DECL
7109          /* Make sure it's a user visible template, if it was named by
7110             the user.  */
7111       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
7112           && !PRIMARY_TEMPLATE_P (templ)))
7113     {
7114       if (complain & tf_error)
7115         {
7116           error ("non-template type %qT used as a template", d1);
7117           if (in_decl)
7118             error ("for template declaration %q+D", in_decl);
7119         }
7120       return error_mark_node;
7121     }
7122
7123   complain &= ~tf_user;
7124
7125   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
7126     {
7127       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
7128          template arguments */
7129
7130       tree parm;
7131       tree arglist2;
7132       tree outer;
7133
7134       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7135
7136       /* Consider an example where a template template parameter declared as
7137
7138            template <class T, class U = std::allocator<T> > class TT
7139
7140          The template parameter level of T and U are one level larger than
7141          of TT.  To proper process the default argument of U, say when an
7142          instantiation `TT<int>' is seen, we need to build the full
7143          arguments containing {int} as the innermost level.  Outer levels,
7144          available when not appearing as default template argument, can be
7145          obtained from the arguments of the enclosing template.
7146
7147          Suppose that TT is later substituted with std::vector.  The above
7148          instantiation is `TT<int, std::allocator<T> >' with TT at
7149          level 1, and T at level 2, while the template arguments at level 1
7150          becomes {std::vector} and the inner level 2 is {int}.  */
7151
7152       outer = DECL_CONTEXT (templ);
7153       if (outer)
7154         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
7155       else if (current_template_parms)
7156         /* This is an argument of the current template, so we haven't set
7157            DECL_CONTEXT yet.  */
7158         outer = current_template_args ();
7159
7160       if (outer)
7161         arglist = add_to_template_args (outer, arglist);
7162
7163       arglist2 = coerce_template_parms (parmlist, arglist, templ,
7164                                         complain,
7165                                         /*require_all_args=*/true,
7166                                         /*use_default_args=*/true);
7167       if (arglist2 == error_mark_node
7168           || (!uses_template_parms (arglist2)
7169               && check_instantiated_args (templ, arglist2, complain)))
7170         return error_mark_node;
7171
7172       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
7173       return parm;
7174     }
7175   else
7176     {
7177       tree template_type = TREE_TYPE (templ);
7178       tree gen_tmpl;
7179       tree type_decl;
7180       tree found = NULL_TREE;
7181       int arg_depth;
7182       int parm_depth;
7183       int is_dependent_type;
7184       int use_partial_inst_tmpl = false;
7185
7186       gen_tmpl = most_general_template (templ);
7187       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
7188       parm_depth = TMPL_PARMS_DEPTH (parmlist);
7189       arg_depth = TMPL_ARGS_DEPTH (arglist);
7190
7191       if (arg_depth == 1 && parm_depth > 1)
7192         {
7193           /* We've been given an incomplete set of template arguments.
7194              For example, given:
7195
7196                template <class T> struct S1 {
7197                  template <class U> struct S2 {};
7198                  template <class U> struct S2<U*> {};
7199                 };
7200
7201              we will be called with an ARGLIST of `U*', but the
7202              TEMPLATE will be `template <class T> template
7203              <class U> struct S1<T>::S2'.  We must fill in the missing
7204              arguments.  */
7205           arglist
7206             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
7207                                            arglist);
7208           arg_depth = TMPL_ARGS_DEPTH (arglist);
7209         }
7210
7211       /* Now we should have enough arguments.  */
7212       gcc_assert (parm_depth == arg_depth);
7213
7214       /* From here on, we're only interested in the most general
7215          template.  */
7216
7217       /* Calculate the BOUND_ARGS.  These will be the args that are
7218          actually tsubst'd into the definition to create the
7219          instantiation.  */
7220       if (parm_depth > 1)
7221         {
7222           /* We have multiple levels of arguments to coerce, at once.  */
7223           int i;
7224           int saved_depth = TMPL_ARGS_DEPTH (arglist);
7225
7226           tree bound_args = make_tree_vec (parm_depth);
7227
7228           for (i = saved_depth,
7229                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
7230                i > 0 && t != NULL_TREE;
7231                --i, t = TREE_CHAIN (t))
7232             {
7233               tree a;
7234               if (i == saved_depth)
7235                 a = coerce_template_parms (TREE_VALUE (t),
7236                                            arglist, gen_tmpl,
7237                                            complain,
7238                                            /*require_all_args=*/true,
7239                                            /*use_default_args=*/true);
7240               else
7241                 /* Outer levels should have already been coerced.  */
7242                 a = TMPL_ARGS_LEVEL (arglist, i);
7243
7244               /* Don't process further if one of the levels fails.  */
7245               if (a == error_mark_node)
7246                 {
7247                   /* Restore the ARGLIST to its full size.  */
7248                   TREE_VEC_LENGTH (arglist) = saved_depth;
7249                   return error_mark_node;
7250                 }
7251
7252               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
7253
7254               /* We temporarily reduce the length of the ARGLIST so
7255                  that coerce_template_parms will see only the arguments
7256                  corresponding to the template parameters it is
7257                  examining.  */
7258               TREE_VEC_LENGTH (arglist)--;
7259             }
7260
7261           /* Restore the ARGLIST to its full size.  */
7262           TREE_VEC_LENGTH (arglist) = saved_depth;
7263
7264           arglist = bound_args;
7265         }
7266       else
7267         arglist
7268           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
7269                                    INNERMOST_TEMPLATE_ARGS (arglist),
7270                                    gen_tmpl,
7271                                    complain,
7272                                    /*require_all_args=*/true,
7273                                    /*use_default_args=*/true);
7274
7275       if (arglist == error_mark_node)
7276         /* We were unable to bind the arguments.  */
7277         return error_mark_node;
7278
7279       /* In the scope of a template class, explicit references to the
7280          template class refer to the type of the template, not any
7281          instantiation of it.  For example, in:
7282
7283            template <class T> class C { void f(C<T>); }
7284
7285          the `C<T>' is just the same as `C'.  Outside of the
7286          class, however, such a reference is an instantiation.  */
7287       if ((entering_scope
7288            || !PRIMARY_TEMPLATE_P (gen_tmpl)
7289            || currently_open_class (template_type))
7290           /* comp_template_args is expensive, check it last.  */
7291           && comp_template_args (TYPE_TI_ARGS (template_type),
7292                                  arglist))
7293         return template_type;
7294
7295       /* If we already have this specialization, return it.  */
7296       elt.tmpl = gen_tmpl;
7297       elt.args = arglist;
7298       hash = hash_specialization (&elt);
7299       entry = (spec_entry *) htab_find_with_hash (type_specializations,
7300                                                   &elt, hash);
7301
7302       if (entry)
7303         return entry->spec;
7304
7305       is_dependent_type = uses_template_parms (arglist);
7306
7307       /* If the deduced arguments are invalid, then the binding
7308          failed.  */
7309       if (!is_dependent_type
7310           && check_instantiated_args (gen_tmpl,
7311                                       INNERMOST_TEMPLATE_ARGS (arglist),
7312                                       complain))
7313         return error_mark_node;
7314
7315       if (!is_dependent_type
7316           && !PRIMARY_TEMPLATE_P (gen_tmpl)
7317           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
7318           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
7319         {
7320           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
7321                                       DECL_NAME (gen_tmpl),
7322                                       /*tag_scope=*/ts_global);
7323           return found;
7324         }
7325
7326       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
7327                         complain, in_decl);
7328       if (!context)
7329         context = global_namespace;
7330
7331       /* Create the type.  */
7332       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
7333         {
7334           if (!is_dependent_type)
7335             {
7336               set_current_access_from_decl (TYPE_NAME (template_type));
7337               t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
7338                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
7339                                       arglist, complain, in_decl),
7340                               SCOPED_ENUM_P (template_type), NULL);
7341             }
7342           else
7343             {
7344               /* We don't want to call start_enum for this type, since
7345                  the values for the enumeration constants may involve
7346                  template parameters.  And, no one should be interested
7347                  in the enumeration constants for such a type.  */
7348               t = cxx_make_type (ENUMERAL_TYPE);
7349               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
7350             }
7351           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
7352           ENUM_FIXED_UNDERLYING_TYPE_P (t)
7353             = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
7354         }
7355       else
7356         {
7357           t = make_class_type (TREE_CODE (template_type));
7358           CLASSTYPE_DECLARED_CLASS (t)
7359             = CLASSTYPE_DECLARED_CLASS (template_type);
7360           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
7361           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
7362
7363           /* A local class.  Make sure the decl gets registered properly.  */
7364           if (context == current_function_decl)
7365             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
7366
7367           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
7368             /* This instantiation is another name for the primary
7369                template type. Set the TYPE_CANONICAL field
7370                appropriately. */
7371             TYPE_CANONICAL (t) = template_type;
7372           else if (any_template_arguments_need_structural_equality_p (arglist))
7373             /* Some of the template arguments require structural
7374                equality testing, so this template class requires
7375                structural equality testing. */
7376             SET_TYPE_STRUCTURAL_EQUALITY (t);
7377         }
7378
7379       /* If we called start_enum or pushtag above, this information
7380          will already be set up.  */
7381       if (!TYPE_NAME (t))
7382         {
7383           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
7384
7385           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
7386           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
7387           DECL_SOURCE_LOCATION (type_decl)
7388             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
7389         }
7390       else
7391         type_decl = TYPE_NAME (t);
7392
7393       TREE_PRIVATE (type_decl)
7394         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
7395       TREE_PROTECTED (type_decl)
7396         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
7397       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
7398         {
7399           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
7400           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
7401         }
7402
7403       /* Let's consider the explicit specialization of a member
7404          of a class template specialization that is implicitely instantiated,
7405          e.g.:
7406              template<class T>
7407              struct S
7408              {
7409                template<class U> struct M {}; //#0
7410              };
7411
7412              template<>
7413              template<>
7414              struct S<int>::M<char> //#1
7415              {
7416                int i;
7417              };
7418         [temp.expl.spec]/4 says this is valid.
7419
7420         In this case, when we write:
7421         S<int>::M<char> m;
7422
7423         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
7424         the one of #0.
7425
7426         When we encounter #1, we want to store the partial instantiation
7427         of M (template<class T> S<int>::M<T>) in it's CLASSTYPE_TI_TEMPLATE.
7428
7429         For all cases other than this "explicit specialization of member of a
7430         class template", we just want to store the most general template into
7431         the CLASSTYPE_TI_TEMPLATE of M.
7432
7433         This case of "explicit specialization of member of a class template"
7434         only happens when:
7435         1/ the enclosing class is an instantiation of, and therefore not
7436         the same as, the context of the most general template, and
7437         2/ we aren't looking at the partial instantiation itself, i.e.
7438         the innermost arguments are not the same as the innermost parms of
7439         the most general template.
7440
7441         So it's only when 1/ and 2/ happens that we want to use the partial
7442         instantiation of the member template in lieu of its most general
7443         template.  */
7444
7445       if (PRIMARY_TEMPLATE_P (gen_tmpl)
7446           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
7447           /* the enclosing class must be an instantiation...  */
7448           && CLASS_TYPE_P (context)
7449           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
7450         {
7451           tree partial_inst_args;
7452           TREE_VEC_LENGTH (arglist)--;
7453           ++processing_template_decl;
7454           partial_inst_args =
7455             tsubst (INNERMOST_TEMPLATE_ARGS
7456                         (CLASSTYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
7457                     arglist, complain, NULL_TREE);
7458           --processing_template_decl;
7459           TREE_VEC_LENGTH (arglist)++;
7460           use_partial_inst_tmpl =
7461             /*...and we must not be looking at the partial instantiation
7462              itself. */
7463             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
7464                                  partial_inst_args);
7465         }
7466
7467       if (!use_partial_inst_tmpl)
7468         /* This case is easy; there are no member templates involved.  */
7469         found = gen_tmpl;
7470       else
7471         {
7472           /* This is a full instantiation of a member template.  Find
7473              the partial instantiation of which this is an instance.  */
7474
7475           /* Temporarily reduce by one the number of levels in the ARGLIST
7476              so as to avoid comparing the last set of arguments.  */
7477           TREE_VEC_LENGTH (arglist)--;
7478           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
7479           TREE_VEC_LENGTH (arglist)++;
7480           found = CLASSTYPE_TI_TEMPLATE (found);
7481         }
7482
7483       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
7484
7485       elt.spec = t;
7486       slot = htab_find_slot_with_hash (type_specializations,
7487                                        &elt, hash, INSERT);
7488       entry = ggc_alloc_spec_entry ();
7489       *entry = elt;
7490       *slot = entry;
7491
7492       /* Note this use of the partial instantiation so we can check it
7493          later in maybe_process_partial_specialization.  */
7494       DECL_TEMPLATE_INSTANTIATIONS (templ)
7495         = tree_cons (arglist, t,
7496                      DECL_TEMPLATE_INSTANTIATIONS (templ));
7497
7498       if (TREE_CODE (t) == ENUMERAL_TYPE && !is_dependent_type)
7499         /* Now that the type has been registered on the instantiations
7500            list, we set up the enumerators.  Because the enumeration
7501            constants may involve the enumeration type itself, we make
7502            sure to register the type first, and then create the
7503            constants.  That way, doing tsubst_expr for the enumeration
7504            constants won't result in recursive calls here; we'll find
7505            the instantiation and exit above.  */
7506         tsubst_enum (template_type, t, arglist);
7507
7508       if (is_dependent_type)
7509         /* If the type makes use of template parameters, the
7510            code that generates debugging information will crash.  */
7511         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
7512
7513       /* Possibly limit visibility based on template args.  */
7514       TREE_PUBLIC (type_decl) = 1;
7515       determine_visibility (type_decl);
7516
7517       return t;
7518     }
7519 }
7520
7521 /* Wrapper for lookup_template_class_1.  */
7522
7523 tree
7524 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
7525                        int entering_scope, tsubst_flags_t complain)
7526 {
7527   tree ret;
7528   timevar_push (TV_TEMPLATE_INST);
7529   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
7530                                  entering_scope, complain);
7531   timevar_pop (TV_TEMPLATE_INST);
7532   return ret;
7533 }
7534 \f
7535 struct pair_fn_data
7536 {
7537   tree_fn_t fn;
7538   void *data;
7539   /* True when we should also visit template parameters that occur in
7540      non-deduced contexts.  */
7541   bool include_nondeduced_p;
7542   struct pointer_set_t *visited;
7543 };
7544
7545 /* Called from for_each_template_parm via walk_tree.  */
7546
7547 static tree
7548 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
7549 {
7550   tree t = *tp;
7551   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
7552   tree_fn_t fn = pfd->fn;
7553   void *data = pfd->data;
7554
7555   if (TYPE_P (t)
7556       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
7557       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
7558                                  pfd->include_nondeduced_p))
7559     return error_mark_node;
7560
7561   switch (TREE_CODE (t))
7562     {
7563     case RECORD_TYPE:
7564       if (TYPE_PTRMEMFUNC_P (t))
7565         break;
7566       /* Fall through.  */
7567
7568     case UNION_TYPE:
7569     case ENUMERAL_TYPE:
7570       if (!TYPE_TEMPLATE_INFO (t))
7571         *walk_subtrees = 0;
7572       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
7573                                        fn, data, pfd->visited, 
7574                                        pfd->include_nondeduced_p))
7575         return error_mark_node;
7576       break;
7577
7578     case INTEGER_TYPE:
7579       if (for_each_template_parm (TYPE_MIN_VALUE (t),
7580                                   fn, data, pfd->visited, 
7581                                   pfd->include_nondeduced_p)
7582           || for_each_template_parm (TYPE_MAX_VALUE (t),
7583                                      fn, data, pfd->visited,
7584                                      pfd->include_nondeduced_p))
7585         return error_mark_node;
7586       break;
7587
7588     case METHOD_TYPE:
7589       /* Since we're not going to walk subtrees, we have to do this
7590          explicitly here.  */
7591       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
7592                                   pfd->visited, pfd->include_nondeduced_p))
7593         return error_mark_node;
7594       /* Fall through.  */
7595
7596     case FUNCTION_TYPE:
7597       /* Check the return type.  */
7598       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7599                                   pfd->include_nondeduced_p))
7600         return error_mark_node;
7601
7602       /* Check the parameter types.  Since default arguments are not
7603          instantiated until they are needed, the TYPE_ARG_TYPES may
7604          contain expressions that involve template parameters.  But,
7605          no-one should be looking at them yet.  And, once they're
7606          instantiated, they don't contain template parameters, so
7607          there's no point in looking at them then, either.  */
7608       {
7609         tree parm;
7610
7611         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
7612           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
7613                                       pfd->visited, pfd->include_nondeduced_p))
7614             return error_mark_node;
7615
7616         /* Since we've already handled the TYPE_ARG_TYPES, we don't
7617            want walk_tree walking into them itself.  */
7618         *walk_subtrees = 0;
7619       }
7620       break;
7621
7622     case TYPEOF_TYPE:
7623     case UNDERLYING_TYPE:
7624       if (pfd->include_nondeduced_p
7625           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
7626                                      pfd->visited, 
7627                                      pfd->include_nondeduced_p))
7628         return error_mark_node;
7629       break;
7630
7631     case FUNCTION_DECL:
7632     case VAR_DECL:
7633       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
7634           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
7635                                      pfd->visited, pfd->include_nondeduced_p))
7636         return error_mark_node;
7637       /* Fall through.  */
7638
7639     case PARM_DECL:
7640     case CONST_DECL:
7641       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
7642           && for_each_template_parm (DECL_INITIAL (t), fn, data,
7643                                      pfd->visited, pfd->include_nondeduced_p))
7644         return error_mark_node;
7645       if (DECL_CONTEXT (t)
7646           && pfd->include_nondeduced_p
7647           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
7648                                      pfd->visited, pfd->include_nondeduced_p))
7649         return error_mark_node;
7650       break;
7651
7652     case BOUND_TEMPLATE_TEMPLATE_PARM:
7653       /* Record template parameters such as `T' inside `TT<T>'.  */
7654       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
7655                                   pfd->include_nondeduced_p))
7656         return error_mark_node;
7657       /* Fall through.  */
7658
7659     case TEMPLATE_TEMPLATE_PARM:
7660     case TEMPLATE_TYPE_PARM:
7661     case TEMPLATE_PARM_INDEX:
7662       if (fn && (*fn)(t, data))
7663         return error_mark_node;
7664       else if (!fn)
7665         return error_mark_node;
7666       break;
7667
7668     case TEMPLATE_DECL:
7669       /* A template template parameter is encountered.  */
7670       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
7671           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7672                                      pfd->include_nondeduced_p))
7673         return error_mark_node;
7674
7675       /* Already substituted template template parameter */
7676       *walk_subtrees = 0;
7677       break;
7678
7679     case TYPENAME_TYPE:
7680       if (!fn
7681           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
7682                                      data, pfd->visited, 
7683                                      pfd->include_nondeduced_p))
7684         return error_mark_node;
7685       break;
7686
7687     case CONSTRUCTOR:
7688       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
7689           && pfd->include_nondeduced_p
7690           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
7691                                      (TREE_TYPE (t)), fn, data,
7692                                      pfd->visited, pfd->include_nondeduced_p))
7693         return error_mark_node;
7694       break;
7695
7696     case INDIRECT_REF:
7697     case COMPONENT_REF:
7698       /* If there's no type, then this thing must be some expression
7699          involving template parameters.  */
7700       if (!fn && !TREE_TYPE (t))
7701         return error_mark_node;
7702       break;
7703
7704     case MODOP_EXPR:
7705     case CAST_EXPR:
7706     case IMPLICIT_CONV_EXPR:
7707     case REINTERPRET_CAST_EXPR:
7708     case CONST_CAST_EXPR:
7709     case STATIC_CAST_EXPR:
7710     case DYNAMIC_CAST_EXPR:
7711     case ARROW_EXPR:
7712     case DOTSTAR_EXPR:
7713     case TYPEID_EXPR:
7714     case PSEUDO_DTOR_EXPR:
7715       if (!fn)
7716         return error_mark_node;
7717       break;
7718
7719     default:
7720       break;
7721     }
7722
7723   /* We didn't find any template parameters we liked.  */
7724   return NULL_TREE;
7725 }
7726
7727 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
7728    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
7729    call FN with the parameter and the DATA.
7730    If FN returns nonzero, the iteration is terminated, and
7731    for_each_template_parm returns 1.  Otherwise, the iteration
7732    continues.  If FN never returns a nonzero value, the value
7733    returned by for_each_template_parm is 0.  If FN is NULL, it is
7734    considered to be the function which always returns 1.
7735
7736    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
7737    parameters that occur in non-deduced contexts.  When false, only
7738    visits those template parameters that can be deduced.  */
7739
7740 static int
7741 for_each_template_parm (tree t, tree_fn_t fn, void* data,
7742                         struct pointer_set_t *visited,
7743                         bool include_nondeduced_p)
7744 {
7745   struct pair_fn_data pfd;
7746   int result;
7747
7748   /* Set up.  */
7749   pfd.fn = fn;
7750   pfd.data = data;
7751   pfd.include_nondeduced_p = include_nondeduced_p;
7752
7753   /* Walk the tree.  (Conceptually, we would like to walk without
7754      duplicates, but for_each_template_parm_r recursively calls
7755      for_each_template_parm, so we would need to reorganize a fair
7756      bit to use walk_tree_without_duplicates, so we keep our own
7757      visited list.)  */
7758   if (visited)
7759     pfd.visited = visited;
7760   else
7761     pfd.visited = pointer_set_create ();
7762   result = cp_walk_tree (&t,
7763                          for_each_template_parm_r,
7764                          &pfd,
7765                          pfd.visited) != NULL_TREE;
7766
7767   /* Clean up.  */
7768   if (!visited)
7769     {
7770       pointer_set_destroy (pfd.visited);
7771       pfd.visited = 0;
7772     }
7773
7774   return result;
7775 }
7776
7777 /* Returns true if T depends on any template parameter.  */
7778
7779 int
7780 uses_template_parms (tree t)
7781 {
7782   bool dependent_p;
7783   int saved_processing_template_decl;
7784
7785   saved_processing_template_decl = processing_template_decl;
7786   if (!saved_processing_template_decl)
7787     processing_template_decl = 1;
7788   if (TYPE_P (t))
7789     dependent_p = dependent_type_p (t);
7790   else if (TREE_CODE (t) == TREE_VEC)
7791     dependent_p = any_dependent_template_arguments_p (t);
7792   else if (TREE_CODE (t) == TREE_LIST)
7793     dependent_p = (uses_template_parms (TREE_VALUE (t))
7794                    || uses_template_parms (TREE_CHAIN (t)));
7795   else if (TREE_CODE (t) == TYPE_DECL)
7796     dependent_p = dependent_type_p (TREE_TYPE (t));
7797   else if (DECL_P (t)
7798            || EXPR_P (t)
7799            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
7800            || TREE_CODE (t) == OVERLOAD
7801            || TREE_CODE (t) == BASELINK
7802            || TREE_CODE (t) == IDENTIFIER_NODE
7803            || TREE_CODE (t) == TRAIT_EXPR
7804            || TREE_CODE (t) == CONSTRUCTOR
7805            || CONSTANT_CLASS_P (t))
7806     dependent_p = (type_dependent_expression_p (t)
7807                    || value_dependent_expression_p (t));
7808   else
7809     {
7810       gcc_assert (t == error_mark_node);
7811       dependent_p = false;
7812     }
7813
7814   processing_template_decl = saved_processing_template_decl;
7815
7816   return dependent_p;
7817 }
7818
7819 /* Returns true if T depends on any template parameter with level LEVEL.  */
7820
7821 int
7822 uses_template_parms_level (tree t, int level)
7823 {
7824   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
7825                                  /*include_nondeduced_p=*/true);
7826 }
7827
7828 /* Returns TRUE iff INST is an instantiation we don't need to do in an
7829    ill-formed translation unit, i.e. a variable or function that isn't
7830    usable in a constant expression.  */
7831
7832 static inline bool
7833 neglectable_inst_p (tree d)
7834 {
7835   return (DECL_P (d)
7836           && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
7837                : decl_maybe_constant_var_p (d)));
7838 }
7839
7840 /* Returns TRUE iff we should refuse to instantiate DECL because it's
7841    neglectable and instantiated from within an erroneous instantiation.  */
7842
7843 static bool
7844 limit_bad_template_recursion (tree decl)
7845 {
7846   struct tinst_level *lev = current_tinst_level;
7847   int errs = errorcount + sorrycount;
7848   if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
7849     return false;
7850
7851   for (; lev; lev = lev->next)
7852     if (neglectable_inst_p (lev->decl))
7853       break;
7854
7855   return (lev && errs > lev->errors);
7856 }
7857
7858 static int tinst_depth;
7859 extern int max_tinst_depth;
7860 #ifdef GATHER_STATISTICS
7861 int depth_reached;
7862 #endif
7863 static GTY(()) struct tinst_level *last_error_tinst_level;
7864
7865 /* We're starting to instantiate D; record the template instantiation context
7866    for diagnostics and to restore it later.  */
7867
7868 int
7869 push_tinst_level (tree d)
7870 {
7871   struct tinst_level *new_level;
7872
7873   if (tinst_depth >= max_tinst_depth)
7874     {
7875       last_error_tinst_level = current_tinst_level;
7876       if (TREE_CODE (d) == TREE_LIST)
7877         error ("template instantiation depth exceeds maximum of %d (use "
7878                "-ftemplate-depth= to increase the maximum) substituting %qS",
7879                max_tinst_depth, d);
7880       else
7881         error ("template instantiation depth exceeds maximum of %d (use "
7882                "-ftemplate-depth= to increase the maximum) instantiating %qD",
7883                max_tinst_depth, d);
7884
7885       print_instantiation_context ();
7886
7887       return 0;
7888     }
7889
7890   /* If the current instantiation caused problems, don't let it instantiate
7891      anything else.  Do allow deduction substitution and decls usable in
7892      constant expressions.  */
7893   if (limit_bad_template_recursion (d))
7894     return 0;
7895
7896   new_level = ggc_alloc_tinst_level ();
7897   new_level->decl = d;
7898   new_level->locus = input_location;
7899   new_level->errors = errorcount+sorrycount;
7900   new_level->in_system_header_p = in_system_header;
7901   new_level->next = current_tinst_level;
7902   current_tinst_level = new_level;
7903
7904   ++tinst_depth;
7905 #ifdef GATHER_STATISTICS
7906   if (tinst_depth > depth_reached)
7907     depth_reached = tinst_depth;
7908 #endif
7909
7910   return 1;
7911 }
7912
7913 /* We're done instantiating this template; return to the instantiation
7914    context.  */
7915
7916 void
7917 pop_tinst_level (void)
7918 {
7919   /* Restore the filename and line number stashed away when we started
7920      this instantiation.  */
7921   input_location = current_tinst_level->locus;
7922   current_tinst_level = current_tinst_level->next;
7923   --tinst_depth;
7924 }
7925
7926 /* We're instantiating a deferred template; restore the template
7927    instantiation context in which the instantiation was requested, which
7928    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
7929
7930 static tree
7931 reopen_tinst_level (struct tinst_level *level)
7932 {
7933   struct tinst_level *t;
7934
7935   tinst_depth = 0;
7936   for (t = level; t; t = t->next)
7937     ++tinst_depth;
7938
7939   current_tinst_level = level;
7940   pop_tinst_level ();
7941   if (current_tinst_level)
7942     current_tinst_level->errors = errorcount+sorrycount;
7943   return level->decl;
7944 }
7945
7946 /* Returns the TINST_LEVEL which gives the original instantiation
7947    context.  */
7948
7949 struct tinst_level *
7950 outermost_tinst_level (void)
7951 {
7952   struct tinst_level *level = current_tinst_level;
7953   if (level)
7954     while (level->next)
7955       level = level->next;
7956   return level;
7957 }
7958
7959 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
7960
7961 bool
7962 parameter_of_template_p (tree parm, tree templ)
7963 {
7964   tree parms;
7965   int i;
7966
7967   if (!parm || !templ)
7968     return false;
7969
7970   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
7971   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7972
7973   parms = DECL_TEMPLATE_PARMS (templ);
7974   parms = INNERMOST_TEMPLATE_PARMS (parms);
7975
7976   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
7977     {
7978       tree p = TREE_VALUE (TREE_VEC_ELT (parms, i));
7979       if (parm == p
7980           || (DECL_INITIAL (parm)
7981               && DECL_INITIAL (parm) == DECL_INITIAL (p)))
7982         return true;
7983     }
7984
7985   return false;
7986 }
7987
7988 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
7989    vector of template arguments, as for tsubst.
7990
7991    Returns an appropriate tsubst'd friend declaration.  */
7992
7993 static tree
7994 tsubst_friend_function (tree decl, tree args)
7995 {
7996   tree new_friend;
7997
7998   if (TREE_CODE (decl) == FUNCTION_DECL
7999       && DECL_TEMPLATE_INSTANTIATION (decl)
8000       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
8001     /* This was a friend declared with an explicit template
8002        argument list, e.g.:
8003
8004        friend void f<>(T);
8005
8006        to indicate that f was a template instantiation, not a new
8007        function declaration.  Now, we have to figure out what
8008        instantiation of what template.  */
8009     {
8010       tree template_id, arglist, fns;
8011       tree new_args;
8012       tree tmpl;
8013       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
8014
8015       /* Friend functions are looked up in the containing namespace scope.
8016          We must enter that scope, to avoid finding member functions of the
8017          current class with same name.  */
8018       push_nested_namespace (ns);
8019       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
8020                          tf_warning_or_error, NULL_TREE,
8021                          /*integral_constant_expression_p=*/false);
8022       pop_nested_namespace (ns);
8023       arglist = tsubst (DECL_TI_ARGS (decl), args,
8024                         tf_warning_or_error, NULL_TREE);
8025       template_id = lookup_template_function (fns, arglist);
8026
8027       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
8028       tmpl = determine_specialization (template_id, new_friend,
8029                                        &new_args,
8030                                        /*need_member_template=*/0,
8031                                        TREE_VEC_LENGTH (args),
8032                                        tsk_none);
8033       return instantiate_template (tmpl, new_args, tf_error);
8034     }
8035
8036   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
8037
8038   /* The NEW_FRIEND will look like an instantiation, to the
8039      compiler, but is not an instantiation from the point of view of
8040      the language.  For example, we might have had:
8041
8042      template <class T> struct S {
8043        template <class U> friend void f(T, U);
8044      };
8045
8046      Then, in S<int>, template <class U> void f(int, U) is not an
8047      instantiation of anything.  */
8048   if (new_friend == error_mark_node)
8049     return error_mark_node;
8050
8051   DECL_USE_TEMPLATE (new_friend) = 0;
8052   if (TREE_CODE (decl) == TEMPLATE_DECL)
8053     {
8054       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
8055       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
8056         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
8057     }
8058
8059   /* The mangled name for the NEW_FRIEND is incorrect.  The function
8060      is not a template instantiation and should not be mangled like
8061      one.  Therefore, we forget the mangling here; we'll recompute it
8062      later if we need it.  */
8063   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
8064     {
8065       SET_DECL_RTL (new_friend, NULL);
8066       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
8067     }
8068
8069   if (DECL_NAMESPACE_SCOPE_P (new_friend))
8070     {
8071       tree old_decl;
8072       tree new_friend_template_info;
8073       tree new_friend_result_template_info;
8074       tree ns;
8075       int  new_friend_is_defn;
8076
8077       /* We must save some information from NEW_FRIEND before calling
8078          duplicate decls since that function will free NEW_FRIEND if
8079          possible.  */
8080       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
8081       new_friend_is_defn =
8082             (DECL_INITIAL (DECL_TEMPLATE_RESULT
8083                            (template_for_substitution (new_friend)))
8084              != NULL_TREE);
8085       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
8086         {
8087           /* This declaration is a `primary' template.  */
8088           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
8089
8090           new_friend_result_template_info
8091             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
8092         }
8093       else
8094         new_friend_result_template_info = NULL_TREE;
8095
8096       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
8097       if (new_friend_is_defn)
8098         DECL_INITIAL (new_friend) = error_mark_node;
8099
8100       /* Inside pushdecl_namespace_level, we will push into the
8101          current namespace. However, the friend function should go
8102          into the namespace of the template.  */
8103       ns = decl_namespace_context (new_friend);
8104       push_nested_namespace (ns);
8105       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
8106       pop_nested_namespace (ns);
8107
8108       if (old_decl == error_mark_node)
8109         return error_mark_node;
8110
8111       if (old_decl != new_friend)
8112         {
8113           /* This new friend declaration matched an existing
8114              declaration.  For example, given:
8115
8116                template <class T> void f(T);
8117                template <class U> class C {
8118                  template <class T> friend void f(T) {}
8119                };
8120
8121              the friend declaration actually provides the definition
8122              of `f', once C has been instantiated for some type.  So,
8123              old_decl will be the out-of-class template declaration,
8124              while new_friend is the in-class definition.
8125
8126              But, if `f' was called before this point, the
8127              instantiation of `f' will have DECL_TI_ARGS corresponding
8128              to `T' but not to `U', references to which might appear
8129              in the definition of `f'.  Previously, the most general
8130              template for an instantiation of `f' was the out-of-class
8131              version; now it is the in-class version.  Therefore, we
8132              run through all specialization of `f', adding to their
8133              DECL_TI_ARGS appropriately.  In particular, they need a
8134              new set of outer arguments, corresponding to the
8135              arguments for this class instantiation.
8136
8137              The same situation can arise with something like this:
8138
8139                friend void f(int);
8140                template <class T> class C {
8141                  friend void f(T) {}
8142                };
8143
8144              when `C<int>' is instantiated.  Now, `f(int)' is defined
8145              in the class.  */
8146
8147           if (!new_friend_is_defn)
8148             /* On the other hand, if the in-class declaration does
8149                *not* provide a definition, then we don't want to alter
8150                existing definitions.  We can just leave everything
8151                alone.  */
8152             ;
8153           else
8154             {
8155               tree new_template = TI_TEMPLATE (new_friend_template_info);
8156               tree new_args = TI_ARGS (new_friend_template_info);
8157
8158               /* Overwrite whatever template info was there before, if
8159                  any, with the new template information pertaining to
8160                  the declaration.  */
8161               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
8162
8163               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
8164                 {
8165                   /* We should have called reregister_specialization in
8166                      duplicate_decls.  */
8167                   gcc_assert (retrieve_specialization (new_template,
8168                                                        new_args, 0)
8169                               == old_decl);
8170
8171                   /* Instantiate it if the global has already been used.  */
8172                   if (DECL_ODR_USED (old_decl))
8173                     instantiate_decl (old_decl, /*defer_ok=*/true,
8174                                       /*expl_inst_class_mem_p=*/false);
8175                 }
8176               else
8177                 {
8178                   tree t;
8179
8180                   /* Indicate that the old function template is a partial
8181                      instantiation.  */
8182                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
8183                     = new_friend_result_template_info;
8184
8185                   gcc_assert (new_template
8186                               == most_general_template (new_template));
8187                   gcc_assert (new_template != old_decl);
8188
8189                   /* Reassign any specializations already in the hash table
8190                      to the new more general template, and add the
8191                      additional template args.  */
8192                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
8193                        t != NULL_TREE;
8194                        t = TREE_CHAIN (t))
8195                     {
8196                       tree spec = TREE_VALUE (t);
8197                       spec_entry elt;
8198
8199                       elt.tmpl = old_decl;
8200                       elt.args = DECL_TI_ARGS (spec);
8201                       elt.spec = NULL_TREE;
8202
8203                       htab_remove_elt (decl_specializations, &elt);
8204
8205                       DECL_TI_ARGS (spec)
8206                         = add_outermost_template_args (new_args,
8207                                                        DECL_TI_ARGS (spec));
8208
8209                       register_specialization
8210                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
8211
8212                     }
8213                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
8214                 }
8215             }
8216
8217           /* The information from NEW_FRIEND has been merged into OLD_DECL
8218              by duplicate_decls.  */
8219           new_friend = old_decl;
8220         }
8221     }
8222   else
8223     {
8224       tree context = DECL_CONTEXT (new_friend);
8225       bool dependent_p;
8226
8227       /* In the code
8228            template <class T> class C {
8229              template <class U> friend void C1<U>::f (); // case 1
8230              friend void C2<T>::f ();                    // case 2
8231            };
8232          we only need to make sure CONTEXT is a complete type for
8233          case 2.  To distinguish between the two cases, we note that
8234          CONTEXT of case 1 remains dependent type after tsubst while
8235          this isn't true for case 2.  */
8236       ++processing_template_decl;
8237       dependent_p = dependent_type_p (context);
8238       --processing_template_decl;
8239
8240       if (!dependent_p
8241           && !complete_type_or_else (context, NULL_TREE))
8242         return error_mark_node;
8243
8244       if (COMPLETE_TYPE_P (context))
8245         {
8246           /* Check to see that the declaration is really present, and,
8247              possibly obtain an improved declaration.  */
8248           tree fn = check_classfn (context,
8249                                    new_friend, NULL_TREE);
8250
8251           if (fn)
8252             new_friend = fn;
8253         }
8254     }
8255
8256   return new_friend;
8257 }
8258
8259 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
8260    template arguments, as for tsubst.
8261
8262    Returns an appropriate tsubst'd friend type or error_mark_node on
8263    failure.  */
8264
8265 static tree
8266 tsubst_friend_class (tree friend_tmpl, tree args)
8267 {
8268   tree friend_type;
8269   tree tmpl;
8270   tree context;
8271
8272   context = CP_DECL_CONTEXT (friend_tmpl);
8273
8274   if (context != global_namespace)
8275     {
8276       if (TREE_CODE (context) == NAMESPACE_DECL)
8277         push_nested_namespace (context);
8278       else
8279         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
8280     }
8281
8282   /* Look for a class template declaration.  We look for hidden names
8283      because two friend declarations of the same template are the
8284      same.  For example, in:
8285
8286        struct A { 
8287          template <typename> friend class F;
8288        };
8289        template <typename> struct B { 
8290          template <typename> friend class F;
8291        };
8292
8293      both F templates are the same.  */
8294   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
8295                            /*block_p=*/true, 0, 
8296                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
8297
8298   /* But, if we don't find one, it might be because we're in a
8299      situation like this:
8300
8301        template <class T>
8302        struct S {
8303          template <class U>
8304          friend struct S;
8305        };
8306
8307      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
8308      for `S<int>', not the TEMPLATE_DECL.  */
8309   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
8310     {
8311       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
8312       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
8313     }
8314
8315   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
8316     {
8317       /* The friend template has already been declared.  Just
8318          check to see that the declarations match, and install any new
8319          default parameters.  We must tsubst the default parameters,
8320          of course.  We only need the innermost template parameters
8321          because that is all that redeclare_class_template will look
8322          at.  */
8323       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
8324           > TMPL_ARGS_DEPTH (args))
8325         {
8326           tree parms;
8327           location_t saved_input_location;
8328           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
8329                                          args, tf_warning_or_error);
8330
8331           saved_input_location = input_location;
8332           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
8333           redeclare_class_template (TREE_TYPE (tmpl), parms);
8334           input_location = saved_input_location;
8335           
8336         }
8337
8338       friend_type = TREE_TYPE (tmpl);
8339     }
8340   else
8341     {
8342       /* The friend template has not already been declared.  In this
8343          case, the instantiation of the template class will cause the
8344          injection of this template into the global scope.  */
8345       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
8346       if (tmpl == error_mark_node)
8347         return error_mark_node;
8348
8349       /* The new TMPL is not an instantiation of anything, so we
8350          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
8351          the new type because that is supposed to be the corresponding
8352          template decl, i.e., TMPL.  */
8353       DECL_USE_TEMPLATE (tmpl) = 0;
8354       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
8355       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
8356       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
8357         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
8358
8359       /* Inject this template into the global scope.  */
8360       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
8361     }
8362
8363   if (context != global_namespace)
8364     {
8365       if (TREE_CODE (context) == NAMESPACE_DECL)
8366         pop_nested_namespace (context);
8367       else
8368         pop_nested_class ();
8369     }
8370
8371   return friend_type;
8372 }
8373
8374 /* Returns zero if TYPE cannot be completed later due to circularity.
8375    Otherwise returns one.  */
8376
8377 static int
8378 can_complete_type_without_circularity (tree type)
8379 {
8380   if (type == NULL_TREE || type == error_mark_node)
8381     return 0;
8382   else if (COMPLETE_TYPE_P (type))
8383     return 1;
8384   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
8385     return can_complete_type_without_circularity (TREE_TYPE (type));
8386   else if (CLASS_TYPE_P (type)
8387            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
8388     return 0;
8389   else
8390     return 1;
8391 }
8392
8393 /* Apply any attributes which had to be deferred until instantiation
8394    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
8395    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
8396
8397 static void
8398 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
8399                                 tree args, tsubst_flags_t complain, tree in_decl)
8400 {
8401   tree last_dep = NULL_TREE;
8402   tree t;
8403   tree *p;
8404
8405   for (t = attributes; t; t = TREE_CHAIN (t))
8406     if (ATTR_IS_DEPENDENT (t))
8407       {
8408         last_dep = t;
8409         attributes = copy_list (attributes);
8410         break;
8411       }
8412
8413   if (DECL_P (*decl_p))
8414     {
8415       if (TREE_TYPE (*decl_p) == error_mark_node)
8416         return;
8417       p = &DECL_ATTRIBUTES (*decl_p);
8418     }
8419   else
8420     p = &TYPE_ATTRIBUTES (*decl_p);
8421
8422   if (last_dep)
8423     {
8424       tree late_attrs = NULL_TREE;
8425       tree *q = &late_attrs;
8426
8427       for (*p = attributes; *p; )
8428         {
8429           t = *p;
8430           if (ATTR_IS_DEPENDENT (t))
8431             {
8432               *p = TREE_CHAIN (t);
8433               TREE_CHAIN (t) = NULL_TREE;
8434               /* If the first attribute argument is an identifier, don't
8435                  pass it through tsubst.  Attributes like mode, format,
8436                  cleanup and several target specific attributes expect it
8437                  unmodified.  */
8438               if (TREE_VALUE (t)
8439                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
8440                   && TREE_VALUE (TREE_VALUE (t))
8441                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
8442                       == IDENTIFIER_NODE))
8443                 {
8444                   tree chain
8445                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
8446                                    in_decl,
8447                                    /*integral_constant_expression_p=*/false);
8448                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
8449                     TREE_VALUE (t)
8450                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
8451                                    chain);
8452                 }
8453               else
8454                 TREE_VALUE (t)
8455                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
8456                                  /*integral_constant_expression_p=*/false);
8457               *q = t;
8458               q = &TREE_CHAIN (t);
8459             }
8460           else
8461             p = &TREE_CHAIN (t);
8462         }
8463
8464       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
8465     }
8466 }
8467
8468 /* Perform (or defer) access check for typedefs that were referenced
8469    from within the template TMPL code.
8470    This is a subroutine of instantiate_template and instantiate_class_template.
8471    TMPL is the template to consider and TARGS is the list of arguments of
8472    that template.  */
8473
8474 static void
8475 perform_typedefs_access_check (tree tmpl, tree targs)
8476 {
8477   location_t saved_location;
8478   int i;
8479   qualified_typedef_usage_t *iter;
8480
8481   if (!tmpl
8482       || (!CLASS_TYPE_P (tmpl)
8483           && TREE_CODE (tmpl) != FUNCTION_DECL))
8484     return;
8485
8486   saved_location = input_location;
8487   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
8488                     get_types_needing_access_check (tmpl),
8489                     i, iter)
8490     {
8491       tree type_decl = iter->typedef_decl;
8492       tree type_scope = iter->context;
8493
8494       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
8495         continue;
8496
8497       if (uses_template_parms (type_decl))
8498         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
8499       if (uses_template_parms (type_scope))
8500         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
8501
8502       /* Make access check error messages point to the location
8503          of the use of the typedef.  */
8504       input_location = iter->locus;
8505       perform_or_defer_access_check (TYPE_BINFO (type_scope),
8506                                      type_decl, type_decl);
8507     }
8508     input_location = saved_location;
8509 }
8510
8511 static tree
8512 instantiate_class_template_1 (tree type)
8513 {
8514   tree templ, args, pattern, t, member;
8515   tree typedecl;
8516   tree pbinfo;
8517   tree base_list;
8518   unsigned int saved_maximum_field_alignment;
8519
8520   if (type == error_mark_node)
8521     return error_mark_node;
8522
8523   if (COMPLETE_OR_OPEN_TYPE_P (type)
8524       || uses_template_parms (type))
8525     return type;
8526
8527   /* Figure out which template is being instantiated.  */
8528   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
8529   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
8530
8531   /* Determine what specialization of the original template to
8532      instantiate.  */
8533   t = most_specialized_class (type, templ, tf_warning_or_error);
8534   if (t == error_mark_node)
8535     {
8536       TYPE_BEING_DEFINED (type) = 1;
8537       return error_mark_node;
8538     }
8539   else if (t)
8540     {
8541       /* This TYPE is actually an instantiation of a partial
8542          specialization.  We replace the innermost set of ARGS with
8543          the arguments appropriate for substitution.  For example,
8544          given:
8545
8546            template <class T> struct S {};
8547            template <class T> struct S<T*> {};
8548
8549          and supposing that we are instantiating S<int*>, ARGS will
8550          presently be {int*} -- but we need {int}.  */
8551       pattern = TREE_TYPE (t);
8552       args = TREE_PURPOSE (t);
8553     }
8554   else
8555     {
8556       pattern = TREE_TYPE (templ);
8557       args = CLASSTYPE_TI_ARGS (type);
8558     }
8559
8560   /* If the template we're instantiating is incomplete, then clearly
8561      there's nothing we can do.  */
8562   if (!COMPLETE_TYPE_P (pattern))
8563     return type;
8564
8565   /* If we've recursively instantiated too many templates, stop.  */
8566   if (! push_tinst_level (type))
8567     return type;
8568
8569   /* Now we're really doing the instantiation.  Mark the type as in
8570      the process of being defined.  */
8571   TYPE_BEING_DEFINED (type) = 1;
8572
8573   /* We may be in the middle of deferred access check.  Disable
8574      it now.  */
8575   push_deferring_access_checks (dk_no_deferred);
8576
8577   push_to_top_level ();
8578   /* Use #pragma pack from the template context.  */
8579   saved_maximum_field_alignment = maximum_field_alignment;
8580   maximum_field_alignment = TYPE_PRECISION (pattern);
8581
8582   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
8583
8584   /* Set the input location to the most specialized template definition.
8585      This is needed if tsubsting causes an error.  */
8586   typedecl = TYPE_MAIN_DECL (pattern);
8587   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
8588     DECL_SOURCE_LOCATION (typedecl);
8589
8590   TYPE_PACKED (type) = TYPE_PACKED (pattern);
8591   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
8592   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
8593   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
8594   if (ANON_AGGR_TYPE_P (pattern))
8595     SET_ANON_AGGR_TYPE_P (type);
8596   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
8597     {
8598       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
8599       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
8600     }
8601   CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
8602
8603   pbinfo = TYPE_BINFO (pattern);
8604
8605   /* We should never instantiate a nested class before its enclosing
8606      class; we need to look up the nested class by name before we can
8607      instantiate it, and that lookup should instantiate the enclosing
8608      class.  */
8609   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
8610               || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
8611
8612   base_list = NULL_TREE;
8613   if (BINFO_N_BASE_BINFOS (pbinfo))
8614     {
8615       tree pbase_binfo;
8616       tree pushed_scope;
8617       int i;
8618
8619       /* We must enter the scope containing the type, as that is where
8620          the accessibility of types named in dependent bases are
8621          looked up from.  */
8622       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
8623
8624       /* Substitute into each of the bases to determine the actual
8625          basetypes.  */
8626       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
8627         {
8628           tree base;
8629           tree access = BINFO_BASE_ACCESS (pbinfo, i);
8630           tree expanded_bases = NULL_TREE;
8631           int idx, len = 1;
8632
8633           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
8634             {
8635               expanded_bases = 
8636                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
8637                                        args, tf_error, NULL_TREE);
8638               if (expanded_bases == error_mark_node)
8639                 continue;
8640
8641               len = TREE_VEC_LENGTH (expanded_bases);
8642             }
8643
8644           for (idx = 0; idx < len; idx++)
8645             {
8646               if (expanded_bases)
8647                 /* Extract the already-expanded base class.  */
8648                 base = TREE_VEC_ELT (expanded_bases, idx);
8649               else
8650                 /* Substitute to figure out the base class.  */
8651                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
8652                                NULL_TREE);
8653
8654               if (base == error_mark_node)
8655                 continue;
8656
8657               base_list = tree_cons (access, base, base_list);
8658               if (BINFO_VIRTUAL_P (pbase_binfo))
8659                 TREE_TYPE (base_list) = integer_type_node;
8660             }
8661         }
8662
8663       /* The list is now in reverse order; correct that.  */
8664       base_list = nreverse (base_list);
8665
8666       if (pushed_scope)
8667         pop_scope (pushed_scope);
8668     }
8669   /* Now call xref_basetypes to set up all the base-class
8670      information.  */
8671   xref_basetypes (type, base_list);
8672
8673   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
8674                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
8675                                   args, tf_error, NULL_TREE);
8676   fixup_attribute_variants (type);
8677
8678   /* Now that our base classes are set up, enter the scope of the
8679      class, so that name lookups into base classes, etc. will work
8680      correctly.  This is precisely analogous to what we do in
8681      begin_class_definition when defining an ordinary non-template
8682      class, except we also need to push the enclosing classes.  */
8683   push_nested_class (type);
8684
8685   /* Now members are processed in the order of declaration.  */
8686   for (member = CLASSTYPE_DECL_LIST (pattern);
8687        member; member = TREE_CHAIN (member))
8688     {
8689       tree t = TREE_VALUE (member);
8690
8691       if (TREE_PURPOSE (member))
8692         {
8693           if (TYPE_P (t))
8694             {
8695               /* Build new CLASSTYPE_NESTED_UTDS.  */
8696
8697               tree newtag;
8698               bool class_template_p;
8699
8700               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
8701                                   && TYPE_LANG_SPECIFIC (t)
8702                                   && CLASSTYPE_IS_TEMPLATE (t));
8703               /* If the member is a class template, then -- even after
8704                  substitution -- there may be dependent types in the
8705                  template argument list for the class.  We increment
8706                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
8707                  that function will assume that no types are dependent
8708                  when outside of a template.  */
8709               if (class_template_p)
8710                 ++processing_template_decl;
8711               newtag = tsubst (t, args, tf_error, NULL_TREE);
8712               if (class_template_p)
8713                 --processing_template_decl;
8714               if (newtag == error_mark_node)
8715                 continue;
8716
8717               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
8718                 {
8719                   tree name = TYPE_IDENTIFIER (t);
8720
8721                   if (class_template_p)
8722                     /* Unfortunately, lookup_template_class sets
8723                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
8724                        instantiation (i.e., for the type of a member
8725                        template class nested within a template class.)
8726                        This behavior is required for
8727                        maybe_process_partial_specialization to work
8728                        correctly, but is not accurate in this case;
8729                        the TAG is not an instantiation of anything.
8730                        (The corresponding TEMPLATE_DECL is an
8731                        instantiation, but the TYPE is not.) */
8732                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
8733
8734                   /* Now, we call pushtag to put this NEWTAG into the scope of
8735                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
8736                      pushtag calling push_template_decl.  We don't have to do
8737                      this for enums because it will already have been done in
8738                      tsubst_enum.  */
8739                   if (name)
8740                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
8741                   pushtag (name, newtag, /*tag_scope=*/ts_current);
8742                 }
8743             }
8744           else if (TREE_CODE (t) == FUNCTION_DECL
8745                    || DECL_FUNCTION_TEMPLATE_P (t))
8746             {
8747               /* Build new TYPE_METHODS.  */
8748               tree r;
8749
8750               if (TREE_CODE (t) == TEMPLATE_DECL)
8751                 ++processing_template_decl;
8752               r = tsubst (t, args, tf_error, NULL_TREE);
8753               if (TREE_CODE (t) == TEMPLATE_DECL)
8754                 --processing_template_decl;
8755               set_current_access_from_decl (r);
8756               finish_member_declaration (r);
8757               /* Instantiate members marked with attribute used.  */
8758               if (r != error_mark_node && DECL_PRESERVE_P (r))
8759                 mark_used (r);
8760             }
8761           else
8762             {
8763               /* Build new TYPE_FIELDS.  */
8764               if (TREE_CODE (t) == STATIC_ASSERT)
8765                 {
8766                   tree condition = 
8767                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
8768                                  tf_warning_or_error, NULL_TREE,
8769                                  /*integral_constant_expression_p=*/true);
8770                   finish_static_assert (condition,
8771                                         STATIC_ASSERT_MESSAGE (t), 
8772                                         STATIC_ASSERT_SOURCE_LOCATION (t),
8773                                         /*member_p=*/true);
8774                 }
8775               else if (TREE_CODE (t) != CONST_DECL)
8776                 {
8777                   tree r;
8778
8779                   /* The file and line for this declaration, to
8780                      assist in error message reporting.  Since we
8781                      called push_tinst_level above, we don't need to
8782                      restore these.  */
8783                   input_location = DECL_SOURCE_LOCATION (t);
8784
8785                   if (TREE_CODE (t) == TEMPLATE_DECL)
8786                     ++processing_template_decl;
8787                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
8788                   if (TREE_CODE (t) == TEMPLATE_DECL)
8789                     --processing_template_decl;
8790                   if (TREE_CODE (r) == VAR_DECL)
8791                     {
8792                       /* In [temp.inst]:
8793
8794                            [t]he initialization (and any associated
8795                            side-effects) of a static data member does
8796                            not occur unless the static data member is
8797                            itself used in a way that requires the
8798                            definition of the static data member to
8799                            exist.
8800
8801                          Therefore, we do not substitute into the
8802                          initialized for the static data member here.  */
8803                       finish_static_data_member_decl
8804                         (r,
8805                          /*init=*/NULL_TREE,
8806                          /*init_const_expr_p=*/false,
8807                          /*asmspec_tree=*/NULL_TREE,
8808                          /*flags=*/0);
8809                       /* Instantiate members marked with attribute used.  */
8810                       if (r != error_mark_node && DECL_PRESERVE_P (r))
8811                         mark_used (r);
8812                     }
8813                   else if (TREE_CODE (r) == FIELD_DECL)
8814                     {
8815                       /* Determine whether R has a valid type and can be
8816                          completed later.  If R is invalid, then it is
8817                          replaced by error_mark_node so that it will not be
8818                          added to TYPE_FIELDS.  */
8819                       tree rtype = TREE_TYPE (r);
8820                       if (can_complete_type_without_circularity (rtype))
8821                         complete_type (rtype);
8822
8823                       if (!COMPLETE_TYPE_P (rtype))
8824                         {
8825                           cxx_incomplete_type_error (r, rtype);
8826                           r = error_mark_node;
8827                         }
8828                     }
8829
8830                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
8831                      such a thing will already have been added to the field
8832                      list by tsubst_enum in finish_member_declaration in the
8833                      CLASSTYPE_NESTED_UTDS case above.  */
8834                   if (!(TREE_CODE (r) == TYPE_DECL
8835                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
8836                         && DECL_ARTIFICIAL (r)))
8837                     {
8838                       set_current_access_from_decl (r);
8839                       finish_member_declaration (r);
8840                     }
8841                 }
8842             }
8843         }
8844       else
8845         {
8846           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
8847             {
8848               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
8849
8850               tree friend_type = t;
8851               bool adjust_processing_template_decl = false;
8852
8853               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8854                 {
8855                   /* template <class T> friend class C;  */
8856                   friend_type = tsubst_friend_class (friend_type, args);
8857                   adjust_processing_template_decl = true;
8858                 }
8859               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
8860                 {
8861                   /* template <class T> friend class C::D;  */
8862                   friend_type = tsubst (friend_type, args,
8863                                         tf_warning_or_error, NULL_TREE);
8864                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8865                     friend_type = TREE_TYPE (friend_type);
8866                   adjust_processing_template_decl = true;
8867                 }
8868               else if (TREE_CODE (friend_type) == TYPENAME_TYPE
8869                        || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
8870                 {
8871                   /* This could be either
8872
8873                        friend class T::C;
8874
8875                      when dependent_type_p is false or
8876
8877                        template <class U> friend class T::C;
8878
8879                      otherwise.  */
8880                   friend_type = tsubst (friend_type, args,
8881                                         tf_warning_or_error, NULL_TREE);
8882                   /* Bump processing_template_decl for correct
8883                      dependent_type_p calculation.  */
8884                   ++processing_template_decl;
8885                   if (dependent_type_p (friend_type))
8886                     adjust_processing_template_decl = true;
8887                   --processing_template_decl;
8888                 }
8889               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
8890                        && hidden_name_p (TYPE_NAME (friend_type)))
8891                 {
8892                   /* friend class C;
8893
8894                      where C hasn't been declared yet.  Let's lookup name
8895                      from namespace scope directly, bypassing any name that
8896                      come from dependent base class.  */
8897                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
8898
8899                   /* The call to xref_tag_from_type does injection for friend
8900                      classes.  */
8901                   push_nested_namespace (ns);
8902                   friend_type =
8903                     xref_tag_from_type (friend_type, NULL_TREE,
8904                                         /*tag_scope=*/ts_current);
8905                   pop_nested_namespace (ns);
8906                 }
8907               else if (uses_template_parms (friend_type))
8908                 /* friend class C<T>;  */
8909                 friend_type = tsubst (friend_type, args,
8910                                       tf_warning_or_error, NULL_TREE);
8911               /* Otherwise it's
8912
8913                    friend class C;
8914
8915                  where C is already declared or
8916
8917                    friend class C<int>;
8918
8919                  We don't have to do anything in these cases.  */
8920
8921               if (adjust_processing_template_decl)
8922                 /* Trick make_friend_class into realizing that the friend
8923                    we're adding is a template, not an ordinary class.  It's
8924                    important that we use make_friend_class since it will
8925                    perform some error-checking and output cross-reference
8926                    information.  */
8927                 ++processing_template_decl;
8928
8929               if (friend_type != error_mark_node)
8930                 make_friend_class (type, friend_type, /*complain=*/false);
8931
8932               if (adjust_processing_template_decl)
8933                 --processing_template_decl;
8934             }
8935           else
8936             {
8937               /* Build new DECL_FRIENDLIST.  */
8938               tree r;
8939
8940               /* The file and line for this declaration, to
8941                  assist in error message reporting.  Since we
8942                  called push_tinst_level above, we don't need to
8943                  restore these.  */
8944               input_location = DECL_SOURCE_LOCATION (t);
8945
8946               if (TREE_CODE (t) == TEMPLATE_DECL)
8947                 {
8948                   ++processing_template_decl;
8949                   push_deferring_access_checks (dk_no_check);
8950                 }
8951
8952               r = tsubst_friend_function (t, args);
8953               add_friend (type, r, /*complain=*/false);
8954               if (TREE_CODE (t) == TEMPLATE_DECL)
8955                 {
8956                   pop_deferring_access_checks ();
8957                   --processing_template_decl;
8958                 }
8959             }
8960         }
8961     }
8962
8963   if (CLASSTYPE_LAMBDA_EXPR (type))
8964     {
8965       tree lambda = CLASSTYPE_LAMBDA_EXPR (type);
8966       if (LAMBDA_EXPR_DEDUCE_RETURN_TYPE_P (lambda))
8967         {
8968           apply_lambda_return_type (lambda, void_type_node);
8969           LAMBDA_EXPR_RETURN_TYPE (lambda) = NULL_TREE;
8970         }
8971       instantiate_decl (lambda_function (type), false, false);
8972       maybe_add_lambda_conv_op (type);
8973     }
8974
8975   /* Set the file and line number information to whatever is given for
8976      the class itself.  This puts error messages involving generated
8977      implicit functions at a predictable point, and the same point
8978      that would be used for non-template classes.  */
8979   input_location = DECL_SOURCE_LOCATION (typedecl);
8980
8981   unreverse_member_declarations (type);
8982   finish_struct_1 (type);
8983   TYPE_BEING_DEFINED (type) = 0;
8984
8985   /* We don't instantiate default arguments for member functions.  14.7.1:
8986
8987      The implicit instantiation of a class template specialization causes
8988      the implicit instantiation of the declarations, but not of the
8989      definitions or default arguments, of the class member functions,
8990      member classes, static data members and member templates....  */
8991
8992   /* Some typedefs referenced from within the template code need to be access
8993      checked at template instantiation time, i.e now. These types were
8994      added to the template at parsing time. Let's get those and perform
8995      the access checks then.  */
8996   perform_typedefs_access_check (pattern, args);
8997   perform_deferred_access_checks ();
8998   pop_nested_class ();
8999   maximum_field_alignment = saved_maximum_field_alignment;
9000   pop_from_top_level ();
9001   pop_deferring_access_checks ();
9002   pop_tinst_level ();
9003
9004   /* The vtable for a template class can be emitted in any translation
9005      unit in which the class is instantiated.  When there is no key
9006      method, however, finish_struct_1 will already have added TYPE to
9007      the keyed_classes list.  */
9008   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
9009     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
9010
9011   return type;
9012 }
9013
9014 /* Wrapper for instantiate_class_template_1.  */
9015
9016 tree
9017 instantiate_class_template (tree type)
9018 {
9019   tree ret;
9020   timevar_push (TV_TEMPLATE_INST);
9021   ret = instantiate_class_template_1 (type);
9022   timevar_pop (TV_TEMPLATE_INST);
9023   return ret;
9024 }
9025
9026 static tree
9027 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9028 {
9029   tree r;
9030
9031   if (!t)
9032     r = t;
9033   else if (TYPE_P (t))
9034     r = tsubst (t, args, complain, in_decl);
9035   else
9036     {
9037       if (!(complain & tf_warning))
9038         ++c_inhibit_evaluation_warnings;
9039       r = tsubst_expr (t, args, complain, in_decl,
9040                        /*integral_constant_expression_p=*/true);
9041       if (!(complain & tf_warning))
9042         --c_inhibit_evaluation_warnings;
9043       /* Preserve the raw-reference nature of T.  */
9044       if (TREE_TYPE (t) && TREE_CODE (TREE_TYPE (t)) == REFERENCE_TYPE
9045           && REFERENCE_REF_P (r))
9046         r = TREE_OPERAND (r, 0);
9047     }
9048   return r;
9049 }
9050
9051 /* Given a function parameter pack TMPL_PARM and some function parameters
9052    instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
9053    and set *SPEC_P to point at the next point in the list.  */
9054
9055 static tree
9056 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
9057 {
9058   /* Collect all of the extra "packed" parameters into an
9059      argument pack.  */
9060   tree parmvec;
9061   tree parmtypevec;
9062   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
9063   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
9064   tree spec_parm = *spec_p;
9065   int i, len;
9066
9067   for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
9068     if (tmpl_parm
9069         && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
9070       break;
9071
9072   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
9073   parmvec = make_tree_vec (len);
9074   parmtypevec = make_tree_vec (len);
9075   spec_parm = *spec_p;
9076   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
9077     {
9078       TREE_VEC_ELT (parmvec, i) = spec_parm;
9079       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
9080     }
9081
9082   /* Build the argument packs.  */
9083   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
9084   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
9085   TREE_TYPE (argpack) = argtypepack;
9086   *spec_p = spec_parm;
9087
9088   return argpack;
9089 }
9090
9091 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
9092    NONTYPE_ARGUMENT_PACK.  */
9093
9094 static tree
9095 make_fnparm_pack (tree spec_parm)
9096 {
9097   return extract_fnparm_pack (NULL_TREE, &spec_parm);
9098 }
9099
9100 /* Substitute ARGS into T, which is an pack expansion
9101    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
9102    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
9103    (if only a partial substitution could be performed) or
9104    ERROR_MARK_NODE if there was an error.  */
9105 tree
9106 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
9107                        tree in_decl)
9108 {
9109   tree pattern;
9110   tree pack, packs = NULL_TREE;
9111   bool unsubstituted_packs = false;
9112   int i, len = -1;
9113   tree result;
9114   htab_t saved_local_specializations = NULL;
9115
9116   gcc_assert (PACK_EXPANSION_P (t));
9117   pattern = PACK_EXPANSION_PATTERN (t);
9118
9119   /* Determine the argument packs that will instantiate the parameter
9120      packs used in the expansion expression. While we're at it,
9121      compute the number of arguments to be expanded and make sure it
9122      is consistent.  */
9123   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
9124        pack = TREE_CHAIN (pack))
9125     {
9126       tree parm_pack = TREE_VALUE (pack);
9127       tree arg_pack = NULL_TREE;
9128       tree orig_arg = NULL_TREE;
9129
9130       if (TREE_CODE (parm_pack) == PARM_DECL)
9131         {
9132           if (!cp_unevaluated_operand)
9133             arg_pack = retrieve_local_specialization (parm_pack);
9134           else
9135             {
9136               /* We can't rely on local_specializations for a parameter
9137                  name used later in a function declaration (such as in a
9138                  late-specified return type).  Even if it exists, it might
9139                  have the wrong value for a recursive call.  Just make a
9140                  dummy decl, since it's only used for its type.  */
9141               arg_pack = tsubst_decl (parm_pack, args, complain);
9142               if (arg_pack && FUNCTION_PARAMETER_PACK_P (arg_pack))
9143                 /* Partial instantiation of the parm_pack, we can't build
9144                    up an argument pack yet.  */
9145                 arg_pack = NULL_TREE;
9146               else
9147                 arg_pack = make_fnparm_pack (arg_pack);
9148             }
9149         }
9150       else
9151         {
9152           int level, idx, levels;
9153           template_parm_level_and_index (parm_pack, &level, &idx);
9154
9155           levels = TMPL_ARGS_DEPTH (args);
9156           if (level <= levels)
9157             arg_pack = TMPL_ARG (args, level, idx);
9158         }
9159
9160       orig_arg = arg_pack;
9161       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
9162         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
9163       
9164       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
9165         /* This can only happen if we forget to expand an argument
9166            pack somewhere else. Just return an error, silently.  */
9167         {
9168           result = make_tree_vec (1);
9169           TREE_VEC_ELT (result, 0) = error_mark_node;
9170           return result;
9171         }
9172
9173       if (arg_from_parm_pack_p (arg_pack, parm_pack))
9174         /* The argument pack that the parameter maps to is just an
9175            expansion of the parameter itself, such as one would find
9176            in the implicit typedef of a class inside the class itself.
9177            Consider this parameter "unsubstituted", so that we will
9178            maintain the outer pack expansion.  */
9179         arg_pack = NULL_TREE;
9180           
9181       if (arg_pack)
9182         {
9183           int my_len = 
9184             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
9185
9186           /* Don't bother trying to do a partial substitution with
9187              incomplete packs; we'll try again after deduction.  */
9188           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
9189             return t;
9190
9191           if (len < 0)
9192             len = my_len;
9193           else if (len != my_len)
9194             {
9195               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
9196                 error ("mismatched argument pack lengths while expanding "
9197                        "%<%T%>",
9198                        pattern);
9199               else
9200                 error ("mismatched argument pack lengths while expanding "
9201                        "%<%E%>",
9202                        pattern);
9203               return error_mark_node;
9204             }
9205
9206           /* Keep track of the parameter packs and their corresponding
9207              argument packs.  */
9208           packs = tree_cons (parm_pack, arg_pack, packs);
9209           TREE_TYPE (packs) = orig_arg;
9210         }
9211       else
9212         {
9213           /* We can't substitute for this parameter pack.  */
9214           unsubstituted_packs = true;
9215           break;
9216         }
9217     }
9218
9219   /* We cannot expand this expansion expression, because we don't have
9220      all of the argument packs we need. Substitute into the pattern
9221      and return a PACK_EXPANSION_*. The caller will need to deal with
9222      that.  */
9223   if (unsubstituted_packs)
9224     {
9225       tree new_pat;
9226       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
9227         new_pat = tsubst_expr (pattern, args, complain, in_decl,
9228                                /*integral_constant_expression_p=*/false);
9229       else
9230         new_pat = tsubst (pattern, args, complain, in_decl);
9231       return make_pack_expansion (new_pat);
9232     }
9233
9234   /* We could not find any argument packs that work.  */
9235   if (len < 0)
9236     return error_mark_node;
9237
9238   if (cp_unevaluated_operand)
9239     {
9240       /* We're in a late-specified return type, so create our own local
9241          specializations table; the current table is either NULL or (in the
9242          case of recursive unification) might have bindings that we don't
9243          want to use or alter.  */
9244       saved_local_specializations = local_specializations;
9245       local_specializations = htab_create (37,
9246                                            hash_local_specialization,
9247                                            eq_local_specializations,
9248                                            NULL);
9249     }
9250
9251   /* For each argument in each argument pack, substitute into the
9252      pattern.  */
9253   result = make_tree_vec (len);
9254   for (i = 0; i < len; ++i)
9255     {
9256       /* For parameter pack, change the substitution of the parameter
9257          pack to the ith argument in its argument pack, then expand
9258          the pattern.  */
9259       for (pack = packs; pack; pack = TREE_CHAIN (pack))
9260         {
9261           tree parm = TREE_PURPOSE (pack);
9262           tree arg;
9263
9264           /* Select the Ith argument from the pack.  */
9265           if (TREE_CODE (parm) == PARM_DECL)
9266             {
9267               if (i == 0)
9268                 {
9269                   arg = make_node (ARGUMENT_PACK_SELECT);
9270                   ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
9271                   mark_used (parm);
9272                   register_local_specialization (arg, parm);
9273                 }
9274               else
9275                 arg = retrieve_local_specialization (parm);
9276             }
9277           else
9278             {
9279               int idx, level;
9280               template_parm_level_and_index (parm, &level, &idx);
9281
9282               if (i == 0)
9283                 {
9284                   arg = make_node (ARGUMENT_PACK_SELECT);
9285                   ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
9286                   /* Update the corresponding argument.  */
9287                   TMPL_ARG (args, level, idx) = arg;
9288                 }
9289               else
9290                 /* Re-use the ARGUMENT_PACK_SELECT.  */
9291                 arg = TMPL_ARG (args, level, idx);
9292             }
9293           ARGUMENT_PACK_SELECT_INDEX (arg) = i;
9294         }
9295
9296       /* Substitute into the PATTERN with the altered arguments.  */
9297       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
9298         TREE_VEC_ELT (result, i) = 
9299           tsubst_expr (pattern, args, complain, in_decl,
9300                        /*integral_constant_expression_p=*/false);
9301       else
9302         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
9303
9304       if (TREE_VEC_ELT (result, i) == error_mark_node)
9305         {
9306           result = error_mark_node;
9307           break;
9308         }
9309     }
9310
9311   /* Update ARGS to restore the substitution from parameter packs to
9312      their argument packs.  */
9313   for (pack = packs; pack; pack = TREE_CHAIN (pack))
9314     {
9315       tree parm = TREE_PURPOSE (pack);
9316
9317       if (TREE_CODE (parm) == PARM_DECL)
9318         register_local_specialization (TREE_TYPE (pack), parm);
9319       else
9320         {
9321           int idx, level;
9322           template_parm_level_and_index (parm, &level, &idx);
9323           
9324           /* Update the corresponding argument.  */
9325           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
9326             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
9327               TREE_TYPE (pack);
9328           else
9329             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
9330         }
9331     }
9332
9333   if (saved_local_specializations)
9334     {
9335       htab_delete (local_specializations);
9336       local_specializations = saved_local_specializations;
9337     }
9338   
9339   return result;
9340 }
9341
9342 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
9343    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
9344    parameter packs; all parms generated from a function parameter pack will
9345    have the same DECL_PARM_INDEX.  */
9346
9347 tree
9348 get_pattern_parm (tree parm, tree tmpl)
9349 {
9350   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
9351   tree patparm;
9352
9353   if (DECL_ARTIFICIAL (parm))
9354     {
9355       for (patparm = DECL_ARGUMENTS (pattern);
9356            patparm; patparm = DECL_CHAIN (patparm))
9357         if (DECL_ARTIFICIAL (patparm)
9358             && DECL_NAME (parm) == DECL_NAME (patparm))
9359           break;
9360     }
9361   else
9362     {
9363       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
9364       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
9365       gcc_assert (DECL_PARM_INDEX (patparm)
9366                   == DECL_PARM_INDEX (parm));
9367     }
9368
9369   return patparm;
9370 }
9371
9372 /* Substitute ARGS into the vector or list of template arguments T.  */
9373
9374 static tree
9375 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9376 {
9377   tree orig_t = t;
9378   int len, need_new = 0, i, expanded_len_adjust = 0, out;
9379   tree *elts;
9380
9381   if (t == error_mark_node)
9382     return error_mark_node;
9383
9384   len = TREE_VEC_LENGTH (t);
9385   elts = XALLOCAVEC (tree, len);
9386
9387   for (i = 0; i < len; i++)
9388     {
9389       tree orig_arg = TREE_VEC_ELT (t, i);
9390       tree new_arg;
9391
9392       if (TREE_CODE (orig_arg) == TREE_VEC)
9393         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
9394       else if (PACK_EXPANSION_P (orig_arg))
9395         {
9396           /* Substitute into an expansion expression.  */
9397           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
9398
9399           if (TREE_CODE (new_arg) == TREE_VEC)
9400             /* Add to the expanded length adjustment the number of
9401                expanded arguments. We subtract one from this
9402                measurement, because the argument pack expression
9403                itself is already counted as 1 in
9404                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
9405                the argument pack is empty.  */
9406             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
9407         }
9408       else if (ARGUMENT_PACK_P (orig_arg))
9409         {
9410           /* Substitute into each of the arguments.  */
9411           new_arg = TYPE_P (orig_arg)
9412             ? cxx_make_type (TREE_CODE (orig_arg))
9413             : make_node (TREE_CODE (orig_arg));
9414           
9415           SET_ARGUMENT_PACK_ARGS (
9416             new_arg,
9417             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
9418                                   args, complain, in_decl));
9419
9420           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
9421             new_arg = error_mark_node;
9422
9423           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
9424             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
9425                                           complain, in_decl);
9426             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
9427
9428             if (TREE_TYPE (new_arg) == error_mark_node)
9429               new_arg = error_mark_node;
9430           }
9431         }
9432       else
9433         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
9434
9435       if (new_arg == error_mark_node)
9436         return error_mark_node;
9437
9438       elts[i] = new_arg;
9439       if (new_arg != orig_arg)
9440         need_new = 1;
9441     }
9442
9443   if (!need_new)
9444     return t;
9445
9446   /* Make space for the expanded arguments coming from template
9447      argument packs.  */
9448   t = make_tree_vec (len + expanded_len_adjust);
9449   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
9450      arguments for a member template.
9451      In that case each TREE_VEC in ORIG_T represents a level of template
9452      arguments, and ORIG_T won't carry any non defaulted argument count.
9453      It will rather be the nested TREE_VECs that will carry one.
9454      In other words, ORIG_T carries a non defaulted argument count only
9455      if it doesn't contain any nested TREE_VEC.  */
9456   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
9457     {
9458       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
9459       count += expanded_len_adjust;
9460       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
9461     }
9462   for (i = 0, out = 0; i < len; i++)
9463     {
9464       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
9465            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
9466           && TREE_CODE (elts[i]) == TREE_VEC)
9467         {
9468           int idx;
9469
9470           /* Now expand the template argument pack "in place".  */
9471           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
9472             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
9473         }
9474       else
9475         {
9476           TREE_VEC_ELT (t, out) = elts[i];
9477           out++;
9478         }
9479     }
9480
9481   return t;
9482 }
9483
9484 /* Return the result of substituting ARGS into the template parameters
9485    given by PARMS.  If there are m levels of ARGS and m + n levels of
9486    PARMS, then the result will contain n levels of PARMS.  For
9487    example, if PARMS is `template <class T> template <class U>
9488    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
9489    result will be `template <int*, double, class V>'.  */
9490
9491 static tree
9492 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
9493 {
9494   tree r = NULL_TREE;
9495   tree* new_parms;
9496
9497   /* When substituting into a template, we must set
9498      PROCESSING_TEMPLATE_DECL as the template parameters may be
9499      dependent if they are based on one-another, and the dependency
9500      predicates are short-circuit outside of templates.  */
9501   ++processing_template_decl;
9502
9503   for (new_parms = &r;
9504        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
9505        new_parms = &(TREE_CHAIN (*new_parms)),
9506          parms = TREE_CHAIN (parms))
9507     {
9508       tree new_vec =
9509         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
9510       int i;
9511
9512       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
9513         {
9514           tree tuple;
9515
9516           if (parms == error_mark_node)
9517             continue;
9518
9519           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
9520
9521           if (tuple == error_mark_node)
9522             continue;
9523
9524           TREE_VEC_ELT (new_vec, i) =
9525             tsubst_template_parm (tuple, args, complain);
9526         }
9527
9528       *new_parms =
9529         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
9530                              - TMPL_ARGS_DEPTH (args)),
9531                    new_vec, NULL_TREE);
9532     }
9533
9534   --processing_template_decl;
9535
9536   return r;
9537 }
9538
9539 /* Return the result of substituting ARGS into one template parameter
9540    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
9541    parameter and which TREE_PURPOSE is the default argument of the
9542    template parameter.  */
9543
9544 static tree
9545 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
9546 {
9547   tree default_value, parm_decl;
9548
9549   if (args == NULL_TREE
9550       || t == NULL_TREE
9551       || t == error_mark_node)
9552     return t;
9553
9554   gcc_assert (TREE_CODE (t) == TREE_LIST);
9555
9556   default_value = TREE_PURPOSE (t);
9557   parm_decl = TREE_VALUE (t);
9558
9559   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
9560   if (TREE_CODE (parm_decl) == PARM_DECL
9561       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
9562     parm_decl = error_mark_node;
9563   default_value = tsubst_template_arg (default_value, args,
9564                                        complain, NULL_TREE);
9565
9566   return build_tree_list (default_value, parm_decl);
9567 }
9568
9569 /* Substitute the ARGS into the indicated aggregate (or enumeration)
9570    type T.  If T is not an aggregate or enumeration type, it is
9571    handled as if by tsubst.  IN_DECL is as for tsubst.  If
9572    ENTERING_SCOPE is nonzero, T is the context for a template which
9573    we are presently tsubst'ing.  Return the substituted value.  */
9574
9575 static tree
9576 tsubst_aggr_type (tree t,
9577                   tree args,
9578                   tsubst_flags_t complain,
9579                   tree in_decl,
9580                   int entering_scope)
9581 {
9582   if (t == NULL_TREE)
9583     return NULL_TREE;
9584
9585   switch (TREE_CODE (t))
9586     {
9587     case RECORD_TYPE:
9588       if (TYPE_PTRMEMFUNC_P (t))
9589         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
9590
9591       /* Else fall through.  */
9592     case ENUMERAL_TYPE:
9593     case UNION_TYPE:
9594       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
9595         {
9596           tree argvec;
9597           tree context;
9598           tree r;
9599           int saved_unevaluated_operand;
9600           int saved_inhibit_evaluation_warnings;
9601
9602           /* In "sizeof(X<I>)" we need to evaluate "I".  */
9603           saved_unevaluated_operand = cp_unevaluated_operand;
9604           cp_unevaluated_operand = 0;
9605           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
9606           c_inhibit_evaluation_warnings = 0;
9607
9608           /* First, determine the context for the type we are looking
9609              up.  */
9610           context = TYPE_CONTEXT (t);
9611           if (context && TYPE_P (context))
9612             {
9613               context = tsubst_aggr_type (context, args, complain,
9614                                           in_decl, /*entering_scope=*/1);
9615               /* If context is a nested class inside a class template,
9616                  it may still need to be instantiated (c++/33959).  */
9617               context = complete_type (context);
9618             }
9619
9620           /* Then, figure out what arguments are appropriate for the
9621              type we are trying to find.  For example, given:
9622
9623                template <class T> struct S;
9624                template <class T, class U> void f(T, U) { S<U> su; }
9625
9626              and supposing that we are instantiating f<int, double>,
9627              then our ARGS will be {int, double}, but, when looking up
9628              S we only want {double}.  */
9629           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
9630                                          complain, in_decl);
9631           if (argvec == error_mark_node)
9632             r = error_mark_node;
9633           else
9634             {
9635               r = lookup_template_class (t, argvec, in_decl, context,
9636                                          entering_scope, complain);
9637               r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
9638             }
9639
9640           cp_unevaluated_operand = saved_unevaluated_operand;
9641           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
9642
9643           return r;
9644         }
9645       else
9646         /* This is not a template type, so there's nothing to do.  */
9647         return t;
9648
9649     default:
9650       return tsubst (t, args, complain, in_decl);
9651     }
9652 }
9653
9654 /* Substitute into the default argument ARG (a default argument for
9655    FN), which has the indicated TYPE.  */
9656
9657 tree
9658 tsubst_default_argument (tree fn, tree type, tree arg)
9659 {
9660   tree saved_class_ptr = NULL_TREE;
9661   tree saved_class_ref = NULL_TREE;
9662
9663   /* This can happen in invalid code.  */
9664   if (TREE_CODE (arg) == DEFAULT_ARG)
9665     return arg;
9666
9667   /* This default argument came from a template.  Instantiate the
9668      default argument here, not in tsubst.  In the case of
9669      something like:
9670
9671        template <class T>
9672        struct S {
9673          static T t();
9674          void f(T = t());
9675        };
9676
9677      we must be careful to do name lookup in the scope of S<T>,
9678      rather than in the current class.  */
9679   push_access_scope (fn);
9680   /* The "this" pointer is not valid in a default argument.  */
9681   if (cfun)
9682     {
9683       saved_class_ptr = current_class_ptr;
9684       cp_function_chain->x_current_class_ptr = NULL_TREE;
9685       saved_class_ref = current_class_ref;
9686       cp_function_chain->x_current_class_ref = NULL_TREE;
9687     }
9688
9689   push_deferring_access_checks(dk_no_deferred);
9690   /* The default argument expression may cause implicitly defined
9691      member functions to be synthesized, which will result in garbage
9692      collection.  We must treat this situation as if we were within
9693      the body of function so as to avoid collecting live data on the
9694      stack.  */
9695   ++function_depth;
9696   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
9697                      tf_warning_or_error, NULL_TREE,
9698                      /*integral_constant_expression_p=*/false);
9699   --function_depth;
9700   pop_deferring_access_checks();
9701
9702   /* Restore the "this" pointer.  */
9703   if (cfun)
9704     {
9705       cp_function_chain->x_current_class_ptr = saved_class_ptr;
9706       cp_function_chain->x_current_class_ref = saved_class_ref;
9707     }
9708
9709   /* Make sure the default argument is reasonable.  */
9710   arg = check_default_argument (type, arg);
9711
9712   pop_access_scope (fn);
9713
9714   return arg;
9715 }
9716
9717 /* Substitute into all the default arguments for FN.  */
9718
9719 static void
9720 tsubst_default_arguments (tree fn)
9721 {
9722   tree arg;
9723   tree tmpl_args;
9724
9725   tmpl_args = DECL_TI_ARGS (fn);
9726
9727   /* If this function is not yet instantiated, we certainly don't need
9728      its default arguments.  */
9729   if (uses_template_parms (tmpl_args))
9730     return;
9731   /* Don't do this again for clones.  */
9732   if (DECL_CLONED_FUNCTION_P (fn))
9733     return;
9734
9735   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
9736        arg;
9737        arg = TREE_CHAIN (arg))
9738     if (TREE_PURPOSE (arg))
9739       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
9740                                                     TREE_VALUE (arg),
9741                                                     TREE_PURPOSE (arg));
9742 }
9743
9744 /* Substitute the ARGS into the T, which is a _DECL.  Return the
9745    result of the substitution.  Issue error and warning messages under
9746    control of COMPLAIN.  */
9747
9748 static tree
9749 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
9750 {
9751 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
9752   location_t saved_loc;
9753   tree r = NULL_TREE;
9754   tree in_decl = t;
9755   hashval_t hash = 0;
9756
9757   /* Set the filename and linenumber to improve error-reporting.  */
9758   saved_loc = input_location;
9759   input_location = DECL_SOURCE_LOCATION (t);
9760
9761   switch (TREE_CODE (t))
9762     {
9763     case TEMPLATE_DECL:
9764       {
9765         /* We can get here when processing a member function template,
9766            member class template, or template template parameter.  */
9767         tree decl = DECL_TEMPLATE_RESULT (t);
9768         tree spec;
9769         tree tmpl_args;
9770         tree full_args;
9771
9772         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9773           {
9774             /* Template template parameter is treated here.  */
9775             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9776             if (new_type == error_mark_node)
9777               RETURN (error_mark_node);
9778
9779             r = copy_decl (t);
9780             DECL_CHAIN (r) = NULL_TREE;
9781             TREE_TYPE (r) = new_type;
9782             DECL_TEMPLATE_RESULT (r)
9783               = build_decl (DECL_SOURCE_LOCATION (decl),
9784                             TYPE_DECL, DECL_NAME (decl), new_type);
9785             DECL_TEMPLATE_PARMS (r)
9786               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9787                                        complain);
9788             TYPE_NAME (new_type) = r;
9789             break;
9790           }
9791
9792         /* We might already have an instance of this template.
9793            The ARGS are for the surrounding class type, so the
9794            full args contain the tsubst'd args for the context,
9795            plus the innermost args from the template decl.  */
9796         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
9797           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
9798           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
9799         /* Because this is a template, the arguments will still be
9800            dependent, even after substitution.  If
9801            PROCESSING_TEMPLATE_DECL is not set, the dependency
9802            predicates will short-circuit.  */
9803         ++processing_template_decl;
9804         full_args = tsubst_template_args (tmpl_args, args,
9805                                           complain, in_decl);
9806         --processing_template_decl;
9807         if (full_args == error_mark_node)
9808           RETURN (error_mark_node);
9809
9810         /* If this is a default template template argument,
9811            tsubst might not have changed anything.  */
9812         if (full_args == tmpl_args)
9813           RETURN (t);
9814
9815         hash = hash_tmpl_and_args (t, full_args);
9816         spec = retrieve_specialization (t, full_args, hash);
9817         if (spec != NULL_TREE)
9818           {
9819             r = spec;
9820             break;
9821           }
9822
9823         /* Make a new template decl.  It will be similar to the
9824            original, but will record the current template arguments.
9825            We also create a new function declaration, which is just
9826            like the old one, but points to this new template, rather
9827            than the old one.  */
9828         r = copy_decl (t);
9829         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
9830         DECL_CHAIN (r) = NULL_TREE;
9831
9832         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
9833
9834         if (TREE_CODE (decl) == TYPE_DECL)
9835           {
9836             tree new_type;
9837             ++processing_template_decl;
9838             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9839             --processing_template_decl;
9840             if (new_type == error_mark_node)
9841               RETURN (error_mark_node);
9842
9843             TREE_TYPE (r) = new_type;
9844             CLASSTYPE_TI_TEMPLATE (new_type) = r;
9845             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
9846             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
9847             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
9848           }
9849         else
9850           {
9851             tree new_decl;
9852             ++processing_template_decl;
9853             new_decl = tsubst (decl, args, complain, in_decl);
9854             --processing_template_decl;
9855             if (new_decl == error_mark_node)
9856               RETURN (error_mark_node);
9857
9858             DECL_TEMPLATE_RESULT (r) = new_decl;
9859             DECL_TI_TEMPLATE (new_decl) = r;
9860             TREE_TYPE (r) = TREE_TYPE (new_decl);
9861             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
9862             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
9863           }
9864
9865         SET_DECL_IMPLICIT_INSTANTIATION (r);
9866         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
9867         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
9868
9869         /* The template parameters for this new template are all the
9870            template parameters for the old template, except the
9871            outermost level of parameters.  */
9872         DECL_TEMPLATE_PARMS (r)
9873           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9874                                    complain);
9875
9876         if (PRIMARY_TEMPLATE_P (t))
9877           DECL_PRIMARY_TEMPLATE (r) = r;
9878
9879         if (TREE_CODE (decl) != TYPE_DECL)
9880           /* Record this non-type partial instantiation.  */
9881           register_specialization (r, t,
9882                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
9883                                    false, hash);
9884       }
9885       break;
9886
9887     case FUNCTION_DECL:
9888       {
9889         tree ctx;
9890         tree argvec = NULL_TREE;
9891         tree *friends;
9892         tree gen_tmpl;
9893         tree type;
9894         int member;
9895         int args_depth;
9896         int parms_depth;
9897
9898         /* Nobody should be tsubst'ing into non-template functions.  */
9899         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
9900
9901         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
9902           {
9903             tree spec;
9904             bool dependent_p;
9905
9906             /* If T is not dependent, just return it.  We have to
9907                increment PROCESSING_TEMPLATE_DECL because
9908                value_dependent_expression_p assumes that nothing is
9909                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
9910             ++processing_template_decl;
9911             dependent_p = value_dependent_expression_p (t);
9912             --processing_template_decl;
9913             if (!dependent_p)
9914               RETURN (t);
9915
9916             /* Calculate the most general template of which R is a
9917                specialization, and the complete set of arguments used to
9918                specialize R.  */
9919             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
9920             argvec = tsubst_template_args (DECL_TI_ARGS
9921                                           (DECL_TEMPLATE_RESULT
9922                                                  (DECL_TI_TEMPLATE (t))),
9923                                            args, complain, in_decl);
9924             if (argvec == error_mark_node)
9925               RETURN (error_mark_node);
9926
9927             /* Check to see if we already have this specialization.  */
9928             hash = hash_tmpl_and_args (gen_tmpl, argvec);
9929             spec = retrieve_specialization (gen_tmpl, argvec, hash);
9930
9931             if (spec)
9932               {
9933                 r = spec;
9934                 break;
9935               }
9936
9937             /* We can see more levels of arguments than parameters if
9938                there was a specialization of a member template, like
9939                this:
9940
9941                  template <class T> struct S { template <class U> void f(); }
9942                  template <> template <class U> void S<int>::f(U);
9943
9944                Here, we'll be substituting into the specialization,
9945                because that's where we can find the code we actually
9946                want to generate, but we'll have enough arguments for
9947                the most general template.
9948
9949                We also deal with the peculiar case:
9950
9951                  template <class T> struct S {
9952                    template <class U> friend void f();
9953                  };
9954                  template <class U> void f() {}
9955                  template S<int>;
9956                  template void f<double>();
9957
9958                Here, the ARGS for the instantiation of will be {int,
9959                double}.  But, we only need as many ARGS as there are
9960                levels of template parameters in CODE_PATTERN.  We are
9961                careful not to get fooled into reducing the ARGS in
9962                situations like:
9963
9964                  template <class T> struct S { template <class U> void f(U); }
9965                  template <class T> template <> void S<T>::f(int) {}
9966
9967                which we can spot because the pattern will be a
9968                specialization in this case.  */
9969             args_depth = TMPL_ARGS_DEPTH (args);
9970             parms_depth =
9971               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
9972             if (args_depth > parms_depth
9973                 && !DECL_TEMPLATE_SPECIALIZATION (t))
9974               args = get_innermost_template_args (args, parms_depth);
9975           }
9976         else
9977           {
9978             /* This special case arises when we have something like this:
9979
9980                  template <class T> struct S {
9981                    friend void f<int>(int, double);
9982                  };
9983
9984                Here, the DECL_TI_TEMPLATE for the friend declaration
9985                will be an IDENTIFIER_NODE.  We are being called from
9986                tsubst_friend_function, and we want only to create a
9987                new decl (R) with appropriate types so that we can call
9988                determine_specialization.  */
9989             gen_tmpl = NULL_TREE;
9990           }
9991
9992         if (DECL_CLASS_SCOPE_P (t))
9993           {
9994             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
9995               member = 2;
9996             else
9997               member = 1;
9998             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
9999                                     complain, t, /*entering_scope=*/1);
10000           }
10001         else
10002           {
10003             member = 0;
10004             ctx = DECL_CONTEXT (t);
10005           }
10006         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10007         if (type == error_mark_node)
10008           RETURN (error_mark_node);
10009
10010         /* We do NOT check for matching decls pushed separately at this
10011            point, as they may not represent instantiations of this
10012            template, and in any case are considered separate under the
10013            discrete model.  */
10014         r = copy_decl (t);
10015         DECL_USE_TEMPLATE (r) = 0;
10016         TREE_TYPE (r) = type;
10017         /* Clear out the mangled name and RTL for the instantiation.  */
10018         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
10019         SET_DECL_RTL (r, NULL);
10020         /* Leave DECL_INITIAL set on deleted instantiations.  */
10021         if (!DECL_DELETED_FN (r))
10022           DECL_INITIAL (r) = NULL_TREE;
10023         DECL_CONTEXT (r) = ctx;
10024
10025         if (member && DECL_CONV_FN_P (r))
10026           /* Type-conversion operator.  Reconstruct the name, in
10027              case it's the name of one of the template's parameters.  */
10028           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
10029
10030         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
10031                                      complain, t);
10032         DECL_RESULT (r) = NULL_TREE;
10033
10034         TREE_STATIC (r) = 0;
10035         TREE_PUBLIC (r) = TREE_PUBLIC (t);
10036         DECL_EXTERNAL (r) = 1;
10037         /* If this is an instantiation of a function with internal
10038            linkage, we already know what object file linkage will be
10039            assigned to the instantiation.  */
10040         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
10041         DECL_DEFER_OUTPUT (r) = 0;
10042         DECL_CHAIN (r) = NULL_TREE;
10043         DECL_PENDING_INLINE_INFO (r) = 0;
10044         DECL_PENDING_INLINE_P (r) = 0;
10045         DECL_SAVED_TREE (r) = NULL_TREE;
10046         DECL_STRUCT_FUNCTION (r) = NULL;
10047         TREE_USED (r) = 0;
10048         /* We'll re-clone as appropriate in instantiate_template.  */
10049         DECL_CLONED_FUNCTION (r) = NULL_TREE;
10050
10051         /* If we aren't complaining now, return on error before we register
10052            the specialization so that we'll complain eventually.  */
10053         if ((complain & tf_error) == 0
10054             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
10055             && !grok_op_properties (r, /*complain=*/false))
10056           RETURN (error_mark_node);
10057
10058         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
10059            this in the special friend case mentioned above where
10060            GEN_TMPL is NULL.  */
10061         if (gen_tmpl)
10062           {
10063             DECL_TEMPLATE_INFO (r)
10064               = build_template_info (gen_tmpl, argvec);
10065             SET_DECL_IMPLICIT_INSTANTIATION (r);
10066             register_specialization (r, gen_tmpl, argvec, false, hash);
10067
10068             /* We're not supposed to instantiate default arguments
10069                until they are called, for a template.  But, for a
10070                declaration like:
10071
10072                  template <class T> void f ()
10073                  { extern void g(int i = T()); }
10074
10075                we should do the substitution when the template is
10076                instantiated.  We handle the member function case in
10077                instantiate_class_template since the default arguments
10078                might refer to other members of the class.  */
10079             if (!member
10080                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
10081                 && !uses_template_parms (argvec))
10082               tsubst_default_arguments (r);
10083           }
10084         else
10085           DECL_TEMPLATE_INFO (r) = NULL_TREE;
10086
10087         /* Copy the list of befriending classes.  */
10088         for (friends = &DECL_BEFRIENDING_CLASSES (r);
10089              *friends;
10090              friends = &TREE_CHAIN (*friends))
10091           {
10092             *friends = copy_node (*friends);
10093             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
10094                                             args, complain,
10095                                             in_decl);
10096           }
10097
10098         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
10099           {
10100             maybe_retrofit_in_chrg (r);
10101             if (DECL_CONSTRUCTOR_P (r))
10102               grok_ctor_properties (ctx, r);
10103             /* If this is an instantiation of a member template, clone it.
10104                If it isn't, that'll be handled by
10105                clone_constructors_and_destructors.  */
10106             if (PRIMARY_TEMPLATE_P (gen_tmpl))
10107               clone_function_decl (r, /*update_method_vec_p=*/0);
10108           }
10109         else if ((complain & tf_error) != 0
10110                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
10111                  && !grok_op_properties (r, /*complain=*/true))
10112           RETURN (error_mark_node);
10113
10114         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
10115           SET_DECL_FRIEND_CONTEXT (r,
10116                                    tsubst (DECL_FRIEND_CONTEXT (t),
10117                                             args, complain, in_decl));
10118
10119         /* Possibly limit visibility based on template args.  */
10120         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10121         if (DECL_VISIBILITY_SPECIFIED (t))
10122           {
10123             DECL_VISIBILITY_SPECIFIED (r) = 0;
10124             DECL_ATTRIBUTES (r)
10125               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10126           }
10127         determine_visibility (r);
10128         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
10129             && !processing_template_decl)
10130           defaulted_late_check (r);
10131
10132         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10133                                         args, complain, in_decl);
10134       }
10135       break;
10136
10137     case PARM_DECL:
10138       {
10139         tree type = NULL_TREE;
10140         int i, len = 1;
10141         tree expanded_types = NULL_TREE;
10142         tree prev_r = NULL_TREE;
10143         tree first_r = NULL_TREE;
10144
10145         if (FUNCTION_PARAMETER_PACK_P (t))
10146           {
10147             /* If there is a local specialization that isn't a
10148                parameter pack, it means that we're doing a "simple"
10149                substitution from inside tsubst_pack_expansion. Just
10150                return the local specialization (which will be a single
10151                parm).  */
10152             tree spec = retrieve_local_specialization (t);
10153             if (spec 
10154                 && TREE_CODE (spec) == PARM_DECL
10155                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
10156               RETURN (spec);
10157
10158             /* Expand the TYPE_PACK_EXPANSION that provides the types for
10159                the parameters in this function parameter pack.  */
10160             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
10161                                                     complain, in_decl);
10162             if (TREE_CODE (expanded_types) == TREE_VEC)
10163               {
10164                 len = TREE_VEC_LENGTH (expanded_types);
10165
10166                 /* Zero-length parameter packs are boring. Just substitute
10167                    into the chain.  */
10168                 if (len == 0)
10169                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
10170                                   TREE_CHAIN (t)));
10171               }
10172             else
10173               {
10174                 /* All we did was update the type. Make a note of that.  */
10175                 type = expanded_types;
10176                 expanded_types = NULL_TREE;
10177               }
10178           }
10179
10180         /* Loop through all of the parameter's we'll build. When T is
10181            a function parameter pack, LEN is the number of expanded
10182            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
10183         r = NULL_TREE;
10184         for (i = 0; i < len; ++i)
10185           {
10186             prev_r = r;
10187             r = copy_node (t);
10188             if (DECL_TEMPLATE_PARM_P (t))
10189               SET_DECL_TEMPLATE_PARM_P (r);
10190
10191             if (expanded_types)
10192               /* We're on the Ith parameter of the function parameter
10193                  pack.  */
10194               {
10195                 /* An argument of a function parameter pack is not a parameter
10196                    pack.  */
10197                 FUNCTION_PARAMETER_PACK_P (r) = false;
10198
10199                 /* Get the Ith type.  */
10200                 type = TREE_VEC_ELT (expanded_types, i);
10201
10202                 if (DECL_NAME (r))
10203                   /* Rename the parameter to include the index.  */
10204                   DECL_NAME (r) =
10205                     make_ith_pack_parameter_name (DECL_NAME (r), i);
10206               }
10207             else if (!type)
10208               /* We're dealing with a normal parameter.  */
10209               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10210
10211             type = type_decays_to (type);
10212             TREE_TYPE (r) = type;
10213             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10214
10215             if (DECL_INITIAL (r))
10216               {
10217                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
10218                   DECL_INITIAL (r) = TREE_TYPE (r);
10219                 else
10220                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
10221                                              complain, in_decl);
10222               }
10223
10224             DECL_CONTEXT (r) = NULL_TREE;
10225
10226             if (!DECL_TEMPLATE_PARM_P (r))
10227               DECL_ARG_TYPE (r) = type_passed_as (type);
10228
10229             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10230                                             args, complain, in_decl);
10231
10232             /* Keep track of the first new parameter we
10233                generate. That's what will be returned to the
10234                caller.  */
10235             if (!first_r)
10236               first_r = r;
10237
10238             /* Build a proper chain of parameters when substituting
10239                into a function parameter pack.  */
10240             if (prev_r)
10241               DECL_CHAIN (prev_r) = r;
10242           }
10243
10244         if (DECL_CHAIN (t))
10245           DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
10246                                    complain, DECL_CHAIN (t));
10247
10248         /* FIRST_R contains the start of the chain we've built.  */
10249         r = first_r;
10250       }
10251       break;
10252
10253     case FIELD_DECL:
10254       {
10255         tree type;
10256
10257         r = copy_decl (t);
10258         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10259         if (type == error_mark_node)
10260           RETURN (error_mark_node);
10261         TREE_TYPE (r) = type;
10262         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10263
10264         if (DECL_C_BIT_FIELD (r))
10265           /* For bit-fields, DECL_INITIAL gives the number of bits.  For
10266              non-bit-fields DECL_INITIAL is a non-static data member
10267              initializer, which gets deferred instantiation.  */
10268           DECL_INITIAL (r)
10269             = tsubst_expr (DECL_INITIAL (t), args,
10270                            complain, in_decl,
10271                            /*integral_constant_expression_p=*/true);
10272         else if (DECL_INITIAL (t))
10273           {
10274             /* Set up DECL_TEMPLATE_INFO so that we can get at the
10275                NSDMI in perform_member_init.  Still set DECL_INITIAL
10276                to error_mark_node so that we know there is one.  */
10277             DECL_INITIAL (r) = error_mark_node;
10278             gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
10279             retrofit_lang_decl (r);
10280             DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
10281           }
10282         /* We don't have to set DECL_CONTEXT here; it is set by
10283            finish_member_declaration.  */
10284         DECL_CHAIN (r) = NULL_TREE;
10285         if (VOID_TYPE_P (type))
10286           error ("instantiation of %q+D as type %qT", r, type);
10287
10288         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10289                                         args, complain, in_decl);
10290       }
10291       break;
10292
10293     case USING_DECL:
10294       /* We reach here only for member using decls.  */
10295       if (DECL_DEPENDENT_P (t))
10296         {
10297           r = do_class_using_decl
10298             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
10299              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
10300           if (!r)
10301             r = error_mark_node;
10302           else
10303             {
10304               TREE_PROTECTED (r) = TREE_PROTECTED (t);
10305               TREE_PRIVATE (r) = TREE_PRIVATE (t);
10306             }
10307         }
10308       else
10309         {
10310           r = copy_node (t);
10311           DECL_CHAIN (r) = NULL_TREE;
10312         }
10313       break;
10314
10315     case TYPE_DECL:
10316     case VAR_DECL:
10317       {
10318         tree argvec = NULL_TREE;
10319         tree gen_tmpl = NULL_TREE;
10320         tree spec;
10321         tree tmpl = NULL_TREE;
10322         tree ctx;
10323         tree type = NULL_TREE;
10324         bool local_p;
10325
10326         if (TREE_CODE (t) == TYPE_DECL
10327             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
10328           {
10329             /* If this is the canonical decl, we don't have to
10330                mess with instantiations, and often we can't (for
10331                typename, template type parms and such).  Note that
10332                TYPE_NAME is not correct for the above test if
10333                we've copied the type for a typedef.  */
10334             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10335             if (type == error_mark_node)
10336               RETURN (error_mark_node);
10337             r = TYPE_NAME (type);
10338             break;
10339           }
10340
10341         /* Check to see if we already have the specialization we
10342            need.  */
10343         spec = NULL_TREE;
10344         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
10345           {
10346             /* T is a static data member or namespace-scope entity.
10347                We have to substitute into namespace-scope variables
10348                (even though such entities are never templates) because
10349                of cases like:
10350                
10351                  template <class T> void f() { extern T t; }
10352
10353                where the entity referenced is not known until
10354                instantiation time.  */
10355             local_p = false;
10356             ctx = DECL_CONTEXT (t);
10357             if (DECL_CLASS_SCOPE_P (t))
10358               {
10359                 ctx = tsubst_aggr_type (ctx, args,
10360                                         complain,
10361                                         in_decl, /*entering_scope=*/1);
10362                 /* If CTX is unchanged, then T is in fact the
10363                    specialization we want.  That situation occurs when
10364                    referencing a static data member within in its own
10365                    class.  We can use pointer equality, rather than
10366                    same_type_p, because DECL_CONTEXT is always
10367                    canonical.  */
10368                 if (ctx == DECL_CONTEXT (t))
10369                   spec = t;
10370               }
10371
10372             if (!spec)
10373               {
10374                 tmpl = DECL_TI_TEMPLATE (t);
10375                 gen_tmpl = most_general_template (tmpl);
10376                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
10377                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
10378                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
10379               }
10380           }
10381         else
10382           {
10383             /* A local variable.  */
10384             local_p = true;
10385             /* Subsequent calls to pushdecl will fill this in.  */
10386             ctx = NULL_TREE;
10387             spec = retrieve_local_specialization (t);
10388           }
10389         /* If we already have the specialization we need, there is
10390            nothing more to do.  */ 
10391         if (spec)
10392           {
10393             r = spec;
10394             break;
10395           }
10396
10397         /* Create a new node for the specialization we need.  */
10398         r = copy_decl (t);
10399         if (type == NULL_TREE)
10400           {
10401             if (is_typedef_decl (t))
10402               type = DECL_ORIGINAL_TYPE (t);
10403             else
10404               type = TREE_TYPE (t);
10405             if (TREE_CODE (t) == VAR_DECL && VAR_HAD_UNKNOWN_BOUND (t))
10406               type = strip_array_domain (type);
10407             type = tsubst (type, args, complain, in_decl);
10408           }
10409         if (TREE_CODE (r) == VAR_DECL)
10410           {
10411             /* Even if the original location is out of scope, the
10412                newly substituted one is not.  */
10413             DECL_DEAD_FOR_LOCAL (r) = 0;
10414             DECL_INITIALIZED_P (r) = 0;
10415             DECL_TEMPLATE_INSTANTIATED (r) = 0;
10416             if (type == error_mark_node)
10417               RETURN (error_mark_node);
10418             if (TREE_CODE (type) == FUNCTION_TYPE)
10419               {
10420                 /* It may seem that this case cannot occur, since:
10421
10422                      typedef void f();
10423                      void g() { f x; }
10424
10425                    declares a function, not a variable.  However:
10426       
10427                      typedef void f();
10428                      template <typename T> void g() { T t; }
10429                      template void g<f>();
10430
10431                    is an attempt to declare a variable with function
10432                    type.  */
10433                 error ("variable %qD has function type",
10434                        /* R is not yet sufficiently initialized, so we
10435                           just use its name.  */
10436                        DECL_NAME (r));
10437                 RETURN (error_mark_node);
10438               }
10439             type = complete_type (type);
10440             /* Wait until cp_finish_decl to set this again, to handle
10441                circular dependency (template/instantiate6.C). */
10442             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
10443             type = check_var_type (DECL_NAME (r), type);
10444
10445             if (DECL_HAS_VALUE_EXPR_P (t))
10446               {
10447                 tree ve = DECL_VALUE_EXPR (t);
10448                 ve = tsubst_expr (ve, args, complain, in_decl,
10449                                   /*constant_expression_p=*/false);
10450                 if (REFERENCE_REF_P (ve))
10451                   {
10452                     gcc_assert (TREE_CODE (type) == REFERENCE_TYPE);
10453                     ve = TREE_OPERAND (ve, 0);
10454                   }
10455                 SET_DECL_VALUE_EXPR (r, ve);
10456               }
10457           }
10458         else if (DECL_SELF_REFERENCE_P (t))
10459           SET_DECL_SELF_REFERENCE_P (r);
10460         TREE_TYPE (r) = type;
10461         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10462         DECL_CONTEXT (r) = ctx;
10463         /* Clear out the mangled name and RTL for the instantiation.  */
10464         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
10465         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10466           SET_DECL_RTL (r, NULL);
10467         /* The initializer must not be expanded until it is required;
10468            see [temp.inst].  */
10469         DECL_INITIAL (r) = NULL_TREE;
10470         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10471           SET_DECL_RTL (r, NULL);
10472         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
10473         if (TREE_CODE (r) == VAR_DECL)
10474           {
10475             /* Possibly limit visibility based on template args.  */
10476             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10477             if (DECL_VISIBILITY_SPECIFIED (t))
10478               {
10479                 DECL_VISIBILITY_SPECIFIED (r) = 0;
10480                 DECL_ATTRIBUTES (r)
10481                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10482               }
10483             determine_visibility (r);
10484           }
10485
10486         if (!local_p)
10487           {
10488             /* A static data member declaration is always marked
10489                external when it is declared in-class, even if an
10490                initializer is present.  We mimic the non-template
10491                processing here.  */
10492             DECL_EXTERNAL (r) = 1;
10493
10494             register_specialization (r, gen_tmpl, argvec, false, hash);
10495             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
10496             SET_DECL_IMPLICIT_INSTANTIATION (r);
10497           }
10498         else if (cp_unevaluated_operand)
10499           {
10500             /* We're substituting this var in a decltype outside of its
10501                scope, such as for a lambda return type.  Don't add it to
10502                local_specializations, do perform auto deduction.  */
10503             tree auto_node = type_uses_auto (type);
10504             if (auto_node)
10505               {
10506                 tree init
10507                   = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
10508                                  /*constant_expression_p=*/false);
10509                 init = resolve_nondeduced_context (init);
10510                 TREE_TYPE (r) = type
10511                   = do_auto_deduction (type, init, auto_node);
10512               }
10513           }
10514         else
10515           register_local_specialization (r, t);
10516
10517         DECL_CHAIN (r) = NULL_TREE;
10518
10519         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
10520                                         /*flags=*/0,
10521                                         args, complain, in_decl);
10522
10523         /* Preserve a typedef that names a type.  */
10524         if (is_typedef_decl (r))
10525           {
10526             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
10527             set_underlying_type (r);
10528           }
10529
10530         layout_decl (r, 0);
10531       }
10532       break;
10533
10534     default:
10535       gcc_unreachable ();
10536     }
10537 #undef RETURN
10538
10539  out:
10540   /* Restore the file and line information.  */
10541   input_location = saved_loc;
10542
10543   return r;
10544 }
10545
10546 /* Substitute into the ARG_TYPES of a function type.  */
10547
10548 static tree
10549 tsubst_arg_types (tree arg_types,
10550                   tree args,
10551                   tsubst_flags_t complain,
10552                   tree in_decl)
10553 {
10554   tree remaining_arg_types;
10555   tree type = NULL_TREE;
10556   int i = 1;
10557   tree expanded_args = NULL_TREE;
10558   tree default_arg;
10559
10560   if (!arg_types || arg_types == void_list_node)
10561     return arg_types;
10562
10563   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
10564                                           args, complain, in_decl);
10565   if (remaining_arg_types == error_mark_node)
10566     return error_mark_node;
10567
10568   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
10569     {
10570       /* For a pack expansion, perform substitution on the
10571          entire expression. Later on, we'll handle the arguments
10572          one-by-one.  */
10573       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
10574                                             args, complain, in_decl);
10575
10576       if (TREE_CODE (expanded_args) == TREE_VEC)
10577         /* So that we'll spin through the parameters, one by one.  */
10578         i = TREE_VEC_LENGTH (expanded_args);
10579       else
10580         {
10581           /* We only partially substituted into the parameter
10582              pack. Our type is TYPE_PACK_EXPANSION.  */
10583           type = expanded_args;
10584           expanded_args = NULL_TREE;
10585         }
10586     }
10587
10588   while (i > 0) {
10589     --i;
10590     
10591     if (expanded_args)
10592       type = TREE_VEC_ELT (expanded_args, i);
10593     else if (!type)
10594       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
10595
10596     if (type == error_mark_node)
10597       return error_mark_node;
10598     if (VOID_TYPE_P (type))
10599       {
10600         if (complain & tf_error)
10601           {
10602             error ("invalid parameter type %qT", type);
10603             if (in_decl)
10604               error ("in declaration %q+D", in_decl);
10605           }
10606         return error_mark_node;
10607     }
10608     
10609     /* Do array-to-pointer, function-to-pointer conversion, and ignore
10610        top-level qualifiers as required.  */
10611     type = cv_unqualified (type_decays_to (type));
10612
10613     /* We do not substitute into default arguments here.  The standard
10614        mandates that they be instantiated only when needed, which is
10615        done in build_over_call.  */
10616     default_arg = TREE_PURPOSE (arg_types);
10617
10618     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
10619       {
10620         /* We've instantiated a template before its default arguments
10621            have been parsed.  This can happen for a nested template
10622            class, and is not an error unless we require the default
10623            argument in a call of this function.  */
10624         remaining_arg_types = 
10625           tree_cons (default_arg, type, remaining_arg_types);
10626         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
10627                        remaining_arg_types);
10628       }
10629     else
10630       remaining_arg_types = 
10631         hash_tree_cons (default_arg, type, remaining_arg_types);
10632   }
10633         
10634   return remaining_arg_types;
10635 }
10636
10637 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
10638    *not* handle the exception-specification for FNTYPE, because the
10639    initial substitution of explicitly provided template parameters
10640    during argument deduction forbids substitution into the
10641    exception-specification:
10642
10643      [temp.deduct]
10644
10645      All references in the function type of the function template to  the
10646      corresponding template parameters are replaced by the specified tem-
10647      plate argument values.  If a substitution in a template parameter or
10648      in  the function type of the function template results in an invalid
10649      type, type deduction fails.  [Note: The equivalent  substitution  in
10650      exception specifications is done only when the function is instanti-
10651      ated, at which point a program is  ill-formed  if  the  substitution
10652      results in an invalid type.]  */
10653
10654 static tree
10655 tsubst_function_type (tree t,
10656                       tree args,
10657                       tsubst_flags_t complain,
10658                       tree in_decl)
10659 {
10660   tree return_type;
10661   tree arg_types;
10662   tree fntype;
10663
10664   /* The TYPE_CONTEXT is not used for function/method types.  */
10665   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
10666
10667   /* Substitute the return type.  */
10668   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10669   if (return_type == error_mark_node)
10670     return error_mark_node;
10671   /* The standard does not presently indicate that creation of a
10672      function type with an invalid return type is a deduction failure.
10673      However, that is clearly analogous to creating an array of "void"
10674      or a reference to a reference.  This is core issue #486.  */
10675   if (TREE_CODE (return_type) == ARRAY_TYPE
10676       || TREE_CODE (return_type) == FUNCTION_TYPE)
10677     {
10678       if (complain & tf_error)
10679         {
10680           if (TREE_CODE (return_type) == ARRAY_TYPE)
10681             error ("function returning an array");
10682           else
10683             error ("function returning a function");
10684         }
10685       return error_mark_node;
10686     }
10687
10688   /* Substitute the argument types.  */
10689   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
10690                                 complain, in_decl);
10691   if (arg_types == error_mark_node)
10692     return error_mark_node;
10693
10694   /* Construct a new type node and return it.  */
10695   if (TREE_CODE (t) == FUNCTION_TYPE)
10696     {
10697       fntype = build_function_type (return_type, arg_types);
10698       fntype = apply_memfn_quals (fntype, type_memfn_quals (t));
10699     }
10700   else
10701     {
10702       tree r = TREE_TYPE (TREE_VALUE (arg_types));
10703       if (! MAYBE_CLASS_TYPE_P (r))
10704         {
10705           /* [temp.deduct]
10706
10707              Type deduction may fail for any of the following
10708              reasons:
10709
10710              -- Attempting to create "pointer to member of T" when T
10711              is not a class type.  */
10712           if (complain & tf_error)
10713             error ("creating pointer to member function of non-class type %qT",
10714                       r);
10715           return error_mark_node;
10716         }
10717
10718       fntype = build_method_type_directly (r, return_type,
10719                                            TREE_CHAIN (arg_types));
10720     }
10721   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
10722
10723   return fntype;
10724 }
10725
10726 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
10727    ARGS into that specification, and return the substituted
10728    specification.  If there is no specification, return NULL_TREE.  */
10729
10730 static tree
10731 tsubst_exception_specification (tree fntype,
10732                                 tree args,
10733                                 tsubst_flags_t complain,
10734                                 tree in_decl,
10735                                 bool defer_ok)
10736 {
10737   tree specs;
10738   tree new_specs;
10739
10740   specs = TYPE_RAISES_EXCEPTIONS (fntype);
10741   new_specs = NULL_TREE;
10742   if (specs && TREE_PURPOSE (specs))
10743     {
10744       /* A noexcept-specifier.  */
10745       tree expr = TREE_PURPOSE (specs);
10746       if (expr == boolean_true_node || expr == boolean_false_node)
10747         new_specs = expr;
10748       else if (defer_ok)
10749         {
10750           /* Defer instantiation of noexcept-specifiers to avoid
10751              excessive instantiations (c++/49107).  */
10752           new_specs = make_node (DEFERRED_NOEXCEPT);
10753           if (DEFERRED_NOEXCEPT_SPEC_P (specs))
10754             {
10755               /* We already partially instantiated this member template,
10756                  so combine the new args with the old.  */
10757               DEFERRED_NOEXCEPT_PATTERN (new_specs)
10758                 = DEFERRED_NOEXCEPT_PATTERN (expr);
10759               DEFERRED_NOEXCEPT_ARGS (new_specs)
10760                 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
10761             }
10762           else
10763             {
10764               DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
10765               DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
10766             }
10767         }
10768       else
10769         new_specs = tsubst_copy_and_build
10770           (expr, args, complain, in_decl, /*function_p=*/false,
10771            /*integral_constant_expression_p=*/true);
10772       new_specs = build_noexcept_spec (new_specs, complain);
10773     }
10774   else if (specs)
10775     {
10776       if (! TREE_VALUE (specs))
10777         new_specs = specs;
10778       else
10779         while (specs)
10780           {
10781             tree spec;
10782             int i, len = 1;
10783             tree expanded_specs = NULL_TREE;
10784
10785             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
10786               {
10787                 /* Expand the pack expansion type.  */
10788                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
10789                                                        args, complain,
10790                                                        in_decl);
10791
10792                 if (expanded_specs == error_mark_node)
10793                   return error_mark_node;
10794                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
10795                   len = TREE_VEC_LENGTH (expanded_specs);
10796                 else
10797                   {
10798                     /* We're substituting into a member template, so
10799                        we got a TYPE_PACK_EXPANSION back.  Add that
10800                        expansion and move on.  */
10801                     gcc_assert (TREE_CODE (expanded_specs) 
10802                                 == TYPE_PACK_EXPANSION);
10803                     new_specs = add_exception_specifier (new_specs,
10804                                                          expanded_specs,
10805                                                          complain);
10806                     specs = TREE_CHAIN (specs);
10807                     continue;
10808                   }
10809               }
10810
10811             for (i = 0; i < len; ++i)
10812               {
10813                 if (expanded_specs)
10814                   spec = TREE_VEC_ELT (expanded_specs, i);
10815                 else
10816                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
10817                 if (spec == error_mark_node)
10818                   return spec;
10819                 new_specs = add_exception_specifier (new_specs, spec, 
10820                                                      complain);
10821               }
10822
10823             specs = TREE_CHAIN (specs);
10824           }
10825     }
10826   return new_specs;
10827 }
10828
10829 /* Take the tree structure T and replace template parameters used
10830    therein with the argument vector ARGS.  IN_DECL is an associated
10831    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
10832    Issue error and warning messages under control of COMPLAIN.  Note
10833    that we must be relatively non-tolerant of extensions here, in
10834    order to preserve conformance; if we allow substitutions that
10835    should not be allowed, we may allow argument deductions that should
10836    not succeed, and therefore report ambiguous overload situations
10837    where there are none.  In theory, we could allow the substitution,
10838    but indicate that it should have failed, and allow our caller to
10839    make sure that the right thing happens, but we don't try to do this
10840    yet.
10841
10842    This function is used for dealing with types, decls and the like;
10843    for expressions, use tsubst_expr or tsubst_copy.  */
10844
10845 tree
10846 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10847 {
10848   enum tree_code code;
10849   tree type, r;
10850
10851   if (t == NULL_TREE || t == error_mark_node
10852       || t == integer_type_node
10853       || t == void_type_node
10854       || t == char_type_node
10855       || t == unknown_type_node
10856       || TREE_CODE (t) == NAMESPACE_DECL
10857       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
10858     return t;
10859
10860   if (DECL_P (t))
10861     return tsubst_decl (t, args, complain);
10862
10863   if (args == NULL_TREE)
10864     return t;
10865
10866   code = TREE_CODE (t);
10867
10868   if (code == IDENTIFIER_NODE)
10869     type = IDENTIFIER_TYPE_VALUE (t);
10870   else
10871     type = TREE_TYPE (t);
10872
10873   gcc_assert (type != unknown_type_node);
10874
10875   /* Reuse typedefs.  We need to do this to handle dependent attributes,
10876      such as attribute aligned.  */
10877   if (TYPE_P (t)
10878       && typedef_variant_p (t))
10879     {
10880       tree decl = TYPE_NAME (t);
10881       
10882       if (DECL_CLASS_SCOPE_P (decl)
10883           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
10884           && uses_template_parms (DECL_CONTEXT (decl)))
10885         {
10886           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
10887           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
10888           r = retrieve_specialization (tmpl, gen_args, 0);
10889         }
10890       else if (DECL_FUNCTION_SCOPE_P (decl)
10891                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
10892                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
10893         r = retrieve_local_specialization (decl);
10894       else
10895         /* The typedef is from a non-template context.  */
10896         return t;
10897
10898       if (r)
10899         {
10900           r = TREE_TYPE (r);
10901           r = cp_build_qualified_type_real
10902             (r, cp_type_quals (t) | cp_type_quals (r),
10903              complain | tf_ignore_bad_quals);
10904           return r;
10905         }
10906       /* Else we must be instantiating the typedef, so fall through.  */
10907     }
10908
10909   if (type
10910       && code != TYPENAME_TYPE
10911       && code != TEMPLATE_TYPE_PARM
10912       && code != IDENTIFIER_NODE
10913       && code != FUNCTION_TYPE
10914       && code != METHOD_TYPE)
10915     type = tsubst (type, args, complain, in_decl);
10916   if (type == error_mark_node)
10917     return error_mark_node;
10918
10919   switch (code)
10920     {
10921     case RECORD_TYPE:
10922     case UNION_TYPE:
10923     case ENUMERAL_TYPE:
10924       return tsubst_aggr_type (t, args, complain, in_decl,
10925                                /*entering_scope=*/0);
10926
10927     case ERROR_MARK:
10928     case IDENTIFIER_NODE:
10929     case VOID_TYPE:
10930     case REAL_TYPE:
10931     case COMPLEX_TYPE:
10932     case VECTOR_TYPE:
10933     case BOOLEAN_TYPE:
10934     case NULLPTR_TYPE:
10935     case LANG_TYPE:
10936       return t;
10937
10938     case INTEGER_TYPE:
10939       if (t == integer_type_node)
10940         return t;
10941
10942       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
10943           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
10944         return t;
10945
10946       {
10947         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
10948
10949         max = tsubst_expr (omax, args, complain, in_decl,
10950                            /*integral_constant_expression_p=*/false);
10951
10952         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
10953            needed.  */
10954         if (TREE_CODE (max) == NOP_EXPR
10955             && TREE_SIDE_EFFECTS (omax)
10956             && !TREE_TYPE (max))
10957           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
10958
10959         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
10960            with TREE_SIDE_EFFECTS that indicates this is not an integral
10961            constant expression.  */
10962         if (processing_template_decl
10963             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
10964           {
10965             gcc_assert (TREE_CODE (max) == NOP_EXPR);
10966             TREE_SIDE_EFFECTS (max) = 1;
10967           }
10968
10969         return compute_array_index_type (NULL_TREE, max, complain);
10970       }
10971
10972     case TEMPLATE_TYPE_PARM:
10973     case TEMPLATE_TEMPLATE_PARM:
10974     case BOUND_TEMPLATE_TEMPLATE_PARM:
10975     case TEMPLATE_PARM_INDEX:
10976       {
10977         int idx;
10978         int level;
10979         int levels;
10980         tree arg = NULL_TREE;
10981
10982         r = NULL_TREE;
10983
10984         gcc_assert (TREE_VEC_LENGTH (args) > 0);
10985         template_parm_level_and_index (t, &level, &idx); 
10986
10987         levels = TMPL_ARGS_DEPTH (args);
10988         if (level <= levels)
10989           {
10990             arg = TMPL_ARG (args, level, idx);
10991
10992             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
10993               /* See through ARGUMENT_PACK_SELECT arguments. */
10994               arg = ARGUMENT_PACK_SELECT_ARG (arg);
10995           }
10996
10997         if (arg == error_mark_node)
10998           return error_mark_node;
10999         else if (arg != NULL_TREE)
11000           {
11001             if (ARGUMENT_PACK_P (arg))
11002               /* If ARG is an argument pack, we don't actually want to
11003                  perform a substitution here, because substitutions
11004                  for argument packs are only done
11005                  element-by-element. We can get to this point when
11006                  substituting the type of a non-type template
11007                  parameter pack, when that type actually contains
11008                  template parameter packs from an outer template, e.g.,
11009
11010                  template<typename... Types> struct A {
11011                    template<Types... Values> struct B { };
11012                  };  */
11013               return t;
11014
11015             if (code == TEMPLATE_TYPE_PARM)
11016               {
11017                 int quals;
11018                 gcc_assert (TYPE_P (arg));
11019
11020                 quals = cp_type_quals (arg) | cp_type_quals (t);
11021                   
11022                 return cp_build_qualified_type_real
11023                   (arg, quals, complain | tf_ignore_bad_quals);
11024               }
11025             else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
11026               {
11027                 /* We are processing a type constructed from a
11028                    template template parameter.  */
11029                 tree argvec = tsubst (TYPE_TI_ARGS (t),
11030                                       args, complain, in_decl);
11031                 if (argvec == error_mark_node)
11032                   return error_mark_node;
11033
11034                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
11035                    are resolving nested-types in the signature of a
11036                    member function templates.  Otherwise ARG is a
11037                    TEMPLATE_DECL and is the real template to be
11038                    instantiated.  */
11039                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
11040                   arg = TYPE_NAME (arg);
11041
11042                 r = lookup_template_class (arg,
11043                                            argvec, in_decl,
11044                                            DECL_CONTEXT (arg),
11045                                             /*entering_scope=*/0,
11046                                            complain);
11047                 return cp_build_qualified_type_real
11048                   (r, cp_type_quals (t), complain);
11049               }
11050             else
11051               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
11052               return convert_from_reference (unshare_expr (arg));
11053           }
11054
11055         if (level == 1)
11056           /* This can happen during the attempted tsubst'ing in
11057              unify.  This means that we don't yet have any information
11058              about the template parameter in question.  */
11059           return t;
11060
11061         /* If we get here, we must have been looking at a parm for a
11062            more deeply nested template.  Make a new version of this
11063            template parameter, but with a lower level.  */
11064         switch (code)
11065           {
11066           case TEMPLATE_TYPE_PARM:
11067           case TEMPLATE_TEMPLATE_PARM:
11068           case BOUND_TEMPLATE_TEMPLATE_PARM:
11069             if (cp_type_quals (t))
11070               {
11071                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
11072                 r = cp_build_qualified_type_real
11073                   (r, cp_type_quals (t),
11074                    complain | (code == TEMPLATE_TYPE_PARM
11075                                ? tf_ignore_bad_quals : 0));
11076               }
11077             else
11078               {
11079                 r = copy_type (t);
11080                 TEMPLATE_TYPE_PARM_INDEX (r)
11081                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
11082                                                 r, levels, args, complain);
11083                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
11084                 TYPE_MAIN_VARIANT (r) = r;
11085                 TYPE_POINTER_TO (r) = NULL_TREE;
11086                 TYPE_REFERENCE_TO (r) = NULL_TREE;
11087
11088                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
11089                   /* We have reduced the level of the template
11090                      template parameter, but not the levels of its
11091                      template parameters, so canonical_type_parameter
11092                      will not be able to find the canonical template
11093                      template parameter for this level. Thus, we
11094                      require structural equality checking to compare
11095                      TEMPLATE_TEMPLATE_PARMs. */
11096                   SET_TYPE_STRUCTURAL_EQUALITY (r);
11097                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
11098                   SET_TYPE_STRUCTURAL_EQUALITY (r);
11099                 else
11100                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
11101
11102                 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
11103                   {
11104                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
11105                                           complain, in_decl);
11106                     if (argvec == error_mark_node)
11107                       return error_mark_node;
11108
11109                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
11110                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
11111                   }
11112               }
11113             break;
11114
11115           case TEMPLATE_PARM_INDEX:
11116             r = reduce_template_parm_level (t, type, levels, args, complain);
11117             break;
11118
11119           default:
11120             gcc_unreachable ();
11121           }
11122
11123         return r;
11124       }
11125
11126     case TREE_LIST:
11127       {
11128         tree purpose, value, chain;
11129
11130         if (t == void_list_node)
11131           return t;
11132
11133         purpose = TREE_PURPOSE (t);
11134         if (purpose)
11135           {
11136             purpose = tsubst (purpose, args, complain, in_decl);
11137             if (purpose == error_mark_node)
11138               return error_mark_node;
11139           }
11140         value = TREE_VALUE (t);
11141         if (value)
11142           {
11143             value = tsubst (value, args, complain, in_decl);
11144             if (value == error_mark_node)
11145               return error_mark_node;
11146           }
11147         chain = TREE_CHAIN (t);
11148         if (chain && chain != void_type_node)
11149           {
11150             chain = tsubst (chain, args, complain, in_decl);
11151             if (chain == error_mark_node)
11152               return error_mark_node;
11153           }
11154         if (purpose == TREE_PURPOSE (t)
11155             && value == TREE_VALUE (t)
11156             && chain == TREE_CHAIN (t))
11157           return t;
11158         return hash_tree_cons (purpose, value, chain);
11159       }
11160
11161     case TREE_BINFO:
11162       /* We should never be tsubsting a binfo.  */
11163       gcc_unreachable ();
11164
11165     case TREE_VEC:
11166       /* A vector of template arguments.  */
11167       gcc_assert (!type);
11168       return tsubst_template_args (t, args, complain, in_decl);
11169
11170     case POINTER_TYPE:
11171     case REFERENCE_TYPE:
11172       {
11173         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
11174           return t;
11175
11176         /* [temp.deduct]
11177
11178            Type deduction may fail for any of the following
11179            reasons:
11180
11181            -- Attempting to create a pointer to reference type.
11182            -- Attempting to create a reference to a reference type or
11183               a reference to void.
11184
11185           Core issue 106 says that creating a reference to a reference
11186           during instantiation is no longer a cause for failure. We
11187           only enforce this check in strict C++98 mode.  */
11188         if ((TREE_CODE (type) == REFERENCE_TYPE
11189              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
11190             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
11191           {
11192             static location_t last_loc;
11193
11194             /* We keep track of the last time we issued this error
11195                message to avoid spewing a ton of messages during a
11196                single bad template instantiation.  */
11197             if (complain & tf_error
11198                 && last_loc != input_location)
11199               {
11200                 if (TREE_CODE (type) == VOID_TYPE)
11201                   error ("forming reference to void");
11202                else if (code == POINTER_TYPE)
11203                  error ("forming pointer to reference type %qT", type);
11204                else
11205                   error ("forming reference to reference type %qT", type);
11206                 last_loc = input_location;
11207               }
11208
11209             return error_mark_node;
11210           }
11211         else if (code == POINTER_TYPE)
11212           {
11213             r = build_pointer_type (type);
11214             if (TREE_CODE (type) == METHOD_TYPE)
11215               r = build_ptrmemfunc_type (r);
11216           }
11217         else if (TREE_CODE (type) == REFERENCE_TYPE)
11218           /* In C++0x, during template argument substitution, when there is an
11219              attempt to create a reference to a reference type, reference
11220              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
11221
11222              "If a template-argument for a template-parameter T names a type
11223              that is a reference to a type A, an attempt to create the type
11224              'lvalue reference to cv T' creates the type 'lvalue reference to
11225              A,' while an attempt to create the type type rvalue reference to
11226              cv T' creates the type T"
11227           */
11228           r = cp_build_reference_type
11229               (TREE_TYPE (type),
11230                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
11231         else
11232           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
11233         r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
11234
11235         if (r != error_mark_node)
11236           /* Will this ever be needed for TYPE_..._TO values?  */
11237           layout_type (r);
11238
11239         return r;
11240       }
11241     case OFFSET_TYPE:
11242       {
11243         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
11244         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
11245           {
11246             /* [temp.deduct]
11247
11248                Type deduction may fail for any of the following
11249                reasons:
11250
11251                -- Attempting to create "pointer to member of T" when T
11252                   is not a class type.  */
11253             if (complain & tf_error)
11254               error ("creating pointer to member of non-class type %qT", r);
11255             return error_mark_node;
11256           }
11257         if (TREE_CODE (type) == REFERENCE_TYPE)
11258           {
11259             if (complain & tf_error)
11260               error ("creating pointer to member reference type %qT", type);
11261             return error_mark_node;
11262           }
11263         if (TREE_CODE (type) == VOID_TYPE)
11264           {
11265             if (complain & tf_error)
11266               error ("creating pointer to member of type void");
11267             return error_mark_node;
11268           }
11269         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
11270         if (TREE_CODE (type) == FUNCTION_TYPE)
11271           {
11272             /* The type of the implicit object parameter gets its
11273                cv-qualifiers from the FUNCTION_TYPE. */
11274             tree memptr;
11275             tree method_type = build_memfn_type (type, r, type_memfn_quals (type));
11276             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
11277             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
11278                                                  complain);
11279           }
11280         else
11281           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
11282                                                cp_type_quals (t),
11283                                                complain);
11284       }
11285     case FUNCTION_TYPE:
11286     case METHOD_TYPE:
11287       {
11288         tree fntype;
11289         tree specs;
11290         fntype = tsubst_function_type (t, args, complain, in_decl);
11291         if (fntype == error_mark_node)
11292           return error_mark_node;
11293
11294         /* Substitute the exception specification.  */
11295         specs = tsubst_exception_specification (t, args, complain,
11296                                                 in_decl, /*defer_ok*/true);
11297         if (specs == error_mark_node)
11298           return error_mark_node;
11299         if (specs)
11300           fntype = build_exception_variant (fntype, specs);
11301         return fntype;
11302       }
11303     case ARRAY_TYPE:
11304       {
11305         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
11306         if (domain == error_mark_node)
11307           return error_mark_node;
11308
11309         /* As an optimization, we avoid regenerating the array type if
11310            it will obviously be the same as T.  */
11311         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
11312           return t;
11313
11314         /* These checks should match the ones in grokdeclarator.
11315
11316            [temp.deduct]
11317
11318            The deduction may fail for any of the following reasons:
11319
11320            -- Attempting to create an array with an element type that
11321               is void, a function type, or a reference type, or [DR337]
11322               an abstract class type.  */
11323         if (TREE_CODE (type) == VOID_TYPE
11324             || TREE_CODE (type) == FUNCTION_TYPE
11325             || TREE_CODE (type) == REFERENCE_TYPE)
11326           {
11327             if (complain & tf_error)
11328               error ("creating array of %qT", type);
11329             return error_mark_node;
11330           }
11331         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
11332           {
11333             if (complain & tf_error)
11334               error ("creating array of %qT, which is an abstract class type",
11335                      type);
11336             return error_mark_node;
11337           }
11338
11339         r = build_cplus_array_type (type, domain);
11340
11341         if (TYPE_USER_ALIGN (t))
11342           {
11343             TYPE_ALIGN (r) = TYPE_ALIGN (t);
11344             TYPE_USER_ALIGN (r) = 1;
11345           }
11346
11347         return r;
11348       }
11349
11350     case TYPENAME_TYPE:
11351       {
11352         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
11353                                      in_decl, /*entering_scope=*/1);
11354         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
11355                               complain, in_decl);
11356
11357         if (ctx == error_mark_node || f == error_mark_node)
11358           return error_mark_node;
11359
11360         if (!MAYBE_CLASS_TYPE_P (ctx))
11361           {
11362             if (complain & tf_error)
11363               error ("%qT is not a class, struct, or union type", ctx);
11364             return error_mark_node;
11365           }
11366         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
11367           {
11368             /* Normally, make_typename_type does not require that the CTX
11369                have complete type in order to allow things like:
11370
11371                  template <class T> struct S { typename S<T>::X Y; };
11372
11373                But, such constructs have already been resolved by this
11374                point, so here CTX really should have complete type, unless
11375                it's a partial instantiation.  */
11376             ctx = complete_type (ctx);
11377             if (!COMPLETE_TYPE_P (ctx))
11378               {
11379                 if (complain & tf_error)
11380                   cxx_incomplete_type_error (NULL_TREE, ctx);
11381                 return error_mark_node;
11382               }
11383           }
11384
11385         f = make_typename_type (ctx, f, typename_type,
11386                                 (complain & tf_error) | tf_keep_type_decl);
11387         if (f == error_mark_node)
11388           return f;
11389         if (TREE_CODE (f) == TYPE_DECL)
11390           {
11391             complain |= tf_ignore_bad_quals;
11392             f = TREE_TYPE (f);
11393           }
11394
11395         if (TREE_CODE (f) != TYPENAME_TYPE)
11396           {
11397             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
11398               {
11399                 if (complain & tf_error)
11400                   error ("%qT resolves to %qT, which is not an enumeration type",
11401                          t, f);
11402                 else
11403                   return error_mark_node;
11404               }
11405             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
11406               {
11407                 if (complain & tf_error)
11408                   error ("%qT resolves to %qT, which is is not a class type",
11409                          t, f);
11410                 else
11411                   return error_mark_node;
11412               }
11413           }
11414
11415         return cp_build_qualified_type_real
11416           (f, cp_type_quals (f) | cp_type_quals (t), complain);
11417       }
11418
11419     case UNBOUND_CLASS_TEMPLATE:
11420       {
11421         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
11422                                      in_decl, /*entering_scope=*/1);
11423         tree name = TYPE_IDENTIFIER (t);
11424         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
11425
11426         if (ctx == error_mark_node || name == error_mark_node)
11427           return error_mark_node;
11428
11429         if (parm_list)
11430           parm_list = tsubst_template_parms (parm_list, args, complain);
11431         return make_unbound_class_template (ctx, name, parm_list, complain);
11432       }
11433
11434     case TYPEOF_TYPE:
11435       {
11436         tree type;
11437
11438         ++cp_unevaluated_operand;
11439         ++c_inhibit_evaluation_warnings;
11440
11441         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
11442                             complain, in_decl,
11443                             /*integral_constant_expression_p=*/false);
11444
11445         --cp_unevaluated_operand;
11446         --c_inhibit_evaluation_warnings;
11447
11448         type = finish_typeof (type);
11449         return cp_build_qualified_type_real (type,
11450                                              cp_type_quals (t)
11451                                              | cp_type_quals (type),
11452                                              complain);
11453       }
11454
11455     case DECLTYPE_TYPE:
11456       {
11457         tree type;
11458
11459         ++cp_unevaluated_operand;
11460         ++c_inhibit_evaluation_warnings;
11461
11462         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
11463                             complain, in_decl,
11464                             /*integral_constant_expression_p=*/false);
11465
11466         --cp_unevaluated_operand;
11467         --c_inhibit_evaluation_warnings;
11468
11469         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
11470           type = lambda_capture_field_type (type);
11471         else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
11472           type = lambda_proxy_type (type);
11473         else
11474           type = finish_decltype_type
11475             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t), complain);
11476         return cp_build_qualified_type_real (type,
11477                                              cp_type_quals (t)
11478                                              | cp_type_quals (type),
11479                                              complain);
11480       }
11481
11482     case UNDERLYING_TYPE:
11483       {
11484         tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
11485                             complain, in_decl);
11486         return finish_underlying_type (type);
11487       }
11488
11489     case TYPE_ARGUMENT_PACK:
11490     case NONTYPE_ARGUMENT_PACK:
11491       {
11492         tree r = TYPE_P (t) ? cxx_make_type (code) : make_node (code);
11493         tree packed_out = 
11494           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
11495                                 args,
11496                                 complain,
11497                                 in_decl);
11498         SET_ARGUMENT_PACK_ARGS (r, packed_out);
11499
11500         /* For template nontype argument packs, also substitute into
11501            the type.  */
11502         if (code == NONTYPE_ARGUMENT_PACK)
11503           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
11504
11505         return r;
11506       }
11507       break;
11508
11509     case INTEGER_CST:
11510     case REAL_CST:
11511     case STRING_CST:
11512     case PLUS_EXPR:
11513     case MINUS_EXPR:
11514     case NEGATE_EXPR:
11515     case NOP_EXPR:
11516     case INDIRECT_REF:
11517     case ADDR_EXPR:
11518     case CALL_EXPR:
11519     case ARRAY_REF:
11520     case SCOPE_REF:
11521       /* We should use one of the expression tsubsts for these codes.  */
11522       gcc_unreachable ();
11523
11524     default:
11525       sorry ("use of %qs in template", tree_code_name [(int) code]);
11526       return error_mark_node;
11527     }
11528 }
11529
11530 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
11531    type of the expression on the left-hand side of the "." or "->"
11532    operator.  */
11533
11534 static tree
11535 tsubst_baselink (tree baselink, tree object_type,
11536                  tree args, tsubst_flags_t complain, tree in_decl)
11537 {
11538     tree name;
11539     tree qualifying_scope;
11540     tree fns;
11541     tree optype;
11542     tree template_args = 0;
11543     bool template_id_p = false;
11544
11545     /* A baselink indicates a function from a base class.  Both the
11546        BASELINK_ACCESS_BINFO and the base class referenced may
11547        indicate bases of the template class, rather than the
11548        instantiated class.  In addition, lookups that were not
11549        ambiguous before may be ambiguous now.  Therefore, we perform
11550        the lookup again.  */
11551     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
11552     qualifying_scope = tsubst (qualifying_scope, args,
11553                                complain, in_decl);
11554     fns = BASELINK_FUNCTIONS (baselink);
11555     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
11556     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
11557       {
11558         template_id_p = true;
11559         template_args = TREE_OPERAND (fns, 1);
11560         fns = TREE_OPERAND (fns, 0);
11561         if (template_args)
11562           template_args = tsubst_template_args (template_args, args,
11563                                                 complain, in_decl);
11564       }
11565     name = DECL_NAME (get_first_fn (fns));
11566     if (IDENTIFIER_TYPENAME_P (name))
11567       name = mangle_conv_op_name_for_type (optype);
11568     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
11569     if (!baselink)
11570       return error_mark_node;
11571
11572     /* If lookup found a single function, mark it as used at this
11573        point.  (If it lookup found multiple functions the one selected
11574        later by overload resolution will be marked as used at that
11575        point.)  */
11576     if (BASELINK_P (baselink))
11577       fns = BASELINK_FUNCTIONS (baselink);
11578     if (!template_id_p && !really_overloaded_fn (fns))
11579       mark_used (OVL_CURRENT (fns));
11580
11581     /* Add back the template arguments, if present.  */
11582     if (BASELINK_P (baselink) && template_id_p)
11583       BASELINK_FUNCTIONS (baselink)
11584         = build_nt (TEMPLATE_ID_EXPR,
11585                     BASELINK_FUNCTIONS (baselink),
11586                     template_args);
11587     /* Update the conversion operator type.  */
11588     BASELINK_OPTYPE (baselink) = optype;
11589
11590     if (!object_type)
11591       object_type = current_class_type;
11592     return adjust_result_of_qualified_name_lookup (baselink,
11593                                                    qualifying_scope,
11594                                                    object_type);
11595 }
11596
11597 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
11598    true if the qualified-id will be a postfix-expression in-and-of
11599    itself; false if more of the postfix-expression follows the
11600    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
11601    of "&".  */
11602
11603 static tree
11604 tsubst_qualified_id (tree qualified_id, tree args,
11605                      tsubst_flags_t complain, tree in_decl,
11606                      bool done, bool address_p)
11607 {
11608   tree expr;
11609   tree scope;
11610   tree name;
11611   bool is_template;
11612   tree template_args;
11613
11614   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
11615
11616   /* Figure out what name to look up.  */
11617   name = TREE_OPERAND (qualified_id, 1);
11618   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
11619     {
11620       is_template = true;
11621       template_args = TREE_OPERAND (name, 1);
11622       if (template_args)
11623         template_args = tsubst_template_args (template_args, args,
11624                                               complain, in_decl);
11625       name = TREE_OPERAND (name, 0);
11626     }
11627   else
11628     {
11629       is_template = false;
11630       template_args = NULL_TREE;
11631     }
11632
11633   /* Substitute into the qualifying scope.  When there are no ARGS, we
11634      are just trying to simplify a non-dependent expression.  In that
11635      case the qualifying scope may be dependent, and, in any case,
11636      substituting will not help.  */
11637   scope = TREE_OPERAND (qualified_id, 0);
11638   if (args)
11639     {
11640       scope = tsubst (scope, args, complain, in_decl);
11641       expr = tsubst_copy (name, args, complain, in_decl);
11642     }
11643   else
11644     expr = name;
11645
11646   if (dependent_scope_p (scope))
11647     {
11648       if (is_template)
11649         expr = build_min_nt (TEMPLATE_ID_EXPR, expr, template_args);
11650       return build_qualified_name (NULL_TREE, scope, expr,
11651                                    QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
11652     }
11653
11654   if (!BASELINK_P (name) && !DECL_P (expr))
11655     {
11656       if (TREE_CODE (expr) == BIT_NOT_EXPR)
11657         {
11658           /* A BIT_NOT_EXPR is used to represent a destructor.  */
11659           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
11660             {
11661               error ("qualifying type %qT does not match destructor name ~%qT",
11662                      scope, TREE_OPERAND (expr, 0));
11663               expr = error_mark_node;
11664             }
11665           else
11666             expr = lookup_qualified_name (scope, complete_dtor_identifier,
11667                                           /*is_type_p=*/0, false);
11668         }
11669       else
11670         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
11671       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
11672                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
11673         {
11674           if (complain & tf_error)
11675             {
11676               error ("dependent-name %qE is parsed as a non-type, but "
11677                      "instantiation yields a type", qualified_id);
11678               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
11679             }
11680           return error_mark_node;
11681         }
11682     }
11683
11684   if (DECL_P (expr))
11685     {
11686       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
11687                                            scope);
11688       /* Remember that there was a reference to this entity.  */
11689       mark_used (expr);
11690     }
11691
11692   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
11693     {
11694       if (complain & tf_error)
11695         qualified_name_lookup_error (scope,
11696                                      TREE_OPERAND (qualified_id, 1),
11697                                      expr, input_location);
11698       return error_mark_node;
11699     }
11700
11701   if (is_template)
11702     expr = lookup_template_function (expr, template_args);
11703
11704   if (expr == error_mark_node && complain & tf_error)
11705     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
11706                                  expr, input_location);
11707   else if (TYPE_P (scope))
11708     {
11709       expr = (adjust_result_of_qualified_name_lookup
11710               (expr, scope, current_class_type));
11711       expr = (finish_qualified_id_expr
11712               (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
11713                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
11714                /*template_arg_p=*/false));
11715     }
11716
11717   /* Expressions do not generally have reference type.  */
11718   if (TREE_CODE (expr) != SCOPE_REF
11719       /* However, if we're about to form a pointer-to-member, we just
11720          want the referenced member referenced.  */
11721       && TREE_CODE (expr) != OFFSET_REF)
11722     expr = convert_from_reference (expr);
11723
11724   return expr;
11725 }
11726
11727 /* Like tsubst, but deals with expressions.  This function just replaces
11728    template parms; to finish processing the resultant expression, use
11729    tsubst_copy_and_build or tsubst_expr.  */
11730
11731 static tree
11732 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11733 {
11734   enum tree_code code;
11735   tree r;
11736
11737   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
11738     return t;
11739
11740   code = TREE_CODE (t);
11741
11742   switch (code)
11743     {
11744     case PARM_DECL:
11745       r = retrieve_local_specialization (t);
11746
11747       if (r == NULL)
11748         {
11749           tree c;
11750
11751           /* We get here for a use of 'this' in an NSDMI.  */
11752           if (DECL_NAME (t) == this_identifier
11753               && at_function_scope_p ()
11754               && DECL_CONSTRUCTOR_P (current_function_decl))
11755             return current_class_ptr;
11756
11757           /* This can happen for a parameter name used later in a function
11758              declaration (such as in a late-specified return type).  Just
11759              make a dummy decl, since it's only used for its type.  */
11760           gcc_assert (cp_unevaluated_operand != 0);
11761           /* We copy T because want to tsubst the PARM_DECL only,
11762              not the following PARM_DECLs that are chained to T.  */
11763           c = copy_node (t);
11764           r = tsubst_decl (c, args, complain);
11765           /* Give it the template pattern as its context; its true context
11766              hasn't been instantiated yet and this is good enough for
11767              mangling.  */
11768           DECL_CONTEXT (r) = DECL_CONTEXT (t);
11769         }
11770       
11771       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
11772         r = ARGUMENT_PACK_SELECT_ARG (r);
11773       mark_used (r);
11774       return r;
11775
11776     case CONST_DECL:
11777       {
11778         tree enum_type;
11779         tree v;
11780
11781         if (DECL_TEMPLATE_PARM_P (t))
11782           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
11783         /* There is no need to substitute into namespace-scope
11784            enumerators.  */
11785         if (DECL_NAMESPACE_SCOPE_P (t))
11786           return t;
11787         /* If ARGS is NULL, then T is known to be non-dependent.  */
11788         if (args == NULL_TREE)
11789           return integral_constant_value (t);
11790
11791         /* Unfortunately, we cannot just call lookup_name here.
11792            Consider:
11793
11794              template <int I> int f() {
11795              enum E { a = I };
11796              struct S { void g() { E e = a; } };
11797              };
11798
11799            When we instantiate f<7>::S::g(), say, lookup_name is not
11800            clever enough to find f<7>::a.  */
11801         enum_type
11802           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
11803                               /*entering_scope=*/0);
11804
11805         for (v = TYPE_VALUES (enum_type);
11806              v != NULL_TREE;
11807              v = TREE_CHAIN (v))
11808           if (TREE_PURPOSE (v) == DECL_NAME (t))
11809             return TREE_VALUE (v);
11810
11811           /* We didn't find the name.  That should never happen; if
11812              name-lookup found it during preliminary parsing, we
11813              should find it again here during instantiation.  */
11814         gcc_unreachable ();
11815       }
11816       return t;
11817
11818     case FIELD_DECL:
11819       if (DECL_CONTEXT (t))
11820         {
11821           tree ctx;
11822
11823           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
11824                                   /*entering_scope=*/1);
11825           if (ctx != DECL_CONTEXT (t))
11826             {
11827               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
11828               if (!r)
11829                 {
11830                   if (complain & tf_error)
11831                     error ("using invalid field %qD", t);
11832                   return error_mark_node;
11833                 }
11834               return r;
11835             }
11836         }
11837
11838       return t;
11839
11840     case VAR_DECL:
11841     case FUNCTION_DECL:
11842       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
11843           || local_variable_p (t))
11844         t = tsubst (t, args, complain, in_decl);
11845       mark_used (t);
11846       return t;
11847
11848     case OVERLOAD:
11849       /* An OVERLOAD will always be a non-dependent overload set; an
11850          overload set from function scope will just be represented with an
11851          IDENTIFIER_NODE, and from class scope with a BASELINK.  */
11852       gcc_assert (!uses_template_parms (t));
11853       return t;
11854
11855     case BASELINK:
11856       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
11857
11858     case TEMPLATE_DECL:
11859       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11860         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
11861                        args, complain, in_decl);
11862       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
11863         return tsubst (t, args, complain, in_decl);
11864       else if (DECL_CLASS_SCOPE_P (t)
11865                && uses_template_parms (DECL_CONTEXT (t)))
11866         {
11867           /* Template template argument like the following example need
11868              special treatment:
11869
11870                template <template <class> class TT> struct C {};
11871                template <class T> struct D {
11872                  template <class U> struct E {};
11873                  C<E> c;                                // #1
11874                };
11875                D<int> d;                                // #2
11876
11877              We are processing the template argument `E' in #1 for
11878              the template instantiation #2.  Originally, `E' is a
11879              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
11880              have to substitute this with one having context `D<int>'.  */
11881
11882           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
11883           return lookup_field (context, DECL_NAME(t), 0, false);
11884         }
11885       else
11886         /* Ordinary template template argument.  */
11887         return t;
11888
11889     case CAST_EXPR:
11890     case REINTERPRET_CAST_EXPR:
11891     case CONST_CAST_EXPR:
11892     case STATIC_CAST_EXPR:
11893     case DYNAMIC_CAST_EXPR:
11894     case IMPLICIT_CONV_EXPR:
11895     case CONVERT_EXPR:
11896     case NOP_EXPR:
11897       return build1
11898         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11899          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11900
11901     case SIZEOF_EXPR:
11902       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11903         {
11904
11905           tree expanded;
11906           int len = 0;
11907
11908           ++cp_unevaluated_operand;
11909           ++c_inhibit_evaluation_warnings;
11910           /* We only want to compute the number of arguments.  */
11911           expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
11912                                             complain, in_decl);
11913           --cp_unevaluated_operand;
11914           --c_inhibit_evaluation_warnings;
11915
11916           if (TREE_CODE (expanded) == TREE_VEC)
11917             len = TREE_VEC_LENGTH (expanded);
11918
11919           if (expanded == error_mark_node)
11920             return error_mark_node;
11921           else if (PACK_EXPANSION_P (expanded)
11922                    || (TREE_CODE (expanded) == TREE_VEC
11923                        && len > 0
11924                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
11925             {
11926               if (TREE_CODE (expanded) == TREE_VEC)
11927                 expanded = TREE_VEC_ELT (expanded, len - 1);
11928
11929               if (TYPE_P (expanded))
11930                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
11931                                                    complain & tf_error);
11932               else
11933                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
11934                                                    complain & tf_error);
11935             }
11936           else
11937             return build_int_cst (size_type_node, len);
11938         }
11939       /* Fall through */
11940
11941     case INDIRECT_REF:
11942     case NEGATE_EXPR:
11943     case TRUTH_NOT_EXPR:
11944     case BIT_NOT_EXPR:
11945     case ADDR_EXPR:
11946     case UNARY_PLUS_EXPR:      /* Unary + */
11947     case ALIGNOF_EXPR:
11948     case AT_ENCODE_EXPR:
11949     case ARROW_EXPR:
11950     case THROW_EXPR:
11951     case TYPEID_EXPR:
11952     case REALPART_EXPR:
11953     case IMAGPART_EXPR:
11954       return build1
11955         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11956          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11957
11958     case COMPONENT_REF:
11959       {
11960         tree object;
11961         tree name;
11962
11963         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
11964         name = TREE_OPERAND (t, 1);
11965         if (TREE_CODE (name) == BIT_NOT_EXPR)
11966           {
11967             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11968                                 complain, in_decl);
11969             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11970           }
11971         else if (TREE_CODE (name) == SCOPE_REF
11972                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
11973           {
11974             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
11975                                      complain, in_decl);
11976             name = TREE_OPERAND (name, 1);
11977             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11978                                 complain, in_decl);
11979             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11980             name = build_qualified_name (/*type=*/NULL_TREE,
11981                                          base, name,
11982                                          /*template_p=*/false);
11983           }
11984         else if (TREE_CODE (name) == BASELINK)
11985           name = tsubst_baselink (name,
11986                                   non_reference (TREE_TYPE (object)),
11987                                   args, complain,
11988                                   in_decl);
11989         else
11990           name = tsubst_copy (name, args, complain, in_decl);
11991         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
11992       }
11993
11994     case PLUS_EXPR:
11995     case MINUS_EXPR:
11996     case MULT_EXPR:
11997     case TRUNC_DIV_EXPR:
11998     case CEIL_DIV_EXPR:
11999     case FLOOR_DIV_EXPR:
12000     case ROUND_DIV_EXPR:
12001     case EXACT_DIV_EXPR:
12002     case BIT_AND_EXPR:
12003     case BIT_IOR_EXPR:
12004     case BIT_XOR_EXPR:
12005     case TRUNC_MOD_EXPR:
12006     case FLOOR_MOD_EXPR:
12007     case TRUTH_ANDIF_EXPR:
12008     case TRUTH_ORIF_EXPR:
12009     case TRUTH_AND_EXPR:
12010     case TRUTH_OR_EXPR:
12011     case RSHIFT_EXPR:
12012     case LSHIFT_EXPR:
12013     case RROTATE_EXPR:
12014     case LROTATE_EXPR:
12015     case EQ_EXPR:
12016     case NE_EXPR:
12017     case MAX_EXPR:
12018     case MIN_EXPR:
12019     case LE_EXPR:
12020     case GE_EXPR:
12021     case LT_EXPR:
12022     case GT_EXPR:
12023     case COMPOUND_EXPR:
12024     case DOTSTAR_EXPR:
12025     case MEMBER_REF:
12026     case PREDECREMENT_EXPR:
12027     case PREINCREMENT_EXPR:
12028     case POSTDECREMENT_EXPR:
12029     case POSTINCREMENT_EXPR:
12030       return build_nt
12031         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12032          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12033
12034     case SCOPE_REF:
12035       return build_qualified_name (/*type=*/NULL_TREE,
12036                                    tsubst_copy (TREE_OPERAND (t, 0),
12037                                                 args, complain, in_decl),
12038                                    tsubst_copy (TREE_OPERAND (t, 1),
12039                                                 args, complain, in_decl),
12040                                    QUALIFIED_NAME_IS_TEMPLATE (t));
12041
12042     case ARRAY_REF:
12043       return build_nt
12044         (ARRAY_REF,
12045          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12046          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12047          NULL_TREE, NULL_TREE);
12048
12049     case CALL_EXPR:
12050       {
12051         int n = VL_EXP_OPERAND_LENGTH (t);
12052         tree result = build_vl_exp (CALL_EXPR, n);
12053         int i;
12054         for (i = 0; i < n; i++)
12055           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
12056                                              complain, in_decl);
12057         return result;
12058       }
12059
12060     case COND_EXPR:
12061     case MODOP_EXPR:
12062     case PSEUDO_DTOR_EXPR:
12063       {
12064         r = build_nt
12065           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12066            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12067            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
12068         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12069         return r;
12070       }
12071
12072     case NEW_EXPR:
12073       {
12074         r = build_nt
12075         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12076          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12077          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
12078         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
12079         return r;
12080       }
12081
12082     case DELETE_EXPR:
12083       {
12084         r = build_nt
12085         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12086          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12087         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
12088         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
12089         return r;
12090       }
12091
12092     case TEMPLATE_ID_EXPR:
12093       {
12094         /* Substituted template arguments */
12095         tree fn = TREE_OPERAND (t, 0);
12096         tree targs = TREE_OPERAND (t, 1);
12097
12098         fn = tsubst_copy (fn, args, complain, in_decl);
12099         if (targs)
12100           targs = tsubst_template_args (targs, args, complain, in_decl);
12101
12102         return lookup_template_function (fn, targs);
12103       }
12104
12105     case TREE_LIST:
12106       {
12107         tree purpose, value, chain;
12108
12109         if (t == void_list_node)
12110           return t;
12111
12112         purpose = TREE_PURPOSE (t);
12113         if (purpose)
12114           purpose = tsubst_copy (purpose, args, complain, in_decl);
12115         value = TREE_VALUE (t);
12116         if (value)
12117           value = tsubst_copy (value, args, complain, in_decl);
12118         chain = TREE_CHAIN (t);
12119         if (chain && chain != void_type_node)
12120           chain = tsubst_copy (chain, args, complain, in_decl);
12121         if (purpose == TREE_PURPOSE (t)
12122             && value == TREE_VALUE (t)
12123             && chain == TREE_CHAIN (t))
12124           return t;
12125         return tree_cons (purpose, value, chain);
12126       }
12127
12128     case RECORD_TYPE:
12129     case UNION_TYPE:
12130     case ENUMERAL_TYPE:
12131     case INTEGER_TYPE:
12132     case TEMPLATE_TYPE_PARM:
12133     case TEMPLATE_TEMPLATE_PARM:
12134     case BOUND_TEMPLATE_TEMPLATE_PARM:
12135     case TEMPLATE_PARM_INDEX:
12136     case POINTER_TYPE:
12137     case REFERENCE_TYPE:
12138     case OFFSET_TYPE:
12139     case FUNCTION_TYPE:
12140     case METHOD_TYPE:
12141     case ARRAY_TYPE:
12142     case TYPENAME_TYPE:
12143     case UNBOUND_CLASS_TEMPLATE:
12144     case TYPEOF_TYPE:
12145     case DECLTYPE_TYPE:
12146     case TYPE_DECL:
12147       return tsubst (t, args, complain, in_decl);
12148
12149     case IDENTIFIER_NODE:
12150       if (IDENTIFIER_TYPENAME_P (t))
12151         {
12152           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12153           return mangle_conv_op_name_for_type (new_type);
12154         }
12155       else
12156         return t;
12157
12158     case CONSTRUCTOR:
12159       /* This is handled by tsubst_copy_and_build.  */
12160       gcc_unreachable ();
12161
12162     case VA_ARG_EXPR:
12163       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
12164                                           in_decl),
12165                              tsubst (TREE_TYPE (t), args, complain, in_decl));
12166
12167     case CLEANUP_POINT_EXPR:
12168       /* We shouldn't have built any of these during initial template
12169          generation.  Instead, they should be built during instantiation
12170          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
12171       gcc_unreachable ();
12172
12173     case OFFSET_REF:
12174       r = build2
12175         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
12176          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12177          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12178       PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
12179       mark_used (TREE_OPERAND (r, 1));
12180       return r;
12181
12182     case EXPR_PACK_EXPANSION:
12183       error ("invalid use of pack expansion expression");
12184       return error_mark_node;
12185
12186     case NONTYPE_ARGUMENT_PACK:
12187       error ("use %<...%> to expand argument pack");
12188       return error_mark_node;
12189
12190     case INTEGER_CST:
12191     case REAL_CST:
12192     case STRING_CST:
12193     case COMPLEX_CST:
12194       {
12195         /* Instantiate any typedefs in the type.  */
12196         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12197         r = fold_convert (type, t);
12198         gcc_assert (TREE_CODE (r) == code);
12199         return r;
12200       }
12201
12202     case PTRMEM_CST:
12203       /* These can sometimes show up in a partial instantiation, but never
12204          involve template parms.  */
12205       gcc_assert (!uses_template_parms (t));
12206       return t;
12207
12208     default:
12209       /* We shouldn't get here, but keep going if !ENABLE_CHECKING.  */
12210       gcc_checking_assert (false);
12211       return t;
12212     }
12213 }
12214
12215 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
12216
12217 static tree
12218 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
12219                     tree in_decl)
12220 {
12221   tree new_clauses = NULL, nc, oc;
12222
12223   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
12224     {
12225       nc = copy_node (oc);
12226       OMP_CLAUSE_CHAIN (nc) = new_clauses;
12227       new_clauses = nc;
12228
12229       switch (OMP_CLAUSE_CODE (nc))
12230         {
12231         case OMP_CLAUSE_LASTPRIVATE:
12232           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
12233             {
12234               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
12235               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
12236                            in_decl, /*integral_constant_expression_p=*/false);
12237               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
12238                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
12239             }
12240           /* FALLTHRU */
12241         case OMP_CLAUSE_PRIVATE:
12242         case OMP_CLAUSE_SHARED:
12243         case OMP_CLAUSE_FIRSTPRIVATE:
12244         case OMP_CLAUSE_REDUCTION:
12245         case OMP_CLAUSE_COPYIN:
12246         case OMP_CLAUSE_COPYPRIVATE:
12247         case OMP_CLAUSE_IF:
12248         case OMP_CLAUSE_NUM_THREADS:
12249         case OMP_CLAUSE_SCHEDULE:
12250         case OMP_CLAUSE_COLLAPSE:
12251         case OMP_CLAUSE_FINAL:
12252           OMP_CLAUSE_OPERAND (nc, 0)
12253             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
12254                            in_decl, /*integral_constant_expression_p=*/false);
12255           break;
12256         case OMP_CLAUSE_NOWAIT:
12257         case OMP_CLAUSE_ORDERED:
12258         case OMP_CLAUSE_DEFAULT:
12259         case OMP_CLAUSE_UNTIED:
12260         case OMP_CLAUSE_MERGEABLE:
12261           break;
12262         default:
12263           gcc_unreachable ();
12264         }
12265     }
12266
12267   return finish_omp_clauses (nreverse (new_clauses));
12268 }
12269
12270 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
12271
12272 static tree
12273 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
12274                           tree in_decl)
12275 {
12276 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
12277
12278   tree purpose, value, chain;
12279
12280   if (t == NULL)
12281     return t;
12282
12283   if (TREE_CODE (t) != TREE_LIST)
12284     return tsubst_copy_and_build (t, args, complain, in_decl,
12285                                   /*function_p=*/false,
12286                                   /*integral_constant_expression_p=*/false);
12287
12288   if (t == void_list_node)
12289     return t;
12290
12291   purpose = TREE_PURPOSE (t);
12292   if (purpose)
12293     purpose = RECUR (purpose);
12294   value = TREE_VALUE (t);
12295   if (value && TREE_CODE (value) != LABEL_DECL)
12296     value = RECUR (value);
12297   chain = TREE_CHAIN (t);
12298   if (chain && chain != void_type_node)
12299     chain = RECUR (chain);
12300   return tree_cons (purpose, value, chain);
12301 #undef RECUR
12302 }
12303
12304 /* Substitute one OMP_FOR iterator.  */
12305
12306 static void
12307 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
12308                          tree condv, tree incrv, tree *clauses,
12309                          tree args, tsubst_flags_t complain, tree in_decl,
12310                          bool integral_constant_expression_p)
12311 {
12312 #define RECUR(NODE)                             \
12313   tsubst_expr ((NODE), args, complain, in_decl, \
12314                integral_constant_expression_p)
12315   tree decl, init, cond, incr, auto_node;
12316
12317   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
12318   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
12319   decl = RECUR (TREE_OPERAND (init, 0));
12320   init = TREE_OPERAND (init, 1);
12321   auto_node = type_uses_auto (TREE_TYPE (decl));
12322   if (auto_node && init)
12323     {
12324       tree init_expr = init;
12325       if (TREE_CODE (init_expr) == DECL_EXPR)
12326         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
12327       init_expr = RECUR (init_expr);
12328       TREE_TYPE (decl)
12329         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
12330     }
12331   gcc_assert (!type_dependent_expression_p (decl));
12332
12333   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
12334     {
12335       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
12336       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
12337       if (TREE_CODE (incr) == MODIFY_EXPR)
12338         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
12339                                     RECUR (TREE_OPERAND (incr, 1)),
12340                                     complain);
12341       else
12342         incr = RECUR (incr);
12343       TREE_VEC_ELT (declv, i) = decl;
12344       TREE_VEC_ELT (initv, i) = init;
12345       TREE_VEC_ELT (condv, i) = cond;
12346       TREE_VEC_ELT (incrv, i) = incr;
12347       return;
12348     }
12349
12350   if (init && TREE_CODE (init) != DECL_EXPR)
12351     {
12352       tree c;
12353       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
12354         {
12355           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
12356                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
12357               && OMP_CLAUSE_DECL (c) == decl)
12358             break;
12359           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
12360                    && OMP_CLAUSE_DECL (c) == decl)
12361             error ("iteration variable %qD should not be firstprivate", decl);
12362           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
12363                    && OMP_CLAUSE_DECL (c) == decl)
12364             error ("iteration variable %qD should not be reduction", decl);
12365         }
12366       if (c == NULL)
12367         {
12368           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
12369           OMP_CLAUSE_DECL (c) = decl;
12370           c = finish_omp_clauses (c);
12371           if (c)
12372             {
12373               OMP_CLAUSE_CHAIN (c) = *clauses;
12374               *clauses = c;
12375             }
12376         }
12377     }
12378   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
12379   if (COMPARISON_CLASS_P (cond))
12380     cond = build2 (TREE_CODE (cond), boolean_type_node,
12381                    RECUR (TREE_OPERAND (cond, 0)),
12382                    RECUR (TREE_OPERAND (cond, 1)));
12383   else
12384     cond = RECUR (cond);
12385   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
12386   switch (TREE_CODE (incr))
12387     {
12388     case PREINCREMENT_EXPR:
12389     case PREDECREMENT_EXPR:
12390     case POSTINCREMENT_EXPR:
12391     case POSTDECREMENT_EXPR:
12392       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
12393                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
12394       break;
12395     case MODIFY_EXPR:
12396       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
12397           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
12398         {
12399           tree rhs = TREE_OPERAND (incr, 1);
12400           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
12401                          RECUR (TREE_OPERAND (incr, 0)),
12402                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
12403                                  RECUR (TREE_OPERAND (rhs, 0)),
12404                                  RECUR (TREE_OPERAND (rhs, 1))));
12405         }
12406       else
12407         incr = RECUR (incr);
12408       break;
12409     case MODOP_EXPR:
12410       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
12411           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
12412         {
12413           tree lhs = RECUR (TREE_OPERAND (incr, 0));
12414           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
12415                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
12416                                  TREE_TYPE (decl), lhs,
12417                                  RECUR (TREE_OPERAND (incr, 2))));
12418         }
12419       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
12420                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
12421                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
12422         {
12423           tree rhs = TREE_OPERAND (incr, 2);
12424           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
12425                          RECUR (TREE_OPERAND (incr, 0)),
12426                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
12427                                  RECUR (TREE_OPERAND (rhs, 0)),
12428                                  RECUR (TREE_OPERAND (rhs, 1))));
12429         }
12430       else
12431         incr = RECUR (incr);
12432       break;
12433     default:
12434       incr = RECUR (incr);
12435       break;
12436     }
12437
12438   TREE_VEC_ELT (declv, i) = decl;
12439   TREE_VEC_ELT (initv, i) = init;
12440   TREE_VEC_ELT (condv, i) = cond;
12441   TREE_VEC_ELT (incrv, i) = incr;
12442 #undef RECUR
12443 }
12444
12445 /* Like tsubst_copy for expressions, etc. but also does semantic
12446    processing.  */
12447
12448 static tree
12449 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
12450              bool integral_constant_expression_p)
12451 {
12452 #define RECUR(NODE)                             \
12453   tsubst_expr ((NODE), args, complain, in_decl, \
12454                integral_constant_expression_p)
12455
12456   tree stmt, tmp;
12457
12458   if (t == NULL_TREE || t == error_mark_node)
12459     return t;
12460
12461   if (EXPR_HAS_LOCATION (t))
12462     input_location = EXPR_LOCATION (t);
12463   if (STATEMENT_CODE_P (TREE_CODE (t)))
12464     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
12465
12466   switch (TREE_CODE (t))
12467     {
12468     case STATEMENT_LIST:
12469       {
12470         tree_stmt_iterator i;
12471         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
12472           RECUR (tsi_stmt (i));
12473         break;
12474       }
12475
12476     case CTOR_INITIALIZER:
12477       finish_mem_initializers (tsubst_initializer_list
12478                                (TREE_OPERAND (t, 0), args));
12479       break;
12480
12481     case RETURN_EXPR:
12482       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
12483       break;
12484
12485     case EXPR_STMT:
12486       tmp = RECUR (EXPR_STMT_EXPR (t));
12487       if (EXPR_STMT_STMT_EXPR_RESULT (t))
12488         finish_stmt_expr_expr (tmp, cur_stmt_expr);
12489       else
12490         finish_expr_stmt (tmp);
12491       break;
12492
12493     case USING_STMT:
12494       do_using_directive (USING_STMT_NAMESPACE (t));
12495       break;
12496
12497     case DECL_EXPR:
12498       {
12499         tree decl, pattern_decl;
12500         tree init;
12501
12502         pattern_decl = decl = DECL_EXPR_DECL (t);
12503         if (TREE_CODE (decl) == LABEL_DECL)
12504           finish_label_decl (DECL_NAME (decl));
12505         else if (TREE_CODE (decl) == USING_DECL)
12506           {
12507             tree scope = USING_DECL_SCOPE (decl);
12508             tree name = DECL_NAME (decl);
12509             tree decl;
12510
12511             scope = tsubst (scope, args, complain, in_decl);
12512             decl = lookup_qualified_name (scope, name,
12513                                           /*is_type_p=*/false,
12514                                           /*complain=*/false);
12515             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
12516               qualified_name_lookup_error (scope, name, decl, input_location);
12517             else
12518               do_local_using_decl (decl, scope, name);
12519           }
12520         else
12521           {
12522             init = DECL_INITIAL (decl);
12523             decl = tsubst (decl, args, complain, in_decl);
12524             if (decl != error_mark_node)
12525               {
12526                 /* By marking the declaration as instantiated, we avoid
12527                    trying to instantiate it.  Since instantiate_decl can't
12528                    handle local variables, and since we've already done
12529                    all that needs to be done, that's the right thing to
12530                    do.  */
12531                 if (TREE_CODE (decl) == VAR_DECL)
12532                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12533                 if (TREE_CODE (decl) == VAR_DECL
12534                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
12535                   /* Anonymous aggregates are a special case.  */
12536                   finish_anon_union (decl);
12537                 else
12538                   {
12539                     int const_init = false;
12540                     maybe_push_decl (decl);
12541                     if (TREE_CODE (decl) == VAR_DECL
12542                         && DECL_PRETTY_FUNCTION_P (decl))
12543                       {
12544                         /* For __PRETTY_FUNCTION__ we have to adjust the
12545                            initializer.  */
12546                         const char *const name
12547                           = cxx_printable_name (current_function_decl, 2);
12548                         init = cp_fname_init (name, &TREE_TYPE (decl));
12549                       }
12550                     else
12551                       {
12552                         tree t = RECUR (init);
12553
12554                         if (init && !t)
12555                           {
12556                             /* If we had an initializer but it
12557                                instantiated to nothing,
12558                                value-initialize the object.  This will
12559                                only occur when the initializer was a
12560                                pack expansion where the parameter packs
12561                                used in that expansion were of length
12562                                zero.  */
12563                             init = build_value_init (TREE_TYPE (decl),
12564                                                      complain);
12565                             if (TREE_CODE (init) == AGGR_INIT_EXPR)
12566                               init = get_target_expr_sfinae (init, complain);
12567                           }
12568                         else
12569                           init = t;
12570                       }
12571
12572                     if (TREE_CODE (decl) == VAR_DECL)
12573                       const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
12574                                     (pattern_decl));
12575                     cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
12576                   }
12577               }
12578           }
12579
12580         /* A DECL_EXPR can also be used as an expression, in the condition
12581            clause of an if/for/while construct.  */
12582         return decl;
12583       }
12584
12585     case FOR_STMT:
12586       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12587       RECUR (FOR_INIT_STMT (t));
12588       finish_for_init_stmt (stmt);
12589       tmp = RECUR (FOR_COND (t));
12590       finish_for_cond (tmp, stmt);
12591       tmp = RECUR (FOR_EXPR (t));
12592       finish_for_expr (tmp, stmt);
12593       RECUR (FOR_BODY (t));
12594       finish_for_stmt (stmt);
12595       break;
12596
12597     case RANGE_FOR_STMT:
12598       {
12599         tree decl, expr;
12600         stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12601         decl = RANGE_FOR_DECL (t);
12602         decl = tsubst (decl, args, complain, in_decl);
12603         maybe_push_decl (decl);
12604         expr = RECUR (RANGE_FOR_EXPR (t));
12605         stmt = cp_convert_range_for (stmt, decl, expr);
12606         RECUR (RANGE_FOR_BODY (t));
12607         finish_for_stmt (stmt);
12608       }
12609       break;
12610
12611     case WHILE_STMT:
12612       stmt = begin_while_stmt ();
12613       tmp = RECUR (WHILE_COND (t));
12614       finish_while_stmt_cond (tmp, stmt);
12615       RECUR (WHILE_BODY (t));
12616       finish_while_stmt (stmt);
12617       break;
12618
12619     case DO_STMT:
12620       stmt = begin_do_stmt ();
12621       RECUR (DO_BODY (t));
12622       finish_do_body (stmt);
12623       tmp = RECUR (DO_COND (t));
12624       finish_do_stmt (tmp, stmt);
12625       break;
12626
12627     case IF_STMT:
12628       stmt = begin_if_stmt ();
12629       tmp = RECUR (IF_COND (t));
12630       finish_if_stmt_cond (tmp, stmt);
12631       RECUR (THEN_CLAUSE (t));
12632       finish_then_clause (stmt);
12633
12634       if (ELSE_CLAUSE (t))
12635         {
12636           begin_else_clause (stmt);
12637           RECUR (ELSE_CLAUSE (t));
12638           finish_else_clause (stmt);
12639         }
12640
12641       finish_if_stmt (stmt);
12642       break;
12643
12644     case BIND_EXPR:
12645       if (BIND_EXPR_BODY_BLOCK (t))
12646         stmt = begin_function_body ();
12647       else
12648         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
12649                                     ? BCS_TRY_BLOCK : 0);
12650
12651       RECUR (BIND_EXPR_BODY (t));
12652
12653       if (BIND_EXPR_BODY_BLOCK (t))
12654         finish_function_body (stmt);
12655       else
12656         finish_compound_stmt (stmt);
12657       break;
12658
12659     case BREAK_STMT:
12660       finish_break_stmt ();
12661       break;
12662
12663     case CONTINUE_STMT:
12664       finish_continue_stmt ();
12665       break;
12666
12667     case SWITCH_STMT:
12668       stmt = begin_switch_stmt ();
12669       tmp = RECUR (SWITCH_STMT_COND (t));
12670       finish_switch_cond (tmp, stmt);
12671       RECUR (SWITCH_STMT_BODY (t));
12672       finish_switch_stmt (stmt);
12673       break;
12674
12675     case CASE_LABEL_EXPR:
12676       finish_case_label (EXPR_LOCATION (t),
12677                          RECUR (CASE_LOW (t)),
12678                          RECUR (CASE_HIGH (t)));
12679       break;
12680
12681     case LABEL_EXPR:
12682       {
12683         tree decl = LABEL_EXPR_LABEL (t);
12684         tree label;
12685
12686         label = finish_label_stmt (DECL_NAME (decl));
12687         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
12688           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
12689       }
12690       break;
12691
12692     case GOTO_EXPR:
12693       tmp = GOTO_DESTINATION (t);
12694       if (TREE_CODE (tmp) != LABEL_DECL)
12695         /* Computed goto's must be tsubst'd into.  On the other hand,
12696            non-computed gotos must not be; the identifier in question
12697            will have no binding.  */
12698         tmp = RECUR (tmp);
12699       else
12700         tmp = DECL_NAME (tmp);
12701       finish_goto_stmt (tmp);
12702       break;
12703
12704     case ASM_EXPR:
12705       tmp = finish_asm_stmt
12706         (ASM_VOLATILE_P (t),
12707          RECUR (ASM_STRING (t)),
12708          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
12709          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
12710          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
12711          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
12712       {
12713         tree asm_expr = tmp;
12714         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
12715           asm_expr = TREE_OPERAND (asm_expr, 0);
12716         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
12717       }
12718       break;
12719
12720     case TRY_BLOCK:
12721       if (CLEANUP_P (t))
12722         {
12723           stmt = begin_try_block ();
12724           RECUR (TRY_STMTS (t));
12725           finish_cleanup_try_block (stmt);
12726           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
12727         }
12728       else
12729         {
12730           tree compound_stmt = NULL_TREE;
12731
12732           if (FN_TRY_BLOCK_P (t))
12733             stmt = begin_function_try_block (&compound_stmt);
12734           else
12735             stmt = begin_try_block ();
12736
12737           RECUR (TRY_STMTS (t));
12738
12739           if (FN_TRY_BLOCK_P (t))
12740             finish_function_try_block (stmt);
12741           else
12742             finish_try_block (stmt);
12743
12744           RECUR (TRY_HANDLERS (t));
12745           if (FN_TRY_BLOCK_P (t))
12746             finish_function_handler_sequence (stmt, compound_stmt);
12747           else
12748             finish_handler_sequence (stmt);
12749         }
12750       break;
12751
12752     case HANDLER:
12753       {
12754         tree decl = HANDLER_PARMS (t);
12755
12756         if (decl)
12757           {
12758             decl = tsubst (decl, args, complain, in_decl);
12759             /* Prevent instantiate_decl from trying to instantiate
12760                this variable.  We've already done all that needs to be
12761                done.  */
12762             if (decl != error_mark_node)
12763               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12764           }
12765         stmt = begin_handler ();
12766         finish_handler_parms (decl, stmt);
12767         RECUR (HANDLER_BODY (t));
12768         finish_handler (stmt);
12769       }
12770       break;
12771
12772     case TAG_DEFN:
12773       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12774       break;
12775
12776     case STATIC_ASSERT:
12777       {
12778         tree condition = 
12779           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
12780                        args,
12781                        complain, in_decl,
12782                        /*integral_constant_expression_p=*/true);
12783         finish_static_assert (condition,
12784                               STATIC_ASSERT_MESSAGE (t),
12785                               STATIC_ASSERT_SOURCE_LOCATION (t),
12786                               /*member_p=*/false);
12787       }
12788       break;
12789
12790     case OMP_PARALLEL:
12791       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
12792                                 args, complain, in_decl);
12793       stmt = begin_omp_parallel ();
12794       RECUR (OMP_PARALLEL_BODY (t));
12795       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
12796         = OMP_PARALLEL_COMBINED (t);
12797       break;
12798
12799     case OMP_TASK:
12800       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
12801                                 args, complain, in_decl);
12802       stmt = begin_omp_task ();
12803       RECUR (OMP_TASK_BODY (t));
12804       finish_omp_task (tmp, stmt);
12805       break;
12806
12807     case OMP_FOR:
12808       {
12809         tree clauses, body, pre_body;
12810         tree declv, initv, condv, incrv;
12811         int i;
12812
12813         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
12814                                       args, complain, in_decl);
12815         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12816         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12817         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12818         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12819
12820         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
12821           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
12822                                    &clauses, args, complain, in_decl,
12823                                    integral_constant_expression_p);
12824
12825         stmt = begin_omp_structured_block ();
12826
12827         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
12828           if (TREE_VEC_ELT (initv, i) == NULL
12829               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
12830             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
12831           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
12832             {
12833               tree init = RECUR (TREE_VEC_ELT (initv, i));
12834               gcc_assert (init == TREE_VEC_ELT (declv, i));
12835               TREE_VEC_ELT (initv, i) = NULL_TREE;
12836             }
12837           else
12838             {
12839               tree decl_expr = TREE_VEC_ELT (initv, i);
12840               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
12841               gcc_assert (init != NULL);
12842               TREE_VEC_ELT (initv, i) = RECUR (init);
12843               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
12844               RECUR (decl_expr);
12845               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
12846             }
12847
12848         pre_body = push_stmt_list ();
12849         RECUR (OMP_FOR_PRE_BODY (t));
12850         pre_body = pop_stmt_list (pre_body);
12851
12852         body = push_stmt_list ();
12853         RECUR (OMP_FOR_BODY (t));
12854         body = pop_stmt_list (body);
12855
12856         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
12857                             body, pre_body, clauses);
12858
12859         add_stmt (finish_omp_structured_block (stmt));
12860       }
12861       break;
12862
12863     case OMP_SECTIONS:
12864     case OMP_SINGLE:
12865       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
12866       stmt = push_stmt_list ();
12867       RECUR (OMP_BODY (t));
12868       stmt = pop_stmt_list (stmt);
12869
12870       t = copy_node (t);
12871       OMP_BODY (t) = stmt;
12872       OMP_CLAUSES (t) = tmp;
12873       add_stmt (t);
12874       break;
12875
12876     case OMP_SECTION:
12877     case OMP_CRITICAL:
12878     case OMP_MASTER:
12879     case OMP_ORDERED:
12880       stmt = push_stmt_list ();
12881       RECUR (OMP_BODY (t));
12882       stmt = pop_stmt_list (stmt);
12883
12884       t = copy_node (t);
12885       OMP_BODY (t) = stmt;
12886       add_stmt (t);
12887       break;
12888
12889     case OMP_ATOMIC:
12890       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
12891       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
12892         {
12893           tree op1 = TREE_OPERAND (t, 1);
12894           tree rhs1 = NULL_TREE;
12895           tree lhs, rhs;
12896           if (TREE_CODE (op1) == COMPOUND_EXPR)
12897             {
12898               rhs1 = RECUR (TREE_OPERAND (op1, 0));
12899               op1 = TREE_OPERAND (op1, 1);
12900             }
12901           lhs = RECUR (TREE_OPERAND (op1, 0));
12902           rhs = RECUR (TREE_OPERAND (op1, 1));
12903           finish_omp_atomic (OMP_ATOMIC, TREE_CODE (op1), lhs, rhs,
12904                              NULL_TREE, NULL_TREE, rhs1);
12905         }
12906       else
12907         {
12908           tree op1 = TREE_OPERAND (t, 1);
12909           tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
12910           tree rhs1 = NULL_TREE;
12911           enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
12912           enum tree_code opcode = NOP_EXPR;
12913           if (code == OMP_ATOMIC_READ)
12914             {
12915               v = RECUR (TREE_OPERAND (op1, 0));
12916               lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
12917             }
12918           else if (code == OMP_ATOMIC_CAPTURE_OLD
12919                    || code == OMP_ATOMIC_CAPTURE_NEW)
12920             {
12921               tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
12922               v = RECUR (TREE_OPERAND (op1, 0));
12923               lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
12924               if (TREE_CODE (op11) == COMPOUND_EXPR)
12925                 {
12926                   rhs1 = RECUR (TREE_OPERAND (op11, 0));
12927                   op11 = TREE_OPERAND (op11, 1);
12928                 }
12929               lhs = RECUR (TREE_OPERAND (op11, 0));
12930               rhs = RECUR (TREE_OPERAND (op11, 1));
12931               opcode = TREE_CODE (op11);
12932             }
12933           else
12934             {
12935               code = OMP_ATOMIC;
12936               lhs = RECUR (TREE_OPERAND (op1, 0));
12937               rhs = RECUR (TREE_OPERAND (op1, 1));
12938             }
12939           finish_omp_atomic (code, opcode, lhs, rhs, v, lhs1, rhs1);
12940         }
12941       break;
12942
12943     case EXPR_PACK_EXPANSION:
12944       error ("invalid use of pack expansion expression");
12945       return error_mark_node;
12946
12947     case NONTYPE_ARGUMENT_PACK:
12948       error ("use %<...%> to expand argument pack");
12949       return error_mark_node;
12950
12951     default:
12952       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
12953
12954       return tsubst_copy_and_build (t, args, complain, in_decl,
12955                                     /*function_p=*/false,
12956                                     integral_constant_expression_p);
12957     }
12958
12959   return NULL_TREE;
12960 #undef RECUR
12961 }
12962
12963 /* T is a postfix-expression that is not being used in a function
12964    call.  Return the substituted version of T.  */
12965
12966 static tree
12967 tsubst_non_call_postfix_expression (tree t, tree args,
12968                                     tsubst_flags_t complain,
12969                                     tree in_decl)
12970 {
12971   if (TREE_CODE (t) == SCOPE_REF)
12972     t = tsubst_qualified_id (t, args, complain, in_decl,
12973                              /*done=*/false, /*address_p=*/false);
12974   else
12975     t = tsubst_copy_and_build (t, args, complain, in_decl,
12976                                /*function_p=*/false,
12977                                /*integral_constant_expression_p=*/false);
12978
12979   return t;
12980 }
12981
12982 /* Like tsubst but deals with expressions and performs semantic
12983    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
12984
12985 tree
12986 tsubst_copy_and_build (tree t,
12987                        tree args,
12988                        tsubst_flags_t complain,
12989                        tree in_decl,
12990                        bool function_p,
12991                        bool integral_constant_expression_p)
12992 {
12993 #define RECUR(NODE)                                             \
12994   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
12995                          /*function_p=*/false,                  \
12996                          integral_constant_expression_p)
12997
12998   tree op1;
12999
13000   if (t == NULL_TREE || t == error_mark_node)
13001     return t;
13002
13003   switch (TREE_CODE (t))
13004     {
13005     case USING_DECL:
13006       t = DECL_NAME (t);
13007       /* Fall through.  */
13008     case IDENTIFIER_NODE:
13009       {
13010         tree decl;
13011         cp_id_kind idk;
13012         bool non_integral_constant_expression_p;
13013         const char *error_msg;
13014
13015         if (IDENTIFIER_TYPENAME_P (t))
13016           {
13017             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13018             t = mangle_conv_op_name_for_type (new_type);
13019           }
13020
13021         /* Look up the name.  */
13022         decl = lookup_name (t);
13023
13024         /* By convention, expressions use ERROR_MARK_NODE to indicate
13025            failure, not NULL_TREE.  */
13026         if (decl == NULL_TREE)
13027           decl = error_mark_node;
13028
13029         decl = finish_id_expression (t, decl, NULL_TREE,
13030                                      &idk,
13031                                      integral_constant_expression_p,
13032                                      /*allow_non_integral_constant_expression_p=*/false,
13033                                      &non_integral_constant_expression_p,
13034                                      /*template_p=*/false,
13035                                      /*done=*/true,
13036                                      /*address_p=*/false,
13037                                      /*template_arg_p=*/false,
13038                                      &error_msg,
13039                                      input_location);
13040         if (error_msg)
13041           error (error_msg);
13042         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
13043           {
13044             if (complain & tf_error)
13045               unqualified_name_lookup_error (decl);
13046             decl = error_mark_node;
13047           }
13048         return decl;
13049       }
13050
13051     case TEMPLATE_ID_EXPR:
13052       {
13053         tree object;
13054         tree templ = RECUR (TREE_OPERAND (t, 0));
13055         tree targs = TREE_OPERAND (t, 1);
13056
13057         if (targs)
13058           targs = tsubst_template_args (targs, args, complain, in_decl);
13059
13060         if (TREE_CODE (templ) == COMPONENT_REF)
13061           {
13062             object = TREE_OPERAND (templ, 0);
13063             templ = TREE_OPERAND (templ, 1);
13064           }
13065         else
13066           object = NULL_TREE;
13067         templ = lookup_template_function (templ, targs);
13068
13069         if (object)
13070           return build3 (COMPONENT_REF, TREE_TYPE (templ),
13071                          object, templ, NULL_TREE);
13072         else
13073           return baselink_for_fns (templ);
13074       }
13075
13076     case INDIRECT_REF:
13077       {
13078         tree r = RECUR (TREE_OPERAND (t, 0));
13079
13080         if (REFERENCE_REF_P (t))
13081           {
13082             /* A type conversion to reference type will be enclosed in
13083                such an indirect ref, but the substitution of the cast
13084                will have also added such an indirect ref.  */
13085             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
13086               r = convert_from_reference (r);
13087           }
13088         else
13089           r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
13090         return r;
13091       }
13092
13093     case NOP_EXPR:
13094       return build_nop
13095         (tsubst (TREE_TYPE (t), args, complain, in_decl),
13096          RECUR (TREE_OPERAND (t, 0)));
13097
13098     case IMPLICIT_CONV_EXPR:
13099       {
13100         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13101         tree expr = RECUR (TREE_OPERAND (t, 0));
13102         int flags = LOOKUP_IMPLICIT;
13103         if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
13104           flags = LOOKUP_NORMAL;
13105         return perform_implicit_conversion_flags (type, expr, complain,
13106                                                   flags);
13107       }
13108
13109     case CONVERT_EXPR:
13110       return build1
13111         (CONVERT_EXPR,
13112          tsubst (TREE_TYPE (t), args, complain, in_decl),
13113          RECUR (TREE_OPERAND (t, 0)));
13114
13115     case CAST_EXPR:
13116     case REINTERPRET_CAST_EXPR:
13117     case CONST_CAST_EXPR:
13118     case DYNAMIC_CAST_EXPR:
13119     case STATIC_CAST_EXPR:
13120       {
13121         tree type;
13122         tree op;
13123
13124         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13125         if (integral_constant_expression_p
13126             && !cast_valid_in_integral_constant_expression_p (type))
13127           {
13128             if (complain & tf_error)
13129               error ("a cast to a type other than an integral or "
13130                      "enumeration type cannot appear in a constant-expression");
13131             return error_mark_node; 
13132           }
13133
13134         op = RECUR (TREE_OPERAND (t, 0));
13135
13136         switch (TREE_CODE (t))
13137           {
13138           case CAST_EXPR:
13139             return build_functional_cast (type, op, complain);
13140           case REINTERPRET_CAST_EXPR:
13141             return build_reinterpret_cast (type, op, complain);
13142           case CONST_CAST_EXPR:
13143             return build_const_cast (type, op, complain);
13144           case DYNAMIC_CAST_EXPR:
13145             return build_dynamic_cast (type, op, complain);
13146           case STATIC_CAST_EXPR:
13147             return build_static_cast (type, op, complain);
13148           default:
13149             gcc_unreachable ();
13150           }
13151       }
13152
13153     case POSTDECREMENT_EXPR:
13154     case POSTINCREMENT_EXPR:
13155       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13156                                                 args, complain, in_decl);
13157       return build_x_unary_op (TREE_CODE (t), op1, complain);
13158
13159     case PREDECREMENT_EXPR:
13160     case PREINCREMENT_EXPR:
13161     case NEGATE_EXPR:
13162     case BIT_NOT_EXPR:
13163     case ABS_EXPR:
13164     case TRUTH_NOT_EXPR:
13165     case UNARY_PLUS_EXPR:  /* Unary + */
13166     case REALPART_EXPR:
13167     case IMAGPART_EXPR:
13168       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
13169                                complain);
13170
13171     case ADDR_EXPR:
13172       op1 = TREE_OPERAND (t, 0);
13173       if (TREE_CODE (op1) == LABEL_DECL)
13174         return finish_label_address_expr (DECL_NAME (op1),
13175                                           EXPR_LOCATION (op1));
13176       if (TREE_CODE (op1) == SCOPE_REF)
13177         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
13178                                    /*done=*/true, /*address_p=*/true);
13179       else
13180         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
13181                                                   in_decl);
13182       return build_x_unary_op (ADDR_EXPR, op1, complain);
13183
13184     case PLUS_EXPR:
13185     case MINUS_EXPR:
13186     case MULT_EXPR:
13187     case TRUNC_DIV_EXPR:
13188     case CEIL_DIV_EXPR:
13189     case FLOOR_DIV_EXPR:
13190     case ROUND_DIV_EXPR:
13191     case EXACT_DIV_EXPR:
13192     case BIT_AND_EXPR:
13193     case BIT_IOR_EXPR:
13194     case BIT_XOR_EXPR:
13195     case TRUNC_MOD_EXPR:
13196     case FLOOR_MOD_EXPR:
13197     case TRUTH_ANDIF_EXPR:
13198     case TRUTH_ORIF_EXPR:
13199     case TRUTH_AND_EXPR:
13200     case TRUTH_OR_EXPR:
13201     case RSHIFT_EXPR:
13202     case LSHIFT_EXPR:
13203     case RROTATE_EXPR:
13204     case LROTATE_EXPR:
13205     case EQ_EXPR:
13206     case NE_EXPR:
13207     case MAX_EXPR:
13208     case MIN_EXPR:
13209     case LE_EXPR:
13210     case GE_EXPR:
13211     case LT_EXPR:
13212     case GT_EXPR:
13213     case MEMBER_REF:
13214     case DOTSTAR_EXPR:
13215       return build_x_binary_op
13216         (TREE_CODE (t),
13217          RECUR (TREE_OPERAND (t, 0)),
13218          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
13219           ? ERROR_MARK
13220           : TREE_CODE (TREE_OPERAND (t, 0))),
13221          RECUR (TREE_OPERAND (t, 1)),
13222          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
13223           ? ERROR_MARK
13224           : TREE_CODE (TREE_OPERAND (t, 1))),
13225          /*overload=*/NULL,
13226          complain);
13227
13228     case SCOPE_REF:
13229       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
13230                                   /*address_p=*/false);
13231     case ARRAY_REF:
13232       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13233                                                 args, complain, in_decl);
13234       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
13235
13236     case SIZEOF_EXPR:
13237       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
13238         return tsubst_copy (t, args, complain, in_decl);
13239       /* Fall through */
13240       
13241     case ALIGNOF_EXPR:
13242       op1 = TREE_OPERAND (t, 0);
13243       if (!args)
13244         {
13245           /* When there are no ARGS, we are trying to evaluate a
13246              non-dependent expression from the parser.  Trying to do
13247              the substitutions may not work.  */
13248           if (!TYPE_P (op1))
13249             op1 = TREE_TYPE (op1);
13250         }
13251       else
13252         {
13253           ++cp_unevaluated_operand;
13254           ++c_inhibit_evaluation_warnings;
13255           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13256                                        /*function_p=*/false,
13257                                        /*integral_constant_expression_p=*/false);
13258           --cp_unevaluated_operand;
13259           --c_inhibit_evaluation_warnings;
13260         }
13261       if (TYPE_P (op1))
13262         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
13263                                            complain & tf_error);
13264       else
13265         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
13266                                            complain & tf_error);
13267
13268     case AT_ENCODE_EXPR:
13269       {
13270         op1 = TREE_OPERAND (t, 0);
13271         ++cp_unevaluated_operand;
13272         ++c_inhibit_evaluation_warnings;
13273         op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13274                                      /*function_p=*/false,
13275                                      /*integral_constant_expression_p=*/false);
13276         --cp_unevaluated_operand;
13277         --c_inhibit_evaluation_warnings;
13278         return objc_build_encode_expr (op1);
13279       }
13280
13281     case NOEXCEPT_EXPR:
13282       op1 = TREE_OPERAND (t, 0);
13283       ++cp_unevaluated_operand;
13284       ++c_inhibit_evaluation_warnings;
13285       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13286                                    /*function_p=*/false,
13287                                    /*integral_constant_expression_p=*/false);
13288       --cp_unevaluated_operand;
13289       --c_inhibit_evaluation_warnings;
13290       return finish_noexcept_expr (op1, complain);
13291
13292     case MODOP_EXPR:
13293       {
13294         tree r = build_x_modify_expr
13295           (RECUR (TREE_OPERAND (t, 0)),
13296            TREE_CODE (TREE_OPERAND (t, 1)),
13297            RECUR (TREE_OPERAND (t, 2)),
13298            complain);
13299         /* TREE_NO_WARNING must be set if either the expression was
13300            parenthesized or it uses an operator such as >>= rather
13301            than plain assignment.  In the former case, it was already
13302            set and must be copied.  In the latter case,
13303            build_x_modify_expr sets it and it must not be reset
13304            here.  */
13305         if (TREE_NO_WARNING (t))
13306           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
13307         return r;
13308       }
13309
13310     case ARROW_EXPR:
13311       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13312                                                 args, complain, in_decl);
13313       /* Remember that there was a reference to this entity.  */
13314       if (DECL_P (op1))
13315         mark_used (op1);
13316       return build_x_arrow (op1);
13317
13318     case NEW_EXPR:
13319       {
13320         tree placement = RECUR (TREE_OPERAND (t, 0));
13321         tree init = RECUR (TREE_OPERAND (t, 3));
13322         VEC(tree,gc) *placement_vec;
13323         VEC(tree,gc) *init_vec;
13324         tree ret;
13325
13326         if (placement == NULL_TREE)
13327           placement_vec = NULL;
13328         else
13329           {
13330             placement_vec = make_tree_vector ();
13331             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
13332               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
13333           }
13334
13335         /* If there was an initializer in the original tree, but it
13336            instantiated to an empty list, then we should pass a
13337            non-NULL empty vector to tell build_new that it was an
13338            empty initializer() rather than no initializer.  This can
13339            only happen when the initializer is a pack expansion whose
13340            parameter packs are of length zero.  */
13341         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
13342           init_vec = NULL;
13343         else
13344           {
13345             init_vec = make_tree_vector ();
13346             if (init == void_zero_node)
13347               gcc_assert (init_vec != NULL);
13348             else
13349               {
13350                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
13351                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
13352               }
13353           }
13354
13355         ret = build_new (&placement_vec,
13356                          tsubst (TREE_OPERAND (t, 1), args, complain, in_decl),
13357                          RECUR (TREE_OPERAND (t, 2)),
13358                          &init_vec,
13359                          NEW_EXPR_USE_GLOBAL (t),
13360                          complain);
13361
13362         if (placement_vec != NULL)
13363           release_tree_vector (placement_vec);
13364         if (init_vec != NULL)
13365           release_tree_vector (init_vec);
13366
13367         return ret;
13368       }
13369
13370     case DELETE_EXPR:
13371      return delete_sanity
13372        (RECUR (TREE_OPERAND (t, 0)),
13373         RECUR (TREE_OPERAND (t, 1)),
13374         DELETE_EXPR_USE_VEC (t),
13375         DELETE_EXPR_USE_GLOBAL (t),
13376         complain);
13377
13378     case COMPOUND_EXPR:
13379       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
13380                                     RECUR (TREE_OPERAND (t, 1)),
13381                                     complain);
13382
13383     case CALL_EXPR:
13384       {
13385         tree function;
13386         VEC(tree,gc) *call_args;
13387         unsigned int nargs, i;
13388         bool qualified_p;
13389         bool koenig_p;
13390         tree ret;
13391
13392         function = CALL_EXPR_FN (t);
13393         /* When we parsed the expression,  we determined whether or
13394            not Koenig lookup should be performed.  */
13395         koenig_p = KOENIG_LOOKUP_P (t);
13396         if (TREE_CODE (function) == SCOPE_REF)
13397           {
13398             qualified_p = true;
13399             function = tsubst_qualified_id (function, args, complain, in_decl,
13400                                             /*done=*/false,
13401                                             /*address_p=*/false);
13402           }
13403         else if (koenig_p && TREE_CODE (function) == IDENTIFIER_NODE)
13404           {
13405             /* Do nothing; calling tsubst_copy_and_build on an identifier
13406                would incorrectly perform unqualified lookup again.
13407
13408                Note that we can also have an IDENTIFIER_NODE if the earlier
13409                unqualified lookup found a member function; in that case
13410                koenig_p will be false and we do want to do the lookup
13411                again to find the instantiated member function.
13412
13413                FIXME but doing that causes c++/15272, so we need to stop
13414                using IDENTIFIER_NODE in that situation.  */
13415             qualified_p = false;
13416           }
13417         else
13418           {
13419             if (TREE_CODE (function) == COMPONENT_REF)
13420               {
13421                 tree op = TREE_OPERAND (function, 1);
13422
13423                 qualified_p = (TREE_CODE (op) == SCOPE_REF
13424                                || (BASELINK_P (op)
13425                                    && BASELINK_QUALIFIED_P (op)));
13426               }
13427             else
13428               qualified_p = false;
13429
13430             function = tsubst_copy_and_build (function, args, complain,
13431                                               in_decl,
13432                                               !qualified_p,
13433                                               integral_constant_expression_p);
13434
13435             if (BASELINK_P (function))
13436               qualified_p = true;
13437           }
13438
13439         nargs = call_expr_nargs (t);
13440         call_args = make_tree_vector ();
13441         for (i = 0; i < nargs; ++i)
13442           {
13443             tree arg = CALL_EXPR_ARG (t, i);
13444
13445             if (!PACK_EXPANSION_P (arg))
13446               VEC_safe_push (tree, gc, call_args,
13447                              RECUR (CALL_EXPR_ARG (t, i)));
13448             else
13449               {
13450                 /* Expand the pack expansion and push each entry onto
13451                    CALL_ARGS.  */
13452                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
13453                 if (TREE_CODE (arg) == TREE_VEC)
13454                   {
13455                     unsigned int len, j;
13456
13457                     len = TREE_VEC_LENGTH (arg);
13458                     for (j = 0; j < len; ++j)
13459                       {
13460                         tree value = TREE_VEC_ELT (arg, j);
13461                         if (value != NULL_TREE)
13462                           value = convert_from_reference (value);
13463                         VEC_safe_push (tree, gc, call_args, value);
13464                       }
13465                   }
13466                 else
13467                   {
13468                     /* A partial substitution.  Add one entry.  */
13469                     VEC_safe_push (tree, gc, call_args, arg);
13470                   }
13471               }
13472           }
13473
13474         /* We do not perform argument-dependent lookup if normal
13475            lookup finds a non-function, in accordance with the
13476            expected resolution of DR 218.  */
13477         if (koenig_p
13478             && ((is_overloaded_fn (function)
13479                  /* If lookup found a member function, the Koenig lookup is
13480                     not appropriate, even if an unqualified-name was used
13481                     to denote the function.  */
13482                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
13483                 || TREE_CODE (function) == IDENTIFIER_NODE)
13484             /* Only do this when substitution turns a dependent call
13485                into a non-dependent call.  */
13486             && type_dependent_expression_p_push (t)
13487             && !any_type_dependent_arguments_p (call_args))
13488           function = perform_koenig_lookup (function, call_args, false,
13489                                             tf_none);
13490
13491         if (TREE_CODE (function) == IDENTIFIER_NODE
13492             && !any_type_dependent_arguments_p (call_args))
13493           {
13494             if (koenig_p && (complain & tf_warning_or_error))
13495               {
13496                 /* For backwards compatibility and good diagnostics, try
13497                    the unqualified lookup again if we aren't in SFINAE
13498                    context.  */
13499                 tree unq = (tsubst_copy_and_build
13500                             (function, args, complain, in_decl, true,
13501                              integral_constant_expression_p));
13502                 if (unq != function)
13503                   {
13504                     tree fn = unq;
13505                     if (TREE_CODE (fn) == COMPONENT_REF)
13506                       fn = TREE_OPERAND (fn, 1);
13507                     if (is_overloaded_fn (fn))
13508                       fn = get_first_fn (fn);
13509                     permerror (EXPR_LOC_OR_HERE (t),
13510                                "%qD was not declared in this scope, "
13511                                "and no declarations were found by "
13512                                "argument-dependent lookup at the point "
13513                                "of instantiation", function);
13514                     if (DECL_CLASS_SCOPE_P (fn))
13515                       {
13516                         inform (EXPR_LOC_OR_HERE (t),
13517                                 "declarations in dependent base %qT are "
13518                                 "not found by unqualified lookup",
13519                                 DECL_CLASS_CONTEXT (fn));
13520                         if (current_class_ptr)
13521                           inform (EXPR_LOC_OR_HERE (t),
13522                                   "use %<this->%D%> instead", function);
13523                         else
13524                           inform (EXPR_LOC_OR_HERE (t),
13525                                   "use %<%T::%D%> instead",
13526                                   current_class_name, function);
13527                       }
13528                     else
13529                       inform (0, "%q+D declared here, later in the "
13530                                 "translation unit", fn);
13531                     function = unq;
13532                   }
13533               }
13534             if (TREE_CODE (function) == IDENTIFIER_NODE)
13535               {
13536                 unqualified_name_lookup_error (function);
13537                 release_tree_vector (call_args);
13538                 return error_mark_node;
13539               }
13540           }
13541
13542         /* Remember that there was a reference to this entity.  */
13543         if (DECL_P (function))
13544           mark_used (function);
13545
13546         if (TREE_CODE (function) == OFFSET_REF)
13547           ret = build_offset_ref_call_from_tree (function, &call_args);
13548         else if (TREE_CODE (function) == COMPONENT_REF)
13549           {
13550             tree instance = TREE_OPERAND (function, 0);
13551             tree fn = TREE_OPERAND (function, 1);
13552
13553             if (processing_template_decl
13554                 && (type_dependent_expression_p (instance)
13555                     || (!BASELINK_P (fn)
13556                         && TREE_CODE (fn) != FIELD_DECL)
13557                     || type_dependent_expression_p (fn)
13558                     || any_type_dependent_arguments_p (call_args)))
13559               ret = build_nt_call_vec (function, call_args);
13560             else if (!BASELINK_P (fn))
13561               ret = finish_call_expr (function, &call_args,
13562                                        /*disallow_virtual=*/false,
13563                                        /*koenig_p=*/false,
13564                                        complain);
13565             else
13566               ret = (build_new_method_call
13567                       (instance, fn,
13568                        &call_args, NULL_TREE,
13569                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
13570                        /*fn_p=*/NULL,
13571                        complain));
13572           }
13573         else
13574           ret = finish_call_expr (function, &call_args,
13575                                   /*disallow_virtual=*/qualified_p,
13576                                   koenig_p,
13577                                   complain);
13578
13579         release_tree_vector (call_args);
13580
13581         return ret;
13582       }
13583
13584     case COND_EXPR:
13585       return build_x_conditional_expr
13586         (RECUR (TREE_OPERAND (t, 0)),
13587          RECUR (TREE_OPERAND (t, 1)),
13588          RECUR (TREE_OPERAND (t, 2)),
13589          complain);
13590
13591     case PSEUDO_DTOR_EXPR:
13592       return finish_pseudo_destructor_expr
13593         (RECUR (TREE_OPERAND (t, 0)),
13594          RECUR (TREE_OPERAND (t, 1)),
13595          tsubst (TREE_OPERAND (t, 2), args, complain, in_decl));
13596
13597     case TREE_LIST:
13598       {
13599         tree purpose, value, chain;
13600
13601         if (t == void_list_node)
13602           return t;
13603
13604         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
13605             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
13606           {
13607             /* We have pack expansions, so expand those and
13608                create a new list out of it.  */
13609             tree purposevec = NULL_TREE;
13610             tree valuevec = NULL_TREE;
13611             tree chain;
13612             int i, len = -1;
13613
13614             /* Expand the argument expressions.  */
13615             if (TREE_PURPOSE (t))
13616               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
13617                                                  complain, in_decl);
13618             if (TREE_VALUE (t))
13619               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
13620                                                complain, in_decl);
13621
13622             /* Build the rest of the list.  */
13623             chain = TREE_CHAIN (t);
13624             if (chain && chain != void_type_node)
13625               chain = RECUR (chain);
13626
13627             /* Determine the number of arguments.  */
13628             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
13629               {
13630                 len = TREE_VEC_LENGTH (purposevec);
13631                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
13632               }
13633             else if (TREE_CODE (valuevec) == TREE_VEC)
13634               len = TREE_VEC_LENGTH (valuevec);
13635             else
13636               {
13637                 /* Since we only performed a partial substitution into
13638                    the argument pack, we only return a single list
13639                    node.  */
13640                 if (purposevec == TREE_PURPOSE (t)
13641                     && valuevec == TREE_VALUE (t)
13642                     && chain == TREE_CHAIN (t))
13643                   return t;
13644
13645                 return tree_cons (purposevec, valuevec, chain);
13646               }
13647             
13648             /* Convert the argument vectors into a TREE_LIST */
13649             i = len;
13650             while (i > 0)
13651               {
13652                 /* Grab the Ith values.  */
13653                 i--;
13654                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
13655                                      : NULL_TREE;
13656                 value 
13657                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
13658                              : NULL_TREE;
13659
13660                 /* Build the list (backwards).  */
13661                 chain = tree_cons (purpose, value, chain);
13662               }
13663
13664             return chain;
13665           }
13666
13667         purpose = TREE_PURPOSE (t);
13668         if (purpose)
13669           purpose = RECUR (purpose);
13670         value = TREE_VALUE (t);
13671         if (value)
13672           value = RECUR (value);
13673         chain = TREE_CHAIN (t);
13674         if (chain && chain != void_type_node)
13675           chain = RECUR (chain);
13676         if (purpose == TREE_PURPOSE (t)
13677             && value == TREE_VALUE (t)
13678             && chain == TREE_CHAIN (t))
13679           return t;
13680         return tree_cons (purpose, value, chain);
13681       }
13682
13683     case COMPONENT_REF:
13684       {
13685         tree object;
13686         tree object_type;
13687         tree member;
13688
13689         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13690                                                      args, complain, in_decl);
13691         /* Remember that there was a reference to this entity.  */
13692         if (DECL_P (object))
13693           mark_used (object);
13694         object_type = TREE_TYPE (object);
13695
13696         member = TREE_OPERAND (t, 1);
13697         if (BASELINK_P (member))
13698           member = tsubst_baselink (member,
13699                                     non_reference (TREE_TYPE (object)),
13700                                     args, complain, in_decl);
13701         else
13702           member = tsubst_copy (member, args, complain, in_decl);
13703         if (member == error_mark_node)
13704           return error_mark_node;
13705
13706         if (object_type && !CLASS_TYPE_P (object_type))
13707           {
13708             if (SCALAR_TYPE_P (object_type))
13709               {
13710                 tree s = NULL_TREE;
13711                 tree dtor = member;
13712
13713                 if (TREE_CODE (dtor) == SCOPE_REF)
13714                   {
13715                     s = TREE_OPERAND (dtor, 0);
13716                     dtor = TREE_OPERAND (dtor, 1);
13717                   }
13718                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
13719                   {
13720                     dtor = TREE_OPERAND (dtor, 0);
13721                     if (TYPE_P (dtor))
13722                       return finish_pseudo_destructor_expr (object, s, dtor);
13723                   }
13724               }
13725           }
13726         else if (TREE_CODE (member) == SCOPE_REF
13727                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
13728           {
13729             tree tmpl;
13730             tree args;
13731
13732             /* Lookup the template functions now that we know what the
13733                scope is.  */
13734             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
13735             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
13736             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
13737                                             /*is_type_p=*/false,
13738                                             /*complain=*/false);
13739             if (BASELINK_P (member))
13740               {
13741                 BASELINK_FUNCTIONS (member)
13742                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
13743                               args);
13744                 member = (adjust_result_of_qualified_name_lookup
13745                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
13746                            object_type));
13747               }
13748             else
13749               {
13750                 qualified_name_lookup_error (object_type, tmpl, member,
13751                                              input_location);
13752                 return error_mark_node;
13753               }
13754           }
13755         else if (TREE_CODE (member) == SCOPE_REF
13756                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
13757                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
13758           {
13759             if (complain & tf_error)
13760               {
13761                 if (TYPE_P (TREE_OPERAND (member, 0)))
13762                   error ("%qT is not a class or namespace",
13763                          TREE_OPERAND (member, 0));
13764                 else
13765                   error ("%qD is not a class or namespace",
13766                          TREE_OPERAND (member, 0));
13767               }
13768             return error_mark_node;
13769           }
13770         else if (TREE_CODE (member) == FIELD_DECL)
13771           return finish_non_static_data_member (member, object, NULL_TREE);
13772
13773         return finish_class_member_access_expr (object, member,
13774                                                 /*template_p=*/false,
13775                                                 complain);
13776       }
13777
13778     case THROW_EXPR:
13779       return build_throw
13780         (RECUR (TREE_OPERAND (t, 0)));
13781
13782     case CONSTRUCTOR:
13783       {
13784         VEC(constructor_elt,gc) *n;
13785         constructor_elt *ce;
13786         unsigned HOST_WIDE_INT idx;
13787         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13788         bool process_index_p;
13789         int newlen;
13790         bool need_copy_p = false;
13791         tree r;
13792
13793         if (type == error_mark_node)
13794           return error_mark_node;
13795
13796         /* digest_init will do the wrong thing if we let it.  */
13797         if (type && TYPE_PTRMEMFUNC_P (type))
13798           return t;
13799
13800         /* We do not want to process the index of aggregate
13801            initializers as they are identifier nodes which will be
13802            looked up by digest_init.  */
13803         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
13804
13805         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
13806         newlen = VEC_length (constructor_elt, n);
13807         FOR_EACH_VEC_ELT (constructor_elt, n, idx, ce)
13808           {
13809             if (ce->index && process_index_p)
13810               ce->index = RECUR (ce->index);
13811
13812             if (PACK_EXPANSION_P (ce->value))
13813               {
13814                 /* Substitute into the pack expansion.  */
13815                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
13816                                                   in_decl);
13817
13818                 if (ce->value == error_mark_node
13819                     || PACK_EXPANSION_P (ce->value))
13820                   ;
13821                 else if (TREE_VEC_LENGTH (ce->value) == 1)
13822                   /* Just move the argument into place.  */
13823                   ce->value = TREE_VEC_ELT (ce->value, 0);
13824                 else
13825                   {
13826                     /* Update the length of the final CONSTRUCTOR
13827                        arguments vector, and note that we will need to
13828                        copy.*/
13829                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
13830                     need_copy_p = true;
13831                   }
13832               }
13833             else
13834               ce->value = RECUR (ce->value);
13835           }
13836
13837         if (need_copy_p)
13838           {
13839             VEC(constructor_elt,gc) *old_n = n;
13840
13841             n = VEC_alloc (constructor_elt, gc, newlen);
13842             FOR_EACH_VEC_ELT (constructor_elt, old_n, idx, ce)
13843               {
13844                 if (TREE_CODE (ce->value) == TREE_VEC)
13845                   {
13846                     int i, len = TREE_VEC_LENGTH (ce->value);
13847                     for (i = 0; i < len; ++i)
13848                       CONSTRUCTOR_APPEND_ELT (n, 0,
13849                                               TREE_VEC_ELT (ce->value, i));
13850                   }
13851                 else
13852                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
13853               }
13854           }
13855
13856         r = build_constructor (init_list_type_node, n);
13857         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
13858
13859         if (TREE_HAS_CONSTRUCTOR (t))
13860           return finish_compound_literal (type, r, complain);
13861
13862         TREE_TYPE (r) = type;
13863         return r;
13864       }
13865
13866     case TYPEID_EXPR:
13867       {
13868         tree operand_0 = TREE_OPERAND (t, 0);
13869         if (TYPE_P (operand_0))
13870           {
13871             operand_0 = tsubst (operand_0, args, complain, in_decl);
13872             return get_typeid (operand_0);
13873           }
13874         else
13875           {
13876             operand_0 = RECUR (operand_0);
13877             return build_typeid (operand_0);
13878           }
13879       }
13880
13881     case VAR_DECL:
13882       if (!args)
13883         return t;
13884       /* Fall through */
13885
13886     case PARM_DECL:
13887       {
13888         tree r = tsubst_copy (t, args, complain, in_decl);
13889
13890         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
13891           /* If the original type was a reference, we'll be wrapped in
13892              the appropriate INDIRECT_REF.  */
13893           r = convert_from_reference (r);
13894         return r;
13895       }
13896
13897     case VA_ARG_EXPR:
13898       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
13899                              tsubst (TREE_TYPE (t), args, complain, in_decl));
13900
13901     case OFFSETOF_EXPR:
13902       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
13903
13904     case TRAIT_EXPR:
13905       {
13906         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
13907                                   complain, in_decl);
13908
13909         tree type2 = TRAIT_EXPR_TYPE2 (t);
13910         if (type2)
13911           type2 = tsubst_copy (type2, args, complain, in_decl);
13912         
13913         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
13914       }
13915
13916     case STMT_EXPR:
13917       {
13918         tree old_stmt_expr = cur_stmt_expr;
13919         tree stmt_expr = begin_stmt_expr ();
13920
13921         cur_stmt_expr = stmt_expr;
13922         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
13923                      integral_constant_expression_p);
13924         stmt_expr = finish_stmt_expr (stmt_expr, false);
13925         cur_stmt_expr = old_stmt_expr;
13926
13927         /* If the resulting list of expression statement is empty,
13928            fold it further into void_zero_node.  */
13929         if (empty_expr_stmt_p (stmt_expr))
13930           stmt_expr = void_zero_node;
13931
13932         return stmt_expr;
13933       }
13934
13935     case CONST_DECL:
13936       t = tsubst_copy (t, args, complain, in_decl);
13937       /* As in finish_id_expression, we resolve enumeration constants
13938          to their underlying values.  */
13939       if (TREE_CODE (t) == CONST_DECL && !processing_template_decl)
13940         {
13941           used_types_insert (TREE_TYPE (t));
13942           return DECL_INITIAL (t);
13943         }
13944       return t;
13945
13946     case LAMBDA_EXPR:
13947       {
13948         tree r = build_lambda_expr ();
13949
13950         tree type = tsubst (LAMBDA_EXPR_CLOSURE (t), args, complain, NULL_TREE);
13951         LAMBDA_EXPR_CLOSURE (r) = type;
13952         CLASSTYPE_LAMBDA_EXPR (type) = r;
13953
13954         LAMBDA_EXPR_LOCATION (r)
13955           = LAMBDA_EXPR_LOCATION (t);
13956         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
13957           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
13958         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
13959         LAMBDA_EXPR_DISCRIMINATOR (r)
13960           = (LAMBDA_EXPR_DISCRIMINATOR (t));
13961         LAMBDA_EXPR_EXTRA_SCOPE (r)
13962           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
13963         if (LAMBDA_EXPR_RETURN_TYPE (t) == dependent_lambda_return_type_node)
13964           {
13965             LAMBDA_EXPR_RETURN_TYPE (r) = dependent_lambda_return_type_node;
13966             LAMBDA_EXPR_DEDUCE_RETURN_TYPE_P (r) = true;
13967           }
13968         else
13969           LAMBDA_EXPR_RETURN_TYPE (r)
13970             = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
13971
13972         gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
13973                     && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
13974
13975         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
13976         determine_visibility (TYPE_NAME (type));
13977         /* Now that we know visibility, instantiate the type so we have a
13978            declaration of the op() for later calls to lambda_function.  */
13979         complete_type (type);
13980
13981         /* The capture list refers to closure members, so this needs to
13982            wait until after we finish instantiating the type.  */
13983         LAMBDA_EXPR_CAPTURE_LIST (r)
13984           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
13985
13986         return build_lambda_object (r);
13987       }
13988
13989     case TARGET_EXPR:
13990       /* We can get here for a constant initializer of non-dependent type.
13991          FIXME stop folding in cp_parser_initializer_clause.  */
13992       gcc_assert (TREE_CONSTANT (t));
13993       {
13994         tree r = get_target_expr (RECUR (TARGET_EXPR_INITIAL (t)));
13995         TREE_CONSTANT (r) = true;
13996         return r;
13997       }
13998
13999     default:
14000       /* Handle Objective-C++ constructs, if appropriate.  */
14001       {
14002         tree subst
14003           = objcp_tsubst_copy_and_build (t, args, complain,
14004                                          in_decl, /*function_p=*/false);
14005         if (subst)
14006           return subst;
14007       }
14008       return tsubst_copy (t, args, complain, in_decl);
14009     }
14010
14011 #undef RECUR
14012 }
14013
14014 /* Verify that the instantiated ARGS are valid. For type arguments,
14015    make sure that the type's linkage is ok. For non-type arguments,
14016    make sure they are constants if they are integral or enumerations.
14017    Emit an error under control of COMPLAIN, and return TRUE on error.  */
14018
14019 static bool
14020 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
14021 {
14022   if (ARGUMENT_PACK_P (t))
14023     {
14024       tree vec = ARGUMENT_PACK_ARGS (t);
14025       int len = TREE_VEC_LENGTH (vec);
14026       bool result = false;
14027       int i;
14028
14029       for (i = 0; i < len; ++i)
14030         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
14031           result = true;
14032       return result;
14033     }
14034   else if (TYPE_P (t))
14035     {
14036       /* [basic.link]: A name with no linkage (notably, the name
14037          of a class or enumeration declared in a local scope)
14038          shall not be used to declare an entity with linkage.
14039          This implies that names with no linkage cannot be used as
14040          template arguments
14041
14042          DR 757 relaxes this restriction for C++0x.  */
14043       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
14044                  : no_linkage_check (t, /*relaxed_p=*/false));
14045
14046       if (nt)
14047         {
14048           /* DR 488 makes use of a type with no linkage cause
14049              type deduction to fail.  */
14050           if (complain & tf_error)
14051             {
14052               if (TYPE_ANONYMOUS_P (nt))
14053                 error ("%qT is/uses anonymous type", t);
14054               else
14055                 error ("template argument for %qD uses local type %qT",
14056                        tmpl, t);
14057             }
14058           return true;
14059         }
14060       /* In order to avoid all sorts of complications, we do not
14061          allow variably-modified types as template arguments.  */
14062       else if (variably_modified_type_p (t, NULL_TREE))
14063         {
14064           if (complain & tf_error)
14065             error ("%qT is a variably modified type", t);
14066           return true;
14067         }
14068     }
14069   /* A non-type argument of integral or enumerated type must be a
14070      constant.  */
14071   else if (TREE_TYPE (t)
14072            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
14073            && !TREE_CONSTANT (t))
14074     {
14075       if (complain & tf_error)
14076         error ("integral expression %qE is not constant", t);
14077       return true;
14078     }
14079   return false;
14080 }
14081
14082 static bool
14083 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
14084 {
14085   int ix, len = DECL_NTPARMS (tmpl);
14086   bool result = false;
14087
14088   for (ix = 0; ix != len; ix++)
14089     {
14090       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
14091         result = true;
14092     }
14093   if (result && (complain & tf_error))
14094     error ("  trying to instantiate %qD", tmpl);
14095   return result;
14096 }
14097
14098 /* In C++0x, it's possible to have a function template whose type depends
14099    on itself recursively.  This is most obvious with decltype, but can also
14100    occur with enumeration scope (c++/48969).  So we need to catch infinite
14101    recursion and reject the substitution at deduction time; this function
14102    will return error_mark_node for any repeated substitution.
14103
14104    This also catches excessive recursion such as when f<N> depends on
14105    f<N-1> across all integers, and returns error_mark_node for all the
14106    substitutions back up to the initial one.
14107
14108    This is, of course, not reentrant.  */
14109
14110 static tree
14111 deduction_tsubst_fntype (tree fn, tree targs, tsubst_flags_t complain)
14112 {
14113   static bool excessive_deduction_depth;
14114   static int deduction_depth;
14115   struct pending_template *old_last_pend = last_pending_template;
14116   struct tinst_level *old_error_tinst = last_error_tinst_level;
14117
14118   tree fntype = TREE_TYPE (fn);
14119   tree tinst;
14120   tree r;
14121
14122   if (excessive_deduction_depth)
14123     return error_mark_node;
14124
14125   tinst = build_tree_list (fn, targs);
14126   if (!push_tinst_level (tinst))
14127     {
14128       excessive_deduction_depth = true;
14129       ggc_free (tinst);
14130       return error_mark_node;
14131     }
14132
14133   input_location = DECL_SOURCE_LOCATION (fn);
14134   ++deduction_depth;
14135   push_deduction_access_scope (fn);
14136   r = tsubst (fntype, targs, complain, NULL_TREE);
14137   pop_deduction_access_scope (fn);
14138   --deduction_depth;
14139
14140   if (excessive_deduction_depth)
14141     {
14142       r = error_mark_node;
14143       if (deduction_depth == 0)
14144         /* Reset once we're all the way out.  */
14145         excessive_deduction_depth = false;
14146     }
14147
14148   pop_tinst_level ();
14149   /* We can't free this if a pending_template entry or last_error_tinst_level
14150      is pointing at it.  */
14151   if (last_pending_template == old_last_pend
14152       && last_error_tinst_level == old_error_tinst)
14153     ggc_free (tinst);
14154   return r;
14155 }
14156
14157 /* Instantiate the indicated variable or function template TMPL with
14158    the template arguments in TARG_PTR.  */
14159
14160 static tree
14161 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
14162 {
14163   tree targ_ptr = orig_args;
14164   tree fndecl;
14165   tree gen_tmpl;
14166   tree spec;
14167   HOST_WIDE_INT saved_processing_template_decl;
14168
14169   if (tmpl == error_mark_node)
14170     return error_mark_node;
14171
14172   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
14173
14174   /* If this function is a clone, handle it specially.  */
14175   if (DECL_CLONED_FUNCTION_P (tmpl))
14176     {
14177       tree spec;
14178       tree clone;
14179
14180       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
14181          DECL_CLONED_FUNCTION.  */
14182       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
14183                                    targ_ptr, complain);
14184       if (spec == error_mark_node)
14185         return error_mark_node;
14186
14187       /* Look for the clone.  */
14188       FOR_EACH_CLONE (clone, spec)
14189         if (DECL_NAME (clone) == DECL_NAME (tmpl))
14190           return clone;
14191       /* We should always have found the clone by now.  */
14192       gcc_unreachable ();
14193       return NULL_TREE;
14194     }
14195
14196   /* Check to see if we already have this specialization.  */
14197   gen_tmpl = most_general_template (tmpl);
14198   if (tmpl != gen_tmpl)
14199     /* The TMPL is a partial instantiation.  To get a full set of
14200        arguments we must add the arguments used to perform the
14201        partial instantiation.  */
14202     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
14203                                             targ_ptr);
14204
14205   /* It would be nice to avoid hashing here and then again in tsubst_decl,
14206      but it doesn't seem to be on the hot path.  */
14207   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
14208
14209   gcc_assert (tmpl == gen_tmpl
14210               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
14211                   == spec)
14212               || fndecl == NULL_TREE);
14213
14214   if (spec != NULL_TREE)
14215     return spec;
14216
14217   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
14218                                complain))
14219     return error_mark_node;
14220
14221   /* We are building a FUNCTION_DECL, during which the access of its
14222      parameters and return types have to be checked.  However this
14223      FUNCTION_DECL which is the desired context for access checking
14224      is not built yet.  We solve this chicken-and-egg problem by
14225      deferring all checks until we have the FUNCTION_DECL.  */
14226   push_deferring_access_checks (dk_deferred);
14227
14228   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
14229      (because, for example, we have encountered a non-dependent
14230      function call in the body of a template function and must now
14231      determine which of several overloaded functions will be called),
14232      within the instantiation itself we are not processing a
14233      template.  */  
14234   saved_processing_template_decl = processing_template_decl;
14235   processing_template_decl = 0;
14236   /* Substitute template parameters to obtain the specialization.  */
14237   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
14238                    targ_ptr, complain, gen_tmpl);
14239   processing_template_decl = saved_processing_template_decl;
14240   if (fndecl == error_mark_node)
14241     return error_mark_node;
14242
14243   /* Now we know the specialization, compute access previously
14244      deferred.  */
14245   push_access_scope (fndecl);
14246
14247   /* Some typedefs referenced from within the template code need to be access
14248      checked at template instantiation time, i.e now. These types were
14249      added to the template at parsing time. Let's get those and perfom
14250      the acces checks then.  */
14251   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
14252   perform_deferred_access_checks ();
14253   pop_access_scope (fndecl);
14254   pop_deferring_access_checks ();
14255
14256   /* The DECL_TI_TEMPLATE should always be the immediate parent
14257      template, not the most general template.  */
14258   DECL_TI_TEMPLATE (fndecl) = tmpl;
14259
14260   /* If we've just instantiated the main entry point for a function,
14261      instantiate all the alternate entry points as well.  We do this
14262      by cloning the instantiation of the main entry point, not by
14263      instantiating the template clones.  */
14264   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
14265     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
14266
14267   return fndecl;
14268 }
14269
14270 /* Wrapper for instantiate_template_1.  */
14271
14272 tree
14273 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
14274 {
14275   tree ret;
14276   timevar_push (TV_TEMPLATE_INST);
14277   ret = instantiate_template_1 (tmpl, orig_args,  complain);
14278   timevar_pop (TV_TEMPLATE_INST);
14279   return ret;
14280 }
14281
14282 /* We're going to do deduction substitution on the type of TMPL, a function
14283    template.  In C++11 mode, push into that access scope.  In C++03 mode,
14284    disable access checking.  */
14285
14286 static void
14287 push_deduction_access_scope (tree tmpl)
14288 {
14289   if (cxx_dialect >= cxx0x)
14290     {
14291       int ptd = processing_template_decl;
14292       push_access_scope (DECL_TEMPLATE_RESULT (tmpl));
14293       /* Preserve processing_template_decl across push_to_top_level.  */
14294       if (ptd && !processing_template_decl)
14295         ++processing_template_decl;
14296     }
14297   else
14298     push_deferring_access_checks (dk_no_check);
14299 }
14300
14301 /* And pop back out.  */
14302
14303 static void
14304 pop_deduction_access_scope (tree tmpl)
14305 {
14306   if (cxx_dialect >= cxx0x)
14307     pop_access_scope (DECL_TEMPLATE_RESULT (tmpl));
14308   else
14309     pop_deferring_access_checks ();
14310 }
14311
14312 /* PARM is a template parameter pack for FN.  Returns true iff
14313    PARM is used in a deducible way in the argument list of FN.  */
14314
14315 static bool
14316 pack_deducible_p (tree parm, tree fn)
14317 {
14318   tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
14319   for (; t; t = TREE_CHAIN (t))
14320     {
14321       tree type = TREE_VALUE (t);
14322       tree packs;
14323       if (!PACK_EXPANSION_P (type))
14324         continue;
14325       for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
14326            packs; packs = TREE_CHAIN (packs))
14327         if (TREE_VALUE (packs) == parm)
14328           {
14329             /* The template parameter pack is used in a function parameter
14330                pack.  If this is the end of the parameter list, the
14331                template parameter pack is deducible.  */
14332             if (TREE_CHAIN (t) == void_list_node)
14333               return true;
14334             else
14335               /* Otherwise, not.  Well, it could be deduced from
14336                  a non-pack parameter, but doing so would end up with
14337                  a deduction mismatch, so don't bother.  */
14338               return false;
14339           }
14340     }
14341   /* The template parameter pack isn't used in any function parameter
14342      packs, but it might be used deeper, e.g. tuple<Args...>.  */
14343   return true;
14344 }
14345
14346 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
14347    NARGS elements of the arguments that are being used when calling
14348    it.  TARGS is a vector into which the deduced template arguments
14349    are placed.
14350
14351    Return zero for success, 2 for an incomplete match that doesn't resolve
14352    all the types, and 1 for complete failure.  An error message will be
14353    printed only for an incomplete match.
14354
14355    If FN is a conversion operator, or we are trying to produce a specific
14356    specialization, RETURN_TYPE is the return type desired.
14357
14358    The EXPLICIT_TARGS are explicit template arguments provided via a
14359    template-id.
14360
14361    The parameter STRICT is one of:
14362
14363    DEDUCE_CALL:
14364      We are deducing arguments for a function call, as in
14365      [temp.deduct.call].
14366
14367    DEDUCE_CONV:
14368      We are deducing arguments for a conversion function, as in
14369      [temp.deduct.conv].
14370
14371    DEDUCE_EXACT:
14372      We are deducing arguments when doing an explicit instantiation
14373      as in [temp.explicit], when determining an explicit specialization
14374      as in [temp.expl.spec], or when taking the address of a function
14375      template, as in [temp.deduct.funcaddr].  */
14376
14377 int
14378 fn_type_unification (tree fn,
14379                      tree explicit_targs,
14380                      tree targs,
14381                      const tree *args,
14382                      unsigned int nargs,
14383                      tree return_type,
14384                      unification_kind_t strict,
14385                      int flags,
14386                      bool explain_p)
14387 {
14388   tree parms;
14389   tree fntype;
14390   int result;
14391
14392   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
14393
14394   fntype = TREE_TYPE (fn);
14395   if (explicit_targs)
14396     {
14397       /* [temp.deduct]
14398
14399          The specified template arguments must match the template
14400          parameters in kind (i.e., type, nontype, template), and there
14401          must not be more arguments than there are parameters;
14402          otherwise type deduction fails.
14403
14404          Nontype arguments must match the types of the corresponding
14405          nontype template parameters, or must be convertible to the
14406          types of the corresponding nontype parameters as specified in
14407          _temp.arg.nontype_, otherwise type deduction fails.
14408
14409          All references in the function type of the function template
14410          to the corresponding template parameters are replaced by the
14411          specified template argument values.  If a substitution in a
14412          template parameter or in the function type of the function
14413          template results in an invalid type, type deduction fails.  */
14414       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
14415       int i, len = TREE_VEC_LENGTH (tparms);
14416       tree converted_args;
14417       bool incomplete = false;
14418
14419       if (explicit_targs == error_mark_node)
14420         return unify_invalid (explain_p);
14421
14422       converted_args
14423         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE,
14424                                   (explain_p
14425                                    ? tf_warning_or_error
14426                                    : tf_none),
14427                                    /*require_all_args=*/false,
14428                                    /*use_default_args=*/false));
14429       if (converted_args == error_mark_node)
14430         return 1;
14431
14432       /* Substitute the explicit args into the function type.  This is
14433          necessary so that, for instance, explicitly declared function
14434          arguments can match null pointed constants.  If we were given
14435          an incomplete set of explicit args, we must not do semantic
14436          processing during substitution as we could create partial
14437          instantiations.  */
14438       for (i = 0; i < len; i++)
14439         {
14440           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
14441           bool parameter_pack = false;
14442           tree targ = TREE_VEC_ELT (converted_args, i);
14443
14444           /* Dig out the actual parm.  */
14445           if (TREE_CODE (parm) == TYPE_DECL
14446               || TREE_CODE (parm) == TEMPLATE_DECL)
14447             {
14448               parm = TREE_TYPE (parm);
14449               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
14450             }
14451           else if (TREE_CODE (parm) == PARM_DECL)
14452             {
14453               parm = DECL_INITIAL (parm);
14454               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
14455             }
14456
14457           if (!parameter_pack && targ == NULL_TREE)
14458             /* No explicit argument for this template parameter.  */
14459             incomplete = true;
14460
14461           if (parameter_pack && pack_deducible_p (parm, fn))
14462             {
14463               /* Mark the argument pack as "incomplete". We could
14464                  still deduce more arguments during unification.
14465                  We remove this mark in type_unification_real.  */
14466               if (targ)
14467                 {
14468                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
14469                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
14470                     = ARGUMENT_PACK_ARGS (targ);
14471                 }
14472
14473               /* We have some incomplete argument packs.  */
14474               incomplete = true;
14475             }
14476         }
14477
14478       processing_template_decl += incomplete;
14479       fntype = deduction_tsubst_fntype (fn, converted_args,
14480                                         (explain_p
14481                                          ? tf_warning_or_error
14482                                          : tf_none));
14483       processing_template_decl -= incomplete;
14484
14485       if (fntype == error_mark_node)
14486         return 1;
14487
14488       /* Place the explicitly specified arguments in TARGS.  */
14489       for (i = NUM_TMPL_ARGS (converted_args); i--;)
14490         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
14491     }
14492
14493   /* Never do unification on the 'this' parameter.  */
14494   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
14495
14496   if (return_type)
14497     {
14498       tree *new_args;
14499
14500       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
14501       new_args = XALLOCAVEC (tree, nargs + 1);
14502       new_args[0] = return_type;
14503       memcpy (new_args + 1, args, nargs * sizeof (tree));
14504       args = new_args;
14505       ++nargs;
14506     }
14507
14508   /* We allow incomplete unification without an error message here
14509      because the standard doesn't seem to explicitly prohibit it.  Our
14510      callers must be ready to deal with unification failures in any
14511      event.  */
14512   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
14513                                   targs, parms, args, nargs, /*subr=*/0,
14514                                   strict, flags, explain_p);
14515
14516   /* Now that we have bindings for all of the template arguments,
14517      ensure that the arguments deduced for the template template
14518      parameters have compatible template parameter lists.  We cannot
14519      check this property before we have deduced all template
14520      arguments, because the template parameter types of a template
14521      template parameter might depend on prior template parameters
14522      deduced after the template template parameter.  The following
14523      ill-formed example illustrates this issue:
14524
14525        template<typename T, template<T> class C> void f(C<5>, T);
14526
14527        template<int N> struct X {};
14528
14529        void g() {
14530          f(X<5>(), 5l); // error: template argument deduction fails
14531        }
14532
14533      The template parameter list of 'C' depends on the template type
14534      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
14535      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
14536      time that we deduce 'C'.  */
14537   if (result == 0
14538       && !template_template_parm_bindings_ok_p 
14539            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
14540     return unify_inconsistent_template_template_parameters (explain_p);
14541
14542   if (result == 0)
14543     /* All is well so far.  Now, check:
14544
14545        [temp.deduct]
14546
14547        When all template arguments have been deduced, all uses of
14548        template parameters in nondeduced contexts are replaced with
14549        the corresponding deduced argument values.  If the
14550        substitution results in an invalid type, as described above,
14551        type deduction fails.  */
14552     {
14553       tree substed = deduction_tsubst_fntype (fn, targs,
14554                                               (explain_p
14555                                                ? tf_warning_or_error
14556                                                : tf_none));
14557       if (substed == error_mark_node)
14558         return 1;
14559
14560       /* If we're looking for an exact match, check that what we got
14561          is indeed an exact match.  It might not be if some template
14562          parameters are used in non-deduced contexts.  */
14563       if (strict == DEDUCE_EXACT)
14564         {
14565           unsigned int i;
14566
14567           tree sarg
14568             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
14569           if (return_type)
14570             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
14571           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
14572             if (!same_type_p (args[i], TREE_VALUE (sarg)))
14573               return unify_type_mismatch (explain_p, args[i],
14574                                           TREE_VALUE (sarg));
14575         }
14576     }
14577
14578   return result;
14579 }
14580
14581 /* Adjust types before performing type deduction, as described in
14582    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
14583    sections are symmetric.  PARM is the type of a function parameter
14584    or the return type of the conversion function.  ARG is the type of
14585    the argument passed to the call, or the type of the value
14586    initialized with the result of the conversion function.
14587    ARG_EXPR is the original argument expression, which may be null.  */
14588
14589 static int
14590 maybe_adjust_types_for_deduction (unification_kind_t strict,
14591                                   tree* parm,
14592                                   tree* arg,
14593                                   tree arg_expr)
14594 {
14595   int result = 0;
14596
14597   switch (strict)
14598     {
14599     case DEDUCE_CALL:
14600       break;
14601
14602     case DEDUCE_CONV:
14603       {
14604         /* Swap PARM and ARG throughout the remainder of this
14605            function; the handling is precisely symmetric since PARM
14606            will initialize ARG rather than vice versa.  */
14607         tree* temp = parm;
14608         parm = arg;
14609         arg = temp;
14610         break;
14611       }
14612
14613     case DEDUCE_EXACT:
14614       /* Core issue #873: Do the DR606 thing (see below) for these cases,
14615          too, but here handle it by stripping the reference from PARM
14616          rather than by adding it to ARG.  */
14617       if (TREE_CODE (*parm) == REFERENCE_TYPE
14618           && TYPE_REF_IS_RVALUE (*parm)
14619           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
14620           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
14621           && TREE_CODE (*arg) == REFERENCE_TYPE
14622           && !TYPE_REF_IS_RVALUE (*arg))
14623         *parm = TREE_TYPE (*parm);
14624       /* Nothing else to do in this case.  */
14625       return 0;
14626
14627     default:
14628       gcc_unreachable ();
14629     }
14630
14631   if (TREE_CODE (*parm) != REFERENCE_TYPE)
14632     {
14633       /* [temp.deduct.call]
14634
14635          If P is not a reference type:
14636
14637          --If A is an array type, the pointer type produced by the
14638          array-to-pointer standard conversion (_conv.array_) is
14639          used in place of A for type deduction; otherwise,
14640
14641          --If A is a function type, the pointer type produced by
14642          the function-to-pointer standard conversion
14643          (_conv.func_) is used in place of A for type deduction;
14644          otherwise,
14645
14646          --If A is a cv-qualified type, the top level
14647          cv-qualifiers of A's type are ignored for type
14648          deduction.  */
14649       if (TREE_CODE (*arg) == ARRAY_TYPE)
14650         *arg = build_pointer_type (TREE_TYPE (*arg));
14651       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
14652         *arg = build_pointer_type (*arg);
14653       else
14654         *arg = TYPE_MAIN_VARIANT (*arg);
14655     }
14656
14657   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
14658      of the form T&&, where T is a template parameter, and the argument
14659      is an lvalue, T is deduced as A& */
14660   if (TREE_CODE (*parm) == REFERENCE_TYPE
14661       && TYPE_REF_IS_RVALUE (*parm)
14662       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
14663       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
14664       && (arg_expr ? real_lvalue_p (arg_expr)
14665           /* try_one_overload doesn't provide an arg_expr, but
14666              functions are always lvalues.  */
14667           : TREE_CODE (*arg) == FUNCTION_TYPE))
14668     *arg = build_reference_type (*arg);
14669
14670   /* [temp.deduct.call]
14671
14672      If P is a cv-qualified type, the top level cv-qualifiers
14673      of P's type are ignored for type deduction.  If P is a
14674      reference type, the type referred to by P is used for
14675      type deduction.  */
14676   *parm = TYPE_MAIN_VARIANT (*parm);
14677   if (TREE_CODE (*parm) == REFERENCE_TYPE)
14678     {
14679       *parm = TREE_TYPE (*parm);
14680       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14681     }
14682
14683   /* DR 322. For conversion deduction, remove a reference type on parm
14684      too (which has been swapped into ARG).  */
14685   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
14686     *arg = TREE_TYPE (*arg);
14687
14688   return result;
14689 }
14690
14691 /* Subroutine of unify_one_argument.  PARM is a function parameter of a
14692    template which does contain any deducible template parameters; check if
14693    ARG is a suitable match for it.  STRICT, FLAGS and EXPLAIN_P are as in
14694    unify_one_argument.  */
14695
14696 static int
14697 check_non_deducible_conversion (tree parm, tree arg, int strict,
14698                                 int flags, bool explain_p)
14699 {
14700   tree type;
14701
14702   if (!TYPE_P (arg))
14703     type = TREE_TYPE (arg);
14704   else
14705     type = arg;
14706
14707   if (same_type_p (parm, type))
14708     return unify_success (explain_p);
14709
14710   if (strict == DEDUCE_CONV)
14711     {
14712       if (can_convert_arg (type, parm, NULL_TREE, flags))
14713         return unify_success (explain_p);
14714     }
14715   else if (strict != DEDUCE_EXACT)
14716     {
14717       if (can_convert_arg (parm, type,
14718                            TYPE_P (arg) ? NULL_TREE : arg,
14719                            flags))
14720         return unify_success (explain_p);
14721     }
14722
14723   if (strict == DEDUCE_EXACT)
14724     return unify_type_mismatch (explain_p, parm, arg);
14725   else
14726     return unify_arg_conversion (explain_p, parm, type, arg);
14727 }
14728
14729 /* Subroutine of type_unification_real and unify_pack_expansion to
14730    handle unification of a single P/A pair.  Parameters are as
14731    for those functions.  */
14732
14733 static int
14734 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
14735                     int subr, unification_kind_t strict, int flags,
14736                     bool explain_p)
14737 {
14738   tree arg_expr = NULL_TREE;
14739   int arg_strict;
14740
14741   if (arg == error_mark_node || parm == error_mark_node)
14742     return unify_invalid (explain_p);
14743   if (arg == unknown_type_node)
14744     /* We can't deduce anything from this, but we might get all the
14745        template args from other function args.  */
14746     return unify_success (explain_p);
14747
14748   /* FIXME uses_deducible_template_parms */
14749   if (TYPE_P (parm) && !uses_template_parms (parm))
14750     return check_non_deducible_conversion (parm, arg, strict, flags,
14751                                            explain_p);
14752
14753   switch (strict)
14754     {
14755     case DEDUCE_CALL:
14756       arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
14757                     | UNIFY_ALLOW_MORE_CV_QUAL
14758                     | UNIFY_ALLOW_DERIVED);
14759       break;
14760
14761     case DEDUCE_CONV:
14762       arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14763       break;
14764
14765     case DEDUCE_EXACT:
14766       arg_strict = UNIFY_ALLOW_NONE;
14767       break;
14768
14769     default:
14770       gcc_unreachable ();
14771     }
14772
14773   /* We only do these transformations if this is the top-level
14774      parameter_type_list in a call or declaration matching; in other
14775      situations (nested function declarators, template argument lists) we
14776      won't be comparing a type to an expression, and we don't do any type
14777      adjustments.  */
14778   if (!subr)
14779     {
14780       if (!TYPE_P (arg))
14781         {
14782           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14783           if (type_unknown_p (arg))
14784             {
14785               /* [temp.deduct.type] A template-argument can be
14786                  deduced from a pointer to function or pointer
14787                  to member function argument if the set of
14788                  overloaded functions does not contain function
14789                  templates and at most one of a set of
14790                  overloaded functions provides a unique
14791                  match.  */
14792
14793               if (resolve_overloaded_unification
14794                   (tparms, targs, parm, arg, strict,
14795                    arg_strict, explain_p))
14796                 return unify_success (explain_p);
14797               return unify_overload_resolution_failure (explain_p, arg);
14798             }
14799
14800           arg_expr = arg;
14801           arg = unlowered_expr_type (arg);
14802           if (arg == error_mark_node)
14803             return unify_invalid (explain_p);
14804         }
14805
14806       arg_strict |=
14807         maybe_adjust_types_for_deduction (strict, &parm, &arg, arg_expr);
14808     }
14809   else
14810     gcc_assert ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
14811                 == (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL));
14812
14813   /* For deduction from an init-list we need the actual list.  */
14814   if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
14815     arg = arg_expr;
14816   return unify (tparms, targs, parm, arg, arg_strict, explain_p);
14817 }
14818
14819 /* Most parms like fn_type_unification.
14820
14821    If SUBR is 1, we're being called recursively (to unify the
14822    arguments of a function or method parameter of a function
14823    template). */
14824
14825 static int
14826 type_unification_real (tree tparms,
14827                        tree targs,
14828                        tree xparms,
14829                        const tree *xargs,
14830                        unsigned int xnargs,
14831                        int subr,
14832                        unification_kind_t strict,
14833                        int flags,
14834                        bool explain_p)
14835 {
14836   tree parm, arg;
14837   int i;
14838   int ntparms = TREE_VEC_LENGTH (tparms);
14839   int saw_undeduced = 0;
14840   tree parms;
14841   const tree *args;
14842   unsigned int nargs;
14843   unsigned int ia;
14844
14845   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
14846   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
14847   gcc_assert (ntparms > 0);
14848
14849   /* Reset the number of non-defaulted template arguments contained
14850      in TARGS.  */
14851   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
14852
14853  again:
14854   parms = xparms;
14855   args = xargs;
14856   nargs = xnargs;
14857
14858   ia = 0;
14859   while (parms && parms != void_list_node
14860          && ia < nargs)
14861     {
14862       parm = TREE_VALUE (parms);
14863
14864       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
14865           && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
14866         /* For a function parameter pack that occurs at the end of the
14867            parameter-declaration-list, the type A of each remaining
14868            argument of the call is compared with the type P of the
14869            declarator-id of the function parameter pack.  */
14870         break;
14871
14872       parms = TREE_CHAIN (parms);
14873
14874       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
14875         /* For a function parameter pack that does not occur at the
14876            end of the parameter-declaration-list, the type of the
14877            parameter pack is a non-deduced context.  */
14878         continue;
14879
14880       arg = args[ia];
14881       ++ia;
14882
14883       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
14884                               flags, explain_p))
14885         return 1;
14886     }
14887
14888   if (parms 
14889       && parms != void_list_node
14890       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
14891     {
14892       /* Unify the remaining arguments with the pack expansion type.  */
14893       tree argvec;
14894       tree parmvec = make_tree_vec (1);
14895
14896       /* Allocate a TREE_VEC and copy in all of the arguments */ 
14897       argvec = make_tree_vec (nargs - ia);
14898       for (i = 0; ia < nargs; ++ia, ++i)
14899         TREE_VEC_ELT (argvec, i) = args[ia];
14900
14901       /* Copy the parameter into parmvec.  */
14902       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
14903       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
14904                                 /*subr=*/subr, explain_p))
14905         return 1;
14906
14907       /* Advance to the end of the list of parameters.  */
14908       parms = TREE_CHAIN (parms);
14909     }
14910
14911   /* Fail if we've reached the end of the parm list, and more args
14912      are present, and the parm list isn't variadic.  */
14913   if (ia < nargs && parms == void_list_node)
14914     return unify_too_many_arguments (explain_p, nargs, ia);
14915   /* Fail if parms are left and they don't have default values.  */
14916   if (parms && parms != void_list_node
14917       && TREE_PURPOSE (parms) == NULL_TREE)
14918     {
14919       unsigned int count = nargs;
14920       tree p = parms;
14921       while (p && p != void_list_node)
14922         {
14923           count++;
14924           p = TREE_CHAIN (p);
14925         }
14926       return unify_too_few_arguments (explain_p, ia, count);
14927     }
14928
14929   if (!subr)
14930     {
14931       tsubst_flags_t complain = (explain_p
14932                                  ? tf_warning_or_error
14933                                  : tf_none);
14934
14935       /* Check to see if we need another pass before we start clearing
14936          ARGUMENT_PACK_INCOMPLETE_P.  */
14937       for (i = 0; i < ntparms; i++)
14938         {
14939           tree targ = TREE_VEC_ELT (targs, i);
14940           tree tparm = TREE_VEC_ELT (tparms, i);
14941
14942           if (targ || tparm == error_mark_node)
14943             continue;
14944           tparm = TREE_VALUE (tparm);
14945
14946           /* If this is an undeduced nontype parameter that depends on
14947              a type parameter, try another pass; its type may have been
14948              deduced from a later argument than the one from which
14949              this parameter can be deduced.  */
14950           if (TREE_CODE (tparm) == PARM_DECL
14951               && uses_template_parms (TREE_TYPE (tparm))
14952               && !saw_undeduced++)
14953             goto again;
14954         }
14955
14956       for (i = 0; i < ntparms; i++)
14957         {
14958           tree targ = TREE_VEC_ELT (targs, i);
14959           tree tparm = TREE_VEC_ELT (tparms, i);
14960
14961           /* Clear the "incomplete" flags on all argument packs now so that
14962              substituting them into later default arguments works.  */
14963           if (targ && ARGUMENT_PACK_P (targ))
14964             {
14965               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
14966               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
14967             }
14968
14969           if (targ || tparm == error_mark_node)
14970             continue;
14971           tparm = TREE_VALUE (tparm);
14972
14973           /* Core issue #226 (C++0x) [temp.deduct]:
14974
14975              If a template argument has not been deduced, its
14976              default template argument, if any, is used. 
14977
14978              When we are in C++98 mode, TREE_PURPOSE will either
14979              be NULL_TREE or ERROR_MARK_NODE, so we do not need
14980              to explicitly check cxx_dialect here.  */
14981           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
14982             {
14983               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
14984               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
14985               arg = tsubst_template_arg (arg, targs, complain, NULL_TREE);
14986               arg = convert_template_argument (parm, arg, targs, complain,
14987                                                i, NULL_TREE);
14988               if (arg == error_mark_node)
14989                 return 1;
14990               else
14991                 {
14992                   TREE_VEC_ELT (targs, i) = arg;
14993                   /* The position of the first default template argument,
14994                      is also the number of non-defaulted arguments in TARGS.
14995                      Record that.  */
14996                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
14997                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
14998                   continue;
14999                 }
15000             }
15001
15002           /* If the type parameter is a parameter pack, then it will
15003              be deduced to an empty parameter pack.  */
15004           if (template_parameter_pack_p (tparm))
15005             {
15006               tree arg;
15007
15008               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
15009                 {
15010                   arg = make_node (NONTYPE_ARGUMENT_PACK);
15011                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
15012                   TREE_CONSTANT (arg) = 1;
15013                 }
15014               else
15015                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
15016
15017               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
15018
15019               TREE_VEC_ELT (targs, i) = arg;
15020               continue;
15021             }
15022
15023           return unify_parameter_deduction_failure (explain_p, tparm);
15024         }
15025     }
15026 #ifdef ENABLE_CHECKING
15027   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
15028     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
15029 #endif
15030
15031   return unify_success (explain_p);
15032 }
15033
15034 /* Subroutine of type_unification_real.  Args are like the variables
15035    at the call site.  ARG is an overloaded function (or template-id);
15036    we try deducing template args from each of the overloads, and if
15037    only one succeeds, we go with that.  Modifies TARGS and returns
15038    true on success.  */
15039
15040 static bool
15041 resolve_overloaded_unification (tree tparms,
15042                                 tree targs,
15043                                 tree parm,
15044                                 tree arg,
15045                                 unification_kind_t strict,
15046                                 int sub_strict,
15047                                 bool explain_p)
15048 {
15049   tree tempargs = copy_node (targs);
15050   int good = 0;
15051   tree goodfn = NULL_TREE;
15052   bool addr_p;
15053
15054   if (TREE_CODE (arg) == ADDR_EXPR)
15055     {
15056       arg = TREE_OPERAND (arg, 0);
15057       addr_p = true;
15058     }
15059   else
15060     addr_p = false;
15061
15062   if (TREE_CODE (arg) == COMPONENT_REF)
15063     /* Handle `&x' where `x' is some static or non-static member
15064        function name.  */
15065     arg = TREE_OPERAND (arg, 1);
15066
15067   if (TREE_CODE (arg) == OFFSET_REF)
15068     arg = TREE_OPERAND (arg, 1);
15069
15070   /* Strip baselink information.  */
15071   if (BASELINK_P (arg))
15072     arg = BASELINK_FUNCTIONS (arg);
15073
15074   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
15075     {
15076       /* If we got some explicit template args, we need to plug them into
15077          the affected templates before we try to unify, in case the
15078          explicit args will completely resolve the templates in question.  */
15079
15080       int ok = 0;
15081       tree expl_subargs = TREE_OPERAND (arg, 1);
15082       arg = TREE_OPERAND (arg, 0);
15083
15084       for (; arg; arg = OVL_NEXT (arg))
15085         {
15086           tree fn = OVL_CURRENT (arg);
15087           tree subargs, elem;
15088
15089           if (TREE_CODE (fn) != TEMPLATE_DECL)
15090             continue;
15091
15092           ++processing_template_decl;
15093           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
15094                                   expl_subargs, /*check_ret=*/false);
15095           if (subargs && !any_dependent_template_arguments_p (subargs))
15096             {
15097               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
15098               if (try_one_overload (tparms, targs, tempargs, parm,
15099                                     elem, strict, sub_strict, addr_p, explain_p)
15100                   && (!goodfn || !decls_match (goodfn, elem)))
15101                 {
15102                   goodfn = elem;
15103                   ++good;
15104                 }
15105             }
15106           else if (subargs)
15107             ++ok;
15108           --processing_template_decl;
15109         }
15110       /* If no templates (or more than one) are fully resolved by the
15111          explicit arguments, this template-id is a non-deduced context; it
15112          could still be OK if we deduce all template arguments for the
15113          enclosing call through other arguments.  */
15114       if (good != 1)
15115         good = ok;
15116     }
15117   else if (TREE_CODE (arg) != OVERLOAD
15118            && TREE_CODE (arg) != FUNCTION_DECL)
15119     /* If ARG is, for example, "(0, &f)" then its type will be unknown
15120        -- but the deduction does not succeed because the expression is
15121        not just the function on its own.  */
15122     return false;
15123   else
15124     for (; arg; arg = OVL_NEXT (arg))
15125       if (try_one_overload (tparms, targs, tempargs, parm,
15126                             TREE_TYPE (OVL_CURRENT (arg)),
15127                             strict, sub_strict, addr_p, explain_p)
15128           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
15129         {
15130           goodfn = OVL_CURRENT (arg);
15131           ++good;
15132         }
15133
15134   /* [temp.deduct.type] A template-argument can be deduced from a pointer
15135      to function or pointer to member function argument if the set of
15136      overloaded functions does not contain function templates and at most
15137      one of a set of overloaded functions provides a unique match.
15138
15139      So if we found multiple possibilities, we return success but don't
15140      deduce anything.  */
15141
15142   if (good == 1)
15143     {
15144       int i = TREE_VEC_LENGTH (targs);
15145       for (; i--; )
15146         if (TREE_VEC_ELT (tempargs, i))
15147           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
15148     }
15149   if (good)
15150     return true;
15151
15152   return false;
15153 }
15154
15155 /* Core DR 115: In contexts where deduction is done and fails, or in
15156    contexts where deduction is not done, if a template argument list is
15157    specified and it, along with any default template arguments, identifies
15158    a single function template specialization, then the template-id is an
15159    lvalue for the function template specialization.  */
15160
15161 tree
15162 resolve_nondeduced_context (tree orig_expr)
15163 {
15164   tree expr, offset, baselink;
15165   bool addr;
15166
15167   if (!type_unknown_p (orig_expr))
15168     return orig_expr;
15169
15170   expr = orig_expr;
15171   addr = false;
15172   offset = NULL_TREE;
15173   baselink = NULL_TREE;
15174
15175   if (TREE_CODE (expr) == ADDR_EXPR)
15176     {
15177       expr = TREE_OPERAND (expr, 0);
15178       addr = true;
15179     }
15180   if (TREE_CODE (expr) == OFFSET_REF)
15181     {
15182       offset = expr;
15183       expr = TREE_OPERAND (expr, 1);
15184     }
15185   if (TREE_CODE (expr) == BASELINK)
15186     {
15187       baselink = expr;
15188       expr = BASELINK_FUNCTIONS (expr);
15189     }
15190
15191   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
15192     {
15193       int good = 0;
15194       tree goodfn = NULL_TREE;
15195
15196       /* If we got some explicit template args, we need to plug them into
15197          the affected templates before we try to unify, in case the
15198          explicit args will completely resolve the templates in question.  */
15199
15200       tree expl_subargs = TREE_OPERAND (expr, 1);
15201       tree arg = TREE_OPERAND (expr, 0);
15202       tree badfn = NULL_TREE;
15203       tree badargs = NULL_TREE;
15204
15205       for (; arg; arg = OVL_NEXT (arg))
15206         {
15207           tree fn = OVL_CURRENT (arg);
15208           tree subargs, elem;
15209
15210           if (TREE_CODE (fn) != TEMPLATE_DECL)
15211             continue;
15212
15213           ++processing_template_decl;
15214           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
15215                                   expl_subargs, /*check_ret=*/false);
15216           if (subargs && !any_dependent_template_arguments_p (subargs))
15217             {
15218               elem = instantiate_template (fn, subargs, tf_none);
15219               if (elem == error_mark_node)
15220                 {
15221                   badfn = fn;
15222                   badargs = subargs;
15223                 }
15224               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
15225                 {
15226                   goodfn = elem;
15227                   ++good;
15228                 }
15229             }
15230           --processing_template_decl;
15231         }
15232       if (good == 1)
15233         {
15234           mark_used (goodfn);
15235           expr = goodfn;
15236           if (baselink)
15237             expr = build_baselink (BASELINK_BINFO (baselink),
15238                                    BASELINK_ACCESS_BINFO (baselink),
15239                                    expr, BASELINK_OPTYPE (baselink));
15240           if (offset)
15241             {
15242               tree base
15243                 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
15244               expr = build_offset_ref (base, expr, addr);
15245             }
15246           if (addr)
15247             expr = cp_build_addr_expr (expr, tf_warning_or_error);
15248           return expr;
15249         }
15250       else if (good == 0 && badargs)
15251         /* There were no good options and at least one bad one, so let the
15252            user know what the problem is.  */
15253         instantiate_template (badfn, badargs, tf_warning_or_error);
15254     }
15255   return orig_expr;
15256 }
15257
15258 /* Subroutine of resolve_overloaded_unification; does deduction for a single
15259    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
15260    different overloads deduce different arguments for a given parm.
15261    ADDR_P is true if the expression for which deduction is being
15262    performed was of the form "& fn" rather than simply "fn".
15263
15264    Returns 1 on success.  */
15265
15266 static int
15267 try_one_overload (tree tparms,
15268                   tree orig_targs,
15269                   tree targs,
15270                   tree parm,
15271                   tree arg,
15272                   unification_kind_t strict,
15273                   int sub_strict,
15274                   bool addr_p,
15275                   bool explain_p)
15276 {
15277   int nargs;
15278   tree tempargs;
15279   int i;
15280
15281   /* [temp.deduct.type] A template-argument can be deduced from a pointer
15282      to function or pointer to member function argument if the set of
15283      overloaded functions does not contain function templates and at most
15284      one of a set of overloaded functions provides a unique match.
15285
15286      So if this is a template, just return success.  */
15287
15288   if (uses_template_parms (arg))
15289     return 1;
15290
15291   if (TREE_CODE (arg) == METHOD_TYPE)
15292     arg = build_ptrmemfunc_type (build_pointer_type (arg));
15293   else if (addr_p)
15294     arg = build_pointer_type (arg);
15295
15296   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
15297
15298   /* We don't copy orig_targs for this because if we have already deduced
15299      some template args from previous args, unify would complain when we
15300      try to deduce a template parameter for the same argument, even though
15301      there isn't really a conflict.  */
15302   nargs = TREE_VEC_LENGTH (targs);
15303   tempargs = make_tree_vec (nargs);
15304
15305   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
15306     return 0;
15307
15308   /* First make sure we didn't deduce anything that conflicts with
15309      explicitly specified args.  */
15310   for (i = nargs; i--; )
15311     {
15312       tree elt = TREE_VEC_ELT (tempargs, i);
15313       tree oldelt = TREE_VEC_ELT (orig_targs, i);
15314
15315       if (!elt)
15316         /*NOP*/;
15317       else if (uses_template_parms (elt))
15318         /* Since we're unifying against ourselves, we will fill in
15319            template args used in the function parm list with our own
15320            template parms.  Discard them.  */
15321         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
15322       else if (oldelt && !template_args_equal (oldelt, elt))
15323         return 0;
15324     }
15325
15326   for (i = nargs; i--; )
15327     {
15328       tree elt = TREE_VEC_ELT (tempargs, i);
15329
15330       if (elt)
15331         TREE_VEC_ELT (targs, i) = elt;
15332     }
15333
15334   return 1;
15335 }
15336
15337 /* PARM is a template class (perhaps with unbound template
15338    parameters).  ARG is a fully instantiated type.  If ARG can be
15339    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
15340    TARGS are as for unify.  */
15341
15342 static tree
15343 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
15344                        bool explain_p)
15345 {
15346   tree copy_of_targs;
15347
15348   if (!CLASSTYPE_TEMPLATE_INFO (arg)
15349       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
15350           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
15351     return NULL_TREE;
15352
15353   /* We need to make a new template argument vector for the call to
15354      unify.  If we used TARGS, we'd clutter it up with the result of
15355      the attempted unification, even if this class didn't work out.
15356      We also don't want to commit ourselves to all the unifications
15357      we've already done, since unification is supposed to be done on
15358      an argument-by-argument basis.  In other words, consider the
15359      following pathological case:
15360
15361        template <int I, int J, int K>
15362        struct S {};
15363
15364        template <int I, int J>
15365        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
15366
15367        template <int I, int J, int K>
15368        void f(S<I, J, K>, S<I, I, I>);
15369
15370        void g() {
15371          S<0, 0, 0> s0;
15372          S<0, 1, 2> s2;
15373
15374          f(s0, s2);
15375        }
15376
15377      Now, by the time we consider the unification involving `s2', we
15378      already know that we must have `f<0, 0, 0>'.  But, even though
15379      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
15380      because there are two ways to unify base classes of S<0, 1, 2>
15381      with S<I, I, I>.  If we kept the already deduced knowledge, we
15382      would reject the possibility I=1.  */
15383   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
15384
15385   /* If unification failed, we're done.  */
15386   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
15387              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
15388     return NULL_TREE;
15389
15390   return arg;
15391 }
15392
15393 /* Given a template type PARM and a class type ARG, find the unique
15394    base type in ARG that is an instance of PARM.  We do not examine
15395    ARG itself; only its base-classes.  If there is not exactly one
15396    appropriate base class, return NULL_TREE.  PARM may be the type of
15397    a partial specialization, as well as a plain template type.  Used
15398    by unify.  */
15399
15400 static enum template_base_result
15401 get_template_base (tree tparms, tree targs, tree parm, tree arg,
15402                    bool explain_p, tree *result)
15403 {
15404   tree rval = NULL_TREE;
15405   tree binfo;
15406
15407   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
15408
15409   binfo = TYPE_BINFO (complete_type (arg));
15410   if (!binfo)
15411     {
15412       /* The type could not be completed.  */
15413       *result = NULL_TREE;
15414       return tbr_incomplete_type;
15415     }
15416
15417   /* Walk in inheritance graph order.  The search order is not
15418      important, and this avoids multiple walks of virtual bases.  */
15419   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
15420     {
15421       tree r = try_class_unification (tparms, targs, parm,
15422                                       BINFO_TYPE (binfo), explain_p);
15423
15424       if (r)
15425         {
15426           /* If there is more than one satisfactory baseclass, then:
15427
15428                [temp.deduct.call]
15429
15430               If they yield more than one possible deduced A, the type
15431               deduction fails.
15432
15433              applies.  */
15434           if (rval && !same_type_p (r, rval))
15435             {
15436               *result = NULL_TREE;
15437               return tbr_ambiguous_baseclass;
15438             }
15439
15440           rval = r;
15441         }
15442     }
15443
15444   *result = rval;
15445   return tbr_success;
15446 }
15447
15448 /* Returns the level of DECL, which declares a template parameter.  */
15449
15450 static int
15451 template_decl_level (tree decl)
15452 {
15453   switch (TREE_CODE (decl))
15454     {
15455     case TYPE_DECL:
15456     case TEMPLATE_DECL:
15457       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
15458
15459     case PARM_DECL:
15460       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
15461
15462     default:
15463       gcc_unreachable ();
15464     }
15465   return 0;
15466 }
15467
15468 /* Decide whether ARG can be unified with PARM, considering only the
15469    cv-qualifiers of each type, given STRICT as documented for unify.
15470    Returns nonzero iff the unification is OK on that basis.  */
15471
15472 static int
15473 check_cv_quals_for_unify (int strict, tree arg, tree parm)
15474 {
15475   int arg_quals = cp_type_quals (arg);
15476   int parm_quals = cp_type_quals (parm);
15477
15478   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15479       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
15480     {
15481       /*  Although a CVR qualifier is ignored when being applied to a
15482           substituted template parameter ([8.3.2]/1 for example), that
15483           does not allow us to unify "const T" with "int&" because both
15484           types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
15485           It is ok when we're allowing additional CV qualifiers
15486           at the outer level [14.8.2.1]/3,1st bullet.  */
15487       if ((TREE_CODE (arg) == REFERENCE_TYPE
15488            || TREE_CODE (arg) == FUNCTION_TYPE
15489            || TREE_CODE (arg) == METHOD_TYPE)
15490           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
15491         return 0;
15492
15493       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
15494           && (parm_quals & TYPE_QUAL_RESTRICT))
15495         return 0;
15496     }
15497
15498   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
15499       && (arg_quals & parm_quals) != parm_quals)
15500     return 0;
15501
15502   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
15503       && (parm_quals & arg_quals) != arg_quals)
15504     return 0;
15505
15506   return 1;
15507 }
15508
15509 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
15510 void 
15511 template_parm_level_and_index (tree parm, int* level, int* index)
15512 {
15513   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15514       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15515       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15516     {
15517       *index = TEMPLATE_TYPE_IDX (parm);
15518       *level = TEMPLATE_TYPE_LEVEL (parm);
15519     }
15520   else
15521     {
15522       *index = TEMPLATE_PARM_IDX (parm);
15523       *level = TEMPLATE_PARM_LEVEL (parm);
15524     }
15525 }
15526
15527 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)                    \
15528   do {                                                                  \
15529     if (unify (TP, TA, P, A, S, EP))                                    \
15530       return 1;                                                         \
15531   } while (0);
15532
15533 /* Unifies the remaining arguments in PACKED_ARGS with the pack
15534    expansion at the end of PACKED_PARMS. Returns 0 if the type
15535    deduction succeeds, 1 otherwise. STRICT is the same as in
15536    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
15537    call argument list. We'll need to adjust the arguments to make them
15538    types. SUBR tells us if this is from a recursive call to
15539    type_unification_real, or for comparing two template argument
15540    lists. */
15541
15542 static int
15543 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
15544                       tree packed_args, unification_kind_t strict,
15545                       bool subr, bool explain_p)
15546 {
15547   tree parm 
15548     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
15549   tree pattern = PACK_EXPANSION_PATTERN (parm);
15550   tree pack, packs = NULL_TREE;
15551   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
15552   int len = TREE_VEC_LENGTH (packed_args);
15553
15554   /* Determine the parameter packs we will be deducing from the
15555      pattern, and record their current deductions.  */
15556   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
15557        pack; pack = TREE_CHAIN (pack))
15558     {
15559       tree parm_pack = TREE_VALUE (pack);
15560       int idx, level;
15561
15562       /* Determine the index and level of this parameter pack.  */
15563       template_parm_level_and_index (parm_pack, &level, &idx);
15564
15565       /* Keep track of the parameter packs and their corresponding
15566          argument packs.  */
15567       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
15568       TREE_TYPE (packs) = make_tree_vec (len - start);
15569     }
15570   
15571   /* Loop through all of the arguments that have not yet been
15572      unified and unify each with the pattern.  */
15573   for (i = start; i < len; i++)
15574     {
15575       tree parm;
15576       bool any_explicit = false;
15577       tree arg = TREE_VEC_ELT (packed_args, i);
15578
15579       /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
15580          or the element of its argument pack at the current index if
15581          this argument was explicitly specified.  */
15582       for (pack = packs; pack; pack = TREE_CHAIN (pack))
15583         {
15584           int idx, level;
15585           tree arg, pargs;
15586           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15587
15588           arg = NULL_TREE;
15589           if (TREE_VALUE (pack)
15590               && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
15591               && (i < TREE_VEC_LENGTH (pargs)))
15592             {
15593               any_explicit = true;
15594               arg = TREE_VEC_ELT (pargs, i);
15595             }
15596           TMPL_ARG (targs, level, idx) = arg;
15597         }
15598
15599       /* If we had explicit template arguments, substitute them into the
15600          pattern before deduction.  */
15601       if (any_explicit)
15602         {
15603           /* Some arguments might still be unspecified or dependent.  */
15604           bool dependent;
15605           ++processing_template_decl;
15606           dependent = any_dependent_template_arguments_p (targs);
15607           if (!dependent)
15608             --processing_template_decl;
15609           parm = tsubst (pattern, targs,
15610                          explain_p ? tf_warning_or_error : tf_none,
15611                          NULL_TREE);
15612           if (dependent)
15613             --processing_template_decl;
15614           if (parm == error_mark_node)
15615             return 1;
15616         }
15617       else
15618         parm = pattern;
15619
15620       /* Unify the pattern with the current argument.  */
15621       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
15622                               LOOKUP_IMPLICIT, explain_p))
15623         return 1;
15624
15625       /* For each parameter pack, collect the deduced value.  */
15626       for (pack = packs; pack; pack = TREE_CHAIN (pack))
15627         {
15628           int idx, level;
15629           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15630
15631           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
15632             TMPL_ARG (targs, level, idx);
15633         }
15634     }
15635
15636   /* Verify that the results of unification with the parameter packs
15637      produce results consistent with what we've seen before, and make
15638      the deduced argument packs available.  */
15639   for (pack = packs; pack; pack = TREE_CHAIN (pack))
15640     {
15641       tree old_pack = TREE_VALUE (pack);
15642       tree new_args = TREE_TYPE (pack);
15643       int i, len = TREE_VEC_LENGTH (new_args);
15644       int idx, level;
15645       bool nondeduced_p = false;
15646
15647       /* By default keep the original deduced argument pack.
15648          If necessary, more specific code is going to update the
15649          resulting deduced argument later down in this function.  */
15650       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15651       TMPL_ARG (targs, level, idx) = old_pack;
15652
15653       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
15654          actually deduce anything.  */
15655       for (i = 0; i < len && !nondeduced_p; ++i)
15656         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
15657           nondeduced_p = true;
15658       if (nondeduced_p)
15659         continue;
15660
15661       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
15662         {
15663           /* If we had fewer function args than explicit template args,
15664              just use the explicits.  */
15665           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
15666           int explicit_len = TREE_VEC_LENGTH (explicit_args);
15667           if (len < explicit_len)
15668             new_args = explicit_args;
15669         }
15670
15671       if (!old_pack)
15672         {
15673           tree result;
15674           /* Build the deduced *_ARGUMENT_PACK.  */
15675           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
15676             {
15677               result = make_node (NONTYPE_ARGUMENT_PACK);
15678               TREE_TYPE (result) = 
15679                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
15680               TREE_CONSTANT (result) = 1;
15681             }
15682           else
15683             result = cxx_make_type (TYPE_ARGUMENT_PACK);
15684
15685           SET_ARGUMENT_PACK_ARGS (result, new_args);
15686
15687           /* Note the deduced argument packs for this parameter
15688              pack.  */
15689           TMPL_ARG (targs, level, idx) = result;
15690         }
15691       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
15692                && (ARGUMENT_PACK_ARGS (old_pack) 
15693                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
15694         {
15695           /* We only had the explicitly-provided arguments before, but
15696              now we have a complete set of arguments.  */
15697           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
15698
15699           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
15700           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
15701           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
15702         }
15703       else
15704         {
15705           tree bad_old_arg, bad_new_arg;
15706           tree old_args = ARGUMENT_PACK_ARGS (old_pack);
15707
15708           if (!comp_template_args_with_info (old_args, new_args,
15709                                              &bad_old_arg, &bad_new_arg))
15710             /* Inconsistent unification of this parameter pack.  */
15711             return unify_parameter_pack_inconsistent (explain_p,
15712                                                       bad_old_arg,
15713                                                       bad_new_arg);
15714         }
15715     }
15716
15717   return unify_success (explain_p);
15718 }
15719
15720 /* Deduce the value of template parameters.  TPARMS is the (innermost)
15721    set of template parameters to a template.  TARGS is the bindings
15722    for those template parameters, as determined thus far; TARGS may
15723    include template arguments for outer levels of template parameters
15724    as well.  PARM is a parameter to a template function, or a
15725    subcomponent of that parameter; ARG is the corresponding argument.
15726    This function attempts to match PARM with ARG in a manner
15727    consistent with the existing assignments in TARGS.  If more values
15728    are deduced, then TARGS is updated.
15729
15730    Returns 0 if the type deduction succeeds, 1 otherwise.  The
15731    parameter STRICT is a bitwise or of the following flags:
15732
15733      UNIFY_ALLOW_NONE:
15734        Require an exact match between PARM and ARG.
15735      UNIFY_ALLOW_MORE_CV_QUAL:
15736        Allow the deduced ARG to be more cv-qualified (by qualification
15737        conversion) than ARG.
15738      UNIFY_ALLOW_LESS_CV_QUAL:
15739        Allow the deduced ARG to be less cv-qualified than ARG.
15740      UNIFY_ALLOW_DERIVED:
15741        Allow the deduced ARG to be a template base class of ARG,
15742        or a pointer to a template base class of the type pointed to by
15743        ARG.
15744      UNIFY_ALLOW_INTEGER:
15745        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
15746        case for more information.
15747      UNIFY_ALLOW_OUTER_LEVEL:
15748        This is the outermost level of a deduction. Used to determine validity
15749        of qualification conversions. A valid qualification conversion must
15750        have const qualified pointers leading up to the inner type which
15751        requires additional CV quals, except at the outer level, where const
15752        is not required [conv.qual]. It would be normal to set this flag in
15753        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
15754      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
15755        This is the outermost level of a deduction, and PARM can be more CV
15756        qualified at this point.
15757      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
15758        This is the outermost level of a deduction, and PARM can be less CV
15759        qualified at this point.  */
15760
15761 static int
15762 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
15763        bool explain_p)
15764 {
15765   int idx;
15766   tree targ;
15767   tree tparm;
15768   int strict_in = strict;
15769
15770   /* I don't think this will do the right thing with respect to types.
15771      But the only case I've seen it in so far has been array bounds, where
15772      signedness is the only information lost, and I think that will be
15773      okay.  */
15774   while (TREE_CODE (parm) == NOP_EXPR)
15775     parm = TREE_OPERAND (parm, 0);
15776
15777   if (arg == error_mark_node)
15778     return unify_invalid (explain_p);
15779   if (arg == unknown_type_node
15780       || arg == init_list_type_node)
15781     /* We can't deduce anything from this, but we might get all the
15782        template args from other function args.  */
15783     return unify_success (explain_p);
15784
15785   /* If PARM uses template parameters, then we can't bail out here,
15786      even if ARG == PARM, since we won't record unifications for the
15787      template parameters.  We might need them if we're trying to
15788      figure out which of two things is more specialized.  */
15789   if (arg == parm && !uses_template_parms (parm))
15790     return unify_success (explain_p);
15791
15792   /* Handle init lists early, so the rest of the function can assume
15793      we're dealing with a type. */
15794   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
15795     {
15796       tree elt, elttype;
15797       unsigned i;
15798       tree orig_parm = parm;
15799
15800       /* Replace T with std::initializer_list<T> for deduction.  */
15801       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15802           && flag_deduce_init_list)
15803         parm = listify (parm);
15804
15805       if (!is_std_init_list (parm))
15806         /* We can only deduce from an initializer list argument if the
15807            parameter is std::initializer_list; otherwise this is a
15808            non-deduced context. */
15809         return unify_success (explain_p);
15810
15811       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
15812
15813       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
15814         {
15815           int elt_strict = strict;
15816
15817           if (elt == error_mark_node)
15818             return unify_invalid (explain_p);
15819
15820           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
15821             {
15822               tree type = TREE_TYPE (elt);
15823               /* It should only be possible to get here for a call.  */
15824               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
15825               elt_strict |= maybe_adjust_types_for_deduction
15826                 (DEDUCE_CALL, &elttype, &type, elt);
15827               elt = type;
15828             }
15829
15830           RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
15831                                    explain_p);
15832         }
15833
15834       /* If the std::initializer_list<T> deduction worked, replace the
15835          deduced A with std::initializer_list<A>.  */
15836       if (orig_parm != parm)
15837         {
15838           idx = TEMPLATE_TYPE_IDX (orig_parm);
15839           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15840           targ = listify (targ);
15841           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
15842         }
15843       return unify_success (explain_p);
15844     }
15845
15846   /* Immediately reject some pairs that won't unify because of
15847      cv-qualification mismatches.  */
15848   if (TREE_CODE (arg) == TREE_CODE (parm)
15849       && TYPE_P (arg)
15850       /* It is the elements of the array which hold the cv quals of an array
15851          type, and the elements might be template type parms. We'll check
15852          when we recurse.  */
15853       && TREE_CODE (arg) != ARRAY_TYPE
15854       /* We check the cv-qualifiers when unifying with template type
15855          parameters below.  We want to allow ARG `const T' to unify with
15856          PARM `T' for example, when computing which of two templates
15857          is more specialized, for example.  */
15858       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
15859       && !check_cv_quals_for_unify (strict_in, arg, parm))
15860     return unify_cv_qual_mismatch (explain_p, parm, arg);
15861
15862   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
15863       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
15864     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
15865   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
15866   strict &= ~UNIFY_ALLOW_DERIVED;
15867   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
15868   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
15869
15870   switch (TREE_CODE (parm))
15871     {
15872     case TYPENAME_TYPE:
15873     case SCOPE_REF:
15874     case UNBOUND_CLASS_TEMPLATE:
15875       /* In a type which contains a nested-name-specifier, template
15876          argument values cannot be deduced for template parameters used
15877          within the nested-name-specifier.  */
15878       return unify_success (explain_p);
15879
15880     case TEMPLATE_TYPE_PARM:
15881     case TEMPLATE_TEMPLATE_PARM:
15882     case BOUND_TEMPLATE_TEMPLATE_PARM:
15883       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
15884       if (tparm == error_mark_node)
15885         return unify_invalid (explain_p);
15886
15887       if (TEMPLATE_TYPE_LEVEL (parm)
15888           != template_decl_level (tparm))
15889         /* The PARM is not one we're trying to unify.  Just check
15890            to see if it matches ARG.  */
15891         {
15892           if (TREE_CODE (arg) == TREE_CODE (parm)
15893               && same_type_p (parm, arg))
15894             return unify_success (explain_p);
15895           else
15896             return unify_type_mismatch (explain_p, parm, arg);
15897         }
15898       idx = TEMPLATE_TYPE_IDX (parm);
15899       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15900       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
15901
15902       /* Check for mixed types and values.  */
15903       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15904            && TREE_CODE (tparm) != TYPE_DECL)
15905           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15906               && TREE_CODE (tparm) != TEMPLATE_DECL))
15907         gcc_unreachable ();
15908
15909       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15910         {
15911           /* ARG must be constructed from a template class or a template
15912              template parameter.  */
15913           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
15914               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
15915             return unify_template_deduction_failure (explain_p, parm, arg);
15916
15917           {
15918             tree parmvec = TYPE_TI_ARGS (parm);
15919             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
15920             tree full_argvec = add_to_template_args (targs, argvec);
15921             tree parm_parms 
15922               = DECL_INNERMOST_TEMPLATE_PARMS
15923                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
15924             int i, len;
15925             int parm_variadic_p = 0;
15926
15927             /* The resolution to DR150 makes clear that default
15928                arguments for an N-argument may not be used to bind T
15929                to a template template parameter with fewer than N
15930                parameters.  It is not safe to permit the binding of
15931                default arguments as an extension, as that may change
15932                the meaning of a conforming program.  Consider:
15933
15934                   struct Dense { static const unsigned int dim = 1; };
15935
15936                   template <template <typename> class View,
15937                             typename Block>
15938                   void operator+(float, View<Block> const&);
15939
15940                   template <typename Block,
15941                             unsigned int Dim = Block::dim>
15942                   struct Lvalue_proxy { operator float() const; };
15943
15944                   void
15945                   test_1d (void) {
15946                     Lvalue_proxy<Dense> p;
15947                     float b;
15948                     b + p;
15949                   }
15950
15951               Here, if Lvalue_proxy is permitted to bind to View, then
15952               the global operator+ will be used; if they are not, the
15953               Lvalue_proxy will be converted to float.  */
15954             if (coerce_template_parms (parm_parms,
15955                                        full_argvec,
15956                                        TYPE_TI_TEMPLATE (parm),
15957                                        (explain_p
15958                                         ? tf_warning_or_error
15959                                         : tf_none),
15960                                        /*require_all_args=*/true,
15961                                        /*use_default_args=*/false)
15962                 == error_mark_node)
15963               return 1;
15964
15965             /* Deduce arguments T, i from TT<T> or TT<i>.
15966                We check each element of PARMVEC and ARGVEC individually
15967                rather than the whole TREE_VEC since they can have
15968                different number of elements.  */
15969
15970             parmvec = expand_template_argument_pack (parmvec);
15971             argvec = expand_template_argument_pack (argvec);
15972
15973             len = TREE_VEC_LENGTH (parmvec);
15974
15975             /* Check if the parameters end in a pack, making them
15976                variadic.  */
15977             if (len > 0
15978                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
15979               parm_variadic_p = 1;
15980             
15981             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
15982               return unify_too_few_arguments (explain_p,
15983                                               TREE_VEC_LENGTH (argvec), len);
15984
15985              for (i = 0; i < len - parm_variadic_p; ++i)
15986               {
15987                 RECUR_AND_CHECK_FAILURE (tparms, targs,
15988                                          TREE_VEC_ELT (parmvec, i),
15989                                          TREE_VEC_ELT (argvec, i),
15990                                          UNIFY_ALLOW_NONE, explain_p);
15991               }
15992
15993             if (parm_variadic_p
15994                 && unify_pack_expansion (tparms, targs,
15995                                          parmvec, argvec,
15996                                          DEDUCE_EXACT,
15997                                          /*subr=*/true, explain_p))
15998               return 1;
15999           }
16000           arg = TYPE_TI_TEMPLATE (arg);
16001
16002           /* Fall through to deduce template name.  */
16003         }
16004
16005       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
16006           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
16007         {
16008           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
16009
16010           /* Simple cases: Value already set, does match or doesn't.  */
16011           if (targ != NULL_TREE && template_args_equal (targ, arg))
16012             return unify_success (explain_p);
16013           else if (targ)
16014             return unify_inconsistency (explain_p, parm, targ, arg);
16015         }
16016       else
16017         {
16018           /* If PARM is `const T' and ARG is only `int', we don't have
16019              a match unless we are allowing additional qualification.
16020              If ARG is `const int' and PARM is just `T' that's OK;
16021              that binds `const int' to `T'.  */
16022           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
16023                                          arg, parm))
16024             return unify_cv_qual_mismatch (explain_p, parm, arg);
16025
16026           /* Consider the case where ARG is `const volatile int' and
16027              PARM is `const T'.  Then, T should be `volatile int'.  */
16028           arg = cp_build_qualified_type_real
16029             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
16030           if (arg == error_mark_node)
16031             return unify_invalid (explain_p);
16032
16033           /* Simple cases: Value already set, does match or doesn't.  */
16034           if (targ != NULL_TREE && same_type_p (targ, arg))
16035             return unify_success (explain_p);
16036           else if (targ)
16037             return unify_inconsistency (explain_p, parm, targ, arg);
16038
16039           /* Make sure that ARG is not a variable-sized array.  (Note
16040              that were talking about variable-sized arrays (like
16041              `int[n]'), rather than arrays of unknown size (like
16042              `int[]').)  We'll get very confused by such a type since
16043              the bound of the array is not constant, and therefore
16044              not mangleable.  Besides, such types are not allowed in
16045              ISO C++, so we can do as we please here.  We do allow
16046              them for 'auto' deduction, since that isn't ABI-exposed.  */
16047           if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
16048             return unify_vla_arg (explain_p, arg);
16049
16050           /* Strip typedefs as in convert_template_argument.  */
16051           arg = canonicalize_type_argument (arg, tf_none);
16052         }
16053
16054       /* If ARG is a parameter pack or an expansion, we cannot unify
16055          against it unless PARM is also a parameter pack.  */
16056       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
16057           && !template_parameter_pack_p (parm))
16058         return unify_parameter_pack_mismatch (explain_p, parm, arg);
16059
16060       /* If the argument deduction results is a METHOD_TYPE,
16061          then there is a problem.
16062          METHOD_TYPE doesn't map to any real C++ type the result of
16063          the deduction can not be of that type.  */
16064       if (TREE_CODE (arg) == METHOD_TYPE)
16065         return unify_method_type_error (explain_p, arg);
16066
16067       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
16068       return unify_success (explain_p);
16069
16070     case TEMPLATE_PARM_INDEX:
16071       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
16072       if (tparm == error_mark_node)
16073         return unify_invalid (explain_p);
16074
16075       if (TEMPLATE_PARM_LEVEL (parm)
16076           != template_decl_level (tparm))
16077         {
16078           /* The PARM is not one we're trying to unify.  Just check
16079              to see if it matches ARG.  */
16080           int result = !(TREE_CODE (arg) == TREE_CODE (parm)
16081                          && cp_tree_equal (parm, arg));
16082           if (result)
16083             unify_expression_unequal (explain_p, parm, arg);
16084           return result;
16085         }
16086
16087       idx = TEMPLATE_PARM_IDX (parm);
16088       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
16089
16090       if (targ)
16091         {
16092           int x = !cp_tree_equal (targ, arg);
16093           if (x)
16094             unify_inconsistency (explain_p, parm, targ, arg);
16095           return x;
16096         }
16097
16098       /* [temp.deduct.type] If, in the declaration of a function template
16099          with a non-type template-parameter, the non-type
16100          template-parameter is used in an expression in the function
16101          parameter-list and, if the corresponding template-argument is
16102          deduced, the template-argument type shall match the type of the
16103          template-parameter exactly, except that a template-argument
16104          deduced from an array bound may be of any integral type.
16105          The non-type parameter might use already deduced type parameters.  */
16106       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
16107       if (!TREE_TYPE (arg))
16108         /* Template-parameter dependent expression.  Just accept it for now.
16109            It will later be processed in convert_template_argument.  */
16110         ;
16111       else if (same_type_p (TREE_TYPE (arg), tparm))
16112         /* OK */;
16113       else if ((strict & UNIFY_ALLOW_INTEGER)
16114                && (TREE_CODE (tparm) == INTEGER_TYPE
16115                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
16116         /* Convert the ARG to the type of PARM; the deduced non-type
16117            template argument must exactly match the types of the
16118            corresponding parameter.  */
16119         arg = fold (build_nop (tparm, arg));
16120       else if (uses_template_parms (tparm))
16121         /* We haven't deduced the type of this parameter yet.  Try again
16122            later.  */
16123         return unify_success (explain_p);
16124       else
16125         return unify_type_mismatch (explain_p, tparm, arg);
16126
16127       /* If ARG is a parameter pack or an expansion, we cannot unify
16128          against it unless PARM is also a parameter pack.  */
16129       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
16130           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
16131         return unify_parameter_pack_mismatch (explain_p, parm, arg);
16132
16133       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
16134       return unify_success (explain_p);
16135
16136     case PTRMEM_CST:
16137      {
16138         /* A pointer-to-member constant can be unified only with
16139          another constant.  */
16140       if (TREE_CODE (arg) != PTRMEM_CST)
16141         return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
16142
16143       /* Just unify the class member. It would be useless (and possibly
16144          wrong, depending on the strict flags) to unify also
16145          PTRMEM_CST_CLASS, because we want to be sure that both parm and
16146          arg refer to the same variable, even if through different
16147          classes. For instance:
16148
16149          struct A { int x; };
16150          struct B : A { };
16151
16152          Unification of &A::x and &B::x must succeed.  */
16153       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
16154                     PTRMEM_CST_MEMBER (arg), strict, explain_p);
16155      }
16156
16157     case POINTER_TYPE:
16158       {
16159         if (TREE_CODE (arg) != POINTER_TYPE)
16160           return unify_type_mismatch (explain_p, parm, arg);
16161
16162         /* [temp.deduct.call]
16163
16164            A can be another pointer or pointer to member type that can
16165            be converted to the deduced A via a qualification
16166            conversion (_conv.qual_).
16167
16168            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
16169            This will allow for additional cv-qualification of the
16170            pointed-to types if appropriate.  */
16171
16172         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
16173           /* The derived-to-base conversion only persists through one
16174              level of pointers.  */
16175           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
16176
16177         return unify (tparms, targs, TREE_TYPE (parm),
16178                       TREE_TYPE (arg), strict, explain_p);
16179       }
16180
16181     case REFERENCE_TYPE:
16182       if (TREE_CODE (arg) != REFERENCE_TYPE)
16183         return unify_type_mismatch (explain_p, parm, arg);
16184       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16185                     strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
16186
16187     case ARRAY_TYPE:
16188       if (TREE_CODE (arg) != ARRAY_TYPE)
16189         return unify_type_mismatch (explain_p, parm, arg);
16190       if ((TYPE_DOMAIN (parm) == NULL_TREE)
16191           != (TYPE_DOMAIN (arg) == NULL_TREE))
16192         return unify_type_mismatch (explain_p, parm, arg);
16193       if (TYPE_DOMAIN (parm) != NULL_TREE)
16194         {
16195           tree parm_max;
16196           tree arg_max;
16197           bool parm_cst;
16198           bool arg_cst;
16199
16200           /* Our representation of array types uses "N - 1" as the
16201              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
16202              not an integer constant.  We cannot unify arbitrarily
16203              complex expressions, so we eliminate the MINUS_EXPRs
16204              here.  */
16205           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
16206           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
16207           if (!parm_cst)
16208             {
16209               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
16210               parm_max = TREE_OPERAND (parm_max, 0);
16211             }
16212           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
16213           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
16214           if (!arg_cst)
16215             {
16216               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
16217                  trying to unify the type of a variable with the type
16218                  of a template parameter.  For example:
16219
16220                    template <unsigned int N>
16221                    void f (char (&) [N]);
16222                    int g(); 
16223                    void h(int i) {
16224                      char a[g(i)];
16225                      f(a); 
16226                    }
16227
16228                 Here, the type of the ARG will be "int [g(i)]", and
16229                 may be a SAVE_EXPR, etc.  */
16230               if (TREE_CODE (arg_max) != MINUS_EXPR)
16231                 return unify_vla_arg (explain_p, arg);
16232               arg_max = TREE_OPERAND (arg_max, 0);
16233             }
16234
16235           /* If only one of the bounds used a MINUS_EXPR, compensate
16236              by adding one to the other bound.  */
16237           if (parm_cst && !arg_cst)
16238             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
16239                                     integer_type_node,
16240                                     parm_max,
16241                                     integer_one_node);
16242           else if (arg_cst && !parm_cst)
16243             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
16244                                    integer_type_node,
16245                                    arg_max,
16246                                    integer_one_node);
16247
16248           RECUR_AND_CHECK_FAILURE (tparms, targs, parm_max, arg_max,
16249                                    UNIFY_ALLOW_INTEGER, explain_p);
16250         }
16251       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16252                     strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
16253
16254     case REAL_TYPE:
16255     case COMPLEX_TYPE:
16256     case VECTOR_TYPE:
16257     case INTEGER_TYPE:
16258     case BOOLEAN_TYPE:
16259     case ENUMERAL_TYPE:
16260     case VOID_TYPE:
16261       if (TREE_CODE (arg) != TREE_CODE (parm))
16262         return unify_type_mismatch (explain_p, parm, arg);
16263
16264       /* We have already checked cv-qualification at the top of the
16265          function.  */
16266       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
16267         return unify_type_mismatch (explain_p, parm, arg);
16268
16269       /* As far as unification is concerned, this wins.  Later checks
16270          will invalidate it if necessary.  */
16271       return unify_success (explain_p);
16272
16273       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
16274       /* Type INTEGER_CST can come from ordinary constant template args.  */
16275     case INTEGER_CST:
16276       while (TREE_CODE (arg) == NOP_EXPR)
16277         arg = TREE_OPERAND (arg, 0);
16278
16279       if (TREE_CODE (arg) != INTEGER_CST)
16280         return unify_template_argument_mismatch (explain_p, parm, arg);
16281       return (tree_int_cst_equal (parm, arg)
16282               ? unify_success (explain_p)
16283               : unify_template_argument_mismatch (explain_p, parm, arg));
16284
16285     case TREE_VEC:
16286       {
16287         int i, len, argslen;
16288         int parm_variadic_p = 0;
16289
16290         if (TREE_CODE (arg) != TREE_VEC)
16291           return unify_template_argument_mismatch (explain_p, parm, arg);
16292
16293         len = TREE_VEC_LENGTH (parm);
16294         argslen = TREE_VEC_LENGTH (arg);
16295
16296         /* Check for pack expansions in the parameters.  */
16297         for (i = 0; i < len; ++i)
16298           {
16299             if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
16300               {
16301                 if (i == len - 1)
16302                   /* We can unify against something with a trailing
16303                      parameter pack.  */
16304                   parm_variadic_p = 1;
16305                 else
16306                   /* [temp.deduct.type]/9: If the template argument list of
16307                      P contains a pack expansion that is not the last
16308                      template argument, the entire template argument list
16309                      is a non-deduced context.  */
16310                   return unify_success (explain_p);
16311               }
16312           }
16313
16314         /* If we don't have enough arguments to satisfy the parameters
16315            (not counting the pack expression at the end), or we have
16316            too many arguments for a parameter list that doesn't end in
16317            a pack expression, we can't unify.  */
16318         if (parm_variadic_p
16319             ? argslen < len - parm_variadic_p
16320             : argslen != len)
16321           return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
16322
16323         /* Unify all of the parameters that precede the (optional)
16324            pack expression.  */
16325         for (i = 0; i < len - parm_variadic_p; ++i)
16326           {
16327             RECUR_AND_CHECK_FAILURE (tparms, targs,
16328                                      TREE_VEC_ELT (parm, i),
16329                                      TREE_VEC_ELT (arg, i),
16330                                      UNIFY_ALLOW_NONE, explain_p);
16331           }
16332         if (parm_variadic_p)
16333           return unify_pack_expansion (tparms, targs, parm, arg,
16334                                        DEDUCE_EXACT,
16335                                        /*subr=*/true, explain_p);
16336         return unify_success (explain_p);
16337       }
16338
16339     case RECORD_TYPE:
16340     case UNION_TYPE:
16341       if (TREE_CODE (arg) != TREE_CODE (parm))
16342         return unify_type_mismatch (explain_p, parm, arg);
16343
16344       if (TYPE_PTRMEMFUNC_P (parm))
16345         {
16346           if (!TYPE_PTRMEMFUNC_P (arg))
16347             return unify_type_mismatch (explain_p, parm, arg);
16348
16349           return unify (tparms, targs,
16350                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
16351                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
16352                         strict, explain_p);
16353         }
16354
16355       if (CLASSTYPE_TEMPLATE_INFO (parm))
16356         {
16357           tree t = NULL_TREE;
16358
16359           if (strict_in & UNIFY_ALLOW_DERIVED)
16360             {
16361               /* First, we try to unify the PARM and ARG directly.  */
16362               t = try_class_unification (tparms, targs,
16363                                          parm, arg, explain_p);
16364
16365               if (!t)
16366                 {
16367                   /* Fallback to the special case allowed in
16368                      [temp.deduct.call]:
16369
16370                        If P is a class, and P has the form
16371                        template-id, then A can be a derived class of
16372                        the deduced A.  Likewise, if P is a pointer to
16373                        a class of the form template-id, A can be a
16374                        pointer to a derived class pointed to by the
16375                        deduced A.  */
16376                   enum template_base_result r;
16377                   r = get_template_base (tparms, targs, parm, arg,
16378                                          explain_p, &t);
16379
16380                   if (!t)
16381                     return unify_no_common_base (explain_p, r, parm, arg);
16382                 }
16383             }
16384           else if (CLASSTYPE_TEMPLATE_INFO (arg)
16385                    && (CLASSTYPE_TI_TEMPLATE (parm)
16386                        == CLASSTYPE_TI_TEMPLATE (arg)))
16387             /* Perhaps PARM is something like S<U> and ARG is S<int>.
16388                Then, we should unify `int' and `U'.  */
16389             t = arg;
16390           else
16391             /* There's no chance of unification succeeding.  */
16392             return unify_type_mismatch (explain_p, parm, arg);
16393
16394           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
16395                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
16396         }
16397       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
16398         return unify_type_mismatch (explain_p, parm, arg);
16399       return unify_success (explain_p);
16400
16401     case METHOD_TYPE:
16402     case FUNCTION_TYPE:
16403       {
16404         unsigned int nargs;
16405         tree *args;
16406         tree a;
16407         unsigned int i;
16408
16409         if (TREE_CODE (arg) != TREE_CODE (parm))
16410           return unify_type_mismatch (explain_p, parm, arg);
16411
16412         /* CV qualifications for methods can never be deduced, they must
16413            match exactly.  We need to check them explicitly here,
16414            because type_unification_real treats them as any other
16415            cv-qualified parameter.  */
16416         if (TREE_CODE (parm) == METHOD_TYPE
16417             && (!check_cv_quals_for_unify
16418                 (UNIFY_ALLOW_NONE,
16419                  class_of_this_parm (arg),
16420                  class_of_this_parm (parm))))
16421           return unify_cv_qual_mismatch (explain_p, parm, arg);
16422
16423         RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
16424                                  TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
16425
16426         nargs = list_length (TYPE_ARG_TYPES (arg));
16427         args = XALLOCAVEC (tree, nargs);
16428         for (a = TYPE_ARG_TYPES (arg), i = 0;
16429              a != NULL_TREE && a != void_list_node;
16430              a = TREE_CHAIN (a), ++i)
16431           args[i] = TREE_VALUE (a);
16432         nargs = i;
16433
16434         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
16435                                       args, nargs, 1, DEDUCE_EXACT,
16436                                       LOOKUP_NORMAL, explain_p);
16437       }
16438
16439     case OFFSET_TYPE:
16440       /* Unify a pointer to member with a pointer to member function, which
16441          deduces the type of the member as a function type. */
16442       if (TYPE_PTRMEMFUNC_P (arg))
16443         {
16444           tree method_type;
16445           tree fntype;
16446
16447           /* Check top-level cv qualifiers */
16448           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
16449             return unify_cv_qual_mismatch (explain_p, parm, arg);
16450
16451           RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
16452                                    TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
16453                                    UNIFY_ALLOW_NONE, explain_p);
16454
16455           /* Determine the type of the function we are unifying against. */
16456           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
16457           fntype =
16458             build_function_type (TREE_TYPE (method_type),
16459                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
16460
16461           /* Extract the cv-qualifiers of the member function from the
16462              implicit object parameter and place them on the function
16463              type to be restored later. */
16464           fntype = apply_memfn_quals (fntype, type_memfn_quals (method_type));
16465           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
16466         }
16467
16468       if (TREE_CODE (arg) != OFFSET_TYPE)
16469         return unify_type_mismatch (explain_p, parm, arg);
16470       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
16471                                TYPE_OFFSET_BASETYPE (arg),
16472                                UNIFY_ALLOW_NONE, explain_p);
16473       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16474                     strict, explain_p);
16475
16476     case CONST_DECL:
16477       if (DECL_TEMPLATE_PARM_P (parm))
16478         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
16479       if (arg != integral_constant_value (parm))
16480         return unify_template_argument_mismatch (explain_p, parm, arg);
16481       return unify_success (explain_p);
16482
16483     case FIELD_DECL:
16484     case TEMPLATE_DECL:
16485       /* Matched cases are handled by the ARG == PARM test above.  */
16486       return unify_template_argument_mismatch (explain_p, parm, arg);
16487
16488     case VAR_DECL:
16489       /* A non-type template parameter that is a variable should be a
16490          an integral constant, in which case, it whould have been
16491          folded into its (constant) value. So we should not be getting
16492          a variable here.  */
16493       gcc_unreachable ();
16494
16495     case TYPE_ARGUMENT_PACK:
16496     case NONTYPE_ARGUMENT_PACK:
16497       return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
16498                     ARGUMENT_PACK_ARGS (arg), strict, explain_p);
16499
16500     case TYPEOF_TYPE:
16501     case DECLTYPE_TYPE:
16502     case UNDERLYING_TYPE:
16503       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
16504          or UNDERLYING_TYPE nodes.  */
16505       return unify_success (explain_p);
16506
16507     case ERROR_MARK:
16508       /* Unification fails if we hit an error node.  */
16509       return unify_invalid (explain_p);
16510
16511     default:
16512       /* An unresolved overload is a nondeduced context.  */
16513       if (type_unknown_p (parm))
16514         return unify_success (explain_p);
16515       gcc_assert (EXPR_P (parm));
16516
16517       /* We must be looking at an expression.  This can happen with
16518          something like:
16519
16520            template <int I>
16521            void foo(S<I>, S<I + 2>);
16522
16523          This is a "nondeduced context":
16524
16525            [deduct.type]
16526
16527            The nondeduced contexts are:
16528
16529            --A type that is a template-id in which one or more of
16530              the template-arguments is an expression that references
16531              a template-parameter.
16532
16533          In these cases, we assume deduction succeeded, but don't
16534          actually infer any unifications.  */
16535
16536       if (!uses_template_parms (parm)
16537           && !template_args_equal (parm, arg))
16538         return unify_expression_unequal (explain_p, parm, arg);
16539       else
16540         return unify_success (explain_p);
16541     }
16542 }
16543 #undef RECUR_AND_CHECK_FAILURE
16544 \f
16545 /* Note that DECL can be defined in this translation unit, if
16546    required.  */
16547
16548 static void
16549 mark_definable (tree decl)
16550 {
16551   tree clone;
16552   DECL_NOT_REALLY_EXTERN (decl) = 1;
16553   FOR_EACH_CLONE (clone, decl)
16554     DECL_NOT_REALLY_EXTERN (clone) = 1;
16555 }
16556
16557 /* Called if RESULT is explicitly instantiated, or is a member of an
16558    explicitly instantiated class.  */
16559
16560 void
16561 mark_decl_instantiated (tree result, int extern_p)
16562 {
16563   SET_DECL_EXPLICIT_INSTANTIATION (result);
16564
16565   /* If this entity has already been written out, it's too late to
16566      make any modifications.  */
16567   if (TREE_ASM_WRITTEN (result))
16568     return;
16569
16570   if (TREE_CODE (result) != FUNCTION_DECL)
16571     /* The TREE_PUBLIC flag for function declarations will have been
16572        set correctly by tsubst.  */
16573     TREE_PUBLIC (result) = 1;
16574
16575   /* This might have been set by an earlier implicit instantiation.  */
16576   DECL_COMDAT (result) = 0;
16577
16578   if (extern_p)
16579     DECL_NOT_REALLY_EXTERN (result) = 0;
16580   else
16581     {
16582       mark_definable (result);
16583       /* Always make artificials weak.  */
16584       if (DECL_ARTIFICIAL (result) && flag_weak)
16585         comdat_linkage (result);
16586       /* For WIN32 we also want to put explicit instantiations in
16587          linkonce sections.  */
16588       else if (TREE_PUBLIC (result))
16589         maybe_make_one_only (result);
16590     }
16591
16592   /* If EXTERN_P, then this function will not be emitted -- unless
16593      followed by an explicit instantiation, at which point its linkage
16594      will be adjusted.  If !EXTERN_P, then this function will be
16595      emitted here.  In neither circumstance do we want
16596      import_export_decl to adjust the linkage.  */
16597   DECL_INTERFACE_KNOWN (result) = 1;
16598 }
16599
16600 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
16601    important template arguments.  If any are missing, we check whether
16602    they're important by using error_mark_node for substituting into any
16603    args that were used for partial ordering (the ones between ARGS and END)
16604    and seeing if it bubbles up.  */
16605
16606 static bool
16607 check_undeduced_parms (tree targs, tree args, tree end)
16608 {
16609   bool found = false;
16610   int i;
16611   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
16612     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
16613       {
16614         found = true;
16615         TREE_VEC_ELT (targs, i) = error_mark_node;
16616       }
16617   if (found)
16618     {
16619       for (; args != end; args = TREE_CHAIN (args))
16620         {
16621           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
16622           if (substed == error_mark_node)
16623             return true;
16624         }
16625     }
16626   return false;
16627 }
16628
16629 /* Given two function templates PAT1 and PAT2, return:
16630
16631    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
16632    -1 if PAT2 is more specialized than PAT1.
16633    0 if neither is more specialized.
16634
16635    LEN indicates the number of parameters we should consider
16636    (defaulted parameters should not be considered).
16637
16638    The 1998 std underspecified function template partial ordering, and
16639    DR214 addresses the issue.  We take pairs of arguments, one from
16640    each of the templates, and deduce them against each other.  One of
16641    the templates will be more specialized if all the *other*
16642    template's arguments deduce against its arguments and at least one
16643    of its arguments *does* *not* deduce against the other template's
16644    corresponding argument.  Deduction is done as for class templates.
16645    The arguments used in deduction have reference and top level cv
16646    qualifiers removed.  Iff both arguments were originally reference
16647    types *and* deduction succeeds in both directions, the template
16648    with the more cv-qualified argument wins for that pairing (if
16649    neither is more cv-qualified, they both are equal).  Unlike regular
16650    deduction, after all the arguments have been deduced in this way,
16651    we do *not* verify the deduced template argument values can be
16652    substituted into non-deduced contexts.
16653
16654    The logic can be a bit confusing here, because we look at deduce1 and
16655    targs1 to see if pat2 is at least as specialized, and vice versa; if we
16656    can find template arguments for pat1 to make arg1 look like arg2, that
16657    means that arg2 is at least as specialized as arg1.  */
16658
16659 int
16660 more_specialized_fn (tree pat1, tree pat2, int len)
16661 {
16662   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
16663   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
16664   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
16665   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
16666   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
16667   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
16668   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
16669   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
16670   tree origs1, origs2;
16671   bool lose1 = false;
16672   bool lose2 = false;
16673
16674   /* Remove the this parameter from non-static member functions.  If
16675      one is a non-static member function and the other is not a static
16676      member function, remove the first parameter from that function
16677      also.  This situation occurs for operator functions where we
16678      locate both a member function (with this pointer) and non-member
16679      operator (with explicit first operand).  */
16680   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
16681     {
16682       len--; /* LEN is the number of significant arguments for DECL1 */
16683       args1 = TREE_CHAIN (args1);
16684       if (!DECL_STATIC_FUNCTION_P (decl2))
16685         args2 = TREE_CHAIN (args2);
16686     }
16687   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
16688     {
16689       args2 = TREE_CHAIN (args2);
16690       if (!DECL_STATIC_FUNCTION_P (decl1))
16691         {
16692           len--;
16693           args1 = TREE_CHAIN (args1);
16694         }
16695     }
16696
16697   /* If only one is a conversion operator, they are unordered.  */
16698   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
16699     return 0;
16700
16701   /* Consider the return type for a conversion function */
16702   if (DECL_CONV_FN_P (decl1))
16703     {
16704       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
16705       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
16706       len++;
16707     }
16708
16709   processing_template_decl++;
16710
16711   origs1 = args1;
16712   origs2 = args2;
16713
16714   while (len--
16715          /* Stop when an ellipsis is seen.  */
16716          && args1 != NULL_TREE && args2 != NULL_TREE)
16717     {
16718       tree arg1 = TREE_VALUE (args1);
16719       tree arg2 = TREE_VALUE (args2);
16720       int deduce1, deduce2;
16721       int quals1 = -1;
16722       int quals2 = -1;
16723
16724       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
16725           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16726         {
16727           /* When both arguments are pack expansions, we need only
16728              unify the patterns themselves.  */
16729           arg1 = PACK_EXPANSION_PATTERN (arg1);
16730           arg2 = PACK_EXPANSION_PATTERN (arg2);
16731
16732           /* This is the last comparison we need to do.  */
16733           len = 0;
16734         }
16735
16736       if (TREE_CODE (arg1) == REFERENCE_TYPE)
16737         {
16738           arg1 = TREE_TYPE (arg1);
16739           quals1 = cp_type_quals (arg1);
16740         }
16741
16742       if (TREE_CODE (arg2) == REFERENCE_TYPE)
16743         {
16744           arg2 = TREE_TYPE (arg2);
16745           quals2 = cp_type_quals (arg2);
16746         }
16747
16748       if ((quals1 < 0) != (quals2 < 0))
16749         {
16750           /* Only of the args is a reference, see if we should apply
16751              array/function pointer decay to it.  This is not part of
16752              DR214, but is, IMHO, consistent with the deduction rules
16753              for the function call itself, and with our earlier
16754              implementation of the underspecified partial ordering
16755              rules.  (nathan).  */
16756           if (quals1 >= 0)
16757             {
16758               switch (TREE_CODE (arg1))
16759                 {
16760                 case ARRAY_TYPE:
16761                   arg1 = TREE_TYPE (arg1);
16762                   /* FALLTHROUGH. */
16763                 case FUNCTION_TYPE:
16764                   arg1 = build_pointer_type (arg1);
16765                   break;
16766
16767                 default:
16768                   break;
16769                 }
16770             }
16771           else
16772             {
16773               switch (TREE_CODE (arg2))
16774                 {
16775                 case ARRAY_TYPE:
16776                   arg2 = TREE_TYPE (arg2);
16777                   /* FALLTHROUGH. */
16778                 case FUNCTION_TYPE:
16779                   arg2 = build_pointer_type (arg2);
16780                   break;
16781
16782                 default:
16783                   break;
16784                 }
16785             }
16786         }
16787
16788       arg1 = TYPE_MAIN_VARIANT (arg1);
16789       arg2 = TYPE_MAIN_VARIANT (arg2);
16790
16791       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
16792         {
16793           int i, len2 = list_length (args2);
16794           tree parmvec = make_tree_vec (1);
16795           tree argvec = make_tree_vec (len2);
16796           tree ta = args2;
16797
16798           /* Setup the parameter vector, which contains only ARG1.  */
16799           TREE_VEC_ELT (parmvec, 0) = arg1;
16800
16801           /* Setup the argument vector, which contains the remaining
16802              arguments.  */
16803           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
16804             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
16805
16806           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
16807                                            argvec, DEDUCE_EXACT,
16808                                            /*subr=*/true, /*explain_p=*/false)
16809                      == 0);
16810
16811           /* We cannot deduce in the other direction, because ARG1 is
16812              a pack expansion but ARG2 is not.  */
16813           deduce2 = 0;
16814         }
16815       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16816         {
16817           int i, len1 = list_length (args1);
16818           tree parmvec = make_tree_vec (1);
16819           tree argvec = make_tree_vec (len1);
16820           tree ta = args1;
16821
16822           /* Setup the parameter vector, which contains only ARG1.  */
16823           TREE_VEC_ELT (parmvec, 0) = arg2;
16824
16825           /* Setup the argument vector, which contains the remaining
16826              arguments.  */
16827           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
16828             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
16829
16830           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
16831                                            argvec, DEDUCE_EXACT,
16832                                            /*subr=*/true, /*explain_p=*/false)
16833                      == 0);
16834
16835           /* We cannot deduce in the other direction, because ARG2 is
16836              a pack expansion but ARG1 is not.*/
16837           deduce1 = 0;
16838         }
16839
16840       else
16841         {
16842           /* The normal case, where neither argument is a pack
16843              expansion.  */
16844           deduce1 = (unify (tparms1, targs1, arg1, arg2,
16845                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
16846                      == 0);
16847           deduce2 = (unify (tparms2, targs2, arg2, arg1,
16848                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
16849                      == 0);
16850         }
16851
16852       /* If we couldn't deduce arguments for tparms1 to make arg1 match
16853          arg2, then arg2 is not as specialized as arg1.  */
16854       if (!deduce1)
16855         lose2 = true;
16856       if (!deduce2)
16857         lose1 = true;
16858
16859       /* "If, for a given type, deduction succeeds in both directions
16860          (i.e., the types are identical after the transformations above)
16861          and if the type from the argument template is more cv-qualified
16862          than the type from the parameter template (as described above)
16863          that type is considered to be more specialized than the other. If
16864          neither type is more cv-qualified than the other then neither type
16865          is more specialized than the other."  */
16866
16867       if (deduce1 && deduce2
16868           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
16869         {
16870           if ((quals1 & quals2) == quals2)
16871             lose2 = true;
16872           if ((quals1 & quals2) == quals1)
16873             lose1 = true;
16874         }
16875
16876       if (lose1 && lose2)
16877         /* We've failed to deduce something in either direction.
16878            These must be unordered.  */
16879         break;
16880
16881       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
16882           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16883         /* We have already processed all of the arguments in our
16884            handing of the pack expansion type.  */
16885         len = 0;
16886
16887       args1 = TREE_CHAIN (args1);
16888       args2 = TREE_CHAIN (args2);
16889     }
16890
16891   /* "In most cases, all template parameters must have values in order for
16892      deduction to succeed, but for partial ordering purposes a template
16893      parameter may remain without a value provided it is not used in the
16894      types being used for partial ordering."
16895
16896      Thus, if we are missing any of the targs1 we need to substitute into
16897      origs1, then pat2 is not as specialized as pat1.  This can happen when
16898      there is a nondeduced context.  */
16899   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
16900     lose2 = true;
16901   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
16902     lose1 = true;
16903
16904   processing_template_decl--;
16905
16906   /* All things being equal, if the next argument is a pack expansion
16907      for one function but not for the other, prefer the
16908      non-variadic function.  FIXME this is bogus; see c++/41958.  */
16909   if (lose1 == lose2
16910       && args1 && TREE_VALUE (args1)
16911       && args2 && TREE_VALUE (args2))
16912     {
16913       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
16914       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
16915     }
16916
16917   if (lose1 == lose2)
16918     return 0;
16919   else if (!lose1)
16920     return 1;
16921   else
16922     return -1;
16923 }
16924
16925 /* Determine which of two partial specializations is more specialized.
16926
16927    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
16928    to the first partial specialization.  The TREE_VALUE is the
16929    innermost set of template parameters for the partial
16930    specialization.  PAT2 is similar, but for the second template.
16931
16932    Return 1 if the first partial specialization is more specialized;
16933    -1 if the second is more specialized; 0 if neither is more
16934    specialized.
16935
16936    See [temp.class.order] for information about determining which of
16937    two templates is more specialized.  */
16938
16939 static int
16940 more_specialized_class (tree pat1, tree pat2)
16941 {
16942   tree targs;
16943   tree tmpl1, tmpl2;
16944   int winner = 0;
16945   bool any_deductions = false;
16946
16947   tmpl1 = TREE_TYPE (pat1);
16948   tmpl2 = TREE_TYPE (pat2);
16949
16950   /* Just like what happens for functions, if we are ordering between
16951      different class template specializations, we may encounter dependent
16952      types in the arguments, and we need our dependency check functions
16953      to behave correctly.  */
16954   ++processing_template_decl;
16955   targs = get_class_bindings (TREE_VALUE (pat1),
16956                               CLASSTYPE_TI_ARGS (tmpl1),
16957                               CLASSTYPE_TI_ARGS (tmpl2));
16958   if (targs)
16959     {
16960       --winner;
16961       any_deductions = true;
16962     }
16963
16964   targs = get_class_bindings (TREE_VALUE (pat2),
16965                               CLASSTYPE_TI_ARGS (tmpl2),
16966                               CLASSTYPE_TI_ARGS (tmpl1));
16967   if (targs)
16968     {
16969       ++winner;
16970       any_deductions = true;
16971     }
16972   --processing_template_decl;
16973
16974   /* In the case of a tie where at least one of the class templates
16975      has a parameter pack at the end, the template with the most
16976      non-packed parameters wins.  */
16977   if (winner == 0
16978       && any_deductions
16979       && (template_args_variadic_p (TREE_PURPOSE (pat1))
16980           || template_args_variadic_p (TREE_PURPOSE (pat2))))
16981     {
16982       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
16983       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
16984       int len1 = TREE_VEC_LENGTH (args1);
16985       int len2 = TREE_VEC_LENGTH (args2);
16986
16987       /* We don't count the pack expansion at the end.  */
16988       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
16989         --len1;
16990       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
16991         --len2;
16992
16993       if (len1 > len2)
16994         return 1;
16995       else if (len1 < len2)
16996         return -1;
16997     }
16998
16999   return winner;
17000 }
17001
17002 /* Return the template arguments that will produce the function signature
17003    DECL from the function template FN, with the explicit template
17004    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
17005    also match.  Return NULL_TREE if no satisfactory arguments could be
17006    found.  */
17007
17008 static tree
17009 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
17010 {
17011   int ntparms = DECL_NTPARMS (fn);
17012   tree targs = make_tree_vec (ntparms);
17013   tree decl_type;
17014   tree decl_arg_types;
17015   tree *args;
17016   unsigned int nargs, ix;
17017   tree arg;
17018
17019   /* Substitute the explicit template arguments into the type of DECL.
17020      The call to fn_type_unification will handle substitution into the
17021      FN.  */
17022   decl_type = TREE_TYPE (decl);
17023   if (explicit_args && uses_template_parms (decl_type))
17024     {
17025       tree tmpl;
17026       tree converted_args;
17027
17028       if (DECL_TEMPLATE_INFO (decl))
17029         tmpl = DECL_TI_TEMPLATE (decl);
17030       else
17031         /* We can get here for some invalid specializations.  */
17032         return NULL_TREE;
17033
17034       converted_args
17035         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
17036                                  explicit_args, NULL_TREE,
17037                                  tf_none,
17038                                  /*require_all_args=*/false,
17039                                  /*use_default_args=*/false);
17040       if (converted_args == error_mark_node)
17041         return NULL_TREE;
17042
17043       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
17044       if (decl_type == error_mark_node)
17045         return NULL_TREE;
17046     }
17047
17048   /* Never do unification on the 'this' parameter.  */
17049   decl_arg_types = skip_artificial_parms_for (decl, 
17050                                               TYPE_ARG_TYPES (decl_type));
17051
17052   nargs = list_length (decl_arg_types);
17053   args = XALLOCAVEC (tree, nargs);
17054   for (arg = decl_arg_types, ix = 0;
17055        arg != NULL_TREE && arg != void_list_node;
17056        arg = TREE_CHAIN (arg), ++ix)
17057     args[ix] = TREE_VALUE (arg);
17058
17059   if (fn_type_unification (fn, explicit_args, targs,
17060                            args, ix,
17061                            (check_rettype || DECL_CONV_FN_P (fn)
17062                             ? TREE_TYPE (decl_type) : NULL_TREE),
17063                            DEDUCE_EXACT, LOOKUP_NORMAL, /*explain_p=*/false))
17064     return NULL_TREE;
17065
17066   return targs;
17067 }
17068
17069 /* Return the innermost template arguments that, when applied to a
17070    template specialization whose innermost template parameters are
17071    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
17072    ARGS.
17073
17074    For example, suppose we have:
17075
17076      template <class T, class U> struct S {};
17077      template <class T> struct S<T*, int> {};
17078
17079    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
17080    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
17081    int}.  The resulting vector will be {double}, indicating that `T'
17082    is bound to `double'.  */
17083
17084 static tree
17085 get_class_bindings (tree tparms, tree spec_args, tree args)
17086 {
17087   int i, ntparms = TREE_VEC_LENGTH (tparms);
17088   tree deduced_args;
17089   tree innermost_deduced_args;
17090
17091   innermost_deduced_args = make_tree_vec (ntparms);
17092   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
17093     {
17094       deduced_args = copy_node (args);
17095       SET_TMPL_ARGS_LEVEL (deduced_args,
17096                            TMPL_ARGS_DEPTH (deduced_args),
17097                            innermost_deduced_args);
17098     }
17099   else
17100     deduced_args = innermost_deduced_args;
17101
17102   if (unify (tparms, deduced_args,
17103              INNERMOST_TEMPLATE_ARGS (spec_args),
17104              INNERMOST_TEMPLATE_ARGS (args),
17105              UNIFY_ALLOW_NONE, /*explain_p=*/false))
17106     return NULL_TREE;
17107
17108   for (i =  0; i < ntparms; ++i)
17109     if (! TREE_VEC_ELT (innermost_deduced_args, i))
17110       return NULL_TREE;
17111
17112   /* Verify that nondeduced template arguments agree with the type
17113      obtained from argument deduction.
17114
17115      For example:
17116
17117        struct A { typedef int X; };
17118        template <class T, class U> struct C {};
17119        template <class T> struct C<T, typename T::X> {};
17120
17121      Then with the instantiation `C<A, int>', we can deduce that
17122      `T' is `A' but unify () does not check whether `typename T::X'
17123      is `int'.  */
17124   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
17125   if (spec_args == error_mark_node
17126       /* We only need to check the innermost arguments; the other
17127          arguments will always agree.  */
17128       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
17129                               INNERMOST_TEMPLATE_ARGS (args)))
17130     return NULL_TREE;
17131
17132   /* Now that we have bindings for all of the template arguments,
17133      ensure that the arguments deduced for the template template
17134      parameters have compatible template parameter lists.  See the use
17135      of template_template_parm_bindings_ok_p in fn_type_unification
17136      for more information.  */
17137   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
17138     return NULL_TREE;
17139
17140   return deduced_args;
17141 }
17142
17143 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
17144    Return the TREE_LIST node with the most specialized template, if
17145    any.  If there is no most specialized template, the error_mark_node
17146    is returned.
17147
17148    Note that this function does not look at, or modify, the
17149    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
17150    returned is one of the elements of INSTANTIATIONS, callers may
17151    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
17152    and retrieve it from the value returned.  */
17153
17154 tree
17155 most_specialized_instantiation (tree templates)
17156 {
17157   tree fn, champ;
17158
17159   ++processing_template_decl;
17160
17161   champ = templates;
17162   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
17163     {
17164       int fate = 0;
17165
17166       if (get_bindings (TREE_VALUE (champ),
17167                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
17168                         NULL_TREE, /*check_ret=*/true))
17169         fate--;
17170
17171       if (get_bindings (TREE_VALUE (fn),
17172                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
17173                         NULL_TREE, /*check_ret=*/true))
17174         fate++;
17175
17176       if (fate == -1)
17177         champ = fn;
17178       else if (!fate)
17179         {
17180           /* Equally specialized, move to next function.  If there
17181              is no next function, nothing's most specialized.  */
17182           fn = TREE_CHAIN (fn);
17183           champ = fn;
17184           if (!fn)
17185             break;
17186         }
17187     }
17188
17189   if (champ)
17190     /* Now verify that champ is better than everything earlier in the
17191        instantiation list.  */
17192     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
17193       if (get_bindings (TREE_VALUE (champ),
17194                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
17195                         NULL_TREE, /*check_ret=*/true)
17196           || !get_bindings (TREE_VALUE (fn),
17197                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
17198                             NULL_TREE, /*check_ret=*/true))
17199         {
17200           champ = NULL_TREE;
17201           break;
17202         }
17203
17204   processing_template_decl--;
17205
17206   if (!champ)
17207     return error_mark_node;
17208
17209   return champ;
17210 }
17211
17212 /* If DECL is a specialization of some template, return the most
17213    general such template.  Otherwise, returns NULL_TREE.
17214
17215    For example, given:
17216
17217      template <class T> struct S { template <class U> void f(U); };
17218
17219    if TMPL is `template <class U> void S<int>::f(U)' this will return
17220    the full template.  This function will not trace past partial
17221    specializations, however.  For example, given in addition:
17222
17223      template <class T> struct S<T*> { template <class U> void f(U); };
17224
17225    if TMPL is `template <class U> void S<int*>::f(U)' this will return
17226    `template <class T> template <class U> S<T*>::f(U)'.  */
17227
17228 tree
17229 most_general_template (tree decl)
17230 {
17231   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
17232      an immediate specialization.  */
17233   if (TREE_CODE (decl) == FUNCTION_DECL)
17234     {
17235       if (DECL_TEMPLATE_INFO (decl)) {
17236         decl = DECL_TI_TEMPLATE (decl);
17237
17238         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
17239            template friend.  */
17240         if (TREE_CODE (decl) != TEMPLATE_DECL)
17241           return NULL_TREE;
17242       } else
17243         return NULL_TREE;
17244     }
17245
17246   /* Look for more and more general templates.  */
17247   while (DECL_TEMPLATE_INFO (decl))
17248     {
17249       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
17250          (See cp-tree.h for details.)  */
17251       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
17252         break;
17253
17254       if (CLASS_TYPE_P (TREE_TYPE (decl))
17255           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
17256         break;
17257
17258       /* Stop if we run into an explicitly specialized class template.  */
17259       if (!DECL_NAMESPACE_SCOPE_P (decl)
17260           && DECL_CONTEXT (decl)
17261           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
17262         break;
17263
17264       decl = DECL_TI_TEMPLATE (decl);
17265     }
17266
17267   return decl;
17268 }
17269
17270 /* Return the most specialized of the class template partial
17271    specializations of TMPL which can produce TYPE, a specialization of
17272    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
17273    a _TYPE node corresponding to the partial specialization, while the
17274    TREE_PURPOSE is the set of template arguments that must be
17275    substituted into the TREE_TYPE in order to generate TYPE.
17276
17277    If the choice of partial specialization is ambiguous, a diagnostic
17278    is issued, and the error_mark_node is returned.  If there are no
17279    partial specializations of TMPL matching TYPE, then NULL_TREE is
17280    returned.  */
17281
17282 static tree
17283 most_specialized_class (tree type, tree tmpl, tsubst_flags_t complain)
17284 {
17285   tree list = NULL_TREE;
17286   tree t;
17287   tree champ;
17288   int fate;
17289   bool ambiguous_p;
17290   tree args;
17291   tree outer_args = NULL_TREE;
17292
17293   tmpl = most_general_template (tmpl);
17294   args = CLASSTYPE_TI_ARGS (type);
17295
17296   /* For determining which partial specialization to use, only the
17297      innermost args are interesting.  */
17298   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
17299     {
17300       outer_args = strip_innermost_template_args (args, 1);
17301       args = INNERMOST_TEMPLATE_ARGS (args);
17302     }
17303
17304   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
17305     {
17306       tree partial_spec_args;
17307       tree spec_args;
17308       tree parms = TREE_VALUE (t);
17309
17310       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
17311
17312       ++processing_template_decl;
17313
17314       if (outer_args)
17315         {
17316           int i;
17317
17318           /* Discard the outer levels of args, and then substitute in the
17319              template args from the enclosing class.  */
17320           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
17321           partial_spec_args = tsubst_template_args
17322             (partial_spec_args, outer_args, tf_none, NULL_TREE);
17323
17324           /* PARMS already refers to just the innermost parms, but the
17325              template parms in partial_spec_args had their levels lowered
17326              by tsubst, so we need to do the same for the parm list.  We
17327              can't just tsubst the TREE_VEC itself, as tsubst wants to
17328              treat a TREE_VEC as an argument vector.  */
17329           parms = copy_node (parms);
17330           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
17331             TREE_VEC_ELT (parms, i) =
17332               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
17333
17334         }
17335
17336       partial_spec_args =
17337           coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
17338                                  add_to_template_args (outer_args,
17339                                                        partial_spec_args),
17340                                  tmpl, tf_none,
17341                                  /*require_all_args=*/true,
17342                                  /*use_default_args=*/true);
17343
17344       --processing_template_decl;
17345
17346       if (partial_spec_args == error_mark_node)
17347         return error_mark_node;
17348
17349       spec_args = get_class_bindings (parms,
17350                                       partial_spec_args,
17351                                       args);
17352       if (spec_args)
17353         {
17354           if (outer_args)
17355             spec_args = add_to_template_args (outer_args, spec_args);
17356           list = tree_cons (spec_args, TREE_VALUE (t), list);
17357           TREE_TYPE (list) = TREE_TYPE (t);
17358         }
17359     }
17360
17361   if (! list)
17362     return NULL_TREE;
17363
17364   ambiguous_p = false;
17365   t = list;
17366   champ = t;
17367   t = TREE_CHAIN (t);
17368   for (; t; t = TREE_CHAIN (t))
17369     {
17370       fate = more_specialized_class (champ, t);
17371       if (fate == 1)
17372         ;
17373       else
17374         {
17375           if (fate == 0)
17376             {
17377               t = TREE_CHAIN (t);
17378               if (! t)
17379                 {
17380                   ambiguous_p = true;
17381                   break;
17382                 }
17383             }
17384           champ = t;
17385         }
17386     }
17387
17388   if (!ambiguous_p)
17389     for (t = list; t && t != champ; t = TREE_CHAIN (t))
17390       {
17391         fate = more_specialized_class (champ, t);
17392         if (fate != 1)
17393           {
17394             ambiguous_p = true;
17395             break;
17396           }
17397       }
17398
17399   if (ambiguous_p)
17400     {
17401       const char *str;
17402       char *spaces = NULL;
17403       if (!(complain & tf_error))
17404         return error_mark_node;
17405       error ("ambiguous class template instantiation for %q#T", type);
17406       str = ngettext ("candidate is:", "candidates are:", list_length (list));
17407       for (t = list; t; t = TREE_CHAIN (t))
17408         {
17409           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
17410           spaces = spaces ? spaces : get_spaces (str);
17411         }
17412       free (spaces);
17413       return error_mark_node;
17414     }
17415
17416   return champ;
17417 }
17418
17419 /* Explicitly instantiate DECL.  */
17420
17421 void
17422 do_decl_instantiation (tree decl, tree storage)
17423 {
17424   tree result = NULL_TREE;
17425   int extern_p = 0;
17426
17427   if (!decl || decl == error_mark_node)
17428     /* An error occurred, for which grokdeclarator has already issued
17429        an appropriate message.  */
17430     return;
17431   else if (! DECL_LANG_SPECIFIC (decl))
17432     {
17433       error ("explicit instantiation of non-template %q#D", decl);
17434       return;
17435     }
17436   else if (TREE_CODE (decl) == VAR_DECL)
17437     {
17438       /* There is an asymmetry here in the way VAR_DECLs and
17439          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
17440          the latter, the DECL we get back will be marked as a
17441          template instantiation, and the appropriate
17442          DECL_TEMPLATE_INFO will be set up.  This does not happen for
17443          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
17444          should handle VAR_DECLs as it currently handles
17445          FUNCTION_DECLs.  */
17446       if (!DECL_CLASS_SCOPE_P (decl))
17447         {
17448           error ("%qD is not a static data member of a class template", decl);
17449           return;
17450         }
17451       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
17452       if (!result || TREE_CODE (result) != VAR_DECL)
17453         {
17454           error ("no matching template for %qD found", decl);
17455           return;
17456         }
17457       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
17458         {
17459           error ("type %qT for explicit instantiation %qD does not match "
17460                  "declared type %qT", TREE_TYPE (result), decl,
17461                  TREE_TYPE (decl));
17462           return;
17463         }
17464     }
17465   else if (TREE_CODE (decl) != FUNCTION_DECL)
17466     {
17467       error ("explicit instantiation of %q#D", decl);
17468       return;
17469     }
17470   else
17471     result = decl;
17472
17473   /* Check for various error cases.  Note that if the explicit
17474      instantiation is valid the RESULT will currently be marked as an
17475      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
17476      until we get here.  */
17477
17478   if (DECL_TEMPLATE_SPECIALIZATION (result))
17479     {
17480       /* DR 259 [temp.spec].
17481
17482          Both an explicit instantiation and a declaration of an explicit
17483          specialization shall not appear in a program unless the explicit
17484          instantiation follows a declaration of the explicit specialization.
17485
17486          For a given set of template parameters, if an explicit
17487          instantiation of a template appears after a declaration of an
17488          explicit specialization for that template, the explicit
17489          instantiation has no effect.  */
17490       return;
17491     }
17492   else if (DECL_EXPLICIT_INSTANTIATION (result))
17493     {
17494       /* [temp.spec]
17495
17496          No program shall explicitly instantiate any template more
17497          than once.
17498
17499          We check DECL_NOT_REALLY_EXTERN so as not to complain when
17500          the first instantiation was `extern' and the second is not,
17501          and EXTERN_P for the opposite case.  */
17502       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
17503         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
17504       /* If an "extern" explicit instantiation follows an ordinary
17505          explicit instantiation, the template is instantiated.  */
17506       if (extern_p)
17507         return;
17508     }
17509   else if (!DECL_IMPLICIT_INSTANTIATION (result))
17510     {
17511       error ("no matching template for %qD found", result);
17512       return;
17513     }
17514   else if (!DECL_TEMPLATE_INFO (result))
17515     {
17516       permerror (input_location, "explicit instantiation of non-template %q#D", result);
17517       return;
17518     }
17519
17520   if (storage == NULL_TREE)
17521     ;
17522   else if (storage == ridpointers[(int) RID_EXTERN])
17523     {
17524       if (!in_system_header && (cxx_dialect == cxx98))
17525         pedwarn (input_location, OPT_pedantic, 
17526                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
17527                  "instantiations");
17528       extern_p = 1;
17529     }
17530   else
17531     error ("storage class %qD applied to template instantiation", storage);
17532
17533   check_explicit_instantiation_namespace (result);
17534   mark_decl_instantiated (result, extern_p);
17535   if (! extern_p)
17536     instantiate_decl (result, /*defer_ok=*/1,
17537                       /*expl_inst_class_mem_p=*/false);
17538 }
17539
17540 static void
17541 mark_class_instantiated (tree t, int extern_p)
17542 {
17543   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
17544   SET_CLASSTYPE_INTERFACE_KNOWN (t);
17545   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
17546   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
17547   if (! extern_p)
17548     {
17549       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
17550       rest_of_type_compilation (t, 1);
17551     }
17552 }
17553
17554 /* Called from do_type_instantiation through binding_table_foreach to
17555    do recursive instantiation for the type bound in ENTRY.  */
17556 static void
17557 bt_instantiate_type_proc (binding_entry entry, void *data)
17558 {
17559   tree storage = *(tree *) data;
17560
17561   if (MAYBE_CLASS_TYPE_P (entry->type)
17562       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
17563     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
17564 }
17565
17566 /* Called from do_type_instantiation to instantiate a member
17567    (a member function or a static member variable) of an
17568    explicitly instantiated class template.  */
17569 static void
17570 instantiate_class_member (tree decl, int extern_p)
17571 {
17572   mark_decl_instantiated (decl, extern_p);
17573   if (! extern_p)
17574     instantiate_decl (decl, /*defer_ok=*/1,
17575                       /*expl_inst_class_mem_p=*/true);
17576 }
17577
17578 /* Perform an explicit instantiation of template class T.  STORAGE, if
17579    non-null, is the RID for extern, inline or static.  COMPLAIN is
17580    nonzero if this is called from the parser, zero if called recursively,
17581    since the standard is unclear (as detailed below).  */
17582
17583 void
17584 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
17585 {
17586   int extern_p = 0;
17587   int nomem_p = 0;
17588   int static_p = 0;
17589   int previous_instantiation_extern_p = 0;
17590
17591   if (TREE_CODE (t) == TYPE_DECL)
17592     t = TREE_TYPE (t);
17593
17594   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
17595     {
17596       error ("explicit instantiation of non-template type %qT", t);
17597       return;
17598     }
17599
17600   complete_type (t);
17601
17602   if (!COMPLETE_TYPE_P (t))
17603     {
17604       if (complain & tf_error)
17605         error ("explicit instantiation of %q#T before definition of template",
17606                t);
17607       return;
17608     }
17609
17610   if (storage != NULL_TREE)
17611     {
17612       if (!in_system_header)
17613         {
17614           if (storage == ridpointers[(int) RID_EXTERN])
17615             {
17616               if (cxx_dialect == cxx98)
17617                 pedwarn (input_location, OPT_pedantic, 
17618                          "ISO C++ 1998 forbids the use of %<extern%> on "
17619                          "explicit instantiations");
17620             }
17621           else
17622             pedwarn (input_location, OPT_pedantic, 
17623                      "ISO C++ forbids the use of %qE"
17624                      " on explicit instantiations", storage);
17625         }
17626
17627       if (storage == ridpointers[(int) RID_INLINE])
17628         nomem_p = 1;
17629       else if (storage == ridpointers[(int) RID_EXTERN])
17630         extern_p = 1;
17631       else if (storage == ridpointers[(int) RID_STATIC])
17632         static_p = 1;
17633       else
17634         {
17635           error ("storage class %qD applied to template instantiation",
17636                  storage);
17637           extern_p = 0;
17638         }
17639     }
17640
17641   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
17642     {
17643       /* DR 259 [temp.spec].
17644
17645          Both an explicit instantiation and a declaration of an explicit
17646          specialization shall not appear in a program unless the explicit
17647          instantiation follows a declaration of the explicit specialization.
17648
17649          For a given set of template parameters, if an explicit
17650          instantiation of a template appears after a declaration of an
17651          explicit specialization for that template, the explicit
17652          instantiation has no effect.  */
17653       return;
17654     }
17655   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
17656     {
17657       /* [temp.spec]
17658
17659          No program shall explicitly instantiate any template more
17660          than once.
17661
17662          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
17663          instantiation was `extern'.  If EXTERN_P then the second is.
17664          These cases are OK.  */
17665       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
17666
17667       if (!previous_instantiation_extern_p && !extern_p
17668           && (complain & tf_error))
17669         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
17670
17671       /* If we've already instantiated the template, just return now.  */
17672       if (!CLASSTYPE_INTERFACE_ONLY (t))
17673         return;
17674     }
17675
17676   check_explicit_instantiation_namespace (TYPE_NAME (t));
17677   mark_class_instantiated (t, extern_p);
17678
17679   if (nomem_p)
17680     return;
17681
17682   {
17683     tree tmp;
17684
17685     /* In contrast to implicit instantiation, where only the
17686        declarations, and not the definitions, of members are
17687        instantiated, we have here:
17688
17689          [temp.explicit]
17690
17691          The explicit instantiation of a class template specialization
17692          implies the instantiation of all of its members not
17693          previously explicitly specialized in the translation unit
17694          containing the explicit instantiation.
17695
17696        Of course, we can't instantiate member template classes, since
17697        we don't have any arguments for them.  Note that the standard
17698        is unclear on whether the instantiation of the members are
17699        *explicit* instantiations or not.  However, the most natural
17700        interpretation is that it should be an explicit instantiation.  */
17701
17702     if (! static_p)
17703       for (tmp = TYPE_METHODS (t); tmp; tmp = DECL_CHAIN (tmp))
17704         if (TREE_CODE (tmp) == FUNCTION_DECL
17705             && DECL_TEMPLATE_INSTANTIATION (tmp))
17706           instantiate_class_member (tmp, extern_p);
17707
17708     for (tmp = TYPE_FIELDS (t); tmp; tmp = DECL_CHAIN (tmp))
17709       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
17710         instantiate_class_member (tmp, extern_p);
17711
17712     if (CLASSTYPE_NESTED_UTDS (t))
17713       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
17714                              bt_instantiate_type_proc, &storage);
17715   }
17716 }
17717
17718 /* Given a function DECL, which is a specialization of TMPL, modify
17719    DECL to be a re-instantiation of TMPL with the same template
17720    arguments.  TMPL should be the template into which tsubst'ing
17721    should occur for DECL, not the most general template.
17722
17723    One reason for doing this is a scenario like this:
17724
17725      template <class T>
17726      void f(const T&, int i);
17727
17728      void g() { f(3, 7); }
17729
17730      template <class T>
17731      void f(const T& t, const int i) { }
17732
17733    Note that when the template is first instantiated, with
17734    instantiate_template, the resulting DECL will have no name for the
17735    first parameter, and the wrong type for the second.  So, when we go
17736    to instantiate the DECL, we regenerate it.  */
17737
17738 static void
17739 regenerate_decl_from_template (tree decl, tree tmpl)
17740 {
17741   /* The arguments used to instantiate DECL, from the most general
17742      template.  */
17743   tree args;
17744   tree code_pattern;
17745
17746   args = DECL_TI_ARGS (decl);
17747   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
17748
17749   /* Make sure that we can see identifiers, and compute access
17750      correctly.  */
17751   push_access_scope (decl);
17752
17753   if (TREE_CODE (decl) == FUNCTION_DECL)
17754     {
17755       tree decl_parm;
17756       tree pattern_parm;
17757       tree specs;
17758       int args_depth;
17759       int parms_depth;
17760
17761       args_depth = TMPL_ARGS_DEPTH (args);
17762       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
17763       if (args_depth > parms_depth)
17764         args = get_innermost_template_args (args, parms_depth);
17765
17766       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
17767                                               args, tf_error, NULL_TREE,
17768                                               /*defer_ok*/false);
17769       if (specs && specs != error_mark_node)
17770         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
17771                                                     specs);
17772
17773       /* Merge parameter declarations.  */
17774       decl_parm = skip_artificial_parms_for (decl,
17775                                              DECL_ARGUMENTS (decl));
17776       pattern_parm
17777         = skip_artificial_parms_for (code_pattern,
17778                                      DECL_ARGUMENTS (code_pattern));
17779       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
17780         {
17781           tree parm_type;
17782           tree attributes;
17783           
17784           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
17785             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
17786           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
17787                               NULL_TREE);
17788           parm_type = type_decays_to (parm_type);
17789           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
17790             TREE_TYPE (decl_parm) = parm_type;
17791           attributes = DECL_ATTRIBUTES (pattern_parm);
17792           if (DECL_ATTRIBUTES (decl_parm) != attributes)
17793             {
17794               DECL_ATTRIBUTES (decl_parm) = attributes;
17795               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
17796             }
17797           decl_parm = DECL_CHAIN (decl_parm);
17798           pattern_parm = DECL_CHAIN (pattern_parm);
17799         }
17800       /* Merge any parameters that match with the function parameter
17801          pack.  */
17802       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
17803         {
17804           int i, len;
17805           tree expanded_types;
17806           /* Expand the TYPE_PACK_EXPANSION that provides the types for
17807              the parameters in this function parameter pack.  */
17808           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
17809                                                  args, tf_error, NULL_TREE);
17810           len = TREE_VEC_LENGTH (expanded_types);
17811           for (i = 0; i < len; i++)
17812             {
17813               tree parm_type;
17814               tree attributes;
17815           
17816               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
17817                 /* Rename the parameter to include the index.  */
17818                 DECL_NAME (decl_parm) = 
17819                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
17820               parm_type = TREE_VEC_ELT (expanded_types, i);
17821               parm_type = type_decays_to (parm_type);
17822               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
17823                 TREE_TYPE (decl_parm) = parm_type;
17824               attributes = DECL_ATTRIBUTES (pattern_parm);
17825               if (DECL_ATTRIBUTES (decl_parm) != attributes)
17826                 {
17827                   DECL_ATTRIBUTES (decl_parm) = attributes;
17828                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
17829                 }
17830               decl_parm = DECL_CHAIN (decl_parm);
17831             }
17832         }
17833       /* Merge additional specifiers from the CODE_PATTERN.  */
17834       if (DECL_DECLARED_INLINE_P (code_pattern)
17835           && !DECL_DECLARED_INLINE_P (decl))
17836         DECL_DECLARED_INLINE_P (decl) = 1;
17837     }
17838   else if (TREE_CODE (decl) == VAR_DECL)
17839     {
17840       DECL_INITIAL (decl) =
17841         tsubst_expr (DECL_INITIAL (code_pattern), args,
17842                      tf_error, DECL_TI_TEMPLATE (decl),
17843                      /*integral_constant_expression_p=*/false);
17844       if (VAR_HAD_UNKNOWN_BOUND (decl))
17845         TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
17846                                    tf_error, DECL_TI_TEMPLATE (decl));
17847     }
17848   else
17849     gcc_unreachable ();
17850
17851   pop_access_scope (decl);
17852 }
17853
17854 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
17855    substituted to get DECL.  */
17856
17857 tree
17858 template_for_substitution (tree decl)
17859 {
17860   tree tmpl = DECL_TI_TEMPLATE (decl);
17861
17862   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
17863      for the instantiation.  This is not always the most general
17864      template.  Consider, for example:
17865
17866         template <class T>
17867         struct S { template <class U> void f();
17868                    template <> void f<int>(); };
17869
17870      and an instantiation of S<double>::f<int>.  We want TD to be the
17871      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
17872   while (/* An instantiation cannot have a definition, so we need a
17873             more general template.  */
17874          DECL_TEMPLATE_INSTANTIATION (tmpl)
17875            /* We must also deal with friend templates.  Given:
17876
17877                 template <class T> struct S {
17878                   template <class U> friend void f() {};
17879                 };
17880
17881               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
17882               so far as the language is concerned, but that's still
17883               where we get the pattern for the instantiation from.  On
17884               other hand, if the definition comes outside the class, say:
17885
17886                 template <class T> struct S {
17887                   template <class U> friend void f();
17888                 };
17889                 template <class U> friend void f() {}
17890
17891               we don't need to look any further.  That's what the check for
17892               DECL_INITIAL is for.  */
17893           || (TREE_CODE (decl) == FUNCTION_DECL
17894               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
17895               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
17896     {
17897       /* The present template, TD, should not be a definition.  If it
17898          were a definition, we should be using it!  Note that we
17899          cannot restructure the loop to just keep going until we find
17900          a template with a definition, since that might go too far if
17901          a specialization was declared, but not defined.  */
17902       gcc_assert (TREE_CODE (decl) != VAR_DECL
17903                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
17904
17905       /* Fetch the more general template.  */
17906       tmpl = DECL_TI_TEMPLATE (tmpl);
17907     }
17908
17909   return tmpl;
17910 }
17911
17912 /* Returns true if we need to instantiate this template instance even if we
17913    know we aren't going to emit it..  */
17914
17915 bool
17916 always_instantiate_p (tree decl)
17917 {
17918   /* We always instantiate inline functions so that we can inline them.  An
17919      explicit instantiation declaration prohibits implicit instantiation of
17920      non-inline functions.  With high levels of optimization, we would
17921      normally inline non-inline functions -- but we're not allowed to do
17922      that for "extern template" functions.  Therefore, we check
17923      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
17924   return ((TREE_CODE (decl) == FUNCTION_DECL
17925            && DECL_DECLARED_INLINE_P (decl))
17926           /* And we need to instantiate static data members so that
17927              their initializers are available in integral constant
17928              expressions.  */
17929           || (TREE_CODE (decl) == VAR_DECL
17930               && decl_maybe_constant_var_p (decl)));
17931 }
17932
17933 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
17934    instantiate it now, modifying TREE_TYPE (fn).  */
17935
17936 void
17937 maybe_instantiate_noexcept (tree fn)
17938 {
17939   tree fntype, spec, noex, clone;
17940
17941   if (DECL_CLONED_FUNCTION_P (fn))
17942     fn = DECL_CLONED_FUNCTION (fn);
17943   fntype = TREE_TYPE (fn);
17944   spec = TYPE_RAISES_EXCEPTIONS (fntype);
17945
17946   if (!DEFERRED_NOEXCEPT_SPEC_P (spec))
17947     return;
17948
17949   noex = TREE_PURPOSE (spec);
17950
17951   if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
17952     {
17953       push_tinst_level (fn);
17954       push_access_scope (fn);
17955       input_location = DECL_SOURCE_LOCATION (fn);
17956       noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
17957                                     DEFERRED_NOEXCEPT_ARGS (noex),
17958                                     tf_warning_or_error, fn, /*function_p=*/false,
17959                                     /*integral_constant_expression_p=*/true);
17960       pop_access_scope (fn);
17961       pop_tinst_level ();
17962       spec = build_noexcept_spec (noex, tf_warning_or_error);
17963       if (spec == error_mark_node)
17964         spec = noexcept_false_spec;
17965     }
17966   else
17967     {
17968       /* This is an implicitly declared function, so NOEX is a list of
17969          other functions to evaluate and merge.  */
17970       tree elt;
17971       spec = noexcept_true_spec;
17972       for (elt = noex; elt; elt = OVL_NEXT (elt))
17973         {
17974           tree fn = OVL_CURRENT (elt);
17975           tree subspec;
17976           maybe_instantiate_noexcept (fn);
17977           subspec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn));
17978           spec = merge_exception_specifiers (spec, subspec, NULL_TREE);
17979         }
17980     }
17981
17982   TREE_TYPE (fn) = build_exception_variant (fntype, spec);
17983
17984   FOR_EACH_CLONE (clone, fn)
17985     {
17986       if (TREE_TYPE (clone) == fntype)
17987         TREE_TYPE (clone) = TREE_TYPE (fn);
17988       else
17989         TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
17990     }
17991 }
17992
17993 /* Produce the definition of D, a _DECL generated from a template.  If
17994    DEFER_OK is nonzero, then we don't have to actually do the
17995    instantiation now; we just have to do it sometime.  Normally it is
17996    an error if this is an explicit instantiation but D is undefined.
17997    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
17998    explicitly instantiated class template.  */
17999
18000 tree
18001 instantiate_decl (tree d, int defer_ok,
18002                   bool expl_inst_class_mem_p)
18003 {
18004   tree tmpl = DECL_TI_TEMPLATE (d);
18005   tree gen_args;
18006   tree args;
18007   tree td;
18008   tree code_pattern;
18009   tree spec;
18010   tree gen_tmpl;
18011   bool pattern_defined;
18012   int need_push;
18013   location_t saved_loc = input_location;
18014   bool external_p;
18015
18016   /* This function should only be used to instantiate templates for
18017      functions and static member variables.  */
18018   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
18019               || TREE_CODE (d) == VAR_DECL);
18020
18021   /* Variables are never deferred; if instantiation is required, they
18022      are instantiated right away.  That allows for better code in the
18023      case that an expression refers to the value of the variable --
18024      if the variable has a constant value the referring expression can
18025      take advantage of that fact.  */
18026   if (TREE_CODE (d) == VAR_DECL
18027       || DECL_DECLARED_CONSTEXPR_P (d))
18028     defer_ok = 0;
18029
18030   /* Don't instantiate cloned functions.  Instead, instantiate the
18031      functions they cloned.  */
18032   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
18033     d = DECL_CLONED_FUNCTION (d);
18034
18035   if (DECL_TEMPLATE_INSTANTIATED (d)
18036       || DECL_TEMPLATE_SPECIALIZATION (d))
18037     /* D has already been instantiated or explicitly specialized, so
18038        there's nothing for us to do here.
18039
18040        It might seem reasonable to check whether or not D is an explicit
18041        instantiation, and, if so, stop here.  But when an explicit
18042        instantiation is deferred until the end of the compilation,
18043        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
18044        the instantiation.  */
18045     return d;
18046
18047   /* Check to see whether we know that this template will be
18048      instantiated in some other file, as with "extern template"
18049      extension.  */
18050   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
18051
18052   /* In general, we do not instantiate such templates.  */
18053   if (external_p && !always_instantiate_p (d))
18054     return d;
18055
18056   gen_tmpl = most_general_template (tmpl);
18057   gen_args = DECL_TI_ARGS (d);
18058
18059   if (tmpl != gen_tmpl)
18060     /* We should already have the extra args.  */
18061     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
18062                 == TMPL_ARGS_DEPTH (gen_args));
18063   /* And what's in the hash table should match D.  */
18064   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
18065               || spec == NULL_TREE);
18066
18067   /* This needs to happen before any tsubsting.  */
18068   if (! push_tinst_level (d))
18069     return d;
18070
18071   timevar_push (TV_TEMPLATE_INST);
18072
18073   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
18074      for the instantiation.  */
18075   td = template_for_substitution (d);
18076   code_pattern = DECL_TEMPLATE_RESULT (td);
18077
18078   /* We should never be trying to instantiate a member of a class
18079      template or partial specialization.  */
18080   gcc_assert (d != code_pattern);
18081
18082   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
18083       || DECL_TEMPLATE_SPECIALIZATION (td))
18084     /* In the case of a friend template whose definition is provided
18085        outside the class, we may have too many arguments.  Drop the
18086        ones we don't need.  The same is true for specializations.  */
18087     args = get_innermost_template_args
18088       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
18089   else
18090     args = gen_args;
18091
18092   if (TREE_CODE (d) == FUNCTION_DECL)
18093     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE
18094                        || DECL_DEFAULTED_OUTSIDE_CLASS_P (code_pattern));
18095   else
18096     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
18097
18098   /* We may be in the middle of deferred access check.  Disable it now.  */
18099   push_deferring_access_checks (dk_no_deferred);
18100
18101   /* Unless an explicit instantiation directive has already determined
18102      the linkage of D, remember that a definition is available for
18103      this entity.  */
18104   if (pattern_defined
18105       && !DECL_INTERFACE_KNOWN (d)
18106       && !DECL_NOT_REALLY_EXTERN (d))
18107     mark_definable (d);
18108
18109   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
18110   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
18111   input_location = DECL_SOURCE_LOCATION (d);
18112
18113   /* If D is a member of an explicitly instantiated class template,
18114      and no definition is available, treat it like an implicit
18115      instantiation.  */
18116   if (!pattern_defined && expl_inst_class_mem_p
18117       && DECL_EXPLICIT_INSTANTIATION (d))
18118     {
18119       /* Leave linkage flags alone on instantiations with anonymous
18120          visibility.  */
18121       if (TREE_PUBLIC (d))
18122         {
18123           DECL_NOT_REALLY_EXTERN (d) = 0;
18124           DECL_INTERFACE_KNOWN (d) = 0;
18125         }
18126       SET_DECL_IMPLICIT_INSTANTIATION (d);
18127     }
18128
18129   if (TREE_CODE (d) == FUNCTION_DECL)
18130     maybe_instantiate_noexcept (d);
18131
18132   /* Recheck the substitutions to obtain any warning messages
18133      about ignoring cv qualifiers.  Don't do this for artificial decls,
18134      as it breaks the context-sensitive substitution for lambda op(). */
18135   if (!defer_ok && !DECL_ARTIFICIAL (d))
18136     {
18137       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
18138       tree type = TREE_TYPE (gen);
18139
18140       /* Make sure that we can see identifiers, and compute access
18141          correctly.  D is already the target FUNCTION_DECL with the
18142          right context.  */
18143       push_access_scope (d);
18144
18145       if (TREE_CODE (gen) == FUNCTION_DECL)
18146         {
18147           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
18148           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
18149                                           d, /*defer_ok*/true);
18150           /* Don't simply tsubst the function type, as that will give
18151              duplicate warnings about poor parameter qualifications.
18152              The function arguments are the same as the decl_arguments
18153              without the top level cv qualifiers.  */
18154           type = TREE_TYPE (type);
18155         }
18156       tsubst (type, gen_args, tf_warning_or_error, d);
18157
18158       pop_access_scope (d);
18159     }
18160
18161   /* Defer all other templates, unless we have been explicitly
18162      forbidden from doing so.  */
18163   if (/* If there is no definition, we cannot instantiate the
18164          template.  */
18165       ! pattern_defined
18166       /* If it's OK to postpone instantiation, do so.  */
18167       || defer_ok
18168       /* If this is a static data member that will be defined
18169          elsewhere, we don't want to instantiate the entire data
18170          member, but we do want to instantiate the initializer so that
18171          we can substitute that elsewhere.  */
18172       || (external_p && TREE_CODE (d) == VAR_DECL))
18173     {
18174       /* The definition of the static data member is now required so
18175          we must substitute the initializer.  */
18176       if (TREE_CODE (d) == VAR_DECL
18177           && !DECL_INITIAL (d)
18178           && DECL_INITIAL (code_pattern))
18179         {
18180           tree ns;
18181           tree init;
18182           bool const_init = false;
18183
18184           ns = decl_namespace_context (d);
18185           push_nested_namespace (ns);
18186           push_nested_class (DECL_CONTEXT (d));
18187           init = tsubst_expr (DECL_INITIAL (code_pattern),
18188                               args,
18189                               tf_warning_or_error, NULL_TREE,
18190                               /*integral_constant_expression_p=*/false);
18191           /* Make sure the initializer is still constant, in case of
18192              circular dependency (template/instantiate6.C). */
18193           const_init
18194             = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
18195           cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
18196                           /*asmspec_tree=*/NULL_TREE,
18197                           LOOKUP_ONLYCONVERTING);
18198           pop_nested_class ();
18199           pop_nested_namespace (ns);
18200         }
18201
18202       /* We restore the source position here because it's used by
18203          add_pending_template.  */
18204       input_location = saved_loc;
18205
18206       if (at_eof && !pattern_defined
18207           && DECL_EXPLICIT_INSTANTIATION (d)
18208           && DECL_NOT_REALLY_EXTERN (d))
18209         /* [temp.explicit]
18210
18211            The definition of a non-exported function template, a
18212            non-exported member function template, or a non-exported
18213            member function or static data member of a class template
18214            shall be present in every translation unit in which it is
18215            explicitly instantiated.  */
18216         permerror (input_location,  "explicit instantiation of %qD "
18217                    "but no definition available", d);
18218
18219       /* If we're in unevaluated context, we just wanted to get the
18220          constant value; this isn't an odr use, so don't queue
18221          a full instantiation.  */
18222       if (cp_unevaluated_operand != 0)
18223         goto out;
18224       /* ??? Historically, we have instantiated inline functions, even
18225          when marked as "extern template".  */
18226       if (!(external_p && TREE_CODE (d) == VAR_DECL))
18227         add_pending_template (d);
18228       goto out;
18229     }
18230   /* Tell the repository that D is available in this translation unit
18231      -- and see if it is supposed to be instantiated here.  */
18232   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
18233     {
18234       /* In a PCH file, despite the fact that the repository hasn't
18235          requested instantiation in the PCH it is still possible that
18236          an instantiation will be required in a file that includes the
18237          PCH.  */
18238       if (pch_file)
18239         add_pending_template (d);
18240       /* Instantiate inline functions so that the inliner can do its
18241          job, even though we'll not be emitting a copy of this
18242          function.  */
18243       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
18244         goto out;
18245     }
18246
18247   need_push = !cfun || !global_bindings_p ();
18248   if (need_push)
18249     push_to_top_level ();
18250
18251   /* Mark D as instantiated so that recursive calls to
18252      instantiate_decl do not try to instantiate it again.  */
18253   DECL_TEMPLATE_INSTANTIATED (d) = 1;
18254
18255   /* Regenerate the declaration in case the template has been modified
18256      by a subsequent redeclaration.  */
18257   regenerate_decl_from_template (d, td);
18258
18259   /* We already set the file and line above.  Reset them now in case
18260      they changed as a result of calling regenerate_decl_from_template.  */
18261   input_location = DECL_SOURCE_LOCATION (d);
18262
18263   if (TREE_CODE (d) == VAR_DECL)
18264     {
18265       tree init;
18266       bool const_init = false;
18267
18268       /* Clear out DECL_RTL; whatever was there before may not be right
18269          since we've reset the type of the declaration.  */
18270       SET_DECL_RTL (d, NULL);
18271       DECL_IN_AGGR_P (d) = 0;
18272
18273       /* The initializer is placed in DECL_INITIAL by
18274          regenerate_decl_from_template so we don't need to
18275          push/pop_access_scope again here.  Pull it out so that
18276          cp_finish_decl can process it.  */
18277       init = DECL_INITIAL (d);
18278       DECL_INITIAL (d) = NULL_TREE;
18279       DECL_INITIALIZED_P (d) = 0;
18280
18281       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
18282          initializer.  That function will defer actual emission until
18283          we have a chance to determine linkage.  */
18284       DECL_EXTERNAL (d) = 0;
18285
18286       /* Enter the scope of D so that access-checking works correctly.  */
18287       push_nested_class (DECL_CONTEXT (d));
18288       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
18289       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
18290       pop_nested_class ();
18291     }
18292   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
18293     synthesize_method (d);
18294   else if (TREE_CODE (d) == FUNCTION_DECL)
18295     {
18296       htab_t saved_local_specializations;
18297       tree subst_decl;
18298       tree tmpl_parm;
18299       tree spec_parm;
18300
18301       /* Save away the current list, in case we are instantiating one
18302          template from within the body of another.  */
18303       saved_local_specializations = local_specializations;
18304
18305       /* Set up the list of local specializations.  */
18306       local_specializations = htab_create (37,
18307                                            hash_local_specialization,
18308                                            eq_local_specializations,
18309                                            NULL);
18310
18311       /* Set up context.  */
18312       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
18313
18314       /* Create substitution entries for the parameters.  */
18315       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
18316       tmpl_parm = DECL_ARGUMENTS (subst_decl);
18317       spec_parm = DECL_ARGUMENTS (d);
18318       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
18319         {
18320           register_local_specialization (spec_parm, tmpl_parm);
18321           spec_parm = skip_artificial_parms_for (d, spec_parm);
18322           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
18323         }
18324       for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
18325         {
18326           if (!FUNCTION_PARAMETER_PACK_P (tmpl_parm))
18327             {
18328               register_local_specialization (spec_parm, tmpl_parm);
18329               spec_parm = DECL_CHAIN (spec_parm);
18330             }
18331           else
18332             {
18333               /* Register the (value) argument pack as a specialization of
18334                  TMPL_PARM, then move on.  */
18335               tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
18336               register_local_specialization (argpack, tmpl_parm);
18337             }
18338         }
18339       gcc_assert (!spec_parm);
18340
18341       /* Substitute into the body of the function.  */
18342       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
18343                    tf_warning_or_error, tmpl,
18344                    /*integral_constant_expression_p=*/false);
18345
18346       /* Set the current input_location to the end of the function
18347          so that finish_function knows where we are.  */
18348       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
18349
18350       /* We don't need the local specializations any more.  */
18351       htab_delete (local_specializations);
18352       local_specializations = saved_local_specializations;
18353
18354       /* Finish the function.  */
18355       d = finish_function (0);
18356       expand_or_defer_fn (d);
18357     }
18358
18359   /* We're not deferring instantiation any more.  */
18360   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
18361
18362   if (need_push)
18363     pop_from_top_level ();
18364
18365 out:
18366   input_location = saved_loc;
18367   pop_deferring_access_checks ();
18368   pop_tinst_level ();
18369
18370   timevar_pop (TV_TEMPLATE_INST);
18371
18372   return d;
18373 }
18374
18375 /* Run through the list of templates that we wish we could
18376    instantiate, and instantiate any we can.  RETRIES is the
18377    number of times we retry pending template instantiation.  */
18378
18379 void
18380 instantiate_pending_templates (int retries)
18381 {
18382   int reconsider;
18383   location_t saved_loc = input_location;
18384
18385   /* Instantiating templates may trigger vtable generation.  This in turn
18386      may require further template instantiations.  We place a limit here
18387      to avoid infinite loop.  */
18388   if (pending_templates && retries >= max_tinst_depth)
18389     {
18390       tree decl = pending_templates->tinst->decl;
18391
18392       error ("template instantiation depth exceeds maximum of %d"
18393              " instantiating %q+D, possibly from virtual table generation"
18394              " (use -ftemplate-depth= to increase the maximum)",
18395              max_tinst_depth, decl);
18396       if (TREE_CODE (decl) == FUNCTION_DECL)
18397         /* Pretend that we defined it.  */
18398         DECL_INITIAL (decl) = error_mark_node;
18399       return;
18400     }
18401
18402   do
18403     {
18404       struct pending_template **t = &pending_templates;
18405       struct pending_template *last = NULL;
18406       reconsider = 0;
18407       while (*t)
18408         {
18409           tree instantiation = reopen_tinst_level ((*t)->tinst);
18410           bool complete = false;
18411
18412           if (TYPE_P (instantiation))
18413             {
18414               tree fn;
18415
18416               if (!COMPLETE_TYPE_P (instantiation))
18417                 {
18418                   instantiate_class_template (instantiation);
18419                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
18420                     for (fn = TYPE_METHODS (instantiation);
18421                          fn;
18422                          fn = TREE_CHAIN (fn))
18423                       if (! DECL_ARTIFICIAL (fn))
18424                         instantiate_decl (fn,
18425                                           /*defer_ok=*/0,
18426                                           /*expl_inst_class_mem_p=*/false);
18427                   if (COMPLETE_TYPE_P (instantiation))
18428                     reconsider = 1;
18429                 }
18430
18431               complete = COMPLETE_TYPE_P (instantiation);
18432             }
18433           else
18434             {
18435               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
18436                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
18437                 {
18438                   instantiation
18439                     = instantiate_decl (instantiation,
18440                                         /*defer_ok=*/0,
18441                                         /*expl_inst_class_mem_p=*/false);
18442                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
18443                     reconsider = 1;
18444                 }
18445
18446               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
18447                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
18448             }
18449
18450           if (complete)
18451             /* If INSTANTIATION has been instantiated, then we don't
18452                need to consider it again in the future.  */
18453             *t = (*t)->next;
18454           else
18455             {
18456               last = *t;
18457               t = &(*t)->next;
18458             }
18459           tinst_depth = 0;
18460           current_tinst_level = NULL;
18461         }
18462       last_pending_template = last;
18463     }
18464   while (reconsider);
18465
18466   input_location = saved_loc;
18467 }
18468
18469 /* Substitute ARGVEC into T, which is a list of initializers for
18470    either base class or a non-static data member.  The TREE_PURPOSEs
18471    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
18472    instantiate_decl.  */
18473
18474 static tree
18475 tsubst_initializer_list (tree t, tree argvec)
18476 {
18477   tree inits = NULL_TREE;
18478
18479   for (; t; t = TREE_CHAIN (t))
18480     {
18481       tree decl;
18482       tree init;
18483       tree expanded_bases = NULL_TREE;
18484       tree expanded_arguments = NULL_TREE;
18485       int i, len = 1;
18486
18487       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
18488         {
18489           tree expr;
18490           tree arg;
18491
18492           /* Expand the base class expansion type into separate base
18493              classes.  */
18494           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
18495                                                  tf_warning_or_error,
18496                                                  NULL_TREE);
18497           if (expanded_bases == error_mark_node)
18498             continue;
18499           
18500           /* We'll be building separate TREE_LISTs of arguments for
18501              each base.  */
18502           len = TREE_VEC_LENGTH (expanded_bases);
18503           expanded_arguments = make_tree_vec (len);
18504           for (i = 0; i < len; i++)
18505             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
18506
18507           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
18508              expand each argument in the TREE_VALUE of t.  */
18509           expr = make_node (EXPR_PACK_EXPANSION);
18510           PACK_EXPANSION_PARAMETER_PACKS (expr) =
18511             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
18512
18513           if (TREE_VALUE (t) == void_type_node)
18514             /* VOID_TYPE_NODE is used to indicate
18515                value-initialization.  */
18516             {
18517               for (i = 0; i < len; i++)
18518                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
18519             }
18520           else
18521             {
18522               /* Substitute parameter packs into each argument in the
18523                  TREE_LIST.  */
18524               in_base_initializer = 1;
18525               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
18526                 {
18527                   tree expanded_exprs;
18528
18529                   /* Expand the argument.  */
18530                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
18531                   expanded_exprs 
18532                     = tsubst_pack_expansion (expr, argvec,
18533                                              tf_warning_or_error,
18534                                              NULL_TREE);
18535                   if (expanded_exprs == error_mark_node)
18536                     continue;
18537
18538                   /* Prepend each of the expanded expressions to the
18539                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
18540                   for (i = 0; i < len; i++)
18541                     {
18542                       TREE_VEC_ELT (expanded_arguments, i) = 
18543                         tree_cons (NULL_TREE, 
18544                                    TREE_VEC_ELT (expanded_exprs, i),
18545                                    TREE_VEC_ELT (expanded_arguments, i));
18546                     }
18547                 }
18548               in_base_initializer = 0;
18549
18550               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
18551                  since we built them backwards.  */
18552               for (i = 0; i < len; i++)
18553                 {
18554                   TREE_VEC_ELT (expanded_arguments, i) = 
18555                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
18556                 }
18557             }
18558         }
18559
18560       for (i = 0; i < len; ++i)
18561         {
18562           if (expanded_bases)
18563             {
18564               decl = TREE_VEC_ELT (expanded_bases, i);
18565               decl = expand_member_init (decl);
18566               init = TREE_VEC_ELT (expanded_arguments, i);
18567             }
18568           else
18569             {
18570               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
18571                                   tf_warning_or_error, NULL_TREE);
18572
18573               decl = expand_member_init (decl);
18574               if (decl && !DECL_P (decl))
18575                 in_base_initializer = 1;
18576
18577               init = TREE_VALUE (t);
18578               if (init != void_type_node)
18579                 init = tsubst_expr (init, argvec,
18580                                     tf_warning_or_error, NULL_TREE,
18581                                     /*integral_constant_expression_p=*/false);
18582               in_base_initializer = 0;
18583             }
18584
18585           if (decl)
18586             {
18587               init = build_tree_list (decl, init);
18588               TREE_CHAIN (init) = inits;
18589               inits = init;
18590             }
18591         }
18592     }
18593   return inits;
18594 }
18595
18596 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
18597
18598 static void
18599 set_current_access_from_decl (tree decl)
18600 {
18601   if (TREE_PRIVATE (decl))
18602     current_access_specifier = access_private_node;
18603   else if (TREE_PROTECTED (decl))
18604     current_access_specifier = access_protected_node;
18605   else
18606     current_access_specifier = access_public_node;
18607 }
18608
18609 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
18610    is the instantiation (which should have been created with
18611    start_enum) and ARGS are the template arguments to use.  */
18612
18613 static void
18614 tsubst_enum (tree tag, tree newtag, tree args)
18615 {
18616   tree e;
18617
18618   if (SCOPED_ENUM_P (newtag))
18619     begin_scope (sk_scoped_enum, newtag);
18620
18621   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
18622     {
18623       tree value;
18624       tree decl;
18625
18626       decl = TREE_VALUE (e);
18627       /* Note that in a template enum, the TREE_VALUE is the
18628          CONST_DECL, not the corresponding INTEGER_CST.  */
18629       value = tsubst_expr (DECL_INITIAL (decl),
18630                            args, tf_warning_or_error, NULL_TREE,
18631                            /*integral_constant_expression_p=*/true);
18632
18633       /* Give this enumeration constant the correct access.  */
18634       set_current_access_from_decl (decl);
18635
18636       /* Actually build the enumerator itself.  */
18637       build_enumerator
18638         (DECL_NAME (decl), value, newtag, DECL_SOURCE_LOCATION (decl));
18639     }
18640
18641   if (SCOPED_ENUM_P (newtag))
18642     finish_scope ();
18643
18644   finish_enum_value_list (newtag);
18645   finish_enum (newtag);
18646
18647   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
18648     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
18649 }
18650
18651 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
18652    its type -- but without substituting the innermost set of template
18653    arguments.  So, innermost set of template parameters will appear in
18654    the type.  */
18655
18656 tree
18657 get_mostly_instantiated_function_type (tree decl)
18658 {
18659   tree fn_type;
18660   tree tmpl;
18661   tree targs;
18662   tree tparms;
18663   int parm_depth;
18664
18665   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
18666   targs = DECL_TI_ARGS (decl);
18667   tparms = DECL_TEMPLATE_PARMS (tmpl);
18668   parm_depth = TMPL_PARMS_DEPTH (tparms);
18669
18670   /* There should be as many levels of arguments as there are levels
18671      of parameters.  */
18672   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
18673
18674   fn_type = TREE_TYPE (tmpl);
18675
18676   if (parm_depth == 1)
18677     /* No substitution is necessary.  */
18678     ;
18679   else
18680     {
18681       int i;
18682       tree partial_args;
18683
18684       /* Replace the innermost level of the TARGS with NULL_TREEs to
18685          let tsubst know not to substitute for those parameters.  */
18686       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
18687       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
18688         SET_TMPL_ARGS_LEVEL (partial_args, i,
18689                              TMPL_ARGS_LEVEL (targs, i));
18690       SET_TMPL_ARGS_LEVEL (partial_args,
18691                            TMPL_ARGS_DEPTH (targs),
18692                            make_tree_vec (DECL_NTPARMS (tmpl)));
18693
18694       /* Make sure that we can see identifiers, and compute access
18695          correctly.  */
18696       push_access_scope (decl);
18697
18698       ++processing_template_decl;
18699       /* Now, do the (partial) substitution to figure out the
18700          appropriate function type.  */
18701       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
18702       --processing_template_decl;
18703
18704       /* Substitute into the template parameters to obtain the real
18705          innermost set of parameters.  This step is important if the
18706          innermost set of template parameters contains value
18707          parameters whose types depend on outer template parameters.  */
18708       TREE_VEC_LENGTH (partial_args)--;
18709       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
18710
18711       pop_access_scope (decl);
18712     }
18713
18714   return fn_type;
18715 }
18716
18717 /* Return truthvalue if we're processing a template different from
18718    the last one involved in diagnostics.  */
18719 int
18720 problematic_instantiation_changed (void)
18721 {
18722   return current_tinst_level != last_error_tinst_level;
18723 }
18724
18725 /* Remember current template involved in diagnostics.  */
18726 void
18727 record_last_problematic_instantiation (void)
18728 {
18729   last_error_tinst_level = current_tinst_level;
18730 }
18731
18732 struct tinst_level *
18733 current_instantiation (void)
18734 {
18735   return current_tinst_level;
18736 }
18737
18738 /* [temp.param] Check that template non-type parm TYPE is of an allowable
18739    type. Return zero for ok, nonzero for disallowed. Issue error and
18740    warning messages under control of COMPLAIN.  */
18741
18742 static int
18743 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
18744 {
18745   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
18746     return 0;
18747   else if (POINTER_TYPE_P (type))
18748     return 0;
18749   else if (TYPE_PTR_TO_MEMBER_P (type))
18750     return 0;
18751   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
18752     return 0;
18753   else if (TREE_CODE (type) == TYPENAME_TYPE)
18754     return 0;
18755   else if (TREE_CODE (type) == DECLTYPE_TYPE)
18756     return 0;
18757   else if (TREE_CODE (type) == NULLPTR_TYPE)
18758     return 0;
18759
18760   if (complain & tf_error)
18761     error ("%q#T is not a valid type for a template constant parameter", type);
18762   return 1;
18763 }
18764
18765 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
18766    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
18767
18768 static bool
18769 dependent_type_p_r (tree type)
18770 {
18771   tree scope;
18772
18773   /* [temp.dep.type]
18774
18775      A type is dependent if it is:
18776
18777      -- a template parameter. Template template parameters are types
18778         for us (since TYPE_P holds true for them) so we handle
18779         them here.  */
18780   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18781       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
18782     return true;
18783   /* -- a qualified-id with a nested-name-specifier which contains a
18784         class-name that names a dependent type or whose unqualified-id
18785         names a dependent type.  */
18786   if (TREE_CODE (type) == TYPENAME_TYPE)
18787     return true;
18788   /* -- a cv-qualified type where the cv-unqualified type is
18789         dependent.  */
18790   type = TYPE_MAIN_VARIANT (type);
18791   /* -- a compound type constructed from any dependent type.  */
18792   if (TYPE_PTR_TO_MEMBER_P (type))
18793     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
18794             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
18795                                            (type)));
18796   else if (TREE_CODE (type) == POINTER_TYPE
18797            || TREE_CODE (type) == REFERENCE_TYPE)
18798     return dependent_type_p (TREE_TYPE (type));
18799   else if (TREE_CODE (type) == FUNCTION_TYPE
18800            || TREE_CODE (type) == METHOD_TYPE)
18801     {
18802       tree arg_type;
18803
18804       if (dependent_type_p (TREE_TYPE (type)))
18805         return true;
18806       for (arg_type = TYPE_ARG_TYPES (type);
18807            arg_type;
18808            arg_type = TREE_CHAIN (arg_type))
18809         if (dependent_type_p (TREE_VALUE (arg_type)))
18810           return true;
18811       return false;
18812     }
18813   /* -- an array type constructed from any dependent type or whose
18814         size is specified by a constant expression that is
18815         value-dependent.
18816
18817         We checked for type- and value-dependence of the bounds in
18818         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
18819   if (TREE_CODE (type) == ARRAY_TYPE)
18820     {
18821       if (TYPE_DOMAIN (type)
18822           && dependent_type_p (TYPE_DOMAIN (type)))
18823         return true;
18824       return dependent_type_p (TREE_TYPE (type));
18825     }
18826
18827   /* -- a template-id in which either the template name is a template
18828      parameter ...  */
18829   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
18830     return true;
18831   /* ... or any of the template arguments is a dependent type or
18832         an expression that is type-dependent or value-dependent.  */
18833   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
18834            && (any_dependent_template_arguments_p
18835                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
18836     return true;
18837
18838   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
18839      dependent; if the argument of the `typeof' expression is not
18840      type-dependent, then it should already been have resolved.  */
18841   if (TREE_CODE (type) == TYPEOF_TYPE
18842       || TREE_CODE (type) == DECLTYPE_TYPE
18843       || TREE_CODE (type) == UNDERLYING_TYPE)
18844     return true;
18845
18846   /* A template argument pack is dependent if any of its packed
18847      arguments are.  */
18848   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
18849     {
18850       tree args = ARGUMENT_PACK_ARGS (type);
18851       int i, len = TREE_VEC_LENGTH (args);
18852       for (i = 0; i < len; ++i)
18853         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
18854           return true;
18855     }
18856
18857   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
18858      be template parameters.  */
18859   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
18860     return true;
18861
18862   /* The standard does not specifically mention types that are local
18863      to template functions or local classes, but they should be
18864      considered dependent too.  For example:
18865
18866        template <int I> void f() {
18867          enum E { a = I };
18868          S<sizeof (E)> s;
18869        }
18870
18871      The size of `E' cannot be known until the value of `I' has been
18872      determined.  Therefore, `E' must be considered dependent.  */
18873   scope = TYPE_CONTEXT (type);
18874   if (scope && TYPE_P (scope))
18875     return dependent_type_p (scope);
18876   /* Don't use type_dependent_expression_p here, as it can lead
18877      to infinite recursion trying to determine whether a lambda
18878      nested in a lambda is dependent (c++/47687).  */
18879   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
18880            && DECL_LANG_SPECIFIC (scope)
18881            && DECL_TEMPLATE_INFO (scope)
18882            && (any_dependent_template_arguments_p
18883                (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
18884     return true;
18885
18886   /* Other types are non-dependent.  */
18887   return false;
18888 }
18889
18890 /* Returns TRUE if TYPE is dependent, in the sense of
18891    [temp.dep.type].  Note that a NULL type is considered dependent.  */
18892
18893 bool
18894 dependent_type_p (tree type)
18895 {
18896   /* If there are no template parameters in scope, then there can't be
18897      any dependent types.  */
18898   if (!processing_template_decl)
18899     {
18900       /* If we are not processing a template, then nobody should be
18901          providing us with a dependent type.  */
18902       gcc_assert (type);
18903       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
18904       return false;
18905     }
18906
18907   /* If the type is NULL, we have not computed a type for the entity
18908      in question; in that case, the type is dependent.  */
18909   if (!type)
18910     return true;
18911
18912   /* Erroneous types can be considered non-dependent.  */
18913   if (type == error_mark_node)
18914     return false;
18915
18916   /* If we have not already computed the appropriate value for TYPE,
18917      do so now.  */
18918   if (!TYPE_DEPENDENT_P_VALID (type))
18919     {
18920       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
18921       TYPE_DEPENDENT_P_VALID (type) = 1;
18922     }
18923
18924   return TYPE_DEPENDENT_P (type);
18925 }
18926
18927 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
18928    lookup.  In other words, a dependent type that is not the current
18929    instantiation.  */
18930
18931 bool
18932 dependent_scope_p (tree scope)
18933 {
18934   return (scope && TYPE_P (scope) && dependent_type_p (scope)
18935           && !currently_open_class (scope));
18936 }
18937
18938 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
18939    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
18940    expression.  */
18941
18942 /* Note that this predicate is not appropriate for general expressions;
18943    only constant expressions (that satisfy potential_constant_expression)
18944    can be tested for value dependence.
18945
18946    We should really also have a predicate for "instantiation-dependent".
18947
18948    fold_non_dependent_expr: fold if constant and not type-dependent and not value-dependent.
18949      (what about instantiation-dependent constant-expressions?)
18950    is_late_template_attribute: defer if instantiation-dependent.
18951    compute_array_index_type: proceed if constant and not t- or v-dependent
18952      if instantiation-dependent, need to remember full expression
18953    uses_template_parms: FIXME - need to audit callers
18954    tsubst_decl [function_decl]: Why is this using value_dependent_expression_p?
18955    dependent_type_p [array_type]: dependent if index type is dependent
18956      (or non-constant?)
18957    static_assert - instantiation-dependent */
18958
18959 bool
18960 value_dependent_expression_p (tree expression)
18961 {
18962   if (!processing_template_decl)
18963     return false;
18964
18965   /* A name declared with a dependent type.  */
18966   if (DECL_P (expression) && type_dependent_expression_p (expression))
18967     return true;
18968
18969   switch (TREE_CODE (expression))
18970     {
18971     case IDENTIFIER_NODE:
18972       /* A name that has not been looked up -- must be dependent.  */
18973       return true;
18974
18975     case TEMPLATE_PARM_INDEX:
18976       /* A non-type template parm.  */
18977       return true;
18978
18979     case CONST_DECL:
18980       /* A non-type template parm.  */
18981       if (DECL_TEMPLATE_PARM_P (expression))
18982         return true;
18983       return value_dependent_expression_p (DECL_INITIAL (expression));
18984
18985     case VAR_DECL:
18986        /* A constant with literal type and is initialized
18987           with an expression that is value-dependent.  */
18988       if (DECL_INITIAL (expression)
18989           && decl_constant_var_p (expression)
18990           && value_dependent_expression_p (DECL_INITIAL (expression)))
18991         return true;
18992       return false;
18993
18994     case DYNAMIC_CAST_EXPR:
18995     case STATIC_CAST_EXPR:
18996     case CONST_CAST_EXPR:
18997     case REINTERPRET_CAST_EXPR:
18998     case CAST_EXPR:
18999       /* These expressions are value-dependent if the type to which
19000          the cast occurs is dependent or the expression being casted
19001          is value-dependent.  */
19002       {
19003         tree type = TREE_TYPE (expression);
19004
19005         if (dependent_type_p (type))
19006           return true;
19007
19008         /* A functional cast has a list of operands.  */
19009         expression = TREE_OPERAND (expression, 0);
19010         if (!expression)
19011           {
19012             /* If there are no operands, it must be an expression such
19013                as "int()". This should not happen for aggregate types
19014                because it would form non-constant expressions.  */
19015             gcc_assert (cxx_dialect >= cxx0x
19016                         || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
19017
19018             return false;
19019           }
19020
19021         if (TREE_CODE (expression) == TREE_LIST)
19022           return any_value_dependent_elements_p (expression);
19023
19024         return value_dependent_expression_p (expression);
19025       }
19026
19027     case SIZEOF_EXPR:
19028     case ALIGNOF_EXPR:
19029     case TYPEID_EXPR:
19030       /* A `sizeof' expression is value-dependent if the operand is
19031          type-dependent or is a pack expansion.  */
19032       expression = TREE_OPERAND (expression, 0);
19033       if (PACK_EXPANSION_P (expression))
19034         return true;
19035       else if (TYPE_P (expression))
19036         return dependent_type_p (expression);
19037       return type_dependent_expression_p (expression);
19038
19039     case AT_ENCODE_EXPR:
19040       /* An 'encode' expression is value-dependent if the operand is
19041          type-dependent.  */
19042       expression = TREE_OPERAND (expression, 0);
19043       return dependent_type_p (expression);
19044
19045     case NOEXCEPT_EXPR:
19046       expression = TREE_OPERAND (expression, 0);
19047       return type_dependent_expression_p (expression);
19048
19049     case SCOPE_REF:
19050       {
19051         tree name = TREE_OPERAND (expression, 1);
19052         return value_dependent_expression_p (name);
19053       }
19054
19055     case COMPONENT_REF:
19056       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
19057               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
19058
19059     case NONTYPE_ARGUMENT_PACK:
19060       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
19061          is value-dependent.  */
19062       {
19063         tree values = ARGUMENT_PACK_ARGS (expression);
19064         int i, len = TREE_VEC_LENGTH (values);
19065         
19066         for (i = 0; i < len; ++i)
19067           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
19068             return true;
19069         
19070         return false;
19071       }
19072
19073     case TRAIT_EXPR:
19074       {
19075         tree type2 = TRAIT_EXPR_TYPE2 (expression);
19076         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
19077                 || (type2 ? dependent_type_p (type2) : false));
19078       }
19079
19080     case MODOP_EXPR:
19081       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
19082               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
19083
19084     case ARRAY_REF:
19085       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
19086               || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
19087
19088     case ADDR_EXPR:
19089       {
19090         tree op = TREE_OPERAND (expression, 0);
19091         return (value_dependent_expression_p (op)
19092                 || has_value_dependent_address (op));
19093       }
19094
19095     case CALL_EXPR:
19096       {
19097         tree fn = get_callee_fndecl (expression);
19098         int i, nargs;
19099         if (!fn && value_dependent_expression_p (CALL_EXPR_FN (expression)))
19100           return true;
19101         nargs = call_expr_nargs (expression);
19102         for (i = 0; i < nargs; ++i)
19103           {
19104             tree op = CALL_EXPR_ARG (expression, i);
19105             /* In a call to a constexpr member function, look through the
19106                implicit ADDR_EXPR on the object argument so that it doesn't
19107                cause the call to be considered value-dependent.  We also
19108                look through it in potential_constant_expression.  */
19109             if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
19110                 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
19111                 && TREE_CODE (op) == ADDR_EXPR)
19112               op = TREE_OPERAND (op, 0);
19113             if (value_dependent_expression_p (op))
19114               return true;
19115           }
19116         return false;
19117       }
19118
19119     case TEMPLATE_ID_EXPR:
19120       /* If a TEMPLATE_ID_EXPR involves a dependent name, it will be
19121          type-dependent.  */
19122       return type_dependent_expression_p (expression);
19123
19124     case CONSTRUCTOR:
19125       {
19126         unsigned ix;
19127         tree val;
19128         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
19129           if (value_dependent_expression_p (val))
19130             return true;
19131         return false;
19132       }
19133
19134     default:
19135       /* A constant expression is value-dependent if any subexpression is
19136          value-dependent.  */
19137       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
19138         {
19139         case tcc_reference:
19140         case tcc_unary:
19141         case tcc_comparison:
19142         case tcc_binary:
19143         case tcc_expression:
19144         case tcc_vl_exp:
19145           {
19146             int i, len = cp_tree_operand_length (expression);
19147
19148             for (i = 0; i < len; i++)
19149               {
19150                 tree t = TREE_OPERAND (expression, i);
19151
19152                 /* In some cases, some of the operands may be missing.l
19153                    (For example, in the case of PREDECREMENT_EXPR, the
19154                    amount to increment by may be missing.)  That doesn't
19155                    make the expression dependent.  */
19156                 if (t && value_dependent_expression_p (t))
19157                   return true;
19158               }
19159           }
19160           break;
19161         default:
19162           break;
19163         }
19164       break;
19165     }
19166
19167   /* The expression is not value-dependent.  */
19168   return false;
19169 }
19170
19171 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
19172    [temp.dep.expr].  Note that an expression with no type is
19173    considered dependent.  Other parts of the compiler arrange for an
19174    expression with type-dependent subexpressions to have no type, so
19175    this function doesn't have to be fully recursive.  */
19176
19177 bool
19178 type_dependent_expression_p (tree expression)
19179 {
19180   if (!processing_template_decl)
19181     return false;
19182
19183   if (expression == error_mark_node)
19184     return false;
19185
19186   /* An unresolved name is always dependent.  */
19187   if (TREE_CODE (expression) == IDENTIFIER_NODE
19188       || TREE_CODE (expression) == USING_DECL)
19189     return true;
19190
19191   /* Some expression forms are never type-dependent.  */
19192   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
19193       || TREE_CODE (expression) == SIZEOF_EXPR
19194       || TREE_CODE (expression) == ALIGNOF_EXPR
19195       || TREE_CODE (expression) == AT_ENCODE_EXPR
19196       || TREE_CODE (expression) == NOEXCEPT_EXPR
19197       || TREE_CODE (expression) == TRAIT_EXPR
19198       || TREE_CODE (expression) == TYPEID_EXPR
19199       || TREE_CODE (expression) == DELETE_EXPR
19200       || TREE_CODE (expression) == VEC_DELETE_EXPR
19201       || TREE_CODE (expression) == THROW_EXPR)
19202     return false;
19203
19204   /* The types of these expressions depends only on the type to which
19205      the cast occurs.  */
19206   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
19207       || TREE_CODE (expression) == STATIC_CAST_EXPR
19208       || TREE_CODE (expression) == CONST_CAST_EXPR
19209       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
19210       || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
19211       || TREE_CODE (expression) == CAST_EXPR)
19212     return dependent_type_p (TREE_TYPE (expression));
19213
19214   /* The types of these expressions depends only on the type created
19215      by the expression.  */
19216   if (TREE_CODE (expression) == NEW_EXPR
19217       || TREE_CODE (expression) == VEC_NEW_EXPR)
19218     {
19219       /* For NEW_EXPR tree nodes created inside a template, either
19220          the object type itself or a TREE_LIST may appear as the
19221          operand 1.  */
19222       tree type = TREE_OPERAND (expression, 1);
19223       if (TREE_CODE (type) == TREE_LIST)
19224         /* This is an array type.  We need to check array dimensions
19225            as well.  */
19226         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
19227                || value_dependent_expression_p
19228                     (TREE_OPERAND (TREE_VALUE (type), 1));
19229       else
19230         return dependent_type_p (type);
19231     }
19232
19233   if (TREE_CODE (expression) == SCOPE_REF)
19234     {
19235       tree scope = TREE_OPERAND (expression, 0);
19236       tree name = TREE_OPERAND (expression, 1);
19237
19238       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
19239          contains an identifier associated by name lookup with one or more
19240          declarations declared with a dependent type, or...a
19241          nested-name-specifier or qualified-id that names a member of an
19242          unknown specialization.  */
19243       return (type_dependent_expression_p (name)
19244               || dependent_scope_p (scope));
19245     }
19246
19247   if (TREE_CODE (expression) == FUNCTION_DECL
19248       && DECL_LANG_SPECIFIC (expression)
19249       && DECL_TEMPLATE_INFO (expression)
19250       && (any_dependent_template_arguments_p
19251           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
19252     return true;
19253
19254   if (TREE_CODE (expression) == TEMPLATE_DECL
19255       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
19256     return false;
19257
19258   if (TREE_CODE (expression) == STMT_EXPR)
19259     expression = stmt_expr_value_expr (expression);
19260
19261   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
19262     {
19263       tree elt;
19264       unsigned i;
19265
19266       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
19267         {
19268           if (type_dependent_expression_p (elt))
19269             return true;
19270         }
19271       return false;
19272     }
19273
19274   /* A static data member of the current instantiation with incomplete
19275      array type is type-dependent, as the definition and specializations
19276      can have different bounds.  */
19277   if (TREE_CODE (expression) == VAR_DECL
19278       && DECL_CLASS_SCOPE_P (expression)
19279       && dependent_type_p (DECL_CONTEXT (expression))
19280       && VAR_HAD_UNKNOWN_BOUND (expression))
19281     return true;
19282
19283   if (TREE_TYPE (expression) == unknown_type_node)
19284     {
19285       if (TREE_CODE (expression) == ADDR_EXPR)
19286         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
19287       if (TREE_CODE (expression) == COMPONENT_REF
19288           || TREE_CODE (expression) == OFFSET_REF)
19289         {
19290           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
19291             return true;
19292           expression = TREE_OPERAND (expression, 1);
19293           if (TREE_CODE (expression) == IDENTIFIER_NODE)
19294             return false;
19295         }
19296       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
19297       if (TREE_CODE (expression) == SCOPE_REF)
19298         return false;
19299
19300       if (TREE_CODE (expression) == BASELINK)
19301         expression = BASELINK_FUNCTIONS (expression);
19302
19303       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
19304         {
19305           if (any_dependent_template_arguments_p
19306               (TREE_OPERAND (expression, 1)))
19307             return true;
19308           expression = TREE_OPERAND (expression, 0);
19309         }
19310       gcc_assert (TREE_CODE (expression) == OVERLOAD
19311                   || TREE_CODE (expression) == FUNCTION_DECL);
19312
19313       while (expression)
19314         {
19315           if (type_dependent_expression_p (OVL_CURRENT (expression)))
19316             return true;
19317           expression = OVL_NEXT (expression);
19318         }
19319       return false;
19320     }
19321
19322   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
19323
19324   return (dependent_type_p (TREE_TYPE (expression)));
19325 }
19326
19327 /* Like type_dependent_expression_p, but it also works while not processing
19328    a template definition, i.e. during substitution or mangling.  */
19329
19330 bool
19331 type_dependent_expression_p_push (tree expr)
19332 {
19333   bool b;
19334   ++processing_template_decl;
19335   b = type_dependent_expression_p (expr);
19336   --processing_template_decl;
19337   return b;
19338 }
19339
19340 /* Returns TRUE if ARGS contains a type-dependent expression.  */
19341
19342 bool
19343 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
19344 {
19345   unsigned int i;
19346   tree arg;
19347
19348   FOR_EACH_VEC_ELT (tree, args, i, arg)
19349     {
19350       if (type_dependent_expression_p (arg))
19351         return true;
19352     }
19353   return false;
19354 }
19355
19356 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
19357    expressions) contains any type-dependent expressions.  */
19358
19359 bool
19360 any_type_dependent_elements_p (const_tree list)
19361 {
19362   for (; list; list = TREE_CHAIN (list))
19363     if (value_dependent_expression_p (TREE_VALUE (list)))
19364       return true;
19365
19366   return false;
19367 }
19368
19369 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
19370    expressions) contains any value-dependent expressions.  */
19371
19372 bool
19373 any_value_dependent_elements_p (const_tree list)
19374 {
19375   for (; list; list = TREE_CHAIN (list))
19376     if (value_dependent_expression_p (TREE_VALUE (list)))
19377       return true;
19378
19379   return false;
19380 }
19381
19382 /* Returns TRUE if the ARG (a template argument) is dependent.  */
19383
19384 bool
19385 dependent_template_arg_p (tree arg)
19386 {
19387   if (!processing_template_decl)
19388     return false;
19389
19390   /* Assume a template argument that was wrongly written by the user
19391      is dependent. This is consistent with what
19392      any_dependent_template_arguments_p [that calls this function]
19393      does.  */
19394   if (!arg || arg == error_mark_node)
19395     return true;
19396
19397   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
19398     arg = ARGUMENT_PACK_SELECT_ARG (arg);
19399
19400   if (TREE_CODE (arg) == TEMPLATE_DECL
19401       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
19402     return dependent_template_p (arg);
19403   else if (ARGUMENT_PACK_P (arg))
19404     {
19405       tree args = ARGUMENT_PACK_ARGS (arg);
19406       int i, len = TREE_VEC_LENGTH (args);
19407       for (i = 0; i < len; ++i)
19408         {
19409           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
19410             return true;
19411         }
19412
19413       return false;
19414     }
19415   else if (TYPE_P (arg))
19416     return dependent_type_p (arg);
19417   else
19418     return (type_dependent_expression_p (arg)
19419             || value_dependent_expression_p (arg));
19420 }
19421
19422 /* Returns true if ARGS (a collection of template arguments) contains
19423    any types that require structural equality testing.  */
19424
19425 bool
19426 any_template_arguments_need_structural_equality_p (tree args)
19427 {
19428   int i;
19429   int j;
19430
19431   if (!args)
19432     return false;
19433   if (args == error_mark_node)
19434     return true;
19435
19436   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
19437     {
19438       tree level = TMPL_ARGS_LEVEL (args, i + 1);
19439       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
19440         {
19441           tree arg = TREE_VEC_ELT (level, j);
19442           tree packed_args = NULL_TREE;
19443           int k, len = 1;
19444
19445           if (ARGUMENT_PACK_P (arg))
19446             {
19447               /* Look inside the argument pack.  */
19448               packed_args = ARGUMENT_PACK_ARGS (arg);
19449               len = TREE_VEC_LENGTH (packed_args);
19450             }
19451
19452           for (k = 0; k < len; ++k)
19453             {
19454               if (packed_args)
19455                 arg = TREE_VEC_ELT (packed_args, k);
19456
19457               if (error_operand_p (arg))
19458                 return true;
19459               else if (TREE_CODE (arg) == TEMPLATE_DECL
19460                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
19461                 continue;
19462               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
19463                 return true;
19464               else if (!TYPE_P (arg) && TREE_TYPE (arg)
19465                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
19466                 return true;
19467             }
19468         }
19469     }
19470
19471   return false;
19472 }
19473
19474 /* Returns true if ARGS (a collection of template arguments) contains
19475    any dependent arguments.  */
19476
19477 bool
19478 any_dependent_template_arguments_p (const_tree args)
19479 {
19480   int i;
19481   int j;
19482
19483   if (!args)
19484     return false;
19485   if (args == error_mark_node)
19486     return true;
19487
19488   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
19489     {
19490       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
19491       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
19492         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
19493           return true;
19494     }
19495
19496   return false;
19497 }
19498
19499 /* Returns TRUE if the template TMPL is dependent.  */
19500
19501 bool
19502 dependent_template_p (tree tmpl)
19503 {
19504   if (TREE_CODE (tmpl) == OVERLOAD)
19505     {
19506       while (tmpl)
19507         {
19508           if (dependent_template_p (OVL_CURRENT (tmpl)))
19509             return true;
19510           tmpl = OVL_NEXT (tmpl);
19511         }
19512       return false;
19513     }
19514
19515   /* Template template parameters are dependent.  */
19516   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
19517       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
19518     return true;
19519   /* So are names that have not been looked up.  */
19520   if (TREE_CODE (tmpl) == SCOPE_REF
19521       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
19522     return true;
19523   /* So are member templates of dependent classes.  */
19524   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
19525     return dependent_type_p (DECL_CONTEXT (tmpl));
19526   return false;
19527 }
19528
19529 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
19530
19531 bool
19532 dependent_template_id_p (tree tmpl, tree args)
19533 {
19534   return (dependent_template_p (tmpl)
19535           || any_dependent_template_arguments_p (args));
19536 }
19537
19538 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
19539    is dependent.  */
19540
19541 bool
19542 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
19543 {
19544   int i;
19545
19546   if (!processing_template_decl)
19547     return false;
19548
19549   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
19550     {
19551       tree decl = TREE_VEC_ELT (declv, i);
19552       tree init = TREE_VEC_ELT (initv, i);
19553       tree cond = TREE_VEC_ELT (condv, i);
19554       tree incr = TREE_VEC_ELT (incrv, i);
19555
19556       if (type_dependent_expression_p (decl))
19557         return true;
19558
19559       if (init && type_dependent_expression_p (init))
19560         return true;
19561
19562       if (type_dependent_expression_p (cond))
19563         return true;
19564
19565       if (COMPARISON_CLASS_P (cond)
19566           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
19567               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
19568         return true;
19569
19570       if (TREE_CODE (incr) == MODOP_EXPR)
19571         {
19572           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
19573               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
19574             return true;
19575         }
19576       else if (type_dependent_expression_p (incr))
19577         return true;
19578       else if (TREE_CODE (incr) == MODIFY_EXPR)
19579         {
19580           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
19581             return true;
19582           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
19583             {
19584               tree t = TREE_OPERAND (incr, 1);
19585               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
19586                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
19587                 return true;
19588             }
19589         }
19590     }
19591
19592   return false;
19593 }
19594
19595 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
19596    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
19597    no such TYPE can be found.  Note that this function peers inside
19598    uninstantiated templates and therefore should be used only in
19599    extremely limited situations.  ONLY_CURRENT_P restricts this
19600    peering to the currently open classes hierarchy (which is required
19601    when comparing types).  */
19602
19603 tree
19604 resolve_typename_type (tree type, bool only_current_p)
19605 {
19606   tree scope;
19607   tree name;
19608   tree decl;
19609   int quals;
19610   tree pushed_scope;
19611   tree result;
19612
19613   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
19614
19615   scope = TYPE_CONTEXT (type);
19616   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
19617      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
19618      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
19619      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
19620      identifier  of the TYPENAME_TYPE anymore.
19621      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
19622      TYPENAME_TYPE instead, we avoid messing up with a possible
19623      typedef variant case.  */
19624   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
19625
19626   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
19627      it first before we can figure out what NAME refers to.  */
19628   if (TREE_CODE (scope) == TYPENAME_TYPE)
19629     scope = resolve_typename_type (scope, only_current_p);
19630   /* If we don't know what SCOPE refers to, then we cannot resolve the
19631      TYPENAME_TYPE.  */
19632   if (TREE_CODE (scope) == TYPENAME_TYPE)
19633     return type;
19634   /* If the SCOPE is a template type parameter, we have no way of
19635      resolving the name.  */
19636   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
19637     return type;
19638   /* If the SCOPE is not the current instantiation, there's no reason
19639      to look inside it.  */
19640   if (only_current_p && !currently_open_class (scope))
19641     return type;
19642   /* If this is a typedef, we don't want to look inside (c++/11987).  */
19643   if (typedef_variant_p (type))
19644     return type;
19645   /* If SCOPE isn't the template itself, it will not have a valid
19646      TYPE_FIELDS list.  */
19647   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
19648     /* scope is either the template itself or a compatible instantiation
19649        like X<T>, so look up the name in the original template.  */
19650     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
19651   else
19652     /* scope is a partial instantiation, so we can't do the lookup or we
19653        will lose the template arguments.  */
19654     return type;
19655   /* Enter the SCOPE so that name lookup will be resolved as if we
19656      were in the class definition.  In particular, SCOPE will no
19657      longer be considered a dependent type.  */
19658   pushed_scope = push_scope (scope);
19659   /* Look up the declaration.  */
19660   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
19661
19662   result = NULL_TREE;
19663   
19664   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
19665      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
19666   if (!decl)
19667     /*nop*/;
19668   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
19669            && TREE_CODE (decl) == TYPE_DECL)
19670     {
19671       result = TREE_TYPE (decl);
19672       if (result == error_mark_node)
19673         result = NULL_TREE;
19674     }
19675   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
19676            && DECL_CLASS_TEMPLATE_P (decl))
19677     {
19678       tree tmpl;
19679       tree args;
19680       /* Obtain the template and the arguments.  */
19681       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
19682       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
19683       /* Instantiate the template.  */
19684       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
19685                                       /*entering_scope=*/0,
19686                                       tf_error | tf_user);
19687       if (result == error_mark_node)
19688         result = NULL_TREE;
19689     }
19690   
19691   /* Leave the SCOPE.  */
19692   if (pushed_scope)
19693     pop_scope (pushed_scope);
19694
19695   /* If we failed to resolve it, return the original typename.  */
19696   if (!result)
19697     return type;
19698   
19699   /* If lookup found a typename type, resolve that too.  */
19700   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
19701     {
19702       /* Ill-formed programs can cause infinite recursion here, so we
19703          must catch that.  */
19704       TYPENAME_IS_RESOLVING_P (type) = 1;
19705       result = resolve_typename_type (result, only_current_p);
19706       TYPENAME_IS_RESOLVING_P (type) = 0;
19707     }
19708   
19709   /* Qualify the resulting type.  */
19710   quals = cp_type_quals (type);
19711   if (quals)
19712     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
19713
19714   return result;
19715 }
19716
19717 /* EXPR is an expression which is not type-dependent.  Return a proxy
19718    for EXPR that can be used to compute the types of larger
19719    expressions containing EXPR.  */
19720
19721 tree
19722 build_non_dependent_expr (tree expr)
19723 {
19724   tree inner_expr;
19725
19726 #ifdef ENABLE_CHECKING
19727   /* Try to get a constant value for all non-type-dependent expressions in
19728       order to expose bugs in *_dependent_expression_p and constexpr.  */
19729   if (cxx_dialect >= cxx0x)
19730     maybe_constant_value (fold_non_dependent_expr_sfinae (expr, tf_none));
19731 #endif
19732
19733   /* Preserve OVERLOADs; the functions must be available to resolve
19734      types.  */
19735   inner_expr = expr;
19736   if (TREE_CODE (inner_expr) == STMT_EXPR)
19737     inner_expr = stmt_expr_value_expr (inner_expr);
19738   if (TREE_CODE (inner_expr) == ADDR_EXPR)
19739     inner_expr = TREE_OPERAND (inner_expr, 0);
19740   if (TREE_CODE (inner_expr) == COMPONENT_REF)
19741     inner_expr = TREE_OPERAND (inner_expr, 1);
19742   if (is_overloaded_fn (inner_expr)
19743       || TREE_CODE (inner_expr) == OFFSET_REF)
19744     return expr;
19745   /* There is no need to return a proxy for a variable.  */
19746   if (TREE_CODE (expr) == VAR_DECL)
19747     return expr;
19748   /* Preserve string constants; conversions from string constants to
19749      "char *" are allowed, even though normally a "const char *"
19750      cannot be used to initialize a "char *".  */
19751   if (TREE_CODE (expr) == STRING_CST)
19752     return expr;
19753   /* Preserve arithmetic constants, as an optimization -- there is no
19754      reason to create a new node.  */
19755   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
19756     return expr;
19757   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
19758      There is at least one place where we want to know that a
19759      particular expression is a throw-expression: when checking a ?:
19760      expression, there are special rules if the second or third
19761      argument is a throw-expression.  */
19762   if (TREE_CODE (expr) == THROW_EXPR)
19763     return expr;
19764
19765   /* Don't wrap an initializer list, we need to be able to look inside.  */
19766   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
19767     return expr;
19768
19769   if (TREE_CODE (expr) == COND_EXPR)
19770     return build3 (COND_EXPR,
19771                    TREE_TYPE (expr),
19772                    TREE_OPERAND (expr, 0),
19773                    (TREE_OPERAND (expr, 1)
19774                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
19775                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
19776                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
19777   if (TREE_CODE (expr) == COMPOUND_EXPR
19778       && !COMPOUND_EXPR_OVERLOADED (expr))
19779     return build2 (COMPOUND_EXPR,
19780                    TREE_TYPE (expr),
19781                    TREE_OPERAND (expr, 0),
19782                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
19783
19784   /* If the type is unknown, it can't really be non-dependent */
19785   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
19786
19787   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
19788   return build1 (NON_DEPENDENT_EXPR, TREE_TYPE (expr), expr);
19789 }
19790
19791 /* ARGS is a vector of expressions as arguments to a function call.
19792    Replace the arguments with equivalent non-dependent expressions.
19793    This modifies ARGS in place.  */
19794
19795 void
19796 make_args_non_dependent (VEC(tree,gc) *args)
19797 {
19798   unsigned int ix;
19799   tree arg;
19800
19801   FOR_EACH_VEC_ELT (tree, args, ix, arg)
19802     {
19803       tree newarg = build_non_dependent_expr (arg);
19804       if (newarg != arg)
19805         VEC_replace (tree, args, ix, newarg);
19806     }
19807 }
19808
19809 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
19810    with a level one deeper than the actual template parms.  */
19811
19812 tree
19813 make_auto (void)
19814 {
19815   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
19816   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
19817                                TYPE_DECL, get_identifier ("auto"), au);
19818   TYPE_STUB_DECL (au) = TYPE_NAME (au);
19819   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
19820     (0, processing_template_decl + 1, processing_template_decl + 1,
19821      0, TYPE_NAME (au), NULL_TREE);
19822   TYPE_CANONICAL (au) = canonical_type_parameter (au);
19823   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
19824   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
19825
19826   return au;
19827 }
19828
19829 /* Given type ARG, return std::initializer_list<ARG>.  */
19830
19831 static tree
19832 listify (tree arg)
19833 {
19834   tree std_init_list = namespace_binding
19835     (get_identifier ("initializer_list"), std_node);
19836   tree argvec;
19837   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
19838     {    
19839       error ("deducing from brace-enclosed initializer list requires "
19840              "#include <initializer_list>");
19841       return error_mark_node;
19842     }
19843   argvec = make_tree_vec (1);
19844   TREE_VEC_ELT (argvec, 0) = arg;
19845   return lookup_template_class (std_init_list, argvec, NULL_TREE,
19846                                 NULL_TREE, 0, tf_warning_or_error);
19847 }
19848
19849 /* Replace auto in TYPE with std::initializer_list<auto>.  */
19850
19851 static tree
19852 listify_autos (tree type, tree auto_node)
19853 {
19854   tree init_auto = listify (auto_node);
19855   tree argvec = make_tree_vec (1);
19856   TREE_VEC_ELT (argvec, 0) = init_auto;
19857   if (processing_template_decl)
19858     argvec = add_to_template_args (current_template_args (), argvec);
19859   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
19860 }
19861
19862 /* walk_tree helper for do_auto_deduction.  */
19863
19864 static tree
19865 contains_auto_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
19866                  void *type)
19867 {
19868   /* Is this a variable with the type we're looking for?  */
19869   if (DECL_P (*tp)
19870       && TREE_TYPE (*tp) == type)
19871     return *tp;
19872   else
19873     return NULL_TREE;
19874 }
19875
19876 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
19877    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
19878
19879 tree
19880 do_auto_deduction (tree type, tree init, tree auto_node)
19881 {
19882   tree parms, tparms, targs;
19883   tree args[1];
19884   tree decl;
19885   int val;
19886
19887   if (processing_template_decl
19888       && (TREE_TYPE (init) == NULL_TREE
19889           || BRACE_ENCLOSED_INITIALIZER_P (init)))
19890     /* Not enough information to try this yet.  */
19891     return type;
19892
19893   /* The name of the object being declared shall not appear in the
19894      initializer expression.  */
19895   decl = cp_walk_tree_without_duplicates (&init, contains_auto_r, type);
19896   if (decl)
19897     {
19898       error ("variable %q#D with %<auto%> type used in its own "
19899              "initializer", decl);
19900       return error_mark_node;
19901     }
19902
19903   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
19904      with either a new invented type template parameter U or, if the
19905      initializer is a braced-init-list (8.5.4), with
19906      std::initializer_list<U>.  */
19907   if (BRACE_ENCLOSED_INITIALIZER_P (init))
19908     type = listify_autos (type, auto_node);
19909
19910   init = resolve_nondeduced_context (init);
19911
19912   parms = build_tree_list (NULL_TREE, type);
19913   args[0] = init;
19914   tparms = make_tree_vec (1);
19915   targs = make_tree_vec (1);
19916   TREE_VEC_ELT (tparms, 0)
19917     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
19918   val = type_unification_real (tparms, targs, parms, args, 1, 0,
19919                                DEDUCE_CALL, LOOKUP_NORMAL,
19920                                /*explain_p=*/false);
19921   if (val > 0)
19922     {
19923       if (processing_template_decl)
19924         /* Try again at instantiation time.  */
19925         return type;
19926       if (type && type != error_mark_node)
19927         /* If type is error_mark_node a diagnostic must have been
19928            emitted by now.  Also, having a mention to '<type error>'
19929            in the diagnostic is not really useful to the user.  */
19930         error ("unable to deduce %qT from %qE", type, init);
19931       return error_mark_node;
19932     }
19933
19934   /* If the list of declarators contains more than one declarator, the type
19935      of each declared variable is determined as described above. If the
19936      type deduced for the template parameter U is not the same in each
19937      deduction, the program is ill-formed.  */
19938   if (TREE_TYPE (auto_node)
19939       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
19940     {
19941       error ("inconsistent deduction for %qT: %qT and then %qT",
19942              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
19943       return error_mark_node;
19944     }
19945   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
19946
19947   if (processing_template_decl)
19948     targs = add_to_template_args (current_template_args (), targs);
19949   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
19950 }
19951
19952 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
19953    result.  */
19954
19955 tree
19956 splice_late_return_type (tree type, tree late_return_type)
19957 {
19958   tree argvec;
19959
19960   if (late_return_type == NULL_TREE)
19961     return type;
19962   argvec = make_tree_vec (1);
19963   TREE_VEC_ELT (argvec, 0) = late_return_type;
19964   if (processing_template_parmlist)
19965     /* For a late-specified return type in a template type-parameter, we
19966        need to add a dummy argument level for its parmlist.  */
19967     argvec = add_to_template_args
19968       (make_tree_vec (processing_template_parmlist), argvec);
19969   if (current_template_parms)
19970     argvec = add_to_template_args (current_template_args (), argvec);
19971   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
19972 }
19973
19974 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
19975
19976 bool
19977 is_auto (const_tree type)
19978 {
19979   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
19980       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
19981     return true;
19982   else
19983     return false;
19984 }
19985
19986 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
19987    appear as a type-specifier for the declaration in question, we don't
19988    have to look through the whole type.  */
19989
19990 tree
19991 type_uses_auto (tree type)
19992 {
19993   enum tree_code code;
19994   if (is_auto (type))
19995     return type;
19996
19997   code = TREE_CODE (type);
19998
19999   if (code == POINTER_TYPE || code == REFERENCE_TYPE
20000       || code == OFFSET_TYPE || code == FUNCTION_TYPE
20001       || code == METHOD_TYPE || code == ARRAY_TYPE)
20002     return type_uses_auto (TREE_TYPE (type));
20003
20004   if (TYPE_PTRMEMFUNC_P (type))
20005     return type_uses_auto (TREE_TYPE (TREE_TYPE
20006                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
20007
20008   return NULL_TREE;
20009 }
20010
20011 /* For a given template T, return the vector of typedefs referenced
20012    in T for which access check is needed at T instantiation time.
20013    T is either  a FUNCTION_DECL or a RECORD_TYPE.
20014    Those typedefs were added to T by the function
20015    append_type_to_template_for_access_check.  */
20016
20017 VEC(qualified_typedef_usage_t,gc)*
20018 get_types_needing_access_check (tree t)
20019 {
20020   tree ti;
20021   VEC(qualified_typedef_usage_t,gc) *result = NULL;
20022
20023   if (!t || t == error_mark_node)
20024     return NULL;
20025
20026   if (!(ti = get_template_info (t)))
20027     return NULL;
20028
20029   if (CLASS_TYPE_P (t)
20030       || TREE_CODE (t) == FUNCTION_DECL)
20031     {
20032       if (!TI_TEMPLATE (ti))
20033         return NULL;
20034
20035       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
20036     }
20037
20038   return result;
20039 }
20040
20041 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
20042    tied to T. That list of typedefs will be access checked at
20043    T instantiation time.
20044    T is either a FUNCTION_DECL or a RECORD_TYPE.
20045    TYPE_DECL is a TYPE_DECL node representing a typedef.
20046    SCOPE is the scope through which TYPE_DECL is accessed.
20047    LOCATION is the location of the usage point of TYPE_DECL.
20048
20049    This function is a subroutine of
20050    append_type_to_template_for_access_check.  */
20051
20052 static void
20053 append_type_to_template_for_access_check_1 (tree t,
20054                                             tree type_decl,
20055                                             tree scope,
20056                                             location_t location)
20057 {
20058   qualified_typedef_usage_t typedef_usage;
20059   tree ti;
20060
20061   if (!t || t == error_mark_node)
20062     return;
20063
20064   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
20065                || CLASS_TYPE_P (t))
20066               && type_decl
20067               && TREE_CODE (type_decl) == TYPE_DECL
20068               && scope);
20069
20070   if (!(ti = get_template_info (t)))
20071     return;
20072
20073   gcc_assert (TI_TEMPLATE (ti));
20074
20075   typedef_usage.typedef_decl = type_decl;
20076   typedef_usage.context = scope;
20077   typedef_usage.locus = location;
20078
20079   VEC_safe_push (qualified_typedef_usage_t, gc,
20080                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
20081                  &typedef_usage);
20082 }
20083
20084 /* Append TYPE_DECL to the template TEMPL.
20085    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
20086    At TEMPL instanciation time, TYPE_DECL will be checked to see
20087    if it can be accessed through SCOPE.
20088    LOCATION is the location of the usage point of TYPE_DECL.
20089
20090    e.g. consider the following code snippet:
20091
20092      class C
20093      {
20094        typedef int myint;
20095      };
20096
20097      template<class U> struct S
20098      {
20099        C::myint mi; // <-- usage point of the typedef C::myint
20100      };
20101
20102      S<char> s;
20103
20104    At S<char> instantiation time, we need to check the access of C::myint
20105    In other words, we need to check the access of the myint typedef through
20106    the C scope. For that purpose, this function will add the myint typedef
20107    and the scope C through which its being accessed to a list of typedefs
20108    tied to the template S. That list will be walked at template instantiation
20109    time and access check performed on each typedefs it contains.
20110    Note that this particular code snippet should yield an error because
20111    myint is private to C.  */
20112
20113 void
20114 append_type_to_template_for_access_check (tree templ,
20115                                           tree type_decl,
20116                                           tree scope,
20117                                           location_t location)
20118 {
20119   qualified_typedef_usage_t *iter;
20120   int i;
20121
20122   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
20123
20124   /* Make sure we don't append the type to the template twice.  */
20125   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
20126                     get_types_needing_access_check (templ),
20127                     i, iter)
20128     if (iter->typedef_decl == type_decl && scope == iter->context)
20129       return;
20130
20131   append_type_to_template_for_access_check_1 (templ, type_decl,
20132                                               scope, location);
20133 }
20134
20135 /* Set up the hash tables for template instantiations.  */
20136
20137 void
20138 init_template_processing (void)
20139 {
20140   decl_specializations = htab_create_ggc (37,
20141                                           hash_specialization,
20142                                           eq_specializations,
20143                                           ggc_free);
20144   type_specializations = htab_create_ggc (37,
20145                                           hash_specialization,
20146                                           eq_specializations,
20147                                           ggc_free);
20148 }
20149
20150 /* Print stats about the template hash tables for -fstats.  */
20151
20152 void
20153 print_template_statistics (void)
20154 {
20155   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
20156            "%f collisions\n", (long) htab_size (decl_specializations),
20157            (long) htab_elements (decl_specializations),
20158            htab_collisions (decl_specializations));
20159   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
20160            "%f collisions\n", (long) htab_size (type_specializations),
20161            (long) htab_elements (type_specializations),
20162            htab_collisions (type_specializations));
20163 }
20164
20165 #include "gt-cp-pt.h"