cda9df8d1be5f9cc159cfc93c2b6c39bcd189c5a
[platform/upstream/gcc.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 static void push_access_scope (tree);
113 static void pop_access_scope (tree);
114 static bool resolve_overloaded_unification (tree, tree, tree, tree,
115                                             unification_kind_t, int);
116 static int try_one_overload (tree, tree, tree, tree, tree,
117                              unification_kind_t, int, bool);
118 static int unify (tree, tree, tree, tree, int);
119 static void add_pending_template (tree);
120 static tree reopen_tinst_level (struct tinst_level *);
121 static tree tsubst_initializer_list (tree, tree);
122 static tree get_class_bindings (tree, tree, tree);
123 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
124                                    bool, bool);
125 static void tsubst_enum (tree, tree, tree);
126 static tree add_to_template_args (tree, tree);
127 static tree add_outermost_template_args (tree, tree);
128 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
129 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
130                                              tree);
131 static int type_unification_real (tree, tree, tree, const tree *,
132                                   unsigned int, int, unification_kind_t, int);
133 static void note_template_header (int);
134 static tree convert_nontype_argument_function (tree, tree);
135 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
136 static tree convert_template_argument (tree, tree, tree,
137                                        tsubst_flags_t, int, tree);
138 static int for_each_template_parm (tree, tree_fn_t, void*,
139                                    struct pointer_set_t*, bool);
140 static tree expand_template_argument_pack (tree);
141 static tree build_template_parm_index (int, int, int, int, tree, tree);
142 static bool inline_needs_template_parms (tree);
143 static void push_inline_template_parms_recursive (tree, int);
144 static tree retrieve_local_specialization (tree);
145 static void register_local_specialization (tree, tree);
146 static hashval_t hash_specialization (const void *p);
147 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
148 static int mark_template_parm (tree, void *);
149 static int template_parm_this_level_p (tree, void *);
150 static tree tsubst_friend_function (tree, tree);
151 static tree tsubst_friend_class (tree, tree);
152 static int can_complete_type_without_circularity (tree);
153 static tree get_bindings (tree, tree, tree, bool);
154 static int template_decl_level (tree);
155 static int check_cv_quals_for_unify (int, tree, tree);
156 static void template_parm_level_and_index (tree, int*, int*);
157 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
158 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
159 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
160 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
161 static void regenerate_decl_from_template (tree, tree);
162 static tree most_specialized_class (tree, tree, tsubst_flags_t);
163 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
164 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
165 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
166 static bool check_specialization_scope (void);
167 static tree process_partial_specialization (tree);
168 static void set_current_access_from_decl (tree);
169 static tree get_template_base (tree, tree, tree, tree);
170 static tree try_class_unification (tree, tree, tree, tree);
171 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
172                                            tree, tree);
173 static bool template_template_parm_bindings_ok_p (tree, tree);
174 static int template_args_equal (tree, tree);
175 static void tsubst_default_arguments (tree);
176 static tree for_each_template_parm_r (tree *, int *, void *);
177 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
178 static void copy_default_args_to_explicit_spec (tree);
179 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
180 static int eq_local_specializations (const void *, const void *);
181 static bool dependent_template_arg_p (tree);
182 static bool any_template_arguments_need_structural_equality_p (tree);
183 static bool dependent_type_p_r (tree);
184 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
185 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
186 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
187 static tree tsubst_decl (tree, tree, tsubst_flags_t);
188 static void perform_typedefs_access_check (tree tmpl, tree targs);
189 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
190                                                         location_t);
191 static tree listify (tree);
192 static tree listify_autos (tree, tree);
193 static tree template_parm_to_arg (tree t);
194 static tree current_template_args (void);
195 static tree fixup_template_type_parm_type (tree, int);
196 static tree fixup_template_parm_index (tree, tree, int);
197 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
198
199 /* Make the current scope suitable for access checking when we are
200    processing T.  T can be FUNCTION_DECL for instantiated function
201    template, or VAR_DECL for static member variable (need by
202    instantiate_decl).  */
203
204 static void
205 push_access_scope (tree t)
206 {
207   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
208               || TREE_CODE (t) == VAR_DECL);
209
210   if (DECL_FRIEND_CONTEXT (t))
211     push_nested_class (DECL_FRIEND_CONTEXT (t));
212   else if (DECL_CLASS_SCOPE_P (t))
213     push_nested_class (DECL_CONTEXT (t));
214   else
215     push_to_top_level ();
216
217   if (TREE_CODE (t) == FUNCTION_DECL)
218     {
219       saved_access_scope = tree_cons
220         (NULL_TREE, current_function_decl, saved_access_scope);
221       current_function_decl = t;
222     }
223 }
224
225 /* Restore the scope set up by push_access_scope.  T is the node we
226    are processing.  */
227
228 static void
229 pop_access_scope (tree t)
230 {
231   if (TREE_CODE (t) == FUNCTION_DECL)
232     {
233       current_function_decl = TREE_VALUE (saved_access_scope);
234       saved_access_scope = TREE_CHAIN (saved_access_scope);
235     }
236
237   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
238     pop_nested_class ();
239   else
240     pop_from_top_level ();
241 }
242
243 /* Do any processing required when DECL (a member template
244    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
245    to DECL, unless it is a specialization, in which case the DECL
246    itself is returned.  */
247
248 tree
249 finish_member_template_decl (tree decl)
250 {
251   if (decl == error_mark_node)
252     return error_mark_node;
253
254   gcc_assert (DECL_P (decl));
255
256   if (TREE_CODE (decl) == TYPE_DECL)
257     {
258       tree type;
259
260       type = TREE_TYPE (decl);
261       if (type == error_mark_node)
262         return error_mark_node;
263       if (MAYBE_CLASS_TYPE_P (type)
264           && CLASSTYPE_TEMPLATE_INFO (type)
265           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
266         {
267           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
268           check_member_template (tmpl);
269           return tmpl;
270         }
271       return NULL_TREE;
272     }
273   else if (TREE_CODE (decl) == FIELD_DECL)
274     error ("data member %qD cannot be a member template", decl);
275   else if (DECL_TEMPLATE_INFO (decl))
276     {
277       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
278         {
279           check_member_template (DECL_TI_TEMPLATE (decl));
280           return DECL_TI_TEMPLATE (decl);
281         }
282       else
283         return decl;
284     }
285   else
286     error ("invalid member template declaration %qD", decl);
287
288   return error_mark_node;
289 }
290
291 /* Create a template info node.  */
292
293 tree
294 build_template_info (tree template_decl, tree template_args)
295 {
296   tree result = make_node (TEMPLATE_INFO);
297   TI_TEMPLATE (result) = template_decl;
298   TI_ARGS (result) = template_args;
299   return result;
300 }
301
302 /* Return the template info node corresponding to T, whatever T is.  */
303
304 tree
305 get_template_info (const_tree t)
306 {
307   tree tinfo = NULL_TREE;
308
309   if (!t || t == error_mark_node)
310     return NULL;
311
312   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
313     tinfo = DECL_TEMPLATE_INFO (t);
314
315   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
316     t = TREE_TYPE (t);
317
318   if (TAGGED_TYPE_P (t))
319     tinfo = TYPE_TEMPLATE_INFO (t);
320   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
321     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
322
323   return tinfo;
324 }
325
326 /* Returns the template nesting level of the indicated class TYPE.
327
328    For example, in:
329      template <class T>
330      struct A
331      {
332        template <class U>
333        struct B {};
334      };
335
336    A<T>::B<U> has depth two, while A<T> has depth one.
337    Both A<T>::B<int> and A<int>::B<U> have depth one, if
338    they are instantiations, not specializations.
339
340    This function is guaranteed to return 0 if passed NULL_TREE so
341    that, for example, `template_class_depth (current_class_type)' is
342    always safe.  */
343
344 int
345 template_class_depth (tree type)
346 {
347   int depth;
348
349   for (depth = 0;
350        type && TREE_CODE (type) != NAMESPACE_DECL;
351        type = (TREE_CODE (type) == FUNCTION_DECL)
352          ? CP_DECL_CONTEXT (type) : CP_TYPE_CONTEXT (type))
353     {
354       tree tinfo = get_template_info (type);
355
356       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
357           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
358         ++depth;
359     }
360
361   return depth;
362 }
363
364 /* Subroutine of maybe_begin_member_template_processing.
365    Returns true if processing DECL needs us to push template parms.  */
366
367 static bool
368 inline_needs_template_parms (tree decl)
369 {
370   if (! DECL_TEMPLATE_INFO (decl))
371     return false;
372
373   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
374           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
375 }
376
377 /* Subroutine of maybe_begin_member_template_processing.
378    Push the template parms in PARMS, starting from LEVELS steps into the
379    chain, and ending at the beginning, since template parms are listed
380    innermost first.  */
381
382 static void
383 push_inline_template_parms_recursive (tree parmlist, int levels)
384 {
385   tree parms = TREE_VALUE (parmlist);
386   int i;
387
388   if (levels > 1)
389     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
390
391   ++processing_template_decl;
392   current_template_parms
393     = tree_cons (size_int (processing_template_decl),
394                  parms, current_template_parms);
395   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
396
397   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
398                NULL);
399   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
400     {
401       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
402
403       if (parm == error_mark_node)
404         continue;
405
406       gcc_assert (DECL_P (parm));
407
408       switch (TREE_CODE (parm))
409         {
410         case TYPE_DECL:
411         case TEMPLATE_DECL:
412           pushdecl (parm);
413           break;
414
415         case PARM_DECL:
416           {
417             /* Make a CONST_DECL as is done in process_template_parm.
418                It is ugly that we recreate this here; the original
419                version built in process_template_parm is no longer
420                available.  */
421             tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
422                                     CONST_DECL, DECL_NAME (parm),
423                                     TREE_TYPE (parm));
424             DECL_ARTIFICIAL (decl) = 1;
425             TREE_CONSTANT (decl) = 1;
426             TREE_READONLY (decl) = 1;
427             DECL_INITIAL (decl) = DECL_INITIAL (parm);
428             SET_DECL_TEMPLATE_PARM_P (decl);
429             pushdecl (decl);
430           }
431           break;
432
433         default:
434           gcc_unreachable ();
435         }
436     }
437 }
438
439 /* Restore the template parameter context for a member template or
440    a friend template defined in a class definition.  */
441
442 void
443 maybe_begin_member_template_processing (tree decl)
444 {
445   tree parms;
446   int levels = 0;
447
448   if (inline_needs_template_parms (decl))
449     {
450       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
451       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
452
453       if (DECL_TEMPLATE_SPECIALIZATION (decl))
454         {
455           --levels;
456           parms = TREE_CHAIN (parms);
457         }
458
459       push_inline_template_parms_recursive (parms, levels);
460     }
461
462   /* Remember how many levels of template parameters we pushed so that
463      we can pop them later.  */
464   VEC_safe_push (int, heap, inline_parm_levels, levels);
465 }
466
467 /* Undo the effects of maybe_begin_member_template_processing.  */
468
469 void
470 maybe_end_member_template_processing (void)
471 {
472   int i;
473   int last;
474
475   if (VEC_length (int, inline_parm_levels) == 0)
476     return;
477
478   last = VEC_pop (int, inline_parm_levels);
479   for (i = 0; i < last; ++i)
480     {
481       --processing_template_decl;
482       current_template_parms = TREE_CHAIN (current_template_parms);
483       poplevel (0, 0, 0);
484     }
485 }
486
487 /* Return a new template argument vector which contains all of ARGS,
488    but has as its innermost set of arguments the EXTRA_ARGS.  */
489
490 static tree
491 add_to_template_args (tree args, tree extra_args)
492 {
493   tree new_args;
494   int extra_depth;
495   int i;
496   int j;
497
498   if (args == NULL_TREE || extra_args == error_mark_node)
499     return extra_args;
500
501   extra_depth = TMPL_ARGS_DEPTH (extra_args);
502   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
503
504   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
505     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
506
507   for (j = 1; j <= extra_depth; ++j, ++i)
508     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
509
510   return new_args;
511 }
512
513 /* Like add_to_template_args, but only the outermost ARGS are added to
514    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
515    (EXTRA_ARGS) levels are added.  This function is used to combine
516    the template arguments from a partial instantiation with the
517    template arguments used to attain the full instantiation from the
518    partial instantiation.  */
519
520 static tree
521 add_outermost_template_args (tree args, tree extra_args)
522 {
523   tree new_args;
524
525   /* If there are more levels of EXTRA_ARGS than there are ARGS,
526      something very fishy is going on.  */
527   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
528
529   /* If *all* the new arguments will be the EXTRA_ARGS, just return
530      them.  */
531   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
532     return extra_args;
533
534   /* For the moment, we make ARGS look like it contains fewer levels.  */
535   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
536
537   new_args = add_to_template_args (args, extra_args);
538
539   /* Now, we restore ARGS to its full dimensions.  */
540   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
541
542   return new_args;
543 }
544
545 /* Return the N levels of innermost template arguments from the ARGS.  */
546
547 tree
548 get_innermost_template_args (tree args, int n)
549 {
550   tree new_args;
551   int extra_levels;
552   int i;
553
554   gcc_assert (n >= 0);
555
556   /* If N is 1, just return the innermost set of template arguments.  */
557   if (n == 1)
558     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
559
560   /* If we're not removing anything, just return the arguments we were
561      given.  */
562   extra_levels = TMPL_ARGS_DEPTH (args) - n;
563   gcc_assert (extra_levels >= 0);
564   if (extra_levels == 0)
565     return args;
566
567   /* Make a new set of arguments, not containing the outer arguments.  */
568   new_args = make_tree_vec (n);
569   for (i = 1; i <= n; ++i)
570     SET_TMPL_ARGS_LEVEL (new_args, i,
571                          TMPL_ARGS_LEVEL (args, i + extra_levels));
572
573   return new_args;
574 }
575
576 /* The inverse of get_innermost_template_args: Return all but the innermost
577    EXTRA_LEVELS levels of template arguments from the ARGS.  */
578
579 static tree
580 strip_innermost_template_args (tree args, int extra_levels)
581 {
582   tree new_args;
583   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
584   int i;
585
586   gcc_assert (n >= 0);
587
588   /* If N is 1, just return the outermost set of template arguments.  */
589   if (n == 1)
590     return TMPL_ARGS_LEVEL (args, 1);
591
592   /* If we're not removing anything, just return the arguments we were
593      given.  */
594   gcc_assert (extra_levels >= 0);
595   if (extra_levels == 0)
596     return args;
597
598   /* Make a new set of arguments, not containing the inner arguments.  */
599   new_args = make_tree_vec (n);
600   for (i = 1; i <= n; ++i)
601     SET_TMPL_ARGS_LEVEL (new_args, i,
602                          TMPL_ARGS_LEVEL (args, i));
603
604   return new_args;
605 }
606
607 /* We've got a template header coming up; push to a new level for storing
608    the parms.  */
609
610 void
611 begin_template_parm_list (void)
612 {
613   /* We use a non-tag-transparent scope here, which causes pushtag to
614      put tags in this scope, rather than in the enclosing class or
615      namespace scope.  This is the right thing, since we want
616      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
617      global template class, push_template_decl handles putting the
618      TEMPLATE_DECL into top-level scope.  For a nested template class,
619      e.g.:
620
621        template <class T> struct S1 {
622          template <class T> struct S2 {};
623        };
624
625      pushtag contains special code to call pushdecl_with_scope on the
626      TEMPLATE_DECL for S2.  */
627   begin_scope (sk_template_parms, NULL);
628   ++processing_template_decl;
629   ++processing_template_parmlist;
630   note_template_header (0);
631 }
632
633 /* This routine is called when a specialization is declared.  If it is
634    invalid to declare a specialization here, an error is reported and
635    false is returned, otherwise this routine will return true.  */
636
637 static bool
638 check_specialization_scope (void)
639 {
640   tree scope = current_scope ();
641
642   /* [temp.expl.spec]
643
644      An explicit specialization shall be declared in the namespace of
645      which the template is a member, or, for member templates, in the
646      namespace of which the enclosing class or enclosing class
647      template is a member.  An explicit specialization of a member
648      function, member class or static data member of a class template
649      shall be declared in the namespace of which the class template
650      is a member.  */
651   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
652     {
653       error ("explicit specialization in non-namespace scope %qD", scope);
654       return false;
655     }
656
657   /* [temp.expl.spec]
658
659      In an explicit specialization declaration for a member of a class
660      template or a member template that appears in namespace scope,
661      the member template and some of its enclosing class templates may
662      remain unspecialized, except that the declaration shall not
663      explicitly specialize a class member template if its enclosing
664      class templates are not explicitly specialized as well.  */
665   if (current_template_parms)
666     {
667       error ("enclosing class templates are not explicitly specialized");
668       return false;
669     }
670
671   return true;
672 }
673
674 /* We've just seen template <>.  */
675
676 bool
677 begin_specialization (void)
678 {
679   begin_scope (sk_template_spec, NULL);
680   note_template_header (1);
681   return check_specialization_scope ();
682 }
683
684 /* Called at then end of processing a declaration preceded by
685    template<>.  */
686
687 void
688 end_specialization (void)
689 {
690   finish_scope ();
691   reset_specialization ();
692 }
693
694 /* Any template <>'s that we have seen thus far are not referring to a
695    function specialization.  */
696
697 void
698 reset_specialization (void)
699 {
700   processing_specialization = 0;
701   template_header_count = 0;
702 }
703
704 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
705    it was of the form template <>.  */
706
707 static void
708 note_template_header (int specialization)
709 {
710   processing_specialization = specialization;
711   template_header_count++;
712 }
713
714 /* We're beginning an explicit instantiation.  */
715
716 void
717 begin_explicit_instantiation (void)
718 {
719   gcc_assert (!processing_explicit_instantiation);
720   processing_explicit_instantiation = true;
721 }
722
723
724 void
725 end_explicit_instantiation (void)
726 {
727   gcc_assert (processing_explicit_instantiation);
728   processing_explicit_instantiation = false;
729 }
730
731 /* An explicit specialization or partial specialization TMPL is being
732    declared.  Check that the namespace in which the specialization is
733    occurring is permissible.  Returns false iff it is invalid to
734    specialize TMPL in the current namespace.  */
735
736 static bool
737 check_specialization_namespace (tree tmpl)
738 {
739   tree tpl_ns = decl_namespace_context (tmpl);
740
741   /* [tmpl.expl.spec]
742
743      An explicit specialization shall be declared in the namespace of
744      which the template is a member, or, for member templates, in the
745      namespace of which the enclosing class or enclosing class
746      template is a member.  An explicit specialization of a member
747      function, member class or static data member of a class template
748      shall be declared in the namespace of which the class template is
749      a member.  */
750   if (current_scope() != DECL_CONTEXT (tmpl)
751       && !at_namespace_scope_p ())
752     {
753       error ("specialization of %qD must appear at namespace scope", tmpl);
754       return false;
755     }
756   if (is_associated_namespace (current_namespace, tpl_ns))
757     /* Same or super-using namespace.  */
758     return true;
759   else
760     {
761       permerror (input_location, "specialization of %qD in different namespace", tmpl);
762       permerror (input_location, "  from definition of %q+#D", tmpl);
763       return false;
764     }
765 }
766
767 /* SPEC is an explicit instantiation.  Check that it is valid to
768    perform this explicit instantiation in the current namespace.  */
769
770 static void
771 check_explicit_instantiation_namespace (tree spec)
772 {
773   tree ns;
774
775   /* DR 275: An explicit instantiation shall appear in an enclosing
776      namespace of its template.  */
777   ns = decl_namespace_context (spec);
778   if (!is_ancestor (current_namespace, ns))
779     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
780                "(which does not enclose namespace %qD)",
781                spec, current_namespace, ns);
782 }
783
784 /* The TYPE is being declared.  If it is a template type, that means it
785    is a partial specialization.  Do appropriate error-checking.  */
786
787 tree
788 maybe_process_partial_specialization (tree type)
789 {
790   tree context;
791
792   if (type == error_mark_node)
793     return error_mark_node;
794
795   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
796     {
797       error ("name of class shadows template template parameter %qD",
798              TYPE_NAME (type));
799       return error_mark_node;
800     }
801
802   context = TYPE_CONTEXT (type);
803
804   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
805     {
806       /* This is for ordinary explicit specialization and partial
807          specialization of a template class such as:
808
809            template <> class C<int>;
810
811          or:
812
813            template <class T> class C<T*>;
814
815          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
816
817       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
818           && !COMPLETE_TYPE_P (type))
819         {
820           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
821           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
822           if (processing_template_decl)
823             {
824               if (push_template_decl (TYPE_MAIN_DECL (type))
825                   == error_mark_node)
826                 return error_mark_node;
827             }
828         }
829       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
830         error ("specialization of %qT after instantiation", type);
831     }
832   else if (CLASS_TYPE_P (type)
833            && !CLASSTYPE_USE_TEMPLATE (type)
834            && CLASSTYPE_TEMPLATE_INFO (type)
835            && context && CLASS_TYPE_P (context)
836            && CLASSTYPE_TEMPLATE_INFO (context))
837     {
838       /* This is for an explicit specialization of member class
839          template according to [temp.expl.spec/18]:
840
841            template <> template <class U> class C<int>::D;
842
843          The context `C<int>' must be an implicit instantiation.
844          Otherwise this is just a member class template declared
845          earlier like:
846
847            template <> class C<int> { template <class U> class D; };
848            template <> template <class U> class C<int>::D;
849
850          In the first case, `C<int>::D' is a specialization of `C<T>::D'
851          while in the second case, `C<int>::D' is a primary template
852          and `C<T>::D' may not exist.  */
853
854       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
855           && !COMPLETE_TYPE_P (type))
856         {
857           tree t;
858           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
859
860           if (current_namespace
861               != decl_namespace_context (tmpl))
862             {
863               permerror (input_location, "specializing %q#T in different namespace", type);
864               permerror (input_location, "  from definition of %q+#D", tmpl);
865             }
866
867           /* Check for invalid specialization after instantiation:
868
869                template <> template <> class C<int>::D<int>;
870                template <> template <class U> class C<int>::D;  */
871
872           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
873                t; t = TREE_CHAIN (t))
874             {
875               tree inst = TREE_VALUE (t);
876               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst))
877                 {
878                   /* We already have a full specialization of this partial
879                      instantiation.  Reassign it to the new member
880                      specialization template.  */
881                   spec_entry elt;
882                   spec_entry **slot;
883
884                   elt.tmpl = most_general_template (tmpl);
885                   elt.args = CLASSTYPE_TI_ARGS (inst);
886                   elt.spec = inst;
887
888                   htab_remove_elt (type_specializations, &elt);
889
890                   elt.tmpl = tmpl;
891                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
892
893                   slot = (spec_entry **)
894                     htab_find_slot (type_specializations, &elt, INSERT);
895                   *slot = ggc_alloc_spec_entry ();
896                   **slot = elt;
897                 }
898               else if (COMPLETE_OR_OPEN_TYPE_P (inst))
899                 /* But if we've had an implicit instantiation, that's a
900                    problem ([temp.expl.spec]/6).  */
901                 error ("specialization %qT after instantiation %qT",
902                        type, inst);
903             }
904
905           /* Mark TYPE as a specialization.  And as a result, we only
906              have one level of template argument for the innermost
907              class template.  */
908           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
909           CLASSTYPE_TI_ARGS (type)
910             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
911         }
912     }
913   else if (processing_specialization)
914     {
915        /* Someday C++0x may allow for enum template specialization.  */
916       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
917           && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
918         pedwarn (input_location, OPT_pedantic, "template specialization "
919                  "of %qD not allowed by ISO C++", type);
920       else
921         {
922           error ("explicit specialization of non-template %qT", type);
923           return error_mark_node;
924         }
925     }
926
927   return type;
928 }
929
930 /* Returns nonzero if we can optimize the retrieval of specializations
931    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
932    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
933
934 static inline bool
935 optimize_specialization_lookup_p (tree tmpl)
936 {
937   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
938           && DECL_CLASS_SCOPE_P (tmpl)
939           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
940              parameter.  */
941           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
942           /* The optimized lookup depends on the fact that the
943              template arguments for the member function template apply
944              purely to the containing class, which is not true if the
945              containing class is an explicit or partial
946              specialization.  */
947           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
948           && !DECL_MEMBER_TEMPLATE_P (tmpl)
949           && !DECL_CONV_FN_P (tmpl)
950           /* It is possible to have a template that is not a member
951              template and is not a member of a template class:
952
953              template <typename T>
954              struct S { friend A::f(); };
955
956              Here, the friend function is a template, but the context does
957              not have template information.  The optimized lookup relies
958              on having ARGS be the template arguments for both the class
959              and the function template.  */
960           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
961 }
962
963 /* Retrieve the specialization (in the sense of [temp.spec] - a
964    specialization is either an instantiation or an explicit
965    specialization) of TMPL for the given template ARGS.  If there is
966    no such specialization, return NULL_TREE.  The ARGS are a vector of
967    arguments, or a vector of vectors of arguments, in the case of
968    templates with more than one level of parameters.
969
970    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
971    then we search for a partial specialization matching ARGS.  This
972    parameter is ignored if TMPL is not a class template.  */
973
974 static tree
975 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
976 {
977   if (args == error_mark_node)
978     return NULL_TREE;
979
980   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
981
982   /* There should be as many levels of arguments as there are
983      levels of parameters.  */
984   gcc_assert (TMPL_ARGS_DEPTH (args)
985               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
986
987   if (optimize_specialization_lookup_p (tmpl))
988     {
989       tree class_template;
990       tree class_specialization;
991       VEC(tree,gc) *methods;
992       tree fns;
993       int idx;
994
995       /* The template arguments actually apply to the containing
996          class.  Find the class specialization with those
997          arguments.  */
998       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
999       class_specialization
1000         = retrieve_specialization (class_template, args, 0);
1001       if (!class_specialization)
1002         return NULL_TREE;
1003       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
1004          for the specialization.  */
1005       idx = class_method_index_for_fn (class_specialization, tmpl);
1006       if (idx == -1)
1007         return NULL_TREE;
1008       /* Iterate through the methods with the indicated name, looking
1009          for the one that has an instance of TMPL.  */
1010       methods = CLASSTYPE_METHOD_VEC (class_specialization);
1011       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
1012         {
1013           tree fn = OVL_CURRENT (fns);
1014           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1015               /* using-declarations can add base methods to the method vec,
1016                  and we don't want those here.  */
1017               && DECL_CONTEXT (fn) == class_specialization)
1018             return fn;
1019         }
1020       return NULL_TREE;
1021     }
1022   else
1023     {
1024       spec_entry *found;
1025       spec_entry elt;
1026       htab_t specializations;
1027
1028       elt.tmpl = tmpl;
1029       elt.args = args;
1030       elt.spec = NULL_TREE;
1031
1032       if (DECL_CLASS_TEMPLATE_P (tmpl))
1033         specializations = type_specializations;
1034       else
1035         specializations = decl_specializations;
1036
1037       if (hash == 0)
1038         hash = hash_specialization (&elt);
1039       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1040       if (found)
1041         return found->spec;
1042     }
1043
1044   return NULL_TREE;
1045 }
1046
1047 /* Like retrieve_specialization, but for local declarations.  */
1048
1049 static tree
1050 retrieve_local_specialization (tree tmpl)
1051 {
1052   tree spec;
1053
1054   if (local_specializations == NULL)
1055     return NULL_TREE;
1056
1057   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1058                                      htab_hash_pointer (tmpl));
1059   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1060 }
1061
1062 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1063
1064 int
1065 is_specialization_of (tree decl, tree tmpl)
1066 {
1067   tree t;
1068
1069   if (TREE_CODE (decl) == FUNCTION_DECL)
1070     {
1071       for (t = decl;
1072            t != NULL_TREE;
1073            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1074         if (t == tmpl)
1075           return 1;
1076     }
1077   else
1078     {
1079       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1080
1081       for (t = TREE_TYPE (decl);
1082            t != NULL_TREE;
1083            t = CLASSTYPE_USE_TEMPLATE (t)
1084              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1085         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1086           return 1;
1087     }
1088
1089   return 0;
1090 }
1091
1092 /* Returns nonzero iff DECL is a specialization of friend declaration
1093    FRIEND_DECL according to [temp.friend].  */
1094
1095 bool
1096 is_specialization_of_friend (tree decl, tree friend_decl)
1097 {
1098   bool need_template = true;
1099   int template_depth;
1100
1101   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1102               || TREE_CODE (decl) == TYPE_DECL);
1103
1104   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1105      of a template class, we want to check if DECL is a specialization
1106      if this.  */
1107   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1108       && DECL_TEMPLATE_INFO (friend_decl)
1109       && !DECL_USE_TEMPLATE (friend_decl))
1110     {
1111       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1112       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1113       need_template = false;
1114     }
1115   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1116            && !PRIMARY_TEMPLATE_P (friend_decl))
1117     need_template = false;
1118
1119   /* There is nothing to do if this is not a template friend.  */
1120   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1121     return false;
1122
1123   if (is_specialization_of (decl, friend_decl))
1124     return true;
1125
1126   /* [temp.friend/6]
1127      A member of a class template may be declared to be a friend of a
1128      non-template class.  In this case, the corresponding member of
1129      every specialization of the class template is a friend of the
1130      class granting friendship.
1131
1132      For example, given a template friend declaration
1133
1134        template <class T> friend void A<T>::f();
1135
1136      the member function below is considered a friend
1137
1138        template <> struct A<int> {
1139          void f();
1140        };
1141
1142      For this type of template friend, TEMPLATE_DEPTH below will be
1143      nonzero.  To determine if DECL is a friend of FRIEND, we first
1144      check if the enclosing class is a specialization of another.  */
1145
1146   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1147   if (template_depth
1148       && DECL_CLASS_SCOPE_P (decl)
1149       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1150                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1151     {
1152       /* Next, we check the members themselves.  In order to handle
1153          a few tricky cases, such as when FRIEND_DECL's are
1154
1155            template <class T> friend void A<T>::g(T t);
1156            template <class T> template <T t> friend void A<T>::h();
1157
1158          and DECL's are
1159
1160            void A<int>::g(int);
1161            template <int> void A<int>::h();
1162
1163          we need to figure out ARGS, the template arguments from
1164          the context of DECL.  This is required for template substitution
1165          of `T' in the function parameter of `g' and template parameter
1166          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1167
1168       tree context = DECL_CONTEXT (decl);
1169       tree args = NULL_TREE;
1170       int current_depth = 0;
1171
1172       while (current_depth < template_depth)
1173         {
1174           if (CLASSTYPE_TEMPLATE_INFO (context))
1175             {
1176               if (current_depth == 0)
1177                 args = TYPE_TI_ARGS (context);
1178               else
1179                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1180               current_depth++;
1181             }
1182           context = TYPE_CONTEXT (context);
1183         }
1184
1185       if (TREE_CODE (decl) == FUNCTION_DECL)
1186         {
1187           bool is_template;
1188           tree friend_type;
1189           tree decl_type;
1190           tree friend_args_type;
1191           tree decl_args_type;
1192
1193           /* Make sure that both DECL and FRIEND_DECL are templates or
1194              non-templates.  */
1195           is_template = DECL_TEMPLATE_INFO (decl)
1196                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1197           if (need_template ^ is_template)
1198             return false;
1199           else if (is_template)
1200             {
1201               /* If both are templates, check template parameter list.  */
1202               tree friend_parms
1203                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1204                                          args, tf_none);
1205               if (!comp_template_parms
1206                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1207                       friend_parms))
1208                 return false;
1209
1210               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1211             }
1212           else
1213             decl_type = TREE_TYPE (decl);
1214
1215           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1216                                               tf_none, NULL_TREE);
1217           if (friend_type == error_mark_node)
1218             return false;
1219
1220           /* Check if return types match.  */
1221           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1222             return false;
1223
1224           /* Check if function parameter types match, ignoring the
1225              `this' parameter.  */
1226           friend_args_type = TYPE_ARG_TYPES (friend_type);
1227           decl_args_type = TYPE_ARG_TYPES (decl_type);
1228           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1229             friend_args_type = TREE_CHAIN (friend_args_type);
1230           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1231             decl_args_type = TREE_CHAIN (decl_args_type);
1232
1233           return compparms (decl_args_type, friend_args_type);
1234         }
1235       else
1236         {
1237           /* DECL is a TYPE_DECL */
1238           bool is_template;
1239           tree decl_type = TREE_TYPE (decl);
1240
1241           /* Make sure that both DECL and FRIEND_DECL are templates or
1242              non-templates.  */
1243           is_template
1244             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1245               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1246
1247           if (need_template ^ is_template)
1248             return false;
1249           else if (is_template)
1250             {
1251               tree friend_parms;
1252               /* If both are templates, check the name of the two
1253                  TEMPLATE_DECL's first because is_friend didn't.  */
1254               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1255                   != DECL_NAME (friend_decl))
1256                 return false;
1257
1258               /* Now check template parameter list.  */
1259               friend_parms
1260                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1261                                          args, tf_none);
1262               return comp_template_parms
1263                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1264                  friend_parms);
1265             }
1266           else
1267             return (DECL_NAME (decl)
1268                     == DECL_NAME (friend_decl));
1269         }
1270     }
1271   return false;
1272 }
1273
1274 /* Register the specialization SPEC as a specialization of TMPL with
1275    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1276    is actually just a friend declaration.  Returns SPEC, or an
1277    equivalent prior declaration, if available.  */
1278
1279 static tree
1280 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1281                          hashval_t hash)
1282 {
1283   tree fn;
1284   spec_entry **slot = NULL;
1285   spec_entry elt;
1286
1287   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1288
1289   if (TREE_CODE (spec) == FUNCTION_DECL
1290       && uses_template_parms (DECL_TI_ARGS (spec)))
1291     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1292        register it; we want the corresponding TEMPLATE_DECL instead.
1293        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1294        the more obvious `uses_template_parms (spec)' to avoid problems
1295        with default function arguments.  In particular, given
1296        something like this:
1297
1298           template <class T> void f(T t1, T t = T())
1299
1300        the default argument expression is not substituted for in an
1301        instantiation unless and until it is actually needed.  */
1302     return spec;
1303
1304   if (optimize_specialization_lookup_p (tmpl))
1305     /* We don't put these specializations in the hash table, but we might
1306        want to give an error about a mismatch.  */
1307     fn = retrieve_specialization (tmpl, args, 0);
1308   else
1309     {
1310       elt.tmpl = tmpl;
1311       elt.args = args;
1312       elt.spec = spec;
1313
1314       if (hash == 0)
1315         hash = hash_specialization (&elt);
1316
1317       slot = (spec_entry **)
1318         htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1319       if (*slot)
1320         fn = (*slot)->spec;
1321       else
1322         fn = NULL_TREE;
1323     }
1324
1325   /* We can sometimes try to re-register a specialization that we've
1326      already got.  In particular, regenerate_decl_from_template calls
1327      duplicate_decls which will update the specialization list.  But,
1328      we'll still get called again here anyhow.  It's more convenient
1329      to simply allow this than to try to prevent it.  */
1330   if (fn == spec)
1331     return spec;
1332   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1333     {
1334       if (DECL_TEMPLATE_INSTANTIATION (fn))
1335         {
1336           if (DECL_ODR_USED (fn)
1337               || DECL_EXPLICIT_INSTANTIATION (fn))
1338             {
1339               error ("specialization of %qD after instantiation",
1340                      fn);
1341               return error_mark_node;
1342             }
1343           else
1344             {
1345               tree clone;
1346               /* This situation should occur only if the first
1347                  specialization is an implicit instantiation, the
1348                  second is an explicit specialization, and the
1349                  implicit instantiation has not yet been used.  That
1350                  situation can occur if we have implicitly
1351                  instantiated a member function and then specialized
1352                  it later.
1353
1354                  We can also wind up here if a friend declaration that
1355                  looked like an instantiation turns out to be a
1356                  specialization:
1357
1358                    template <class T> void foo(T);
1359                    class S { friend void foo<>(int) };
1360                    template <> void foo(int);
1361
1362                  We transform the existing DECL in place so that any
1363                  pointers to it become pointers to the updated
1364                  declaration.
1365
1366                  If there was a definition for the template, but not
1367                  for the specialization, we want this to look as if
1368                  there were no definition, and vice versa.  */
1369               DECL_INITIAL (fn) = NULL_TREE;
1370               duplicate_decls (spec, fn, is_friend);
1371               /* The call to duplicate_decls will have applied
1372                  [temp.expl.spec]:
1373
1374                    An explicit specialization of a function template
1375                    is inline only if it is explicitly declared to be,
1376                    and independently of whether its function template
1377                    is.
1378
1379                 to the primary function; now copy the inline bits to
1380                 the various clones.  */
1381               FOR_EACH_CLONE (clone, fn)
1382                 {
1383                   DECL_DECLARED_INLINE_P (clone)
1384                     = DECL_DECLARED_INLINE_P (fn);
1385                   DECL_SOURCE_LOCATION (clone)
1386                     = DECL_SOURCE_LOCATION (fn);
1387                 }
1388               check_specialization_namespace (fn);
1389
1390               return fn;
1391             }
1392         }
1393       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1394         {
1395           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1396             /* Dup decl failed, but this is a new definition. Set the
1397                line number so any errors match this new
1398                definition.  */
1399             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1400
1401           return fn;
1402         }
1403     }
1404   else if (fn)
1405     return duplicate_decls (spec, fn, is_friend);
1406
1407   /* A specialization must be declared in the same namespace as the
1408      template it is specializing.  */
1409   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1410       && !check_specialization_namespace (tmpl))
1411     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1412
1413   if (!optimize_specialization_lookup_p (tmpl))
1414     {
1415       gcc_assert (tmpl && args && spec);
1416       *slot = ggc_alloc_spec_entry ();
1417       **slot = elt;
1418       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1419           && PRIMARY_TEMPLATE_P (tmpl)
1420           && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1421         /* TMPL is a forward declaration of a template function; keep a list
1422            of all specializations in case we need to reassign them to a friend
1423            template later in tsubst_friend_function.  */
1424         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1425           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1426     }
1427
1428   return spec;
1429 }
1430
1431 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1432    TMPL and ARGS members, ignores SPEC.  */
1433
1434 static int
1435 eq_specializations (const void *p1, const void *p2)
1436 {
1437   const spec_entry *e1 = (const spec_entry *)p1;
1438   const spec_entry *e2 = (const spec_entry *)p2;
1439
1440   return (e1->tmpl == e2->tmpl
1441           && comp_template_args (e1->args, e2->args));
1442 }
1443
1444 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1445
1446 static hashval_t
1447 hash_tmpl_and_args (tree tmpl, tree args)
1448 {
1449   hashval_t val = DECL_UID (tmpl);
1450   return iterative_hash_template_arg (args, val);
1451 }
1452
1453 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1454    ignoring SPEC.  */
1455
1456 static hashval_t
1457 hash_specialization (const void *p)
1458 {
1459   const spec_entry *e = (const spec_entry *)p;
1460   return hash_tmpl_and_args (e->tmpl, e->args);
1461 }
1462
1463 /* Recursively calculate a hash value for a template argument ARG, for use
1464    in the hash tables of template specializations.  */
1465
1466 hashval_t
1467 iterative_hash_template_arg (tree arg, hashval_t val)
1468 {
1469   unsigned HOST_WIDE_INT i;
1470   enum tree_code code;
1471   char tclass;
1472
1473   if (arg == NULL_TREE)
1474     return iterative_hash_object (arg, val);
1475
1476   if (!TYPE_P (arg))
1477     STRIP_NOPS (arg);
1478
1479   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1480     /* We can get one of these when re-hashing a previous entry in the middle
1481        of substituting into a pack expansion.  Just look through it.  */
1482     arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1483
1484   code = TREE_CODE (arg);
1485   tclass = TREE_CODE_CLASS (code);
1486
1487   val = iterative_hash_object (code, val);
1488
1489   switch (code)
1490     {
1491     case ERROR_MARK:
1492       return val;
1493
1494     case IDENTIFIER_NODE:
1495       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1496
1497     case TREE_VEC:
1498       {
1499         int i, len = TREE_VEC_LENGTH (arg);
1500         for (i = 0; i < len; ++i)
1501           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1502         return val;
1503       }
1504
1505     case TYPE_PACK_EXPANSION:
1506     case EXPR_PACK_EXPANSION:
1507       return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1508
1509     case TYPE_ARGUMENT_PACK:
1510     case NONTYPE_ARGUMENT_PACK:
1511       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1512
1513     case TREE_LIST:
1514       for (; arg; arg = TREE_CHAIN (arg))
1515         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1516       return val;
1517
1518     case OVERLOAD:
1519       for (; arg; arg = OVL_CHAIN (arg))
1520         val = iterative_hash_template_arg (OVL_FUNCTION (arg), val);
1521       return val;
1522
1523     case CONSTRUCTOR:
1524       {
1525         tree field, value;
1526         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1527           {
1528             val = iterative_hash_template_arg (field, val);
1529             val = iterative_hash_template_arg (value, val);
1530           }
1531         return val;
1532       }
1533
1534     case PARM_DECL:
1535       if (!DECL_ARTIFICIAL (arg))
1536         {
1537           val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1538           val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1539         }
1540       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1541
1542     case TARGET_EXPR:
1543       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1544
1545     case PTRMEM_CST:
1546       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1547       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1548
1549     case TEMPLATE_PARM_INDEX:
1550       val = iterative_hash_template_arg
1551         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1552       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1553       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1554
1555     case TRAIT_EXPR:
1556       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1557       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1558       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1559
1560     case BASELINK:
1561       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1562                                          val);
1563       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1564                                           val);
1565
1566     case MODOP_EXPR:
1567       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1568       code = TREE_CODE (TREE_OPERAND (arg, 1));
1569       val = iterative_hash_object (code, val);
1570       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1571
1572     case ARRAY_TYPE:
1573       /* layout_type sets structural equality for arrays of
1574          incomplete type, so we can't rely on the canonical type
1575          for hashing.  */
1576       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1577       return iterative_hash_template_arg (TYPE_DOMAIN (arg), val);
1578
1579     case LAMBDA_EXPR:
1580       /* A lambda can't appear in a template arg, but don't crash on
1581          erroneous input.  */
1582       gcc_assert (seen_error ());
1583       return val;
1584
1585     case CAST_EXPR:
1586     case STATIC_CAST_EXPR:
1587     case REINTERPRET_CAST_EXPR:
1588     case CONST_CAST_EXPR:
1589     case DYNAMIC_CAST_EXPR:
1590     case NEW_EXPR:
1591       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1592       /* Now hash operands as usual.  */
1593       break;
1594
1595     default:
1596       break;
1597     }
1598
1599   switch (tclass)
1600     {
1601     case tcc_type:
1602       if (TYPE_CANONICAL (arg))
1603         return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1604                                       val);
1605       else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1606         return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1607       /* Otherwise just compare the types during lookup.  */
1608       return val;
1609
1610     case tcc_declaration:
1611     case tcc_constant:
1612       return iterative_hash_expr (arg, val);
1613
1614     default:
1615       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1616       {
1617         unsigned n = TREE_OPERAND_LENGTH (arg);
1618         for (i = 0; i < n; ++i)
1619           val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1620         return val;
1621       }
1622     }
1623   gcc_unreachable ();
1624   return 0;
1625 }
1626
1627 /* Unregister the specialization SPEC as a specialization of TMPL.
1628    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1629    if the SPEC was listed as a specialization of TMPL.
1630
1631    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1632
1633 bool
1634 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1635 {
1636   spec_entry **slot;
1637   spec_entry elt;
1638
1639   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1640   elt.args = TI_ARGS (tinfo);
1641   elt.spec = NULL_TREE;
1642
1643   slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1644   if (*slot)
1645     {
1646       gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1647       gcc_assert (new_spec != NULL_TREE);
1648       (*slot)->spec = new_spec;
1649       return 1;
1650     }
1651
1652   return 0;
1653 }
1654
1655 /* Compare an entry in the local specializations hash table P1 (which
1656    is really a pointer to a TREE_LIST) with P2 (which is really a
1657    DECL).  */
1658
1659 static int
1660 eq_local_specializations (const void *p1, const void *p2)
1661 {
1662   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1663 }
1664
1665 /* Hash P1, an entry in the local specializations table.  */
1666
1667 static hashval_t
1668 hash_local_specialization (const void* p1)
1669 {
1670   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1671 }
1672
1673 /* Like register_specialization, but for local declarations.  We are
1674    registering SPEC, an instantiation of TMPL.  */
1675
1676 static void
1677 register_local_specialization (tree spec, tree tmpl)
1678 {
1679   void **slot;
1680
1681   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1682                                    htab_hash_pointer (tmpl), INSERT);
1683   *slot = build_tree_list (spec, tmpl);
1684 }
1685
1686 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1687    specialized class.  */
1688
1689 bool
1690 explicit_class_specialization_p (tree type)
1691 {
1692   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1693     return false;
1694   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1695 }
1696
1697 /* Print the list of functions at FNS, going through all the overloads
1698    for each element of the list.  Alternatively, FNS can not be a
1699    TREE_LIST, in which case it will be printed together with all the
1700    overloads.
1701
1702    MORE and *STR should respectively be FALSE and NULL when the function
1703    is called from the outside.  They are used internally on recursive
1704    calls.  print_candidates manages the two parameters and leaves NULL
1705    in *STR when it ends.  */
1706
1707 static void
1708 print_candidates_1 (tree fns, bool more, const char **str)
1709 {
1710   tree fn, fn2;
1711   char *spaces = NULL;
1712
1713   for (fn = fns; fn; fn = OVL_NEXT (fn))
1714     if (TREE_CODE (fn) == TREE_LIST)
1715       {
1716         gcc_assert (!OVL_NEXT (fn) && !is_overloaded_fn (fn));
1717         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1718           print_candidates_1 (TREE_VALUE (fn2),
1719                               TREE_CHAIN (fn2) || more, str);
1720       }
1721     else
1722       {
1723         if (!*str)
1724           {
1725             /* Pick the prefix string.  */
1726             if (!more && !OVL_NEXT (fns))
1727               {
1728                 error ("candidate is: %+#D", OVL_CURRENT (fn));
1729                 continue;
1730               }
1731
1732             *str = _("candidates are:");
1733             spaces = get_spaces (*str);
1734           }
1735         error ("%s %+#D", *str, OVL_CURRENT (fn));
1736         *str = spaces ? spaces : *str;
1737       }
1738
1739   if (!more)
1740     {
1741       free (spaces);
1742       *str = NULL;
1743     }
1744 }
1745
1746 /* Print the list of candidate FNS in an error message.  */
1747
1748 void
1749 print_candidates (tree fns)
1750 {
1751   const char *str = NULL;
1752   print_candidates_1 (fns, false, &str);
1753   gcc_assert (str == NULL);
1754 }
1755
1756 /* Returns the template (one of the functions given by TEMPLATE_ID)
1757    which can be specialized to match the indicated DECL with the
1758    explicit template args given in TEMPLATE_ID.  The DECL may be
1759    NULL_TREE if none is available.  In that case, the functions in
1760    TEMPLATE_ID are non-members.
1761
1762    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1763    specialization of a member template.
1764
1765    The TEMPLATE_COUNT is the number of references to qualifying
1766    template classes that appeared in the name of the function. See
1767    check_explicit_specialization for a more accurate description.
1768
1769    TSK indicates what kind of template declaration (if any) is being
1770    declared.  TSK_TEMPLATE indicates that the declaration given by
1771    DECL, though a FUNCTION_DECL, has template parameters, and is
1772    therefore a template function.
1773
1774    The template args (those explicitly specified and those deduced)
1775    are output in a newly created vector *TARGS_OUT.
1776
1777    If it is impossible to determine the result, an error message is
1778    issued.  The error_mark_node is returned to indicate failure.  */
1779
1780 static tree
1781 determine_specialization (tree template_id,
1782                           tree decl,
1783                           tree* targs_out,
1784                           int need_member_template,
1785                           int template_count,
1786                           tmpl_spec_kind tsk)
1787 {
1788   tree fns;
1789   tree targs;
1790   tree explicit_targs;
1791   tree candidates = NULL_TREE;
1792   /* A TREE_LIST of templates of which DECL may be a specialization.
1793      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1794      corresponding TREE_PURPOSE is the set of template arguments that,
1795      when used to instantiate the template, would produce a function
1796      with the signature of DECL.  */
1797   tree templates = NULL_TREE;
1798   int header_count;
1799   struct cp_binding_level *b;
1800
1801   *targs_out = NULL_TREE;
1802
1803   if (template_id == error_mark_node || decl == error_mark_node)
1804     return error_mark_node;
1805
1806   fns = TREE_OPERAND (template_id, 0);
1807   explicit_targs = TREE_OPERAND (template_id, 1);
1808
1809   if (fns == error_mark_node)
1810     return error_mark_node;
1811
1812   /* Check for baselinks.  */
1813   if (BASELINK_P (fns))
1814     fns = BASELINK_FUNCTIONS (fns);
1815
1816   if (!is_overloaded_fn (fns))
1817     {
1818       error ("%qD is not a function template", fns);
1819       return error_mark_node;
1820     }
1821
1822   /* Count the number of template headers specified for this
1823      specialization.  */
1824   header_count = 0;
1825   for (b = current_binding_level;
1826        b->kind == sk_template_parms;
1827        b = b->level_chain)
1828     ++header_count;
1829
1830   for (; fns; fns = OVL_NEXT (fns))
1831     {
1832       tree fn = OVL_CURRENT (fns);
1833
1834       if (TREE_CODE (fn) == TEMPLATE_DECL)
1835         {
1836           tree decl_arg_types;
1837           tree fn_arg_types;
1838
1839           /* In case of explicit specialization, we need to check if
1840              the number of template headers appearing in the specialization
1841              is correct. This is usually done in check_explicit_specialization,
1842              but the check done there cannot be exhaustive when specializing
1843              member functions. Consider the following code:
1844
1845              template <> void A<int>::f(int);
1846              template <> template <> void A<int>::f(int);
1847
1848              Assuming that A<int> is not itself an explicit specialization
1849              already, the first line specializes "f" which is a non-template
1850              member function, whilst the second line specializes "f" which
1851              is a template member function. So both lines are syntactically
1852              correct, and check_explicit_specialization does not reject
1853              them.
1854
1855              Here, we can do better, as we are matching the specialization
1856              against the declarations. We count the number of template
1857              headers, and we check if they match TEMPLATE_COUNT + 1
1858              (TEMPLATE_COUNT is the number of qualifying template classes,
1859              plus there must be another header for the member template
1860              itself).
1861
1862              Notice that if header_count is zero, this is not a
1863              specialization but rather a template instantiation, so there
1864              is no check we can perform here.  */
1865           if (header_count && header_count != template_count + 1)
1866             continue;
1867
1868           /* Check that the number of template arguments at the
1869              innermost level for DECL is the same as for FN.  */
1870           if (current_binding_level->kind == sk_template_parms
1871               && !current_binding_level->explicit_spec_p
1872               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1873                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1874                                       (current_template_parms))))
1875             continue;
1876
1877           /* DECL might be a specialization of FN.  */
1878           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1879           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1880
1881           /* For a non-static member function, we need to make sure
1882              that the const qualification is the same.  Since
1883              get_bindings does not try to merge the "this" parameter,
1884              we must do the comparison explicitly.  */
1885           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1886               && !same_type_p (TREE_VALUE (fn_arg_types),
1887                                TREE_VALUE (decl_arg_types)))
1888             continue;
1889
1890           /* Skip the "this" parameter and, for constructors of
1891              classes with virtual bases, the VTT parameter.  A
1892              full specialization of a constructor will have a VTT
1893              parameter, but a template never will.  */ 
1894           decl_arg_types 
1895             = skip_artificial_parms_for (decl, decl_arg_types);
1896           fn_arg_types 
1897             = skip_artificial_parms_for (fn, fn_arg_types);
1898
1899           /* Check that the number of function parameters matches.
1900              For example,
1901                template <class T> void f(int i = 0);
1902                template <> void f<int>();
1903              The specialization f<int> is invalid but is not caught
1904              by get_bindings below.  */
1905           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1906             continue;
1907
1908           /* Function templates cannot be specializations; there are
1909              no partial specializations of functions.  Therefore, if
1910              the type of DECL does not match FN, there is no
1911              match.  */
1912           if (tsk == tsk_template)
1913             {
1914               if (compparms (fn_arg_types, decl_arg_types))
1915                 candidates = tree_cons (NULL_TREE, fn, candidates);
1916               continue;
1917             }
1918
1919           /* See whether this function might be a specialization of this
1920              template.  */
1921           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1922
1923           if (!targs)
1924             /* We cannot deduce template arguments that when used to
1925                specialize TMPL will produce DECL.  */
1926             continue;
1927
1928           /* Save this template, and the arguments deduced.  */
1929           templates = tree_cons (targs, fn, templates);
1930         }
1931       else if (need_member_template)
1932         /* FN is an ordinary member function, and we need a
1933            specialization of a member template.  */
1934         ;
1935       else if (TREE_CODE (fn) != FUNCTION_DECL)
1936         /* We can get IDENTIFIER_NODEs here in certain erroneous
1937            cases.  */
1938         ;
1939       else if (!DECL_FUNCTION_MEMBER_P (fn))
1940         /* This is just an ordinary non-member function.  Nothing can
1941            be a specialization of that.  */
1942         ;
1943       else if (DECL_ARTIFICIAL (fn))
1944         /* Cannot specialize functions that are created implicitly.  */
1945         ;
1946       else
1947         {
1948           tree decl_arg_types;
1949
1950           /* This is an ordinary member function.  However, since
1951              we're here, we can assume it's enclosing class is a
1952              template class.  For example,
1953
1954                template <typename T> struct S { void f(); };
1955                template <> void S<int>::f() {}
1956
1957              Here, S<int>::f is a non-template, but S<int> is a
1958              template class.  If FN has the same type as DECL, we
1959              might be in business.  */
1960
1961           if (!DECL_TEMPLATE_INFO (fn))
1962             /* Its enclosing class is an explicit specialization
1963                of a template class.  This is not a candidate.  */
1964             continue;
1965
1966           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1967                             TREE_TYPE (TREE_TYPE (fn))))
1968             /* The return types differ.  */
1969             continue;
1970
1971           /* Adjust the type of DECL in case FN is a static member.  */
1972           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1973           if (DECL_STATIC_FUNCTION_P (fn)
1974               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1975             decl_arg_types = TREE_CHAIN (decl_arg_types);
1976
1977           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1978                          decl_arg_types))
1979             /* They match!  */
1980             candidates = tree_cons (NULL_TREE, fn, candidates);
1981         }
1982     }
1983
1984   if (templates && TREE_CHAIN (templates))
1985     {
1986       /* We have:
1987
1988            [temp.expl.spec]
1989
1990            It is possible for a specialization with a given function
1991            signature to be instantiated from more than one function
1992            template.  In such cases, explicit specification of the
1993            template arguments must be used to uniquely identify the
1994            function template specialization being specialized.
1995
1996          Note that here, there's no suggestion that we're supposed to
1997          determine which of the candidate templates is most
1998          specialized.  However, we, also have:
1999
2000            [temp.func.order]
2001
2002            Partial ordering of overloaded function template
2003            declarations is used in the following contexts to select
2004            the function template to which a function template
2005            specialization refers:
2006
2007            -- when an explicit specialization refers to a function
2008               template.
2009
2010          So, we do use the partial ordering rules, at least for now.
2011          This extension can only serve to make invalid programs valid,
2012          so it's safe.  And, there is strong anecdotal evidence that
2013          the committee intended the partial ordering rules to apply;
2014          the EDG front end has that behavior, and John Spicer claims
2015          that the committee simply forgot to delete the wording in
2016          [temp.expl.spec].  */
2017       tree tmpl = most_specialized_instantiation (templates);
2018       if (tmpl != error_mark_node)
2019         {
2020           templates = tmpl;
2021           TREE_CHAIN (templates) = NULL_TREE;
2022         }
2023     }
2024
2025   if (templates == NULL_TREE && candidates == NULL_TREE)
2026     {
2027       error ("template-id %qD for %q+D does not match any template "
2028              "declaration", template_id, decl);
2029       if (header_count && header_count != template_count + 1)
2030         inform (input_location, "saw %d %<template<>%>, need %d for "
2031                 "specializing a member function template",
2032                 header_count, template_count + 1);
2033       return error_mark_node;
2034     }
2035   else if ((templates && TREE_CHAIN (templates))
2036            || (candidates && TREE_CHAIN (candidates))
2037            || (templates && candidates))
2038     {
2039       error ("ambiguous template specialization %qD for %q+D",
2040              template_id, decl);
2041       candidates = chainon (candidates, templates);
2042       print_candidates (candidates);
2043       return error_mark_node;
2044     }
2045
2046   /* We have one, and exactly one, match.  */
2047   if (candidates)
2048     {
2049       tree fn = TREE_VALUE (candidates);
2050       *targs_out = copy_node (DECL_TI_ARGS (fn));
2051       /* DECL is a re-declaration or partial instantiation of a template
2052          function.  */
2053       if (TREE_CODE (fn) == TEMPLATE_DECL)
2054         return fn;
2055       /* It was a specialization of an ordinary member function in a
2056          template class.  */
2057       return DECL_TI_TEMPLATE (fn);
2058     }
2059
2060   /* It was a specialization of a template.  */
2061   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2062   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2063     {
2064       *targs_out = copy_node (targs);
2065       SET_TMPL_ARGS_LEVEL (*targs_out,
2066                            TMPL_ARGS_DEPTH (*targs_out),
2067                            TREE_PURPOSE (templates));
2068     }
2069   else
2070     *targs_out = TREE_PURPOSE (templates);
2071   return TREE_VALUE (templates);
2072 }
2073
2074 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2075    but with the default argument values filled in from those in the
2076    TMPL_TYPES.  */
2077
2078 static tree
2079 copy_default_args_to_explicit_spec_1 (tree spec_types,
2080                                       tree tmpl_types)
2081 {
2082   tree new_spec_types;
2083
2084   if (!spec_types)
2085     return NULL_TREE;
2086
2087   if (spec_types == void_list_node)
2088     return void_list_node;
2089
2090   /* Substitute into the rest of the list.  */
2091   new_spec_types =
2092     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2093                                           TREE_CHAIN (tmpl_types));
2094
2095   /* Add the default argument for this parameter.  */
2096   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2097                          TREE_VALUE (spec_types),
2098                          new_spec_types);
2099 }
2100
2101 /* DECL is an explicit specialization.  Replicate default arguments
2102    from the template it specializes.  (That way, code like:
2103
2104      template <class T> void f(T = 3);
2105      template <> void f(double);
2106      void g () { f (); }
2107
2108    works, as required.)  An alternative approach would be to look up
2109    the correct default arguments at the call-site, but this approach
2110    is consistent with how implicit instantiations are handled.  */
2111
2112 static void
2113 copy_default_args_to_explicit_spec (tree decl)
2114 {
2115   tree tmpl;
2116   tree spec_types;
2117   tree tmpl_types;
2118   tree new_spec_types;
2119   tree old_type;
2120   tree new_type;
2121   tree t;
2122   tree object_type = NULL_TREE;
2123   tree in_charge = NULL_TREE;
2124   tree vtt = NULL_TREE;
2125
2126   /* See if there's anything we need to do.  */
2127   tmpl = DECL_TI_TEMPLATE (decl);
2128   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2129   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2130     if (TREE_PURPOSE (t))
2131       break;
2132   if (!t)
2133     return;
2134
2135   old_type = TREE_TYPE (decl);
2136   spec_types = TYPE_ARG_TYPES (old_type);
2137
2138   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2139     {
2140       /* Remove the this pointer, but remember the object's type for
2141          CV quals.  */
2142       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2143       spec_types = TREE_CHAIN (spec_types);
2144       tmpl_types = TREE_CHAIN (tmpl_types);
2145
2146       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2147         {
2148           /* DECL may contain more parameters than TMPL due to the extra
2149              in-charge parameter in constructors and destructors.  */
2150           in_charge = spec_types;
2151           spec_types = TREE_CHAIN (spec_types);
2152         }
2153       if (DECL_HAS_VTT_PARM_P (decl))
2154         {
2155           vtt = spec_types;
2156           spec_types = TREE_CHAIN (spec_types);
2157         }
2158     }
2159
2160   /* Compute the merged default arguments.  */
2161   new_spec_types =
2162     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2163
2164   /* Compute the new FUNCTION_TYPE.  */
2165   if (object_type)
2166     {
2167       if (vtt)
2168         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2169                                          TREE_VALUE (vtt),
2170                                          new_spec_types);
2171
2172       if (in_charge)
2173         /* Put the in-charge parameter back.  */
2174         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2175                                          TREE_VALUE (in_charge),
2176                                          new_spec_types);
2177
2178       new_type = build_method_type_directly (object_type,
2179                                              TREE_TYPE (old_type),
2180                                              new_spec_types);
2181     }
2182   else
2183     new_type = build_function_type (TREE_TYPE (old_type),
2184                                     new_spec_types);
2185   new_type = cp_build_type_attribute_variant (new_type,
2186                                               TYPE_ATTRIBUTES (old_type));
2187   new_type = build_exception_variant (new_type,
2188                                       TYPE_RAISES_EXCEPTIONS (old_type));
2189   TREE_TYPE (decl) = new_type;
2190 }
2191
2192 /* Check to see if the function just declared, as indicated in
2193    DECLARATOR, and in DECL, is a specialization of a function
2194    template.  We may also discover that the declaration is an explicit
2195    instantiation at this point.
2196
2197    Returns DECL, or an equivalent declaration that should be used
2198    instead if all goes well.  Issues an error message if something is
2199    amiss.  Returns error_mark_node if the error is not easily
2200    recoverable.
2201
2202    FLAGS is a bitmask consisting of the following flags:
2203
2204    2: The function has a definition.
2205    4: The function is a friend.
2206
2207    The TEMPLATE_COUNT is the number of references to qualifying
2208    template classes that appeared in the name of the function.  For
2209    example, in
2210
2211      template <class T> struct S { void f(); };
2212      void S<int>::f();
2213
2214    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2215    classes are not counted in the TEMPLATE_COUNT, so that in
2216
2217      template <class T> struct S {};
2218      template <> struct S<int> { void f(); }
2219      template <> void S<int>::f();
2220
2221    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2222    invalid; there should be no template <>.)
2223
2224    If the function is a specialization, it is marked as such via
2225    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2226    is set up correctly, and it is added to the list of specializations
2227    for that template.  */
2228
2229 tree
2230 check_explicit_specialization (tree declarator,
2231                                tree decl,
2232                                int template_count,
2233                                int flags)
2234 {
2235   int have_def = flags & 2;
2236   int is_friend = flags & 4;
2237   int specialization = 0;
2238   int explicit_instantiation = 0;
2239   int member_specialization = 0;
2240   tree ctype = DECL_CLASS_CONTEXT (decl);
2241   tree dname = DECL_NAME (decl);
2242   tmpl_spec_kind tsk;
2243
2244   if (is_friend)
2245     {
2246       if (!processing_specialization)
2247         tsk = tsk_none;
2248       else
2249         tsk = tsk_excessive_parms;
2250     }
2251   else
2252     tsk = current_tmpl_spec_kind (template_count);
2253
2254   switch (tsk)
2255     {
2256     case tsk_none:
2257       if (processing_specialization)
2258         {
2259           specialization = 1;
2260           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2261         }
2262       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2263         {
2264           if (is_friend)
2265             /* This could be something like:
2266
2267                template <class T> void f(T);
2268                class S { friend void f<>(int); }  */
2269             specialization = 1;
2270           else
2271             {
2272               /* This case handles bogus declarations like template <>
2273                  template <class T> void f<int>(); */
2274
2275               error ("template-id %qD in declaration of primary template",
2276                      declarator);
2277               return decl;
2278             }
2279         }
2280       break;
2281
2282     case tsk_invalid_member_spec:
2283       /* The error has already been reported in
2284          check_specialization_scope.  */
2285       return error_mark_node;
2286
2287     case tsk_invalid_expl_inst:
2288       error ("template parameter list used in explicit instantiation");
2289
2290       /* Fall through.  */
2291
2292     case tsk_expl_inst:
2293       if (have_def)
2294         error ("definition provided for explicit instantiation");
2295
2296       explicit_instantiation = 1;
2297       break;
2298
2299     case tsk_excessive_parms:
2300     case tsk_insufficient_parms:
2301       if (tsk == tsk_excessive_parms)
2302         error ("too many template parameter lists in declaration of %qD",
2303                decl);
2304       else if (template_header_count)
2305         error("too few template parameter lists in declaration of %qD", decl);
2306       else
2307         error("explicit specialization of %qD must be introduced by "
2308               "%<template <>%>", decl);
2309
2310       /* Fall through.  */
2311     case tsk_expl_spec:
2312       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2313       if (ctype)
2314         member_specialization = 1;
2315       else
2316         specialization = 1;
2317       break;
2318
2319     case tsk_template:
2320       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2321         {
2322           /* This case handles bogus declarations like template <>
2323              template <class T> void f<int>(); */
2324
2325           if (uses_template_parms (declarator))
2326             error ("function template partial specialization %qD "
2327                    "is not allowed", declarator);
2328           else
2329             error ("template-id %qD in declaration of primary template",
2330                    declarator);
2331           return decl;
2332         }
2333
2334       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2335         /* This is a specialization of a member template, without
2336            specialization the containing class.  Something like:
2337
2338              template <class T> struct S {
2339                template <class U> void f (U);
2340              };
2341              template <> template <class U> void S<int>::f(U) {}
2342
2343            That's a specialization -- but of the entire template.  */
2344         specialization = 1;
2345       break;
2346
2347     default:
2348       gcc_unreachable ();
2349     }
2350
2351   if (specialization || member_specialization)
2352     {
2353       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2354       for (; t; t = TREE_CHAIN (t))
2355         if (TREE_PURPOSE (t))
2356           {
2357             permerror (input_location, 
2358                        "default argument specified in explicit specialization");
2359             break;
2360           }
2361     }
2362
2363   if (specialization || member_specialization || explicit_instantiation)
2364     {
2365       tree tmpl = NULL_TREE;
2366       tree targs = NULL_TREE;
2367
2368       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2369       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2370         {
2371           tree fns;
2372
2373           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2374           if (ctype)
2375             fns = dname;
2376           else
2377             {
2378               /* If there is no class context, the explicit instantiation
2379                  must be at namespace scope.  */
2380               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2381
2382               /* Find the namespace binding, using the declaration
2383                  context.  */
2384               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2385                                            false, true);
2386               if (fns == error_mark_node || !is_overloaded_fn (fns))
2387                 {
2388                   error ("%qD is not a template function", dname);
2389                   fns = error_mark_node;
2390                 }
2391               else
2392                 {
2393                   tree fn = OVL_CURRENT (fns);
2394                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2395                                                 CP_DECL_CONTEXT (fn)))
2396                     error ("%qD is not declared in %qD",
2397                            decl, current_namespace);
2398                 }
2399             }
2400
2401           declarator = lookup_template_function (fns, NULL_TREE);
2402         }
2403
2404       if (declarator == error_mark_node)
2405         return error_mark_node;
2406
2407       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2408         {
2409           if (!explicit_instantiation)
2410             /* A specialization in class scope.  This is invalid,
2411                but the error will already have been flagged by
2412                check_specialization_scope.  */
2413             return error_mark_node;
2414           else
2415             {
2416               /* It's not valid to write an explicit instantiation in
2417                  class scope, e.g.:
2418
2419                    class C { template void f(); }
2420
2421                    This case is caught by the parser.  However, on
2422                    something like:
2423
2424                    template class C { void f(); };
2425
2426                    (which is invalid) we can get here.  The error will be
2427                    issued later.  */
2428               ;
2429             }
2430
2431           return decl;
2432         }
2433       else if (ctype != NULL_TREE
2434                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2435                    IDENTIFIER_NODE))
2436         {
2437           /* Find the list of functions in ctype that have the same
2438              name as the declared function.  */
2439           tree name = TREE_OPERAND (declarator, 0);
2440           tree fns = NULL_TREE;
2441           int idx;
2442
2443           if (constructor_name_p (name, ctype))
2444             {
2445               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2446
2447               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2448                   : !CLASSTYPE_DESTRUCTORS (ctype))
2449                 {
2450                   /* From [temp.expl.spec]:
2451
2452                      If such an explicit specialization for the member
2453                      of a class template names an implicitly-declared
2454                      special member function (clause _special_), the
2455                      program is ill-formed.
2456
2457                      Similar language is found in [temp.explicit].  */
2458                   error ("specialization of implicitly-declared special member function");
2459                   return error_mark_node;
2460                 }
2461
2462               name = is_constructor ? ctor_identifier : dtor_identifier;
2463             }
2464
2465           if (!DECL_CONV_FN_P (decl))
2466             {
2467               idx = lookup_fnfields_1 (ctype, name);
2468               if (idx >= 0)
2469                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2470             }
2471           else
2472             {
2473               VEC(tree,gc) *methods;
2474               tree ovl;
2475
2476               /* For a type-conversion operator, we cannot do a
2477                  name-based lookup.  We might be looking for `operator
2478                  int' which will be a specialization of `operator T'.
2479                  So, we find *all* the conversion operators, and then
2480                  select from them.  */
2481               fns = NULL_TREE;
2482
2483               methods = CLASSTYPE_METHOD_VEC (ctype);
2484               if (methods)
2485                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2486                      VEC_iterate (tree, methods, idx, ovl);
2487                      ++idx)
2488                   {
2489                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2490                       /* There are no more conversion functions.  */
2491                       break;
2492
2493                     /* Glue all these conversion functions together
2494                        with those we already have.  */
2495                     for (; ovl; ovl = OVL_NEXT (ovl))
2496                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2497                   }
2498             }
2499
2500           if (fns == NULL_TREE)
2501             {
2502               error ("no member function %qD declared in %qT", name, ctype);
2503               return error_mark_node;
2504             }
2505           else
2506             TREE_OPERAND (declarator, 0) = fns;
2507         }
2508
2509       /* Figure out what exactly is being specialized at this point.
2510          Note that for an explicit instantiation, even one for a
2511          member function, we cannot tell apriori whether the
2512          instantiation is for a member template, or just a member
2513          function of a template class.  Even if a member template is
2514          being instantiated, the member template arguments may be
2515          elided if they can be deduced from the rest of the
2516          declaration.  */
2517       tmpl = determine_specialization (declarator, decl,
2518                                        &targs,
2519                                        member_specialization,
2520                                        template_count,
2521                                        tsk);
2522
2523       if (!tmpl || tmpl == error_mark_node)
2524         /* We couldn't figure out what this declaration was
2525            specializing.  */
2526         return error_mark_node;
2527       else
2528         {
2529           tree gen_tmpl = most_general_template (tmpl);
2530
2531           if (explicit_instantiation)
2532             {
2533               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2534                  is done by do_decl_instantiation later.  */
2535
2536               int arg_depth = TMPL_ARGS_DEPTH (targs);
2537               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2538
2539               if (arg_depth > parm_depth)
2540                 {
2541                   /* If TMPL is not the most general template (for
2542                      example, if TMPL is a friend template that is
2543                      injected into namespace scope), then there will
2544                      be too many levels of TARGS.  Remove some of them
2545                      here.  */
2546                   int i;
2547                   tree new_targs;
2548
2549                   new_targs = make_tree_vec (parm_depth);
2550                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2551                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2552                       = TREE_VEC_ELT (targs, i);
2553                   targs = new_targs;
2554                 }
2555
2556               return instantiate_template (tmpl, targs, tf_error);
2557             }
2558
2559           /* If we thought that the DECL was a member function, but it
2560              turns out to be specializing a static member function,
2561              make DECL a static member function as well.  */
2562           if (DECL_STATIC_FUNCTION_P (tmpl)
2563               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2564             revert_static_member_fn (decl);
2565
2566           /* If this is a specialization of a member template of a
2567              template class, we want to return the TEMPLATE_DECL, not
2568              the specialization of it.  */
2569           if (tsk == tsk_template)
2570             {
2571               tree result = DECL_TEMPLATE_RESULT (tmpl);
2572               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2573               DECL_INITIAL (result) = NULL_TREE;
2574               if (have_def)
2575                 {
2576                   tree parm;
2577                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2578                   DECL_SOURCE_LOCATION (result)
2579                     = DECL_SOURCE_LOCATION (decl);
2580                   /* We want to use the argument list specified in the
2581                      definition, not in the original declaration.  */
2582                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2583                   for (parm = DECL_ARGUMENTS (result); parm;
2584                        parm = DECL_CHAIN (parm))
2585                     DECL_CONTEXT (parm) = result;
2586                 }
2587               return register_specialization (tmpl, gen_tmpl, targs,
2588                                               is_friend, 0);
2589             }
2590
2591           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2592           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2593
2594           /* Inherit default function arguments from the template
2595              DECL is specializing.  */
2596           copy_default_args_to_explicit_spec (decl);
2597
2598           /* This specialization has the same protection as the
2599              template it specializes.  */
2600           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2601           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2602
2603           /* 7.1.1-1 [dcl.stc]
2604
2605              A storage-class-specifier shall not be specified in an
2606              explicit specialization...
2607
2608              The parser rejects these, so unless action is taken here,
2609              explicit function specializations will always appear with
2610              global linkage.
2611
2612              The action recommended by the C++ CWG in response to C++
2613              defect report 605 is to make the storage class and linkage
2614              of the explicit specialization match the templated function:
2615
2616              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2617            */
2618           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2619             {
2620               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2621               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2622
2623               /* This specialization has the same linkage and visibility as
2624                  the function template it specializes.  */
2625               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2626               if (! TREE_PUBLIC (decl))
2627                 {
2628                   DECL_INTERFACE_KNOWN (decl) = 1;
2629                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2630                 }
2631               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2632               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2633                 {
2634                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2635                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2636                 }
2637             }
2638
2639           /* If DECL is a friend declaration, declared using an
2640              unqualified name, the namespace associated with DECL may
2641              have been set incorrectly.  For example, in:
2642
2643                template <typename T> void f(T);
2644                namespace N {
2645                  struct S { friend void f<int>(int); }
2646                }
2647
2648              we will have set the DECL_CONTEXT for the friend
2649              declaration to N, rather than to the global namespace.  */
2650           if (DECL_NAMESPACE_SCOPE_P (decl))
2651             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2652
2653           if (is_friend && !have_def)
2654             /* This is not really a declaration of a specialization.
2655                It's just the name of an instantiation.  But, it's not
2656                a request for an instantiation, either.  */
2657             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2658           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2659             /* This is indeed a specialization.  In case of constructors
2660                and destructors, we need in-charge and not-in-charge
2661                versions in V3 ABI.  */
2662             clone_function_decl (decl, /*update_method_vec_p=*/0);
2663
2664           /* Register this specialization so that we can find it
2665              again.  */
2666           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2667         }
2668     }
2669
2670   return decl;
2671 }
2672
2673 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2674    parameters.  These are represented in the same format used for
2675    DECL_TEMPLATE_PARMS.  */
2676
2677 int
2678 comp_template_parms (const_tree parms1, const_tree parms2)
2679 {
2680   const_tree p1;
2681   const_tree p2;
2682
2683   if (parms1 == parms2)
2684     return 1;
2685
2686   for (p1 = parms1, p2 = parms2;
2687        p1 != NULL_TREE && p2 != NULL_TREE;
2688        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2689     {
2690       tree t1 = TREE_VALUE (p1);
2691       tree t2 = TREE_VALUE (p2);
2692       int i;
2693
2694       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2695       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2696
2697       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2698         return 0;
2699
2700       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2701         {
2702           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2703           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2704
2705           /* If either of the template parameters are invalid, assume
2706              they match for the sake of error recovery. */
2707           if (parm1 == error_mark_node || parm2 == error_mark_node)
2708             return 1;
2709
2710           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2711             return 0;
2712
2713           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2714               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2715                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2716             continue;
2717           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2718             return 0;
2719         }
2720     }
2721
2722   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2723     /* One set of parameters has more parameters lists than the
2724        other.  */
2725     return 0;
2726
2727   return 1;
2728 }
2729
2730 /* Determine whether PARM is a parameter pack.  */
2731
2732 bool 
2733 template_parameter_pack_p (const_tree parm)
2734 {
2735   /* Determine if we have a non-type template parameter pack.  */
2736   if (TREE_CODE (parm) == PARM_DECL)
2737     return (DECL_TEMPLATE_PARM_P (parm) 
2738             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2739
2740   /* If this is a list of template parameters, we could get a
2741      TYPE_DECL or a TEMPLATE_DECL.  */ 
2742   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2743     parm = TREE_TYPE (parm);
2744
2745   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2746            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2747           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2748 }
2749
2750 /* Determine if T is a function parameter pack.  */
2751
2752 bool
2753 function_parameter_pack_p (const_tree t)
2754 {
2755   if (t && TREE_CODE (t) == PARM_DECL)
2756     return FUNCTION_PARAMETER_PACK_P (t);
2757   return false;
2758 }
2759
2760 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2761    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2762
2763 tree
2764 get_function_template_decl (const_tree primary_func_tmpl_inst)
2765 {
2766   if (! primary_func_tmpl_inst
2767       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2768       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2769     return NULL;
2770
2771   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2772 }
2773
2774 /* Return true iff the function parameter PARAM_DECL was expanded
2775    from the function parameter pack PACK.  */
2776
2777 bool
2778 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2779 {
2780   if (DECL_ARTIFICIAL (param_decl)
2781       || !function_parameter_pack_p (pack))
2782     return false;
2783
2784   /* The parameter pack and its pack arguments have the same
2785      DECL_PARM_INDEX.  */
2786   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2787 }
2788
2789 /* Determine whether ARGS describes a variadic template args list,
2790    i.e., one that is terminated by a template argument pack.  */
2791
2792 static bool 
2793 template_args_variadic_p (tree args)
2794 {
2795   int nargs;
2796   tree last_parm;
2797
2798   if (args == NULL_TREE)
2799     return false;
2800
2801   args = INNERMOST_TEMPLATE_ARGS (args);
2802   nargs = TREE_VEC_LENGTH (args);
2803
2804   if (nargs == 0)
2805     return false;
2806
2807   last_parm = TREE_VEC_ELT (args, nargs - 1);
2808
2809   return ARGUMENT_PACK_P (last_parm);
2810 }
2811
2812 /* Generate a new name for the parameter pack name NAME (an
2813    IDENTIFIER_NODE) that incorporates its */
2814
2815 static tree
2816 make_ith_pack_parameter_name (tree name, int i)
2817 {
2818   /* Munge the name to include the parameter index.  */
2819 #define NUMBUF_LEN 128
2820   char numbuf[NUMBUF_LEN];
2821   char* newname;
2822   int newname_len;
2823
2824   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2825   newname_len = IDENTIFIER_LENGTH (name)
2826                 + strlen (numbuf) + 2;
2827   newname = (char*)alloca (newname_len);
2828   snprintf (newname, newname_len,
2829             "%s#%i", IDENTIFIER_POINTER (name), i);
2830   return get_identifier (newname);
2831 }
2832
2833 /* Return true if T is a primary function
2834    or class template instantiation.  */
2835
2836 bool
2837 primary_template_instantiation_p (const_tree t)
2838 {
2839   if (!t)
2840     return false;
2841
2842   if (TREE_CODE (t) == FUNCTION_DECL)
2843     return DECL_LANG_SPECIFIC (t)
2844            && DECL_TEMPLATE_INSTANTIATION (t)
2845            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2846   else if (CLASS_TYPE_P (t))
2847     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2848            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2849   return false;
2850 }
2851
2852 /* Return true if PARM is a template template parameter.  */
2853
2854 bool
2855 template_template_parameter_p (const_tree parm)
2856 {
2857   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2858 }
2859
2860 /* Return the template parameters of T if T is a
2861    primary template instantiation, NULL otherwise.  */
2862
2863 tree
2864 get_primary_template_innermost_parameters (const_tree t)
2865 {
2866   tree parms = NULL, template_info = NULL;
2867
2868   if ((template_info = get_template_info (t))
2869       && primary_template_instantiation_p (t))
2870     parms = INNERMOST_TEMPLATE_PARMS
2871         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2872
2873   return parms;
2874 }
2875
2876 /* Return the template parameters of the LEVELth level from the full list
2877    of template parameters PARMS.  */
2878
2879 tree
2880 get_template_parms_at_level (tree parms, int level)
2881 {
2882   tree p;
2883   if (!parms
2884       || TREE_CODE (parms) != TREE_LIST
2885       || level > TMPL_PARMS_DEPTH (parms))
2886     return NULL_TREE;
2887
2888   for (p = parms; p; p = TREE_CHAIN (p))
2889     if (TMPL_PARMS_DEPTH (p) == level)
2890       return p;
2891
2892   return NULL_TREE;
2893 }
2894
2895 /* Returns the template arguments of T if T is a template instantiation,
2896    NULL otherwise.  */
2897
2898 tree
2899 get_template_innermost_arguments (const_tree t)
2900 {
2901   tree args = NULL, template_info = NULL;
2902
2903   if ((template_info = get_template_info (t))
2904       && TI_ARGS (template_info))
2905     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2906
2907   return args;
2908 }
2909
2910 /* Return the argument pack elements of T if T is a template argument pack,
2911    NULL otherwise.  */
2912
2913 tree
2914 get_template_argument_pack_elems (const_tree t)
2915 {
2916   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2917       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2918     return NULL;
2919
2920   return ARGUMENT_PACK_ARGS (t);
2921 }
2922
2923 /* Structure used to track the progress of find_parameter_packs_r.  */
2924 struct find_parameter_pack_data 
2925 {
2926   /* TREE_LIST that will contain all of the parameter packs found by
2927      the traversal.  */
2928   tree* parameter_packs;
2929
2930   /* Set of AST nodes that have been visited by the traversal.  */
2931   struct pointer_set_t *visited;
2932 };
2933
2934 /* Identifies all of the argument packs that occur in a template
2935    argument and appends them to the TREE_LIST inside DATA, which is a
2936    find_parameter_pack_data structure. This is a subroutine of
2937    make_pack_expansion and uses_parameter_packs.  */
2938 static tree
2939 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2940 {
2941   tree t = *tp;
2942   struct find_parameter_pack_data* ppd = 
2943     (struct find_parameter_pack_data*)data;
2944   bool parameter_pack_p = false;
2945
2946   /* Identify whether this is a parameter pack or not.  */
2947   switch (TREE_CODE (t))
2948     {
2949     case TEMPLATE_PARM_INDEX:
2950       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2951         parameter_pack_p = true;
2952       break;
2953
2954     case TEMPLATE_TYPE_PARM:
2955     case TEMPLATE_TEMPLATE_PARM:
2956       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2957         parameter_pack_p = true;
2958       break;
2959
2960     case PARM_DECL:
2961       if (FUNCTION_PARAMETER_PACK_P (t))
2962         {
2963           /* We don't want to walk into the type of a PARM_DECL,
2964              because we don't want to see the type parameter pack.  */
2965           *walk_subtrees = 0;
2966           parameter_pack_p = true;
2967         }
2968       break;
2969
2970     default:
2971       /* Not a parameter pack.  */
2972       break;
2973     }
2974
2975   if (parameter_pack_p)
2976     {
2977       /* Add this parameter pack to the list.  */
2978       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2979     }
2980
2981   if (TYPE_P (t))
2982     cp_walk_tree (&TYPE_CONTEXT (t), 
2983                   &find_parameter_packs_r, ppd, ppd->visited);
2984
2985   /* This switch statement will return immediately if we don't find a
2986      parameter pack.  */
2987   switch (TREE_CODE (t)) 
2988     {
2989     case TEMPLATE_PARM_INDEX:
2990       return NULL_TREE;
2991
2992     case BOUND_TEMPLATE_TEMPLATE_PARM:
2993       /* Check the template itself.  */
2994       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2995                     &find_parameter_packs_r, ppd, ppd->visited);
2996       /* Check the template arguments.  */
2997       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2998                     ppd->visited);
2999       *walk_subtrees = 0;
3000       return NULL_TREE;
3001
3002     case TEMPLATE_TYPE_PARM:
3003     case TEMPLATE_TEMPLATE_PARM:
3004       return NULL_TREE;
3005
3006     case PARM_DECL:
3007       return NULL_TREE;
3008
3009     case RECORD_TYPE:
3010       if (TYPE_PTRMEMFUNC_P (t))
3011         return NULL_TREE;
3012       /* Fall through.  */
3013
3014     case UNION_TYPE:
3015     case ENUMERAL_TYPE:
3016       if (TYPE_TEMPLATE_INFO (t))
3017         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
3018                       &find_parameter_packs_r, ppd, ppd->visited);
3019
3020       *walk_subtrees = 0;
3021       return NULL_TREE;
3022
3023     case TEMPLATE_DECL:
3024       cp_walk_tree (&TREE_TYPE (t),
3025                     &find_parameter_packs_r, ppd, ppd->visited);
3026       return NULL_TREE;
3027  
3028     case TYPENAME_TYPE:
3029       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3030                    ppd, ppd->visited);
3031       *walk_subtrees = 0;
3032       return NULL_TREE;
3033       
3034     case TYPE_PACK_EXPANSION:
3035     case EXPR_PACK_EXPANSION:
3036       *walk_subtrees = 0;
3037       return NULL_TREE;
3038
3039     case INTEGER_TYPE:
3040       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
3041                     ppd, ppd->visited);
3042       *walk_subtrees = 0;
3043       return NULL_TREE;
3044
3045     case IDENTIFIER_NODE:
3046       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
3047                     ppd->visited);
3048       *walk_subtrees = 0;
3049       return NULL_TREE;
3050
3051     default:
3052       return NULL_TREE;
3053     }
3054
3055   return NULL_TREE;
3056 }
3057
3058 /* Determines if the expression or type T uses any parameter packs.  */
3059 bool
3060 uses_parameter_packs (tree t)
3061 {
3062   tree parameter_packs = NULL_TREE;
3063   struct find_parameter_pack_data ppd;
3064   ppd.parameter_packs = &parameter_packs;
3065   ppd.visited = pointer_set_create ();
3066   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3067   pointer_set_destroy (ppd.visited);
3068   return parameter_packs != NULL_TREE;
3069 }
3070
3071 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3072    representation a base-class initializer into a parameter pack
3073    expansion. If all goes well, the resulting node will be an
3074    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3075    respectively.  */
3076 tree 
3077 make_pack_expansion (tree arg)
3078 {
3079   tree result;
3080   tree parameter_packs = NULL_TREE;
3081   bool for_types = false;
3082   struct find_parameter_pack_data ppd;
3083
3084   if (!arg || arg == error_mark_node)
3085     return arg;
3086
3087   if (TREE_CODE (arg) == TREE_LIST)
3088     {
3089       /* The only time we will see a TREE_LIST here is for a base
3090          class initializer.  In this case, the TREE_PURPOSE will be a
3091          _TYPE node (representing the base class expansion we're
3092          initializing) and the TREE_VALUE will be a TREE_LIST
3093          containing the initialization arguments. 
3094
3095          The resulting expansion looks somewhat different from most
3096          expansions. Rather than returning just one _EXPANSION, we
3097          return a TREE_LIST whose TREE_PURPOSE is a
3098          TYPE_PACK_EXPANSION containing the bases that will be
3099          initialized.  The TREE_VALUE will be identical to the
3100          original TREE_VALUE, which is a list of arguments that will
3101          be passed to each base.  We do not introduce any new pack
3102          expansion nodes into the TREE_VALUE (although it is possible
3103          that some already exist), because the TREE_PURPOSE and
3104          TREE_VALUE all need to be expanded together with the same
3105          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3106          resulting TREE_PURPOSE will mention the parameter packs in
3107          both the bases and the arguments to the bases.  */
3108       tree purpose;
3109       tree value;
3110       tree parameter_packs = NULL_TREE;
3111
3112       /* Determine which parameter packs will be used by the base
3113          class expansion.  */
3114       ppd.visited = pointer_set_create ();
3115       ppd.parameter_packs = &parameter_packs;
3116       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3117                     &ppd, ppd.visited);
3118
3119       if (parameter_packs == NULL_TREE)
3120         {
3121           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3122           pointer_set_destroy (ppd.visited);
3123           return error_mark_node;
3124         }
3125
3126       if (TREE_VALUE (arg) != void_type_node)
3127         {
3128           /* Collect the sets of parameter packs used in each of the
3129              initialization arguments.  */
3130           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3131             {
3132               /* Determine which parameter packs will be expanded in this
3133                  argument.  */
3134               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3135                             &ppd, ppd.visited);
3136             }
3137         }
3138
3139       pointer_set_destroy (ppd.visited);
3140
3141       /* Create the pack expansion type for the base type.  */
3142       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3143       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3144       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3145
3146       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3147          they will rarely be compared to anything.  */
3148       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3149
3150       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3151     }
3152
3153   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3154     for_types = true;
3155
3156   /* Build the PACK_EXPANSION_* node.  */
3157   result = for_types
3158      ? cxx_make_type (TYPE_PACK_EXPANSION)
3159      : make_node (EXPR_PACK_EXPANSION);
3160   SET_PACK_EXPANSION_PATTERN (result, arg);
3161   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3162     {
3163       /* Propagate type and const-expression information.  */
3164       TREE_TYPE (result) = TREE_TYPE (arg);
3165       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3166     }
3167   else
3168     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3169        they will rarely be compared to anything.  */
3170     SET_TYPE_STRUCTURAL_EQUALITY (result);
3171
3172   /* Determine which parameter packs will be expanded.  */
3173   ppd.parameter_packs = &parameter_packs;
3174   ppd.visited = pointer_set_create ();
3175   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3176   pointer_set_destroy (ppd.visited);
3177
3178   /* Make sure we found some parameter packs.  */
3179   if (parameter_packs == NULL_TREE)
3180     {
3181       if (TYPE_P (arg))
3182         error ("expansion pattern %<%T%> contains no argument packs", arg);
3183       else
3184         error ("expansion pattern %<%E%> contains no argument packs", arg);
3185       return error_mark_node;
3186     }
3187   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3188
3189   return result;
3190 }
3191
3192 /* Checks T for any "bare" parameter packs, which have not yet been
3193    expanded, and issues an error if any are found. This operation can
3194    only be done on full expressions or types (e.g., an expression
3195    statement, "if" condition, etc.), because we could have expressions like:
3196
3197      foo(f(g(h(args)))...)
3198
3199    where "args" is a parameter pack. check_for_bare_parameter_packs
3200    should not be called for the subexpressions args, h(args),
3201    g(h(args)), or f(g(h(args))), because we would produce erroneous
3202    error messages. 
3203
3204    Returns TRUE and emits an error if there were bare parameter packs,
3205    returns FALSE otherwise.  */
3206 bool 
3207 check_for_bare_parameter_packs (tree t)
3208 {
3209   tree parameter_packs = NULL_TREE;
3210   struct find_parameter_pack_data ppd;
3211
3212   if (!processing_template_decl || !t || t == error_mark_node)
3213     return false;
3214
3215   if (TREE_CODE (t) == TYPE_DECL)
3216     t = TREE_TYPE (t);
3217
3218   ppd.parameter_packs = &parameter_packs;
3219   ppd.visited = pointer_set_create ();
3220   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3221   pointer_set_destroy (ppd.visited);
3222
3223   if (parameter_packs) 
3224     {
3225       error ("parameter packs not expanded with %<...%>:");
3226       while (parameter_packs)
3227         {
3228           tree pack = TREE_VALUE (parameter_packs);
3229           tree name = NULL_TREE;
3230
3231           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3232               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3233             name = TYPE_NAME (pack);
3234           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3235             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3236           else
3237             name = DECL_NAME (pack);
3238
3239           if (name)
3240             inform (input_location, "        %qD", name);
3241           else
3242             inform (input_location, "        <anonymous>");
3243
3244           parameter_packs = TREE_CHAIN (parameter_packs);
3245         }
3246
3247       return true;
3248     }
3249
3250   return false;
3251 }
3252
3253 /* Expand any parameter packs that occur in the template arguments in
3254    ARGS.  */
3255 tree
3256 expand_template_argument_pack (tree args)
3257 {
3258   tree result_args = NULL_TREE;
3259   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3260   int num_result_args = -1;
3261   int non_default_args_count = -1;
3262
3263   /* First, determine if we need to expand anything, and the number of
3264      slots we'll need.  */
3265   for (in_arg = 0; in_arg < nargs; ++in_arg)
3266     {
3267       tree arg = TREE_VEC_ELT (args, in_arg);
3268       if (arg == NULL_TREE)
3269         return args;
3270       if (ARGUMENT_PACK_P (arg))
3271         {
3272           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3273           if (num_result_args < 0)
3274             num_result_args = in_arg + num_packed;
3275           else
3276             num_result_args += num_packed;
3277         }
3278       else
3279         {
3280           if (num_result_args >= 0)
3281             num_result_args++;
3282         }
3283     }
3284
3285   /* If no expansion is necessary, we're done.  */
3286   if (num_result_args < 0)
3287     return args;
3288
3289   /* Expand arguments.  */
3290   result_args = make_tree_vec (num_result_args);
3291   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3292     non_default_args_count =
3293       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3294   for (in_arg = 0; in_arg < nargs; ++in_arg)
3295     {
3296       tree arg = TREE_VEC_ELT (args, in_arg);
3297       if (ARGUMENT_PACK_P (arg))
3298         {
3299           tree packed = ARGUMENT_PACK_ARGS (arg);
3300           int i, num_packed = TREE_VEC_LENGTH (packed);
3301           for (i = 0; i < num_packed; ++i, ++out_arg)
3302             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3303           if (non_default_args_count > 0)
3304             non_default_args_count += num_packed;
3305         }
3306       else
3307         {
3308           TREE_VEC_ELT (result_args, out_arg) = arg;
3309           ++out_arg;
3310         }
3311     }
3312   if (non_default_args_count >= 0)
3313     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3314   return result_args;
3315 }
3316
3317 /* Checks if DECL shadows a template parameter.
3318
3319    [temp.local]: A template-parameter shall not be redeclared within its
3320    scope (including nested scopes).
3321
3322    Emits an error and returns TRUE if the DECL shadows a parameter,
3323    returns FALSE otherwise.  */
3324
3325 bool
3326 check_template_shadow (tree decl)
3327 {
3328   tree olddecl;
3329
3330   /* If we're not in a template, we can't possibly shadow a template
3331      parameter.  */
3332   if (!current_template_parms)
3333     return true;
3334
3335   /* Figure out what we're shadowing.  */
3336   if (TREE_CODE (decl) == OVERLOAD)
3337     decl = OVL_CURRENT (decl);
3338   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3339
3340   /* If there's no previous binding for this name, we're not shadowing
3341      anything, let alone a template parameter.  */
3342   if (!olddecl)
3343     return true;
3344
3345   /* If we're not shadowing a template parameter, we're done.  Note
3346      that OLDDECL might be an OVERLOAD (or perhaps even an
3347      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3348      node.  */
3349   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3350     return true;
3351
3352   /* We check for decl != olddecl to avoid bogus errors for using a
3353      name inside a class.  We check TPFI to avoid duplicate errors for
3354      inline member templates.  */
3355   if (decl == olddecl
3356       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3357     return true;
3358
3359   error ("declaration of %q+#D", decl);
3360   error (" shadows template parm %q+#D", olddecl);
3361   return false;
3362 }
3363
3364 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3365    ORIG_LEVEL, DECL, and TYPE.  NUM_SIBLINGS is the total number of
3366    template parameters.  */
3367
3368 static tree
3369 build_template_parm_index (int index,
3370                            int level,
3371                            int orig_level,
3372                            int num_siblings,
3373                            tree decl,
3374                            tree type)
3375 {
3376   tree t = make_node (TEMPLATE_PARM_INDEX);
3377   TEMPLATE_PARM_IDX (t) = index;
3378   TEMPLATE_PARM_LEVEL (t) = level;
3379   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3380   TEMPLATE_PARM_NUM_SIBLINGS (t) = num_siblings;
3381   TEMPLATE_PARM_DECL (t) = decl;
3382   TREE_TYPE (t) = type;
3383   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3384   TREE_READONLY (t) = TREE_READONLY (decl);
3385
3386   return t;
3387 }
3388
3389 /* Find the canonical type parameter for the given template type
3390    parameter.  Returns the canonical type parameter, which may be TYPE
3391    if no such parameter existed.  */
3392
3393 static tree
3394 canonical_type_parameter (tree type)
3395 {
3396   tree list;
3397   int idx = TEMPLATE_TYPE_IDX (type);
3398   if (!canonical_template_parms)
3399     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3400
3401   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3402     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3403
3404   list = VEC_index (tree, canonical_template_parms, idx);
3405   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3406     list = TREE_CHAIN (list);
3407
3408   if (list)
3409     return TREE_VALUE (list);
3410   else
3411     {
3412       VEC_replace(tree, canonical_template_parms, idx,
3413                   tree_cons (NULL_TREE, type, 
3414                              VEC_index (tree, canonical_template_parms, idx)));
3415       return type;
3416     }
3417 }
3418
3419 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3420    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3421    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3422    new one is created.  */
3423
3424 static tree
3425 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3426                             tsubst_flags_t complain)
3427 {
3428   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3429       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3430           != TEMPLATE_PARM_LEVEL (index) - levels)
3431       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3432     {
3433       tree orig_decl = TEMPLATE_PARM_DECL (index);
3434       tree decl, t;
3435
3436       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3437                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3438       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3439       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3440       DECL_ARTIFICIAL (decl) = 1;
3441       SET_DECL_TEMPLATE_PARM_P (decl);
3442
3443       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3444                                      TEMPLATE_PARM_LEVEL (index) - levels,
3445                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3446                                      TEMPLATE_PARM_NUM_SIBLINGS (index),
3447                                      decl, type);
3448       TEMPLATE_PARM_DESCENDANTS (index) = t;
3449       TEMPLATE_PARM_PARAMETER_PACK (t) 
3450         = TEMPLATE_PARM_PARAMETER_PACK (index);
3451
3452         /* Template template parameters need this.  */
3453       if (TREE_CODE (decl) == TEMPLATE_DECL)
3454         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3455           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3456            args, complain);
3457     }
3458
3459   return TEMPLATE_PARM_DESCENDANTS (index);
3460 }
3461
3462 /* Process information from new template parameter PARM and append it
3463    to the LIST being built.  This new parameter is a non-type
3464    parameter iff IS_NON_TYPE is true. This new parameter is a
3465    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
3466    is in PARM_LOC. NUM_TEMPLATE_PARMS is the size of the template
3467    parameter list PARM belongs to. This is used used to create a
3468    proper canonical type for the type of PARM that is to be created,
3469    iff PARM is a type.  If the size is not known, this parameter shall
3470    be set to 0.  */
3471
3472 tree
3473 process_template_parm (tree list, location_t parm_loc, tree parm,
3474                        bool is_non_type, bool is_parameter_pack,
3475                        unsigned num_template_parms)
3476 {
3477   tree decl = 0;
3478   tree defval;
3479   tree err_parm_list;
3480   int idx = 0;
3481
3482   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3483   defval = TREE_PURPOSE (parm);
3484
3485   if (list)
3486     {
3487       tree p = tree_last (list);
3488
3489       if (p && TREE_VALUE (p) != error_mark_node)
3490         {
3491           p = TREE_VALUE (p);
3492           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3493             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3494           else
3495             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3496         }
3497
3498       ++idx;
3499     }
3500   else
3501     idx = 0;
3502
3503   if (is_non_type)
3504     {
3505       parm = TREE_VALUE (parm);
3506
3507       SET_DECL_TEMPLATE_PARM_P (parm);
3508
3509       if (TREE_TYPE (parm) == error_mark_node)
3510         {
3511           err_parm_list = build_tree_list (defval, parm);
3512           TREE_VALUE (err_parm_list) = error_mark_node;
3513            return chainon (list, err_parm_list);
3514         }
3515       else
3516       {
3517         /* [temp.param]
3518
3519            The top-level cv-qualifiers on the template-parameter are
3520            ignored when determining its type.  */
3521         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3522         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3523           {
3524             err_parm_list = build_tree_list (defval, parm);
3525             TREE_VALUE (err_parm_list) = error_mark_node;
3526              return chainon (list, err_parm_list);
3527           }
3528
3529         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3530           {
3531             /* This template parameter is not a parameter pack, but it
3532                should be. Complain about "bare" parameter packs.  */
3533             check_for_bare_parameter_packs (TREE_TYPE (parm));
3534             
3535             /* Recover by calling this a parameter pack.  */
3536             is_parameter_pack = true;
3537           }
3538       }
3539
3540       /* A template parameter is not modifiable.  */
3541       TREE_CONSTANT (parm) = 1;
3542       TREE_READONLY (parm) = 1;
3543       decl = build_decl (parm_loc,
3544                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3545       TREE_CONSTANT (decl) = 1;
3546       TREE_READONLY (decl) = 1;
3547       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3548         = build_template_parm_index (idx, processing_template_decl,
3549                                      processing_template_decl,
3550                                      num_template_parms,
3551                                      decl, TREE_TYPE (parm));
3552
3553       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3554         = is_parameter_pack;
3555     }
3556   else
3557     {
3558       tree t;
3559       parm = TREE_VALUE (TREE_VALUE (parm));
3560
3561       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3562         {
3563           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3564           /* This is for distinguishing between real templates and template
3565              template parameters */
3566           TREE_TYPE (parm) = t;
3567           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3568           decl = parm;
3569         }
3570       else
3571         {
3572           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3573           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3574           decl = build_decl (parm_loc,
3575                              TYPE_DECL, parm, t);
3576         }
3577
3578       TYPE_NAME (t) = decl;
3579       TYPE_STUB_DECL (t) = decl;
3580       parm = decl;
3581       TEMPLATE_TYPE_PARM_INDEX (t)
3582         = build_template_parm_index (idx, processing_template_decl,
3583                                      processing_template_decl,
3584                                      num_template_parms,
3585                                      decl, TREE_TYPE (parm));
3586       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3587       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3588     }
3589   DECL_ARTIFICIAL (decl) = 1;
3590   SET_DECL_TEMPLATE_PARM_P (decl);
3591   pushdecl (decl);
3592   parm = build_tree_list (defval, parm);
3593   return chainon (list, parm);
3594 }
3595
3596 /* The end of a template parameter list has been reached.  Process the
3597    tree list into a parameter vector, converting each parameter into a more
3598    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3599    as PARM_DECLs.  */
3600
3601 tree
3602 end_template_parm_list (tree parms)
3603 {
3604   int nparms;
3605   tree parm, next;
3606   tree saved_parmlist = make_tree_vec (list_length (parms));
3607
3608   current_template_parms
3609     = tree_cons (size_int (processing_template_decl),
3610                  saved_parmlist, current_template_parms);
3611
3612   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3613     {
3614       next = TREE_CHAIN (parm);
3615       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3616       TREE_CHAIN (parm) = NULL_TREE;
3617     }
3618
3619   --processing_template_parmlist;
3620
3621   return saved_parmlist;
3622 }
3623
3624 /* Create a new type almost identical to TYPE but which has the
3625    following differences:
3626
3627      1/ T has a new TEMPLATE_PARM_INDEX that carries the new number of
3628      template sibling parameters of T.
3629
3630      2/ T has a new canonical type that matches the new number
3631      of sibling parms.
3632
3633      3/ From now on, T is going to be what lookups referring to the
3634      name of TYPE will return. No lookup should return TYPE anymore.
3635
3636    NUM_PARMS is the new number of sibling parms TYPE belongs to.
3637
3638    This is a subroutine of fixup_template_parms.  */
3639
3640 static tree
3641 fixup_template_type_parm_type (tree type, int num_parms)
3642 {
3643   tree orig_idx = TEMPLATE_TYPE_PARM_INDEX (type), idx;
3644   tree t;
3645   /* This is the decl which name is inserted into the symbol table for
3646      the template parm type. So whenever we lookup the type name, this
3647      is the DECL we get.  */
3648   tree decl;
3649
3650   /* Do not fix up the type twice.  */
3651   if (orig_idx && TEMPLATE_PARM_NUM_SIBLINGS (orig_idx) != 0)
3652     return type;
3653
3654   t = copy_type (type);
3655   decl = TYPE_NAME (t);
3656
3657   TYPE_MAIN_VARIANT (t) = t;
3658   TYPE_NEXT_VARIANT (t)= NULL_TREE;
3659   TYPE_POINTER_TO (t) = 0;
3660   TYPE_REFERENCE_TO (t) = 0;
3661
3662   idx = build_template_parm_index (TEMPLATE_PARM_IDX (orig_idx),
3663                                    TEMPLATE_PARM_LEVEL (orig_idx),
3664                                    TEMPLATE_PARM_ORIG_LEVEL (orig_idx),
3665                                    num_parms,
3666                                    decl, t);
3667   TEMPLATE_PARM_DESCENDANTS (idx) = TEMPLATE_PARM_DESCENDANTS (orig_idx);
3668   TEMPLATE_PARM_PARAMETER_PACK (idx) = TEMPLATE_PARM_PARAMETER_PACK (orig_idx);
3669   TEMPLATE_TYPE_PARM_INDEX (t) = idx;
3670
3671   TYPE_STUB_DECL (t) = decl;
3672   TEMPLATE_TYPE_DECL (t) = decl;
3673   if (TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
3674     TREE_TYPE (DECL_TEMPLATE_RESULT  (decl)) = t;
3675
3676   /* Update the type associated to the type name stored in the symbol
3677      table. Now, whenever the type name is looked up, the resulting
3678      type is properly fixed up.  */
3679   TREE_TYPE (decl) = t;
3680
3681   TYPE_CANONICAL (t) = canonical_type_parameter (t);
3682
3683   return t;
3684 }
3685
3686 /* Create and return a new TEMPLATE_PARM_INDEX that is almost
3687    identical to I, but that is fixed up as to:
3688
3689    1/ carry the number of sibling parms (NUM_PARMS) of the template
3690    parm represented by I.
3691
3692    2/ replace all references to template parm types declared before I
3693    (in the same template parm list as I) by references to template
3694    parm types contained in ARGS. ARGS should contain the list of
3695    template parms that have been fixed up so far, in a form suitable
3696    to be passed to tsubst.
3697
3698    This is a subroutine of fixup_template_parms.  */
3699
3700 static tree
3701 fixup_template_parm_index (tree i, tree args, int num_parms)
3702 {
3703   tree index, decl, type;
3704
3705   if (i == NULL_TREE
3706       || TREE_CODE (i) != TEMPLATE_PARM_INDEX
3707       /* Do not fix up the index twice.  */
3708       || (TEMPLATE_PARM_NUM_SIBLINGS (i) != 0))
3709     return i;
3710
3711   decl = TEMPLATE_PARM_DECL (i);
3712   type = TREE_TYPE (decl);
3713
3714   index = build_template_parm_index (TEMPLATE_PARM_IDX (i),
3715                                      TEMPLATE_PARM_LEVEL (i),
3716                                      TEMPLATE_PARM_ORIG_LEVEL (i),
3717                                      num_parms,
3718                                      decl, type);
3719
3720   TEMPLATE_PARM_DESCENDANTS (index) = TEMPLATE_PARM_DESCENDANTS (i);
3721   TEMPLATE_PARM_PARAMETER_PACK (index) = TEMPLATE_PARM_PARAMETER_PACK (i);
3722
3723   type = tsubst (type, args, tf_none, NULL_TREE);
3724   
3725   TREE_TYPE (decl) = type;
3726   TREE_TYPE (index) = type;
3727
3728   return index;
3729 }
3730
3731 /* 
3732    This is a subroutine of fixup_template_parms.
3733
3734    It computes the canonical type of the type of the template
3735    parameter PARM_DESC and update all references to that type so that
3736    they use the newly computed canonical type. No access check is
3737    performed during the fixup. PARM_DESC is a TREE_LIST which
3738    TREE_VALUE is the template parameter and its TREE_PURPOSE is the
3739    default argument of the template parm if any. IDX is the index of
3740    the template parameter, starting at 0. NUM_PARMS is the number of
3741    template parameters in the set PARM_DESC belongs to. ARGLIST is a
3742    TREE_VEC containing the full set of template parameters in a form
3743    suitable to be passed to substs functions as their ARGS
3744    argument. This is what current_template_args returns for a given
3745    template. The innermost vector of args in ARGLIST is the set of
3746    template parms that have been fixed up so far. This function adds
3747    the fixed up parameter into that vector.  */
3748
3749 static void
3750 fixup_template_parm (tree parm_desc,
3751                      int idx,
3752                      int num_parms,
3753                      tree arglist)
3754 {
3755   tree parm = TREE_VALUE (parm_desc);
3756   tree fixedup_args = INNERMOST_TEMPLATE_ARGS (arglist);
3757
3758   push_deferring_access_checks (dk_no_check);
3759
3760   if (TREE_CODE (parm) == TYPE_DECL)
3761     {
3762       /* PARM is a template type parameter. Fix up its type, add
3763          the fixed-up template parm to the vector of fixed-up
3764          template parms so far, and substitute the fixed-up
3765          template parms into the default argument of this
3766          parameter.  */
3767       tree t =
3768         fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
3769       TREE_TYPE (parm) = t;
3770
3771       TREE_VEC_ELT (fixedup_args, idx) = template_parm_to_arg (parm_desc);
3772     }
3773   else if (TREE_CODE (parm) == TEMPLATE_DECL)
3774     {
3775       /* PARM is a template template parameter. This is going to
3776          be interesting.  */
3777       tree tparms, targs, innermost_args, t;
3778       int j;
3779
3780       /* First, fix up the parms of the template template parm
3781          because the parms are involved in defining the new canonical
3782          type of the template template parm.  */
3783
3784       /* So we need to substitute the template parm types that have
3785          been fixed up so far into the template parms of this template
3786          template parm. E.g, consider this:
3787
3788          template<class T, template<T u> class TT> class S;
3789
3790          In this case we want to substitute T into the
3791          template parameters of TT.
3792
3793          So let's walk the template parms of PARM here, and
3794          tsubst ARGLIST into into each of the template
3795          parms.   */
3796
3797       /* For this substitution we need to build the full set of
3798          template parameters and use that as arguments for the
3799          tsubsting function.  */
3800       tparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
3801
3802       /* This will contain the innermost parms of PARM into which
3803          we have substituted so far.  */
3804       innermost_args = make_tree_vec (TREE_VEC_LENGTH (tparms));
3805       targs = add_to_template_args (arglist, innermost_args);
3806       for (j = 0; j < TREE_VEC_LENGTH (tparms); ++j)
3807         {
3808           tree parameter;
3809
3810           parameter = TREE_VEC_ELT (tparms, j);
3811
3812           /* INNERMOST_ARGS needs to have at least the same number
3813              of elements as the index PARAMETER, ortherwise
3814              tsubsting into PARAMETER will result in partially
3815              instantiating it, reducing its tempate parm
3816              level. Let's tactically fill INNERMOST_ARGS for that
3817              purpose.  */
3818           TREE_VEC_ELT (innermost_args, j) =
3819             template_parm_to_arg (parameter);
3820
3821           fixup_template_parm (parameter, j,
3822                                TREE_VEC_LENGTH (tparms),
3823                                targs);
3824         }
3825
3826       /* Now fix up the type of the template template parm.  */
3827
3828       t = fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
3829       TREE_TYPE (parm) = t;
3830
3831       TREE_VEC_ELT (fixedup_args, idx) =
3832         template_parm_to_arg (parm_desc);
3833     }
3834   else if (TREE_CODE (parm) == PARM_DECL)
3835     {
3836       /* PARM is a non-type template parameter. We need to:
3837
3838        * Fix up its TEMPLATE_PARM_INDEX to make it carry the
3839        proper number of sibling parameters.
3840
3841        * Make lookups of the template parameter return a reference
3842        to the fixed-up index. No lookup should return references
3843        to the former index anymore.
3844
3845        * Substitute the template parms that got fixed up so far
3846
3847        * into the type of PARM.  */
3848
3849       tree index = DECL_INITIAL (parm);
3850
3851       /* PUSHED_DECL is the decl added to the symbol table with
3852          the name of the parameter. E,g:
3853              
3854          template<class T, T u> //#0
3855          auto my_function(T t) -> decltype(u); //#1
3856
3857          Here, when looking up u at //#1, we get the decl of u
3858          resulting from the declaration in #0. This is what
3859          PUSHED_DECL is. We need to replace the reference to the
3860          old TEMPLATE_PARM_INDEX carried by PUSHED_DECL by the
3861          fixed-up TEMPLATE_PARM_INDEX.  */
3862       tree pushed_decl = TEMPLATE_PARM_DECL (index);
3863
3864       /* Let's fix up the TEMPLATE_PARM_INDEX then. Note that we must
3865          fixup the type of PUSHED_DECL as well and luckily
3866          fixup_template_parm_index does it for us too.  */
3867       tree fixed_up_index =
3868         fixup_template_parm_index (index, arglist, num_parms);
3869
3870       DECL_INITIAL (pushed_decl) = DECL_INITIAL (parm) = fixed_up_index;
3871
3872       /* Add this fixed up PARM to the template parms we've fixed
3873          up so far and use that to substitute the fixed-up
3874          template parms into the type of PARM.  */
3875       TREE_VEC_ELT (fixedup_args, idx) =
3876         template_parm_to_arg (parm_desc);
3877       TREE_TYPE (parm) = tsubst (TREE_TYPE (parm), arglist,
3878                                  tf_none, NULL_TREE);
3879     }
3880
3881   TREE_PURPOSE (parm_desc) =
3882     tsubst_template_arg (TREE_PURPOSE (parm_desc),
3883                          arglist, tf_none, parm);
3884
3885   pop_deferring_access_checks ();
3886 }
3887
3888 /* Walk the current template parms and properly compute the canonical
3889    types of the dependent types created during
3890    cp_parser_template_parameter_list.  */
3891
3892 void
3893 fixup_template_parms (void)
3894 {
3895   tree arglist;
3896   tree parameter_vec;
3897   tree fixedup_args;
3898   int i, num_parms;
3899
3900   parameter_vec = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3901   if (parameter_vec == NULL_TREE)
3902     return;
3903
3904   num_parms = TREE_VEC_LENGTH (parameter_vec);
3905
3906   /* This vector contains the current innermost template parms that
3907      have been fixed up so far.  The form of FIXEDUP_ARGS is suitable
3908      to be passed to tsubst* functions as their ARGS argument.  */
3909   fixedup_args = make_tree_vec (num_parms);
3910
3911   /* This vector contains the full set of template parms in a form
3912      suitable to be passed to substs functions as their ARGS
3913      argument.  */
3914   arglist = current_template_args ();
3915   arglist = add_outermost_template_args (arglist, fixedup_args);
3916
3917   /* Let's do the proper fixup now.  */
3918   for (i = 0; i < num_parms; ++i)
3919     fixup_template_parm (TREE_VEC_ELT (parameter_vec, i),
3920                          i, num_parms, arglist);
3921 }
3922
3923 /* end_template_decl is called after a template declaration is seen.  */
3924
3925 void
3926 end_template_decl (void)
3927 {
3928   reset_specialization ();
3929
3930   if (! processing_template_decl)
3931     return;
3932
3933   /* This matches the pushlevel in begin_template_parm_list.  */
3934   finish_scope ();
3935
3936   --processing_template_decl;
3937   current_template_parms = TREE_CHAIN (current_template_parms);
3938 }
3939
3940 /* Takes a TREE_LIST representing a template parameter and convert it
3941    into an argument suitable to be passed to the type substitution
3942    functions.  Note that If the TREE_LIST contains an error_mark
3943    node, the returned argument is error_mark_node.  */
3944
3945 static tree
3946 template_parm_to_arg (tree t)
3947 {
3948
3949   if (t == NULL_TREE
3950       || TREE_CODE (t) != TREE_LIST)
3951     return t;
3952
3953   if (error_operand_p (TREE_VALUE (t)))
3954     return error_mark_node;
3955
3956   t = TREE_VALUE (t);
3957
3958   if (TREE_CODE (t) == TYPE_DECL
3959       || TREE_CODE (t) == TEMPLATE_DECL)
3960     {
3961       t = TREE_TYPE (t);
3962
3963       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3964         {
3965           /* Turn this argument into a TYPE_ARGUMENT_PACK
3966              with a single element, which expands T.  */
3967           tree vec = make_tree_vec (1);
3968 #ifdef ENABLE_CHECKING
3969           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3970             (vec, TREE_VEC_LENGTH (vec));
3971 #endif
3972           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3973
3974           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3975           SET_ARGUMENT_PACK_ARGS (t, vec);
3976         }
3977     }
3978   else
3979     {
3980       t = DECL_INITIAL (t);
3981
3982       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3983         {
3984           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3985              with a single element, which expands T.  */
3986           tree vec = make_tree_vec (1);
3987           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3988 #ifdef ENABLE_CHECKING
3989           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3990             (vec, TREE_VEC_LENGTH (vec));
3991 #endif
3992           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3993
3994           t  = make_node (NONTYPE_ARGUMENT_PACK);
3995           SET_ARGUMENT_PACK_ARGS (t, vec);
3996           TREE_TYPE (t) = type;
3997         }
3998     }
3999   return t;
4000 }
4001
4002 /* Within the declaration of a template, return all levels of template
4003    parameters that apply.  The template parameters are represented as
4004    a TREE_VEC, in the form documented in cp-tree.h for template
4005    arguments.  */
4006
4007 static tree
4008 current_template_args (void)
4009 {
4010   tree header;
4011   tree args = NULL_TREE;
4012   int length = TMPL_PARMS_DEPTH (current_template_parms);
4013   int l = length;
4014
4015   /* If there is only one level of template parameters, we do not
4016      create a TREE_VEC of TREE_VECs.  Instead, we return a single
4017      TREE_VEC containing the arguments.  */
4018   if (length > 1)
4019     args = make_tree_vec (length);
4020
4021   for (header = current_template_parms; header; header = TREE_CHAIN (header))
4022     {
4023       tree a = copy_node (TREE_VALUE (header));
4024       int i;
4025
4026       TREE_TYPE (a) = NULL_TREE;
4027       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4028         TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4029
4030 #ifdef ENABLE_CHECKING
4031       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4032 #endif
4033
4034       if (length > 1)
4035         TREE_VEC_ELT (args, --l) = a;
4036       else
4037         args = a;
4038     }
4039
4040     if (length > 1 && TREE_VEC_ELT (args, 0) == NULL_TREE)
4041       /* This can happen for template parms of a template template
4042          parameter, e.g:
4043
4044          template<template<class T, class U> class TT> struct S;
4045
4046          Consider the level of the parms of TT; T and U both have
4047          level 2; TT has no template parm of level 1. So in this case
4048          the first element of full_template_args is NULL_TREE. If we
4049          leave it like this TMPL_ARG_DEPTH on args returns 1 instead
4050          of 2. This will make tsubst wrongly consider that T and U
4051          have level 1. Instead, let's create a dummy vector as the
4052          first element of full_template_args so that TMPL_ARG_DEPTH
4053          returns the correct depth for args.  */
4054       TREE_VEC_ELT (args, 0) = make_tree_vec (1);
4055   return args;
4056 }
4057
4058 /* Update the declared TYPE by doing any lookups which were thought to be
4059    dependent, but are not now that we know the SCOPE of the declarator.  */
4060
4061 tree
4062 maybe_update_decl_type (tree orig_type, tree scope)
4063 {
4064   tree type = orig_type;
4065
4066   if (type == NULL_TREE)
4067     return type;
4068
4069   if (TREE_CODE (orig_type) == TYPE_DECL)
4070     type = TREE_TYPE (type);
4071
4072   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4073       && dependent_type_p (type)
4074       /* Don't bother building up the args in this case.  */
4075       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4076     {
4077       /* tsubst in the args corresponding to the template parameters,
4078          including auto if present.  Most things will be unchanged, but
4079          make_typename_type and tsubst_qualified_id will resolve
4080          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4081       tree args = current_template_args ();
4082       tree auto_node = type_uses_auto (type);
4083       tree pushed;
4084       if (auto_node)
4085         {
4086           tree auto_vec = make_tree_vec (1);
4087           TREE_VEC_ELT (auto_vec, 0) = auto_node;
4088           args = add_to_template_args (args, auto_vec);
4089         }
4090       pushed = push_scope (scope);
4091       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4092       if (pushed)
4093         pop_scope (scope);
4094     }
4095
4096   if (type == error_mark_node)
4097     return orig_type;
4098
4099   if (TREE_CODE (orig_type) == TYPE_DECL)
4100     {
4101       if (same_type_p (type, TREE_TYPE (orig_type)))
4102         type = orig_type;
4103       else
4104         type = TYPE_NAME (type);
4105     }
4106   return type;
4107 }
4108
4109 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4110    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
4111    a member template.  Used by push_template_decl below.  */
4112
4113 static tree
4114 build_template_decl (tree decl, tree parms, bool member_template_p)
4115 {
4116   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4117   DECL_TEMPLATE_PARMS (tmpl) = parms;
4118   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4119   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4120
4121   return tmpl;
4122 }
4123
4124 struct template_parm_data
4125 {
4126   /* The level of the template parameters we are currently
4127      processing.  */
4128   int level;
4129
4130   /* The index of the specialization argument we are currently
4131      processing.  */
4132   int current_arg;
4133
4134   /* An array whose size is the number of template parameters.  The
4135      elements are nonzero if the parameter has been used in any one
4136      of the arguments processed so far.  */
4137   int* parms;
4138
4139   /* An array whose size is the number of template arguments.  The
4140      elements are nonzero if the argument makes use of template
4141      parameters of this level.  */
4142   int* arg_uses_template_parms;
4143 };
4144
4145 /* Subroutine of push_template_decl used to see if each template
4146    parameter in a partial specialization is used in the explicit
4147    argument list.  If T is of the LEVEL given in DATA (which is
4148    treated as a template_parm_data*), then DATA->PARMS is marked
4149    appropriately.  */
4150
4151 static int
4152 mark_template_parm (tree t, void* data)
4153 {
4154   int level;
4155   int idx;
4156   struct template_parm_data* tpd = (struct template_parm_data*) data;
4157
4158   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4159     {
4160       level = TEMPLATE_PARM_LEVEL (t);
4161       idx = TEMPLATE_PARM_IDX (t);
4162     }
4163   else
4164     {
4165       level = TEMPLATE_TYPE_LEVEL (t);
4166       idx = TEMPLATE_TYPE_IDX (t);
4167     }
4168
4169   if (level == tpd->level)
4170     {
4171       tpd->parms[idx] = 1;
4172       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4173     }
4174
4175   /* Return zero so that for_each_template_parm will continue the
4176      traversal of the tree; we want to mark *every* template parm.  */
4177   return 0;
4178 }
4179
4180 /* Process the partial specialization DECL.  */
4181
4182 static tree
4183 process_partial_specialization (tree decl)
4184 {
4185   tree type = TREE_TYPE (decl);
4186   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
4187   tree specargs = CLASSTYPE_TI_ARGS (type);
4188   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4189   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4190   tree inner_parms;
4191   tree inst;
4192   int nargs = TREE_VEC_LENGTH (inner_args);
4193   int ntparms;
4194   int  i;
4195   bool did_error_intro = false;
4196   struct template_parm_data tpd;
4197   struct template_parm_data tpd2;
4198
4199   gcc_assert (current_template_parms);
4200
4201   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4202   ntparms = TREE_VEC_LENGTH (inner_parms);
4203
4204   /* We check that each of the template parameters given in the
4205      partial specialization is used in the argument list to the
4206      specialization.  For example:
4207
4208        template <class T> struct S;
4209        template <class T> struct S<T*>;
4210
4211      The second declaration is OK because `T*' uses the template
4212      parameter T, whereas
4213
4214        template <class T> struct S<int>;
4215
4216      is no good.  Even trickier is:
4217
4218        template <class T>
4219        struct S1
4220        {
4221           template <class U>
4222           struct S2;
4223           template <class U>
4224           struct S2<T>;
4225        };
4226
4227      The S2<T> declaration is actually invalid; it is a
4228      full-specialization.  Of course,
4229
4230           template <class U>
4231           struct S2<T (*)(U)>;
4232
4233      or some such would have been OK.  */
4234   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4235   tpd.parms = XALLOCAVEC (int, ntparms);
4236   memset (tpd.parms, 0, sizeof (int) * ntparms);
4237
4238   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4239   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4240   for (i = 0; i < nargs; ++i)
4241     {
4242       tpd.current_arg = i;
4243       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4244                               &mark_template_parm,
4245                               &tpd,
4246                               NULL,
4247                               /*include_nondeduced_p=*/false);
4248     }
4249   for (i = 0; i < ntparms; ++i)
4250     if (tpd.parms[i] == 0)
4251       {
4252         /* One of the template parms was not used in the
4253            specialization.  */
4254         if (!did_error_intro)
4255           {
4256             error ("template parameters not used in partial specialization:");
4257             did_error_intro = true;
4258           }
4259
4260         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
4261       }
4262
4263   if (did_error_intro)
4264     return error_mark_node;
4265
4266   /* [temp.class.spec]
4267
4268      The argument list of the specialization shall not be identical to
4269      the implicit argument list of the primary template.  */
4270   if (comp_template_args
4271       (inner_args,
4272        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
4273                                                    (maintmpl)))))
4274     error ("partial specialization %qT does not specialize any template arguments", type);
4275
4276   /* [temp.class.spec]
4277
4278      A partially specialized non-type argument expression shall not
4279      involve template parameters of the partial specialization except
4280      when the argument expression is a simple identifier.
4281
4282      The type of a template parameter corresponding to a specialized
4283      non-type argument shall not be dependent on a parameter of the
4284      specialization. 
4285
4286      Also, we verify that pack expansions only occur at the
4287      end of the argument list.  */
4288   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
4289   tpd2.parms = 0;
4290   for (i = 0; i < nargs; ++i)
4291     {
4292       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
4293       tree arg = TREE_VEC_ELT (inner_args, i);
4294       tree packed_args = NULL_TREE;
4295       int j, len = 1;
4296
4297       if (ARGUMENT_PACK_P (arg))
4298         {
4299           /* Extract the arguments from the argument pack. We'll be
4300              iterating over these in the following loop.  */
4301           packed_args = ARGUMENT_PACK_ARGS (arg);
4302           len = TREE_VEC_LENGTH (packed_args);
4303         }
4304
4305       for (j = 0; j < len; j++)
4306         {
4307           if (packed_args)
4308             /* Get the Jth argument in the parameter pack.  */
4309             arg = TREE_VEC_ELT (packed_args, j);
4310
4311           if (PACK_EXPANSION_P (arg))
4312             {
4313               /* Pack expansions must come at the end of the
4314                  argument list.  */
4315               if ((packed_args && j < len - 1)
4316                   || (!packed_args && i < nargs - 1))
4317                 {
4318                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4319                     error ("parameter pack argument %qE must be at the "
4320                            "end of the template argument list", arg);
4321                   else
4322                     error ("parameter pack argument %qT must be at the "
4323                            "end of the template argument list", arg);
4324                 }
4325             }
4326
4327           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4328             /* We only care about the pattern.  */
4329             arg = PACK_EXPANSION_PATTERN (arg);
4330
4331           if (/* These first two lines are the `non-type' bit.  */
4332               !TYPE_P (arg)
4333               && TREE_CODE (arg) != TEMPLATE_DECL
4334               /* This next line is the `argument expression is not just a
4335                  simple identifier' condition and also the `specialized
4336                  non-type argument' bit.  */
4337               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
4338             {
4339               if ((!packed_args && tpd.arg_uses_template_parms[i])
4340                   || (packed_args && uses_template_parms (arg)))
4341                 error ("template argument %qE involves template parameter(s)",
4342                        arg);
4343               else 
4344                 {
4345                   /* Look at the corresponding template parameter,
4346                      marking which template parameters its type depends
4347                      upon.  */
4348                   tree type = TREE_TYPE (parm);
4349
4350                   if (!tpd2.parms)
4351                     {
4352                       /* We haven't yet initialized TPD2.  Do so now.  */
4353                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4354                       /* The number of parameters here is the number in the
4355                          main template, which, as checked in the assertion
4356                          above, is NARGS.  */
4357                       tpd2.parms = XALLOCAVEC (int, nargs);
4358                       tpd2.level = 
4359                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4360                     }
4361
4362                   /* Mark the template parameters.  But this time, we're
4363                      looking for the template parameters of the main
4364                      template, not in the specialization.  */
4365                   tpd2.current_arg = i;
4366                   tpd2.arg_uses_template_parms[i] = 0;
4367                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4368                   for_each_template_parm (type,
4369                                           &mark_template_parm,
4370                                           &tpd2,
4371                                           NULL,
4372                                           /*include_nondeduced_p=*/false);
4373
4374                   if (tpd2.arg_uses_template_parms [i])
4375                     {
4376                       /* The type depended on some template parameters.
4377                          If they are fully specialized in the
4378                          specialization, that's OK.  */
4379                       int j;
4380                       int count = 0;
4381                       for (j = 0; j < nargs; ++j)
4382                         if (tpd2.parms[j] != 0
4383                             && tpd.arg_uses_template_parms [j])
4384                           ++count;
4385                       if (count != 0)
4386                         error_n (input_location, count,
4387                                  "type %qT of template argument %qE depends "
4388                                  "on a template parameter",
4389                                  "type %qT of template argument %qE depends "
4390                                  "on template parameters",
4391                                  type,
4392                                  arg);
4393                     }
4394                 }
4395             }
4396         }
4397     }
4398
4399   /* We should only get here once.  */
4400   gcc_assert (!COMPLETE_TYPE_P (type));
4401
4402   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4403     = tree_cons (specargs, inner_parms,
4404                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4405   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4406
4407   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
4408        inst = TREE_CHAIN (inst))
4409     {
4410       tree inst_type = TREE_VALUE (inst);
4411       if (COMPLETE_TYPE_P (inst_type)
4412           && CLASSTYPE_IMPLICIT_INSTANTIATION (inst_type))
4413         {
4414           tree spec = most_specialized_class (inst_type, maintmpl, tf_none);
4415           if (spec && TREE_TYPE (spec) == type)
4416             permerror (input_location,
4417                        "partial specialization of %qT after instantiation "
4418                        "of %qT", type, inst_type);
4419         }
4420     }
4421
4422   return decl;
4423 }
4424
4425 /* Check that a template declaration's use of default arguments and
4426    parameter packs is not invalid.  Here, PARMS are the template
4427    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
4428    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
4429    specialization.
4430    
4431
4432    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4433    declaration (but not a definition); 1 indicates a declaration, 2
4434    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4435    emitted for extraneous default arguments.
4436
4437    Returns TRUE if there were no errors found, FALSE otherwise. */
4438
4439 bool
4440 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
4441                          int is_partial, int is_friend_decl)
4442 {
4443   const char *msg;
4444   int last_level_to_check;
4445   tree parm_level;
4446   bool no_errors = true;
4447
4448   /* [temp.param]
4449
4450      A default template-argument shall not be specified in a
4451      function template declaration or a function template definition, nor
4452      in the template-parameter-list of the definition of a member of a
4453      class template.  */
4454
4455   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
4456     /* You can't have a function template declaration in a local
4457        scope, nor you can you define a member of a class template in a
4458        local scope.  */
4459     return true;
4460
4461   if (current_class_type
4462       && !TYPE_BEING_DEFINED (current_class_type)
4463       && DECL_LANG_SPECIFIC (decl)
4464       && DECL_DECLARES_FUNCTION_P (decl)
4465       /* If this is either a friend defined in the scope of the class
4466          or a member function.  */
4467       && (DECL_FUNCTION_MEMBER_P (decl)
4468           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4469           : DECL_FRIEND_CONTEXT (decl)
4470           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4471           : false)
4472       /* And, if it was a member function, it really was defined in
4473          the scope of the class.  */
4474       && (!DECL_FUNCTION_MEMBER_P (decl)
4475           || DECL_INITIALIZED_IN_CLASS_P (decl)))
4476     /* We already checked these parameters when the template was
4477        declared, so there's no need to do it again now.  This function
4478        was defined in class scope, but we're processing it's body now
4479        that the class is complete.  */
4480     return true;
4481
4482   /* Core issue 226 (C++0x only): the following only applies to class
4483      templates.  */
4484   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
4485     {
4486       /* [temp.param]
4487
4488          If a template-parameter has a default template-argument, all
4489          subsequent template-parameters shall have a default
4490          template-argument supplied.  */
4491       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4492         {
4493           tree inner_parms = TREE_VALUE (parm_level);
4494           int ntparms = TREE_VEC_LENGTH (inner_parms);
4495           int seen_def_arg_p = 0;
4496           int i;
4497
4498           for (i = 0; i < ntparms; ++i)
4499             {
4500               tree parm = TREE_VEC_ELT (inner_parms, i);
4501
4502               if (parm == error_mark_node)
4503                 continue;
4504
4505               if (TREE_PURPOSE (parm))
4506                 seen_def_arg_p = 1;
4507               else if (seen_def_arg_p
4508                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4509                 {
4510                   error ("no default argument for %qD", TREE_VALUE (parm));
4511                   /* For better subsequent error-recovery, we indicate that
4512                      there should have been a default argument.  */
4513                   TREE_PURPOSE (parm) = error_mark_node;
4514                   no_errors = false;
4515                 }
4516               else if (is_primary
4517                        && !is_partial
4518                        && !is_friend_decl
4519                        /* Don't complain about an enclosing partial
4520                           specialization.  */
4521                        && parm_level == parms
4522                        && TREE_CODE (decl) == TYPE_DECL
4523                        && i < ntparms - 1
4524                        && template_parameter_pack_p (TREE_VALUE (parm)))
4525                 {
4526                   /* A primary class template can only have one
4527                      parameter pack, at the end of the template
4528                      parameter list.  */
4529
4530                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4531                     error ("parameter pack %qE must be at the end of the"
4532                            " template parameter list", TREE_VALUE (parm));
4533                   else
4534                     error ("parameter pack %qT must be at the end of the"
4535                            " template parameter list", 
4536                            TREE_TYPE (TREE_VALUE (parm)));
4537
4538                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4539                     = error_mark_node;
4540                   no_errors = false;
4541                 }
4542             }
4543         }
4544     }
4545
4546   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4547       || is_partial 
4548       || !is_primary
4549       || is_friend_decl)
4550     /* For an ordinary class template, default template arguments are
4551        allowed at the innermost level, e.g.:
4552          template <class T = int>
4553          struct S {};
4554        but, in a partial specialization, they're not allowed even
4555        there, as we have in [temp.class.spec]:
4556
4557          The template parameter list of a specialization shall not
4558          contain default template argument values.
4559
4560        So, for a partial specialization, or for a function template
4561        (in C++98/C++03), we look at all of them.  */
4562     ;
4563   else
4564     /* But, for a primary class template that is not a partial
4565        specialization we look at all template parameters except the
4566        innermost ones.  */
4567     parms = TREE_CHAIN (parms);
4568
4569   /* Figure out what error message to issue.  */
4570   if (is_friend_decl == 2)
4571     msg = G_("default template arguments may not be used in function template "
4572              "friend re-declaration");
4573   else if (is_friend_decl)
4574     msg = G_("default template arguments may not be used in function template "
4575              "friend declarations");
4576   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4577     msg = G_("default template arguments may not be used in function templates "
4578              "without -std=c++0x or -std=gnu++0x");
4579   else if (is_partial)
4580     msg = G_("default template arguments may not be used in "
4581              "partial specializations");
4582   else
4583     msg = G_("default argument for template parameter for class enclosing %qD");
4584
4585   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4586     /* If we're inside a class definition, there's no need to
4587        examine the parameters to the class itself.  On the one
4588        hand, they will be checked when the class is defined, and,
4589        on the other, default arguments are valid in things like:
4590          template <class T = double>
4591          struct S { template <class U> void f(U); };
4592        Here the default argument for `S' has no bearing on the
4593        declaration of `f'.  */
4594     last_level_to_check = template_class_depth (current_class_type) + 1;
4595   else
4596     /* Check everything.  */
4597     last_level_to_check = 0;
4598
4599   for (parm_level = parms;
4600        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4601        parm_level = TREE_CHAIN (parm_level))
4602     {
4603       tree inner_parms = TREE_VALUE (parm_level);
4604       int i;
4605       int ntparms;
4606
4607       ntparms = TREE_VEC_LENGTH (inner_parms);
4608       for (i = 0; i < ntparms; ++i)
4609         {
4610           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4611             continue;
4612
4613           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4614             {
4615               if (msg)
4616                 {
4617                   no_errors = false;
4618                   if (is_friend_decl == 2)
4619                     return no_errors;
4620
4621                   error (msg, decl);
4622                   msg = 0;
4623                 }
4624
4625               /* Clear out the default argument so that we are not
4626                  confused later.  */
4627               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4628             }
4629         }
4630
4631       /* At this point, if we're still interested in issuing messages,
4632          they must apply to classes surrounding the object declared.  */
4633       if (msg)
4634         msg = G_("default argument for template parameter for class "
4635                  "enclosing %qD");
4636     }
4637
4638   return no_errors;
4639 }
4640
4641 /* Worker for push_template_decl_real, called via
4642    for_each_template_parm.  DATA is really an int, indicating the
4643    level of the parameters we are interested in.  If T is a template
4644    parameter of that level, return nonzero.  */
4645
4646 static int
4647 template_parm_this_level_p (tree t, void* data)
4648 {
4649   int this_level = *(int *)data;
4650   int level;
4651
4652   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4653     level = TEMPLATE_PARM_LEVEL (t);
4654   else
4655     level = TEMPLATE_TYPE_LEVEL (t);
4656   return level == this_level;
4657 }
4658
4659 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4660    parameters given by current_template_args, or reuses a
4661    previously existing one, if appropriate.  Returns the DECL, or an
4662    equivalent one, if it is replaced via a call to duplicate_decls.
4663
4664    If IS_FRIEND is true, DECL is a friend declaration.  */
4665
4666 tree
4667 push_template_decl_real (tree decl, bool is_friend)
4668 {
4669   tree tmpl;
4670   tree args;
4671   tree info;
4672   tree ctx;
4673   int primary;
4674   int is_partial;
4675   int new_template_p = 0;
4676   /* True if the template is a member template, in the sense of
4677      [temp.mem].  */
4678   bool member_template_p = false;
4679
4680   if (decl == error_mark_node || !current_template_parms)
4681     return error_mark_node;
4682
4683   /* See if this is a partial specialization.  */
4684   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4685                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4686                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4687
4688   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4689     is_friend = true;
4690
4691   if (is_friend)
4692     /* For a friend, we want the context of the friend function, not
4693        the type of which it is a friend.  */
4694     ctx = CP_DECL_CONTEXT (decl);
4695   else if (CP_DECL_CONTEXT (decl)
4696            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4697     /* In the case of a virtual function, we want the class in which
4698        it is defined.  */
4699     ctx = CP_DECL_CONTEXT (decl);
4700   else
4701     /* Otherwise, if we're currently defining some class, the DECL
4702        is assumed to be a member of the class.  */
4703     ctx = current_scope ();
4704
4705   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4706     ctx = NULL_TREE;
4707
4708   if (!DECL_CONTEXT (decl))
4709     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4710
4711   /* See if this is a primary template.  */
4712   if (is_friend && ctx)
4713     /* A friend template that specifies a class context, i.e.
4714          template <typename T> friend void A<T>::f();
4715        is not primary.  */
4716     primary = 0;
4717   else
4718     primary = template_parm_scope_p ();
4719
4720   if (primary)
4721     {
4722       if (DECL_CLASS_SCOPE_P (decl))
4723         member_template_p = true;
4724       if (TREE_CODE (decl) == TYPE_DECL
4725           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4726         {
4727           error ("template class without a name");
4728           return error_mark_node;
4729         }
4730       else if (TREE_CODE (decl) == FUNCTION_DECL)
4731         {
4732           if (DECL_DESTRUCTOR_P (decl))
4733             {
4734               /* [temp.mem]
4735
4736                  A destructor shall not be a member template.  */
4737               error ("destructor %qD declared as member template", decl);
4738               return error_mark_node;
4739             }
4740           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4741               && (!prototype_p (TREE_TYPE (decl))
4742                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4743                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4744                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4745                       == void_list_node)))
4746             {
4747               /* [basic.stc.dynamic.allocation]
4748
4749                  An allocation function can be a function
4750                  template. ... Template allocation functions shall
4751                  have two or more parameters.  */
4752               error ("invalid template declaration of %qD", decl);
4753               return error_mark_node;
4754             }
4755         }
4756       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4757                && CLASS_TYPE_P (TREE_TYPE (decl)))
4758         /* OK */;
4759       else
4760         {
4761           error ("template declaration of %q#D", decl);
4762           return error_mark_node;
4763         }
4764     }
4765
4766   /* Check to see that the rules regarding the use of default
4767      arguments are not being violated.  */
4768   check_default_tmpl_args (decl, current_template_parms,
4769                            primary, is_partial, /*is_friend_decl=*/0);
4770
4771   /* Ensure that there are no parameter packs in the type of this
4772      declaration that have not been expanded.  */
4773   if (TREE_CODE (decl) == FUNCTION_DECL)
4774     {
4775       /* Check each of the arguments individually to see if there are
4776          any bare parameter packs.  */
4777       tree type = TREE_TYPE (decl);
4778       tree arg = DECL_ARGUMENTS (decl);
4779       tree argtype = TYPE_ARG_TYPES (type);
4780
4781       while (arg && argtype)
4782         {
4783           if (!FUNCTION_PARAMETER_PACK_P (arg)
4784               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4785             {
4786             /* This is a PARM_DECL that contains unexpanded parameter
4787                packs. We have already complained about this in the
4788                check_for_bare_parameter_packs call, so just replace
4789                these types with ERROR_MARK_NODE.  */
4790               TREE_TYPE (arg) = error_mark_node;
4791               TREE_VALUE (argtype) = error_mark_node;
4792             }
4793
4794           arg = DECL_CHAIN (arg);
4795           argtype = TREE_CHAIN (argtype);
4796         }
4797
4798       /* Check for bare parameter packs in the return type and the
4799          exception specifiers.  */
4800       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4801         /* Errors were already issued, set return type to int
4802            as the frontend doesn't expect error_mark_node as
4803            the return type.  */
4804         TREE_TYPE (type) = integer_type_node;
4805       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4806         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4807     }
4808   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4809     {
4810       TREE_TYPE (decl) = error_mark_node;
4811       return error_mark_node;
4812     }
4813
4814   if (is_partial)
4815     return process_partial_specialization (decl);
4816
4817   args = current_template_args ();
4818
4819   if (!ctx
4820       || TREE_CODE (ctx) == FUNCTION_DECL
4821       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4822       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4823     {
4824       if (DECL_LANG_SPECIFIC (decl)
4825           && DECL_TEMPLATE_INFO (decl)
4826           && DECL_TI_TEMPLATE (decl))
4827         tmpl = DECL_TI_TEMPLATE (decl);
4828       /* If DECL is a TYPE_DECL for a class-template, then there won't
4829          be DECL_LANG_SPECIFIC.  The information equivalent to
4830          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4831       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4832                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4833                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4834         {
4835           /* Since a template declaration already existed for this
4836              class-type, we must be redeclaring it here.  Make sure
4837              that the redeclaration is valid.  */
4838           redeclare_class_template (TREE_TYPE (decl),
4839                                     current_template_parms);
4840           /* We don't need to create a new TEMPLATE_DECL; just use the
4841              one we already had.  */
4842           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4843         }
4844       else
4845         {
4846           tmpl = build_template_decl (decl, current_template_parms,
4847                                       member_template_p);
4848           new_template_p = 1;
4849
4850           if (DECL_LANG_SPECIFIC (decl)
4851               && DECL_TEMPLATE_SPECIALIZATION (decl))
4852             {
4853               /* A specialization of a member template of a template
4854                  class.  */
4855               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4856               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4857               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4858             }
4859         }
4860     }
4861   else
4862     {
4863       tree a, t, current, parms;
4864       int i;
4865       tree tinfo = get_template_info (decl);
4866
4867       if (!tinfo)
4868         {
4869           error ("template definition of non-template %q#D", decl);
4870           return error_mark_node;
4871         }
4872
4873       tmpl = TI_TEMPLATE (tinfo);
4874
4875       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4876           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4877           && DECL_TEMPLATE_SPECIALIZATION (decl)
4878           && DECL_MEMBER_TEMPLATE_P (tmpl))
4879         {
4880           tree new_tmpl;
4881
4882           /* The declaration is a specialization of a member
4883              template, declared outside the class.  Therefore, the
4884              innermost template arguments will be NULL, so we
4885              replace them with the arguments determined by the
4886              earlier call to check_explicit_specialization.  */
4887           args = DECL_TI_ARGS (decl);
4888
4889           new_tmpl
4890             = build_template_decl (decl, current_template_parms,
4891                                    member_template_p);
4892           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4893           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4894           DECL_TI_TEMPLATE (decl) = new_tmpl;
4895           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4896           DECL_TEMPLATE_INFO (new_tmpl)
4897             = build_template_info (tmpl, args);
4898
4899           register_specialization (new_tmpl,
4900                                    most_general_template (tmpl),
4901                                    args,
4902                                    is_friend, 0);
4903           return decl;
4904         }
4905
4906       /* Make sure the template headers we got make sense.  */
4907
4908       parms = DECL_TEMPLATE_PARMS (tmpl);
4909       i = TMPL_PARMS_DEPTH (parms);
4910       if (TMPL_ARGS_DEPTH (args) != i)
4911         {
4912           error ("expected %d levels of template parms for %q#D, got %d",
4913                  i, decl, TMPL_ARGS_DEPTH (args));
4914         }
4915       else
4916         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4917           {
4918             a = TMPL_ARGS_LEVEL (args, i);
4919             t = INNERMOST_TEMPLATE_PARMS (parms);
4920
4921             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4922               {
4923                 if (current == decl)
4924                   error ("got %d template parameters for %q#D",
4925                          TREE_VEC_LENGTH (a), decl);
4926                 else
4927                   error ("got %d template parameters for %q#T",
4928                          TREE_VEC_LENGTH (a), current);
4929                 error ("  but %d required", TREE_VEC_LENGTH (t));
4930                 return error_mark_node;
4931               }
4932
4933             if (current == decl)
4934               current = ctx;
4935             else if (current == NULL_TREE)
4936               /* Can happen in erroneous input.  */
4937               break;
4938             else
4939               current = (TYPE_P (current)
4940                          ? TYPE_CONTEXT (current)
4941                          : DECL_CONTEXT (current));
4942           }
4943
4944       /* Check that the parms are used in the appropriate qualifying scopes
4945          in the declarator.  */
4946       if (!comp_template_args
4947           (TI_ARGS (tinfo),
4948            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4949         {
4950           error ("\
4951 template arguments to %qD do not match original template %qD",
4952                  decl, DECL_TEMPLATE_RESULT (tmpl));
4953           if (!uses_template_parms (TI_ARGS (tinfo)))
4954             inform (input_location, "use template<> for an explicit specialization");
4955           /* Avoid crash in import_export_decl.  */
4956           DECL_INTERFACE_KNOWN (decl) = 1;
4957           return error_mark_node;
4958         }
4959     }
4960
4961   DECL_TEMPLATE_RESULT (tmpl) = decl;
4962   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4963
4964   /* Push template declarations for global functions and types.  Note
4965      that we do not try to push a global template friend declared in a
4966      template class; such a thing may well depend on the template
4967      parameters of the class.  */
4968   if (new_template_p && !ctx
4969       && !(is_friend && template_class_depth (current_class_type) > 0))
4970     {
4971       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4972       if (tmpl == error_mark_node)
4973         return error_mark_node;
4974
4975       /* Hide template friend classes that haven't been declared yet.  */
4976       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4977         {
4978           DECL_ANTICIPATED (tmpl) = 1;
4979           DECL_FRIEND_P (tmpl) = 1;
4980         }
4981     }
4982
4983   if (primary)
4984     {
4985       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4986       int i;
4987
4988       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4989       if (DECL_CONV_FN_P (tmpl))
4990         {
4991           int depth = TMPL_PARMS_DEPTH (parms);
4992
4993           /* It is a conversion operator. See if the type converted to
4994              depends on innermost template operands.  */
4995
4996           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4997                                          depth))
4998             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4999         }
5000
5001       /* Give template template parms a DECL_CONTEXT of the template
5002          for which they are a parameter.  */
5003       parms = INNERMOST_TEMPLATE_PARMS (parms);
5004       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
5005         {
5006           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5007           if (TREE_CODE (parm) == TEMPLATE_DECL)
5008             DECL_CONTEXT (parm) = tmpl;
5009         }
5010     }
5011
5012   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
5013      back to its most general template.  If TMPL is a specialization,
5014      ARGS may only have the innermost set of arguments.  Add the missing
5015      argument levels if necessary.  */
5016   if (DECL_TEMPLATE_INFO (tmpl))
5017     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
5018
5019   info = build_template_info (tmpl, args);
5020
5021   if (DECL_IMPLICIT_TYPEDEF_P (decl))
5022     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
5023   else if (DECL_LANG_SPECIFIC (decl))
5024     DECL_TEMPLATE_INFO (decl) = info;
5025
5026   return DECL_TEMPLATE_RESULT (tmpl);
5027 }
5028
5029 tree
5030 push_template_decl (tree decl)
5031 {
5032   return push_template_decl_real (decl, false);
5033 }
5034
5035 /* Called when a class template TYPE is redeclared with the indicated
5036    template PARMS, e.g.:
5037
5038      template <class T> struct S;
5039      template <class T> struct S {};  */
5040
5041 bool
5042 redeclare_class_template (tree type, tree parms)
5043 {
5044   tree tmpl;
5045   tree tmpl_parms;
5046   int i;
5047
5048   if (!TYPE_TEMPLATE_INFO (type))
5049     {
5050       error ("%qT is not a template type", type);
5051       return false;
5052     }
5053
5054   tmpl = TYPE_TI_TEMPLATE (type);
5055   if (!PRIMARY_TEMPLATE_P (tmpl))
5056     /* The type is nested in some template class.  Nothing to worry
5057        about here; there are no new template parameters for the nested
5058        type.  */
5059     return true;
5060
5061   if (!parms)
5062     {
5063       error ("template specifiers not specified in declaration of %qD",
5064              tmpl);
5065       return false;
5066     }
5067
5068   parms = INNERMOST_TEMPLATE_PARMS (parms);
5069   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
5070
5071   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
5072     {
5073       error_n (input_location, TREE_VEC_LENGTH (parms),
5074                "redeclared with %d template parameter",
5075                "redeclared with %d template parameters",
5076                TREE_VEC_LENGTH (parms));
5077       inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
5078                 "previous declaration %q+D used %d template parameter",
5079                 "previous declaration %q+D used %d template parameters",
5080                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
5081       return false;
5082     }
5083
5084   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
5085     {
5086       tree tmpl_parm;
5087       tree parm;
5088       tree tmpl_default;
5089       tree parm_default;
5090
5091       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
5092           || TREE_VEC_ELT (parms, i) == error_mark_node)
5093         continue;
5094
5095       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
5096       if (tmpl_parm == error_mark_node)
5097         return false;
5098
5099       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5100       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
5101       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
5102
5103       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
5104          TEMPLATE_DECL.  */
5105       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
5106           || (TREE_CODE (tmpl_parm) != TYPE_DECL
5107               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
5108           || (TREE_CODE (tmpl_parm) != PARM_DECL
5109               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
5110                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
5111           || (TREE_CODE (tmpl_parm) == PARM_DECL
5112               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
5113                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
5114         {
5115           error ("template parameter %q+#D", tmpl_parm);
5116           error ("redeclared here as %q#D", parm);
5117           return false;
5118         }
5119
5120       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
5121         {
5122           /* We have in [temp.param]:
5123
5124              A template-parameter may not be given default arguments
5125              by two different declarations in the same scope.  */
5126           error_at (input_location, "redefinition of default argument for %q#D", parm);
5127           inform (DECL_SOURCE_LOCATION (tmpl_parm),
5128                   "original definition appeared here");
5129           return false;
5130         }
5131
5132       if (parm_default != NULL_TREE)
5133         /* Update the previous template parameters (which are the ones
5134            that will really count) with the new default value.  */
5135         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
5136       else if (tmpl_default != NULL_TREE)
5137         /* Update the new parameters, too; they'll be used as the
5138            parameters for any members.  */
5139         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
5140     }
5141
5142     return true;
5143 }
5144
5145 /* Simplify EXPR if it is a non-dependent expression.  Returns the
5146    (possibly simplified) expression.  */
5147
5148 static tree
5149 fold_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
5150 {
5151   if (expr == NULL_TREE)
5152     return NULL_TREE;
5153
5154   /* If we're in a template, but EXPR isn't value dependent, simplify
5155      it.  We're supposed to treat:
5156
5157        template <typename T> void f(T[1 + 1]);
5158        template <typename T> void f(T[2]);
5159
5160      as two declarations of the same function, for example.  */
5161   if (processing_template_decl
5162       && !type_dependent_expression_p (expr)
5163       && potential_constant_expression (expr)
5164       && !value_dependent_expression_p (expr))
5165     {
5166       HOST_WIDE_INT saved_processing_template_decl;
5167
5168       saved_processing_template_decl = processing_template_decl;
5169       processing_template_decl = 0;
5170       expr = tsubst_copy_and_build (expr,
5171                                     /*args=*/NULL_TREE,
5172                                     complain,
5173                                     /*in_decl=*/NULL_TREE,
5174                                     /*function_p=*/false,
5175                                     /*integral_constant_expression_p=*/true);
5176       processing_template_decl = saved_processing_template_decl;
5177     }
5178   return expr;
5179 }
5180
5181 tree
5182 fold_non_dependent_expr (tree expr)
5183 {
5184   return fold_non_dependent_expr_sfinae (expr, tf_error);
5185 }
5186
5187 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
5188    must be a function or a pointer-to-function type, as specified
5189    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
5190    and check that the resulting function has external linkage.  */
5191
5192 static tree
5193 convert_nontype_argument_function (tree type, tree expr)
5194 {
5195   tree fns = expr;
5196   tree fn, fn_no_ptr;
5197
5198   fn = instantiate_type (type, fns, tf_none);
5199   if (fn == error_mark_node)
5200     return error_mark_node;
5201
5202   fn_no_ptr = fn;
5203   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
5204     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
5205   if (TREE_CODE (fn_no_ptr) == BASELINK)
5206     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
5207  
5208   /* [temp.arg.nontype]/1
5209
5210      A template-argument for a non-type, non-template template-parameter
5211      shall be one of:
5212      [...]
5213      -- the address of an object or function with external linkage.  */
5214   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
5215     {
5216       error ("%qE is not a valid template argument for type %qT "
5217              "because function %qD has not external linkage",
5218              expr, type, fn_no_ptr);
5219       return NULL_TREE;
5220     }
5221
5222   return fn;
5223 }
5224
5225 /* Subroutine of convert_nontype_argument.
5226    Check if EXPR of type TYPE is a valid pointer-to-member constant.
5227    Emit an error otherwise.  */
5228
5229 static bool
5230 check_valid_ptrmem_cst_expr (tree type, tree expr,
5231                              tsubst_flags_t complain)
5232 {
5233   STRIP_NOPS (expr);
5234   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
5235     return true;
5236   if (complain & tf_error)
5237     {
5238       error ("%qE is not a valid template argument for type %qT",
5239              expr, type);
5240       error ("it must be a pointer-to-member of the form %<&X::Y%>");
5241     }
5242   return false;
5243 }
5244
5245 /* Returns TRUE iff the address of OP is value-dependent.
5246
5247    14.6.2.4 [temp.dep.temp]:
5248    A non-integral non-type template-argument is dependent if its type is
5249    dependent or it has either of the following forms
5250      qualified-id
5251      & qualified-id
5252    and contains a nested-name-specifier which specifies a class-name that
5253    names a dependent type.
5254
5255    We generalize this to just say that the address of a member of a
5256    dependent class is value-dependent; the above doesn't cover the
5257    address of a static data member named with an unqualified-id.  */
5258
5259 static bool
5260 has_value_dependent_address (tree op)
5261 {
5262   /* We could use get_inner_reference here, but there's no need;
5263      this is only relevant for template non-type arguments, which
5264      can only be expressed as &id-expression.  */
5265   if (DECL_P (op))
5266     {
5267       tree ctx = CP_DECL_CONTEXT (op);
5268       if (TYPE_P (ctx) && dependent_type_p (ctx))
5269         return true;
5270     }
5271
5272   return false;
5273 }
5274
5275 /* Attempt to convert the non-type template parameter EXPR to the
5276    indicated TYPE.  If the conversion is successful, return the
5277    converted value.  If the conversion is unsuccessful, return
5278    NULL_TREE if we issued an error message, or error_mark_node if we
5279    did not.  We issue error messages for out-and-out bad template
5280    parameters, but not simply because the conversion failed, since we
5281    might be just trying to do argument deduction.  Both TYPE and EXPR
5282    must be non-dependent.
5283
5284    The conversion follows the special rules described in
5285    [temp.arg.nontype], and it is much more strict than an implicit
5286    conversion.
5287
5288    This function is called twice for each template argument (see
5289    lookup_template_class for a more accurate description of this
5290    problem). This means that we need to handle expressions which
5291    are not valid in a C++ source, but can be created from the
5292    first call (for instance, casts to perform conversions). These
5293    hacks can go away after we fix the double coercion problem.  */
5294
5295 static tree
5296 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
5297 {
5298   tree expr_type;
5299
5300   /* Detect immediately string literals as invalid non-type argument.
5301      This special-case is not needed for correctness (we would easily
5302      catch this later), but only to provide better diagnostic for this
5303      common user mistake. As suggested by DR 100, we do not mention
5304      linkage issues in the diagnostic as this is not the point.  */
5305   /* FIXME we're making this OK.  */
5306   if (TREE_CODE (expr) == STRING_CST)
5307     {
5308       if (complain & tf_error)
5309         error ("%qE is not a valid template argument for type %qT "
5310                "because string literals can never be used in this context",
5311                expr, type);
5312       return NULL_TREE;
5313     }
5314
5315   /* Add the ADDR_EXPR now for the benefit of
5316      value_dependent_expression_p.  */
5317   if (TYPE_PTROBV_P (type))
5318     expr = decay_conversion (expr);
5319
5320   /* If we are in a template, EXPR may be non-dependent, but still
5321      have a syntactic, rather than semantic, form.  For example, EXPR
5322      might be a SCOPE_REF, rather than the VAR_DECL to which the
5323      SCOPE_REF refers.  Preserving the qualifying scope is necessary
5324      so that access checking can be performed when the template is
5325      instantiated -- but here we need the resolved form so that we can
5326      convert the argument.  */
5327   if (TYPE_REF_OBJ_P (type)
5328       && has_value_dependent_address (expr))
5329     /* If we want the address and it's value-dependent, don't fold.  */;
5330   else if (!type_unknown_p (expr))
5331     expr = fold_non_dependent_expr_sfinae (expr, complain);
5332   if (error_operand_p (expr))
5333     return error_mark_node;
5334   expr_type = TREE_TYPE (expr);
5335   if (TREE_CODE (type) == REFERENCE_TYPE)
5336     expr = mark_lvalue_use (expr);
5337   else
5338     expr = mark_rvalue_use (expr);
5339
5340   /* HACK: Due to double coercion, we can get a
5341      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
5342      which is the tree that we built on the first call (see
5343      below when coercing to reference to object or to reference to
5344      function). We just strip everything and get to the arg.
5345      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
5346      for examples.  */
5347   if (TREE_CODE (expr) == NOP_EXPR)
5348     {
5349       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
5350         {
5351           /* ??? Maybe we could use convert_from_reference here, but we
5352              would need to relax its constraints because the NOP_EXPR
5353              could actually change the type to something more cv-qualified,
5354              and this is not folded by convert_from_reference.  */
5355           tree addr = TREE_OPERAND (expr, 0);
5356           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
5357           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
5358           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
5359           gcc_assert (same_type_ignoring_top_level_qualifiers_p
5360                       (TREE_TYPE (expr_type),
5361                        TREE_TYPE (TREE_TYPE (addr))));
5362
5363           expr = TREE_OPERAND (addr, 0);
5364           expr_type = TREE_TYPE (expr);
5365         }
5366
5367       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
5368          parameter is a pointer to object, through decay and
5369          qualification conversion. Let's strip everything.  */
5370       else if (TYPE_PTROBV_P (type))
5371         {
5372           tree sub = expr;
5373           STRIP_NOPS (sub);
5374           if (TREE_CODE (sub) == ADDR_EXPR)
5375             {
5376               gcc_assert (TREE_CODE (TREE_TYPE (sub)) == POINTER_TYPE);
5377               /* Skip the ADDR_EXPR only if it is part of the decay for
5378                  an array. Otherwise, it is part of the original argument
5379                  in the source code.  */
5380               if (TREE_CODE (TREE_TYPE (TREE_OPERAND (sub, 0))) == ARRAY_TYPE)
5381                 expr = TREE_OPERAND (sub, 0);
5382               else
5383                 expr = sub;
5384               expr_type = TREE_TYPE (expr);
5385             }
5386         }
5387     }
5388
5389   /* [temp.arg.nontype]/5, bullet 1
5390
5391      For a non-type template-parameter of integral or enumeration type,
5392      integral promotions (_conv.prom_) and integral conversions
5393      (_conv.integral_) are applied.  */
5394   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5395     {
5396       tree t = build_integral_nontype_arg_conv (type, expr, complain);
5397       t = maybe_constant_value (t);
5398       if (t != error_mark_node)
5399         expr = t;
5400
5401       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
5402         return error_mark_node;
5403
5404       /* Notice that there are constant expressions like '4 % 0' which
5405          do not fold into integer constants.  */
5406       if (TREE_CODE (expr) != INTEGER_CST)
5407         {
5408           if (complain & tf_error)
5409             {
5410               int errs = errorcount, warns = warningcount;
5411               expr = cxx_constant_value (expr);
5412               if (errorcount > errs || warningcount > warns)
5413                 inform (EXPR_LOC_OR_HERE (expr),
5414                         "in template argument for type %qT ", type);
5415               if (expr == error_mark_node)
5416                 return NULL_TREE;
5417               /* else cxx_constant_value complained but gave us
5418                  a real constant, so go ahead.  */
5419               gcc_assert (TREE_CODE (expr) == INTEGER_CST);
5420             }
5421           else
5422             return NULL_TREE;
5423         }
5424     }
5425   /* [temp.arg.nontype]/5, bullet 2
5426
5427      For a non-type template-parameter of type pointer to object,
5428      qualification conversions (_conv.qual_) and the array-to-pointer
5429      conversion (_conv.array_) are applied.  */
5430   else if (TYPE_PTROBV_P (type))
5431     {
5432       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
5433
5434          A template-argument for a non-type, non-template template-parameter
5435          shall be one of: [...]
5436
5437          -- the name of a non-type template-parameter;
5438          -- the address of an object or function with external linkage, [...]
5439             expressed as "& id-expression" where the & is optional if the name
5440             refers to a function or array, or if the corresponding
5441             template-parameter is a reference.
5442
5443         Here, we do not care about functions, as they are invalid anyway
5444         for a parameter of type pointer-to-object.  */
5445
5446       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
5447         /* Non-type template parameters are OK.  */
5448         ;
5449       else if (TREE_CODE (expr) != ADDR_EXPR
5450                && TREE_CODE (expr_type) != ARRAY_TYPE)
5451         {
5452           if (TREE_CODE (expr) == VAR_DECL)
5453             {
5454               error ("%qD is not a valid template argument "
5455                      "because %qD is a variable, not the address of "
5456                      "a variable",
5457                      expr, expr);
5458               return NULL_TREE;
5459             }
5460           /* Other values, like integer constants, might be valid
5461              non-type arguments of some other type.  */
5462           return error_mark_node;
5463         }
5464       else
5465         {
5466           tree decl;
5467
5468           decl = ((TREE_CODE (expr) == ADDR_EXPR)
5469                   ? TREE_OPERAND (expr, 0) : expr);
5470           if (TREE_CODE (decl) != VAR_DECL)
5471             {
5472               error ("%qE is not a valid template argument of type %qT "
5473                      "because %qE is not a variable",
5474                      expr, type, decl);
5475               return NULL_TREE;
5476             }
5477           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
5478             {
5479               error ("%qE is not a valid template argument of type %qT "
5480                      "because %qD does not have external linkage",
5481                      expr, type, decl);
5482               return NULL_TREE;
5483             }
5484         }
5485
5486       expr = decay_conversion (expr);
5487       if (expr == error_mark_node)
5488         return error_mark_node;
5489
5490       expr = perform_qualification_conversions (type, expr);
5491       if (expr == error_mark_node)
5492         return error_mark_node;
5493     }
5494   /* [temp.arg.nontype]/5, bullet 3
5495
5496      For a non-type template-parameter of type reference to object, no
5497      conversions apply. The type referred to by the reference may be more
5498      cv-qualified than the (otherwise identical) type of the
5499      template-argument. The template-parameter is bound directly to the
5500      template-argument, which must be an lvalue.  */
5501   else if (TYPE_REF_OBJ_P (type))
5502     {
5503       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5504                                                       expr_type))
5505         return error_mark_node;
5506
5507       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5508         {
5509           error ("%qE is not a valid template argument for type %qT "
5510                  "because of conflicts in cv-qualification", expr, type);
5511           return NULL_TREE;
5512         }
5513
5514       if (!real_lvalue_p (expr))
5515         {
5516           error ("%qE is not a valid template argument for type %qT "
5517                  "because it is not an lvalue", expr, type);
5518           return NULL_TREE;
5519         }
5520
5521       /* [temp.arg.nontype]/1
5522
5523          A template-argument for a non-type, non-template template-parameter
5524          shall be one of: [...]
5525
5526          -- the address of an object or function with external linkage.  */
5527       if (TREE_CODE (expr) == INDIRECT_REF
5528           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5529         {
5530           expr = TREE_OPERAND (expr, 0);
5531           if (DECL_P (expr))
5532             {
5533               error ("%q#D is not a valid template argument for type %qT "
5534                      "because a reference variable does not have a constant "
5535                      "address", expr, type);
5536               return NULL_TREE;
5537             }
5538         }
5539
5540       if (!DECL_P (expr))
5541         {
5542           error ("%qE is not a valid template argument for type %qT "
5543                  "because it is not an object with external linkage",
5544                  expr, type);
5545           return NULL_TREE;
5546         }
5547
5548       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5549         {
5550           error ("%qE is not a valid template argument for type %qT "
5551                  "because object %qD has not external linkage",
5552                  expr, type, expr);
5553           return NULL_TREE;
5554         }
5555
5556       expr = build_nop (type, build_address (expr));
5557     }
5558   /* [temp.arg.nontype]/5, bullet 4
5559
5560      For a non-type template-parameter of type pointer to function, only
5561      the function-to-pointer conversion (_conv.func_) is applied. If the
5562      template-argument represents a set of overloaded functions (or a
5563      pointer to such), the matching function is selected from the set
5564      (_over.over_).  */
5565   else if (TYPE_PTRFN_P (type))
5566     {
5567       /* If the argument is a template-id, we might not have enough
5568          context information to decay the pointer.  */
5569       if (!type_unknown_p (expr_type))
5570         {
5571           expr = decay_conversion (expr);
5572           if (expr == error_mark_node)
5573             return error_mark_node;
5574         }
5575
5576       expr = convert_nontype_argument_function (type, expr);
5577       if (!expr || expr == error_mark_node)
5578         return expr;
5579
5580       if (TREE_CODE (expr) != ADDR_EXPR)
5581         {
5582           error ("%qE is not a valid template argument for type %qT", expr, type);
5583           error ("it must be the address of a function with external linkage");
5584           return NULL_TREE;
5585         }
5586     }
5587   /* [temp.arg.nontype]/5, bullet 5
5588
5589      For a non-type template-parameter of type reference to function, no
5590      conversions apply. If the template-argument represents a set of
5591      overloaded functions, the matching function is selected from the set
5592      (_over.over_).  */
5593   else if (TYPE_REFFN_P (type))
5594     {
5595       if (TREE_CODE (expr) == ADDR_EXPR)
5596         {
5597           error ("%qE is not a valid template argument for type %qT "
5598                  "because it is a pointer", expr, type);
5599           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5600           return NULL_TREE;
5601         }
5602
5603       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5604       if (!expr || expr == error_mark_node)
5605         return expr;
5606
5607       expr = build_nop (type, build_address (expr));
5608     }
5609   /* [temp.arg.nontype]/5, bullet 6
5610
5611      For a non-type template-parameter of type pointer to member function,
5612      no conversions apply. If the template-argument represents a set of
5613      overloaded member functions, the matching member function is selected
5614      from the set (_over.over_).  */
5615   else if (TYPE_PTRMEMFUNC_P (type))
5616     {
5617       expr = instantiate_type (type, expr, tf_none);
5618       if (expr == error_mark_node)
5619         return error_mark_node;
5620
5621       /* [temp.arg.nontype] bullet 1 says the pointer to member
5622          expression must be a pointer-to-member constant.  */
5623       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5624         return error_mark_node;
5625
5626       /* There is no way to disable standard conversions in
5627          resolve_address_of_overloaded_function (called by
5628          instantiate_type). It is possible that the call succeeded by
5629          converting &B::I to &D::I (where B is a base of D), so we need
5630          to reject this conversion here.
5631
5632          Actually, even if there was a way to disable standard conversions,
5633          it would still be better to reject them here so that we can
5634          provide a superior diagnostic.  */
5635       if (!same_type_p (TREE_TYPE (expr), type))
5636         {
5637           error ("%qE is not a valid template argument for type %qT "
5638                  "because it is of type %qT", expr, type,
5639                  TREE_TYPE (expr));
5640           /* If we are just one standard conversion off, explain.  */
5641           if (can_convert (type, TREE_TYPE (expr)))
5642             inform (input_location,
5643                     "standard conversions are not allowed in this context");
5644           return NULL_TREE;
5645         }
5646     }
5647   /* [temp.arg.nontype]/5, bullet 7
5648
5649      For a non-type template-parameter of type pointer to data member,
5650      qualification conversions (_conv.qual_) are applied.  */
5651   else if (TYPE_PTRMEM_P (type))
5652     {
5653       /* [temp.arg.nontype] bullet 1 says the pointer to member
5654          expression must be a pointer-to-member constant.  */
5655       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5656         return error_mark_node;
5657
5658       expr = perform_qualification_conversions (type, expr);
5659       if (expr == error_mark_node)
5660         return expr;
5661     }
5662   /* A template non-type parameter must be one of the above.  */
5663   else
5664     gcc_unreachable ();
5665
5666   /* Sanity check: did we actually convert the argument to the
5667      right type?  */
5668   gcc_assert (same_type_ignoring_top_level_qualifiers_p
5669               (type, TREE_TYPE (expr)));
5670   return expr;
5671 }
5672
5673 /* Subroutine of coerce_template_template_parms, which returns 1 if
5674    PARM_PARM and ARG_PARM match using the rule for the template
5675    parameters of template template parameters. Both PARM and ARG are
5676    template parameters; the rest of the arguments are the same as for
5677    coerce_template_template_parms.
5678  */
5679 static int
5680 coerce_template_template_parm (tree parm,
5681                               tree arg,
5682                               tsubst_flags_t complain,
5683                               tree in_decl,
5684                               tree outer_args)
5685 {
5686   if (arg == NULL_TREE || arg == error_mark_node
5687       || parm == NULL_TREE || parm == error_mark_node)
5688     return 0;
5689   
5690   if (TREE_CODE (arg) != TREE_CODE (parm))
5691     return 0;
5692   
5693   switch (TREE_CODE (parm))
5694     {
5695     case TEMPLATE_DECL:
5696       /* We encounter instantiations of templates like
5697          template <template <template <class> class> class TT>
5698          class C;  */
5699       {
5700         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5701         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5702         
5703         if (!coerce_template_template_parms
5704             (parmparm, argparm, complain, in_decl, outer_args))
5705           return 0;
5706       }
5707       /* Fall through.  */
5708       
5709     case TYPE_DECL:
5710       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5711           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5712         /* Argument is a parameter pack but parameter is not.  */
5713         return 0;
5714       break;
5715       
5716     case PARM_DECL:
5717       /* The tsubst call is used to handle cases such as
5718          
5719            template <int> class C {};
5720            template <class T, template <T> class TT> class D {};
5721            D<int, C> d;
5722
5723          i.e. the parameter list of TT depends on earlier parameters.  */
5724       if (!uses_template_parms (TREE_TYPE (arg))
5725           && !same_type_p
5726                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5727                  TREE_TYPE (arg)))
5728         return 0;
5729       
5730       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5731           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5732         /* Argument is a parameter pack but parameter is not.  */
5733         return 0;
5734       
5735       break;
5736
5737     default:
5738       gcc_unreachable ();
5739     }
5740
5741   return 1;
5742 }
5743
5744
5745 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5746    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5747    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5748    or PARM_DECL.
5749
5750    Consider the example:
5751      template <class T> class A;
5752      template<template <class U> class TT> class B;
5753
5754    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5755    the parameters to A, and OUTER_ARGS contains A.  */
5756
5757 static int
5758 coerce_template_template_parms (tree parm_parms,
5759                                 tree arg_parms,
5760                                 tsubst_flags_t complain,
5761                                 tree in_decl,
5762                                 tree outer_args)
5763 {
5764   int nparms, nargs, i;
5765   tree parm, arg;
5766   int variadic_p = 0;
5767
5768   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5769   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5770
5771   nparms = TREE_VEC_LENGTH (parm_parms);
5772   nargs = TREE_VEC_LENGTH (arg_parms);
5773
5774   /* Determine whether we have a parameter pack at the end of the
5775      template template parameter's template parameter list.  */
5776   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5777     {
5778       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5779       
5780       if (parm == error_mark_node)
5781         return 0;
5782
5783       switch (TREE_CODE (parm))
5784         {
5785         case TEMPLATE_DECL:
5786         case TYPE_DECL:
5787           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5788             variadic_p = 1;
5789           break;
5790           
5791         case PARM_DECL:
5792           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5793             variadic_p = 1;
5794           break;
5795           
5796         default:
5797           gcc_unreachable ();
5798         }
5799     }
5800  
5801   if (nargs != nparms
5802       && !(variadic_p && nargs >= nparms - 1))
5803     return 0;
5804
5805   /* Check all of the template parameters except the parameter pack at
5806      the end (if any).  */
5807   for (i = 0; i < nparms - variadic_p; ++i)
5808     {
5809       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5810           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5811         continue;
5812
5813       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5814       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5815
5816       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5817                                           outer_args))
5818         return 0;
5819
5820     }
5821
5822   if (variadic_p)
5823     {
5824       /* Check each of the template parameters in the template
5825          argument against the template parameter pack at the end of
5826          the template template parameter.  */
5827       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5828         return 0;
5829
5830       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5831
5832       for (; i < nargs; ++i)
5833         {
5834           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5835             continue;
5836  
5837           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5838  
5839           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5840                                               outer_args))
5841             return 0;
5842         }
5843     }
5844
5845   return 1;
5846 }
5847
5848 /* Verifies that the deduced template arguments (in TARGS) for the
5849    template template parameters (in TPARMS) represent valid bindings,
5850    by comparing the template parameter list of each template argument
5851    to the template parameter list of its corresponding template
5852    template parameter, in accordance with DR150. This
5853    routine can only be called after all template arguments have been
5854    deduced. It will return TRUE if all of the template template
5855    parameter bindings are okay, FALSE otherwise.  */
5856 bool 
5857 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5858 {
5859   int i, ntparms = TREE_VEC_LENGTH (tparms);
5860   bool ret = true;
5861
5862   /* We're dealing with template parms in this process.  */
5863   ++processing_template_decl;
5864
5865   targs = INNERMOST_TEMPLATE_ARGS (targs);
5866
5867   for (i = 0; i < ntparms; ++i)
5868     {
5869       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5870       tree targ = TREE_VEC_ELT (targs, i);
5871
5872       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5873         {
5874           tree packed_args = NULL_TREE;
5875           int idx, len = 1;
5876
5877           if (ARGUMENT_PACK_P (targ))
5878             {
5879               /* Look inside the argument pack.  */
5880               packed_args = ARGUMENT_PACK_ARGS (targ);
5881               len = TREE_VEC_LENGTH (packed_args);
5882             }
5883
5884           for (idx = 0; idx < len; ++idx)
5885             {
5886               tree targ_parms = NULL_TREE;
5887
5888               if (packed_args)
5889                 /* Extract the next argument from the argument
5890                    pack.  */
5891                 targ = TREE_VEC_ELT (packed_args, idx);
5892
5893               if (PACK_EXPANSION_P (targ))
5894                 /* Look at the pattern of the pack expansion.  */
5895                 targ = PACK_EXPANSION_PATTERN (targ);
5896
5897               /* Extract the template parameters from the template
5898                  argument.  */
5899               if (TREE_CODE (targ) == TEMPLATE_DECL)
5900                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5901               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5902                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5903
5904               /* Verify that we can coerce the template template
5905                  parameters from the template argument to the template
5906                  parameter.  This requires an exact match.  */
5907               if (targ_parms
5908                   && !coerce_template_template_parms
5909                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5910                         targ_parms,
5911                         tf_none,
5912                         tparm,
5913                         targs))
5914                 {
5915                   ret = false;
5916                   goto out;
5917                 }
5918             }
5919         }
5920     }
5921
5922  out:
5923
5924   --processing_template_decl;
5925   return ret;
5926 }
5927
5928 /* Convert the indicated template ARG as necessary to match the
5929    indicated template PARM.  Returns the converted ARG, or
5930    error_mark_node if the conversion was unsuccessful.  Error and
5931    warning messages are issued under control of COMPLAIN.  This
5932    conversion is for the Ith parameter in the parameter list.  ARGS is
5933    the full set of template arguments deduced so far.  */
5934
5935 static tree
5936 convert_template_argument (tree parm,
5937                            tree arg,
5938                            tree args,
5939                            tsubst_flags_t complain,
5940                            int i,
5941                            tree in_decl)
5942 {
5943   tree orig_arg;
5944   tree val;
5945   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5946
5947   if (TREE_CODE (arg) == TREE_LIST
5948       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5949     {
5950       /* The template argument was the name of some
5951          member function.  That's usually
5952          invalid, but static members are OK.  In any
5953          case, grab the underlying fields/functions
5954          and issue an error later if required.  */
5955       orig_arg = TREE_VALUE (arg);
5956       TREE_TYPE (arg) = unknown_type_node;
5957     }
5958
5959   orig_arg = arg;
5960
5961   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5962   requires_type = (TREE_CODE (parm) == TYPE_DECL
5963                    || requires_tmpl_type);
5964
5965   /* When determining whether an argument pack expansion is a template,
5966      look at the pattern.  */
5967   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5968     arg = PACK_EXPANSION_PATTERN (arg);
5969
5970   /* Deal with an injected-class-name used as a template template arg.  */
5971   if (requires_tmpl_type && CLASS_TYPE_P (arg))
5972     {
5973       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
5974       if (TREE_CODE (t) == TEMPLATE_DECL)
5975         {
5976           if (complain & tf_warning_or_error)
5977             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
5978                      " used as template template argument", TYPE_NAME (arg));
5979           else if (flag_pedantic_errors)
5980             t = arg;
5981
5982           arg = t;
5983         }
5984     }
5985
5986   is_tmpl_type = 
5987     ((TREE_CODE (arg) == TEMPLATE_DECL
5988       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5989      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5990      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5991
5992   if (is_tmpl_type
5993       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5994           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5995     arg = TYPE_STUB_DECL (arg);
5996
5997   is_type = TYPE_P (arg) || is_tmpl_type;
5998
5999   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
6000       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
6001     {
6002       permerror (input_location, "to refer to a type member of a template parameter, "
6003                  "use %<typename %E%>", orig_arg);
6004
6005       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
6006                                      TREE_OPERAND (arg, 1),
6007                                      typename_type,
6008                                      complain & tf_error);
6009       arg = orig_arg;
6010       is_type = 1;
6011     }
6012   if (is_type != requires_type)
6013     {
6014       if (in_decl)
6015         {
6016           if (complain & tf_error)
6017             {
6018               error ("type/value mismatch at argument %d in template "
6019                      "parameter list for %qD",
6020                      i + 1, in_decl);
6021               if (is_type)
6022                 error ("  expected a constant of type %qT, got %qT",
6023                        TREE_TYPE (parm),
6024                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
6025               else if (requires_tmpl_type)
6026                 error ("  expected a class template, got %qE", orig_arg);
6027               else
6028                 error ("  expected a type, got %qE", orig_arg);
6029             }
6030         }
6031       return error_mark_node;
6032     }
6033   if (is_tmpl_type ^ requires_tmpl_type)
6034     {
6035       if (in_decl && (complain & tf_error))
6036         {
6037           error ("type/value mismatch at argument %d in template "
6038                  "parameter list for %qD",
6039                  i + 1, in_decl);
6040           if (is_tmpl_type)
6041             error ("  expected a type, got %qT", DECL_NAME (arg));
6042           else
6043             error ("  expected a class template, got %qT", orig_arg);
6044         }
6045       return error_mark_node;
6046     }
6047
6048   if (is_type)
6049     {
6050       if (requires_tmpl_type)
6051         {
6052           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
6053             /* The number of argument required is not known yet.
6054                Just accept it for now.  */
6055             val = TREE_TYPE (arg);
6056           else
6057             {
6058               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
6059               tree argparm;
6060
6061               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
6062
6063               if (coerce_template_template_parms (parmparm, argparm,
6064                                                   complain, in_decl,
6065                                                   args))
6066                 {
6067                   val = arg;
6068
6069                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
6070                      TEMPLATE_DECL.  */
6071                   if (val != error_mark_node)
6072                     {
6073                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
6074                         val = TREE_TYPE (val);
6075                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
6076                         val = make_pack_expansion (val);
6077                     }
6078                 }
6079               else
6080                 {
6081                   if (in_decl && (complain & tf_error))
6082                     {
6083                       error ("type/value mismatch at argument %d in "
6084                              "template parameter list for %qD",
6085                              i + 1, in_decl);
6086                       error ("  expected a template of type %qD, got %qT",
6087                              parm, orig_arg);
6088                     }
6089
6090                   val = error_mark_node;
6091                 }
6092             }
6093         }
6094       else
6095         val = orig_arg;
6096       /* We only form one instance of each template specialization.
6097          Therefore, if we use a non-canonical variant (i.e., a
6098          typedef), any future messages referring to the type will use
6099          the typedef, which is confusing if those future uses do not
6100          themselves also use the typedef.  */
6101       if (TYPE_P (val))
6102         val = strip_typedefs (val);
6103     }
6104   else
6105     {
6106       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
6107
6108       if (invalid_nontype_parm_type_p (t, complain))
6109         return error_mark_node;
6110
6111       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
6112         {
6113           if (same_type_p (t, TREE_TYPE (orig_arg)))
6114             val = orig_arg;
6115           else
6116             {
6117               /* Not sure if this is reachable, but it doesn't hurt
6118                  to be robust.  */
6119               error ("type mismatch in nontype parameter pack");
6120               val = error_mark_node;
6121             }
6122         }
6123       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
6124         /* We used to call digest_init here.  However, digest_init
6125            will report errors, which we don't want when complain
6126            is zero.  More importantly, digest_init will try too
6127            hard to convert things: for example, `0' should not be
6128            converted to pointer type at this point according to
6129            the standard.  Accepting this is not merely an
6130            extension, since deciding whether or not these
6131            conversions can occur is part of determining which
6132            function template to call, or whether a given explicit
6133            argument specification is valid.  */
6134         val = convert_nontype_argument (t, orig_arg, complain);
6135       else
6136         val = orig_arg;
6137
6138       if (val == NULL_TREE)
6139         val = error_mark_node;
6140       else if (val == error_mark_node && (complain & tf_error))
6141         error ("could not convert template argument %qE to %qT",  orig_arg, t);
6142
6143       if (TREE_CODE (val) == SCOPE_REF)
6144         {
6145           /* Strip typedefs from the SCOPE_REF.  */
6146           tree type = strip_typedefs (TREE_TYPE (val));
6147           tree scope = strip_typedefs (TREE_OPERAND (val, 0));
6148           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
6149                                       QUALIFIED_NAME_IS_TEMPLATE (val));
6150         }
6151     }
6152
6153   return val;
6154 }
6155
6156 /* Coerces the remaining template arguments in INNER_ARGS (from
6157    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
6158    Returns the coerced argument pack. PARM_IDX is the position of this
6159    parameter in the template parameter list. ARGS is the original
6160    template argument list.  */
6161 static tree
6162 coerce_template_parameter_pack (tree parms,
6163                                 int parm_idx,
6164                                 tree args,
6165                                 tree inner_args,
6166                                 int arg_idx,
6167                                 tree new_args,
6168                                 int* lost,
6169                                 tree in_decl,
6170                                 tsubst_flags_t complain)
6171 {
6172   tree parm = TREE_VEC_ELT (parms, parm_idx);
6173   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6174   tree packed_args;
6175   tree argument_pack;
6176   tree packed_types = NULL_TREE;
6177
6178   if (arg_idx > nargs)
6179     arg_idx = nargs;
6180
6181   packed_args = make_tree_vec (nargs - arg_idx);
6182
6183   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
6184       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
6185     {
6186       /* When the template parameter is a non-type template
6187          parameter pack whose type uses parameter packs, we need
6188          to look at each of the template arguments
6189          separately. Build a vector of the types for these
6190          non-type template parameters in PACKED_TYPES.  */
6191       tree expansion 
6192         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
6193       packed_types = tsubst_pack_expansion (expansion, args,
6194                                             complain, in_decl);
6195
6196       if (packed_types == error_mark_node)
6197         return error_mark_node;
6198
6199       /* Check that we have the right number of arguments.  */
6200       if (arg_idx < nargs
6201           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
6202           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
6203         {
6204           int needed_parms 
6205             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
6206           error ("wrong number of template arguments (%d, should be %d)",
6207                  nargs, needed_parms);
6208           return error_mark_node;
6209         }
6210
6211       /* If we aren't able to check the actual arguments now
6212          (because they haven't been expanded yet), we can at least
6213          verify that all of the types used for the non-type
6214          template parameter pack are, in fact, valid for non-type
6215          template parameters.  */
6216       if (arg_idx < nargs 
6217           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
6218         {
6219           int j, len = TREE_VEC_LENGTH (packed_types);
6220           for (j = 0; j < len; ++j)
6221             {
6222               tree t = TREE_VEC_ELT (packed_types, j);
6223               if (invalid_nontype_parm_type_p (t, complain))
6224                 return error_mark_node;
6225             }
6226         }
6227     }
6228
6229   /* Convert the remaining arguments, which will be a part of the
6230      parameter pack "parm".  */
6231   for (; arg_idx < nargs; ++arg_idx)
6232     {
6233       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
6234       tree actual_parm = TREE_VALUE (parm);
6235
6236       if (packed_types && !PACK_EXPANSION_P (arg))
6237         {
6238           /* When we have a vector of types (corresponding to the
6239              non-type template parameter pack that uses parameter
6240              packs in its type, as mention above), and the
6241              argument is not an expansion (which expands to a
6242              currently unknown number of arguments), clone the
6243              parm and give it the next type in PACKED_TYPES.  */
6244           actual_parm = copy_node (actual_parm);
6245           TREE_TYPE (actual_parm) = 
6246             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
6247         }
6248
6249       if (arg != error_mark_node)
6250         arg = convert_template_argument (actual_parm, 
6251                                          arg, new_args, complain, parm_idx,
6252                                          in_decl);
6253       if (arg == error_mark_node)
6254         (*lost)++;
6255       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
6256     }
6257
6258   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
6259       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
6260     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
6261   else
6262     {
6263       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
6264       TREE_TYPE (argument_pack) 
6265         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
6266       TREE_CONSTANT (argument_pack) = 1;
6267     }
6268
6269   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
6270 #ifdef ENABLE_CHECKING
6271   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
6272                                        TREE_VEC_LENGTH (packed_args));
6273 #endif
6274   return argument_pack;
6275 }
6276
6277 /* Convert all template arguments to their appropriate types, and
6278    return a vector containing the innermost resulting template
6279    arguments.  If any error occurs, return error_mark_node. Error and
6280    warning messages are issued under control of COMPLAIN.
6281
6282    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
6283    for arguments not specified in ARGS.  Otherwise, if
6284    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
6285    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
6286    USE_DEFAULT_ARGS is false, then all arguments must be specified in
6287    ARGS.  */
6288
6289 static tree
6290 coerce_template_parms (tree parms,
6291                        tree args,
6292                        tree in_decl,
6293                        tsubst_flags_t complain,
6294                        bool require_all_args,
6295                        bool use_default_args)
6296 {
6297   int nparms, nargs, parm_idx, arg_idx, lost = 0;
6298   tree inner_args;
6299   tree new_args;
6300   tree new_inner_args;
6301   int saved_unevaluated_operand;
6302   int saved_inhibit_evaluation_warnings;
6303
6304   /* When used as a boolean value, indicates whether this is a
6305      variadic template parameter list. Since it's an int, we can also
6306      subtract it from nparms to get the number of non-variadic
6307      parameters.  */
6308   int variadic_p = 0;
6309
6310   if (args == error_mark_node)
6311     return error_mark_node;
6312
6313   nparms = TREE_VEC_LENGTH (parms);
6314
6315   /* Determine if there are any parameter packs.  */
6316   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
6317     {
6318       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
6319       if (template_parameter_pack_p (tparm))
6320         ++variadic_p;
6321     }
6322
6323   inner_args = INNERMOST_TEMPLATE_ARGS (args);
6324   /* If there are 0 or 1 parameter packs, we need to expand any argument
6325      packs so that we can deduce a parameter pack from some non-packed args
6326      followed by an argument pack, as in variadic85.C.  If there are more
6327      than that, we need to leave argument packs intact so the arguments are
6328      assigned to the right parameter packs.  This should only happen when
6329      dealing with a nested class inside a partial specialization of a class
6330      template, as in variadic92.C.  */
6331   if (variadic_p <= 1)
6332     inner_args = expand_template_argument_pack (inner_args);
6333
6334   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6335   if ((nargs > nparms && !variadic_p)
6336       || (nargs < nparms - variadic_p
6337           && require_all_args
6338           && (!use_default_args
6339               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
6340                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
6341     {
6342       if (complain & tf_error)
6343         {
6344           if (variadic_p)
6345             {
6346               --nparms;
6347               error ("wrong number of template arguments "
6348                      "(%d, should be %d or more)", nargs, nparms);
6349             }
6350           else
6351              error ("wrong number of template arguments "
6352                     "(%d, should be %d)", nargs, nparms);
6353
6354           if (in_decl)
6355             error ("provided for %q+D", in_decl);
6356         }
6357
6358       return error_mark_node;
6359     }
6360
6361   /* We need to evaluate the template arguments, even though this
6362      template-id may be nested within a "sizeof".  */
6363   saved_unevaluated_operand = cp_unevaluated_operand;
6364   cp_unevaluated_operand = 0;
6365   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
6366   c_inhibit_evaluation_warnings = 0;
6367   new_inner_args = make_tree_vec (nparms);
6368   new_args = add_outermost_template_args (args, new_inner_args);
6369   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
6370     {
6371       tree arg;
6372       tree parm;
6373
6374       /* Get the Ith template parameter.  */
6375       parm = TREE_VEC_ELT (parms, parm_idx);
6376  
6377       if (parm == error_mark_node)
6378       {
6379         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
6380         continue;
6381       }
6382
6383       /* Calculate the next argument.  */
6384       if (arg_idx < nargs)
6385         arg = TREE_VEC_ELT (inner_args, arg_idx);
6386       else
6387         arg = NULL_TREE;
6388
6389       if (template_parameter_pack_p (TREE_VALUE (parm))
6390           && !(arg && ARGUMENT_PACK_P (arg)))
6391         {
6392           /* All remaining arguments will be placed in the
6393              template parameter pack PARM.  */
6394           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
6395                                                 inner_args, arg_idx,
6396                                                 new_args, &lost,
6397                                                 in_decl, complain);
6398
6399           /* Store this argument.  */
6400           if (arg == error_mark_node)
6401             lost++;
6402           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
6403
6404           /* We are done with all of the arguments.  */
6405           arg_idx = nargs;
6406           
6407           continue;
6408         }
6409       else if (arg)
6410         {
6411           if (PACK_EXPANSION_P (arg))
6412             {
6413               if (complain & tf_error)
6414                 {
6415                   /* FIXME this restriction was removed by N2555; see
6416                      bug 35722.  */
6417                   /* If ARG is a pack expansion, but PARM is not a
6418                      template parameter pack (if it were, we would have
6419                      handled it above), we're trying to expand into a
6420                      fixed-length argument list.  */
6421                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
6422                     sorry ("cannot expand %<%E%> into a fixed-length "
6423                            "argument list", arg);
6424                   else
6425                     sorry ("cannot expand %<%T%> into a fixed-length "
6426                            "argument list", arg);
6427                 }
6428               ++lost;
6429             }
6430         }
6431       else if (require_all_args)
6432         {
6433           /* There must be a default arg in this case.  */
6434           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
6435                                      complain, in_decl);
6436           /* The position of the first default template argument,
6437              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
6438              Record that.  */
6439           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6440             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
6441         }
6442       else
6443         break;
6444
6445       if (arg == error_mark_node)
6446         {
6447           if (complain & tf_error)
6448             error ("template argument %d is invalid", arg_idx + 1);
6449         }
6450       else if (!arg)
6451         /* This only occurs if there was an error in the template
6452            parameter list itself (which we would already have
6453            reported) that we are trying to recover from, e.g., a class
6454            template with a parameter list such as
6455            template<typename..., typename>.  */
6456         ++lost;
6457       else
6458         arg = convert_template_argument (TREE_VALUE (parm),
6459                                          arg, new_args, complain, 
6460                                          parm_idx, in_decl);
6461
6462       if (arg == error_mark_node)
6463         lost++;
6464       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6465     }
6466   cp_unevaluated_operand = saved_unevaluated_operand;
6467   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6468
6469   if (lost)
6470     return error_mark_node;
6471
6472 #ifdef ENABLE_CHECKING
6473   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6474     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6475                                          TREE_VEC_LENGTH (new_inner_args));
6476 #endif
6477
6478   return new_inner_args;
6479 }
6480
6481 /* Returns 1 if template args OT and NT are equivalent.  */
6482
6483 static int
6484 template_args_equal (tree ot, tree nt)
6485 {
6486   if (nt == ot)
6487     return 1;
6488
6489   if (TREE_CODE (nt) == TREE_VEC)
6490     /* For member templates */
6491     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6492   else if (PACK_EXPANSION_P (ot))
6493     return PACK_EXPANSION_P (nt) 
6494       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6495                               PACK_EXPANSION_PATTERN (nt));
6496   else if (ARGUMENT_PACK_P (ot))
6497     {
6498       int i, len;
6499       tree opack, npack;
6500
6501       if (!ARGUMENT_PACK_P (nt))
6502         return 0;
6503
6504       opack = ARGUMENT_PACK_ARGS (ot);
6505       npack = ARGUMENT_PACK_ARGS (nt);
6506       len = TREE_VEC_LENGTH (opack);
6507       if (TREE_VEC_LENGTH (npack) != len)
6508         return 0;
6509       for (i = 0; i < len; ++i)
6510         if (!template_args_equal (TREE_VEC_ELT (opack, i),
6511                                   TREE_VEC_ELT (npack, i)))
6512           return 0;
6513       return 1;
6514     }
6515   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6516     {
6517       /* We get here probably because we are in the middle of substituting
6518          into the pattern of a pack expansion. In that case the
6519          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6520          interested in. So we want to use the initial pack argument for
6521          the comparison.  */
6522       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6523       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6524         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6525       return template_args_equal (ot, nt);
6526     }
6527   else if (TYPE_P (nt))
6528     return TYPE_P (ot) && same_type_p (ot, nt);
6529   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6530     return 0;
6531   else
6532     return cp_tree_equal (ot, nt);
6533 }
6534
6535 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6536    of template arguments.  Returns 0 otherwise.  */
6537
6538 int
6539 comp_template_args (tree oldargs, tree newargs)
6540 {
6541   int i;
6542
6543   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6544     return 0;
6545
6546   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6547     {
6548       tree nt = TREE_VEC_ELT (newargs, i);
6549       tree ot = TREE_VEC_ELT (oldargs, i);
6550
6551       if (! template_args_equal (ot, nt))
6552         return 0;
6553     }
6554   return 1;
6555 }
6556
6557 static void
6558 add_pending_template (tree d)
6559 {
6560   tree ti = (TYPE_P (d)
6561              ? CLASSTYPE_TEMPLATE_INFO (d)
6562              : DECL_TEMPLATE_INFO (d));
6563   struct pending_template *pt;
6564   int level;
6565
6566   if (TI_PENDING_TEMPLATE_FLAG (ti))
6567     return;
6568
6569   /* We are called both from instantiate_decl, where we've already had a
6570      tinst_level pushed, and instantiate_template, where we haven't.
6571      Compensate.  */
6572   level = !current_tinst_level || current_tinst_level->decl != d;
6573
6574   if (level)
6575     push_tinst_level (d);
6576
6577   pt = ggc_alloc_pending_template ();
6578   pt->next = NULL;
6579   pt->tinst = current_tinst_level;
6580   if (last_pending_template)
6581     last_pending_template->next = pt;
6582   else
6583     pending_templates = pt;
6584
6585   last_pending_template = pt;
6586
6587   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6588
6589   if (level)
6590     pop_tinst_level ();
6591 }
6592
6593
6594 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6595    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6596    documentation for TEMPLATE_ID_EXPR.  */
6597
6598 tree
6599 lookup_template_function (tree fns, tree arglist)
6600 {
6601   tree type;
6602
6603   if (fns == error_mark_node || arglist == error_mark_node)
6604     return error_mark_node;
6605
6606   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6607   gcc_assert (fns && (is_overloaded_fn (fns)
6608                       || TREE_CODE (fns) == IDENTIFIER_NODE));
6609
6610   if (BASELINK_P (fns))
6611     {
6612       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6613                                          unknown_type_node,
6614                                          BASELINK_FUNCTIONS (fns),
6615                                          arglist);
6616       return fns;
6617     }
6618
6619   type = TREE_TYPE (fns);
6620   if (TREE_CODE (fns) == OVERLOAD || !type)
6621     type = unknown_type_node;
6622
6623   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6624 }
6625
6626 /* Within the scope of a template class S<T>, the name S gets bound
6627    (in build_self_reference) to a TYPE_DECL for the class, not a
6628    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6629    or one of its enclosing classes, and that type is a template,
6630    return the associated TEMPLATE_DECL.  Otherwise, the original
6631    DECL is returned.
6632
6633    Also handle the case when DECL is a TREE_LIST of ambiguous
6634    injected-class-names from different bases.  */
6635
6636 tree
6637 maybe_get_template_decl_from_type_decl (tree decl)
6638 {
6639   if (decl == NULL_TREE)
6640     return decl;
6641
6642   /* DR 176: A lookup that finds an injected-class-name (10.2
6643      [class.member.lookup]) can result in an ambiguity in certain cases
6644      (for example, if it is found in more than one base class). If all of
6645      the injected-class-names that are found refer to specializations of
6646      the same class template, and if the name is followed by a
6647      template-argument-list, the reference refers to the class template
6648      itself and not a specialization thereof, and is not ambiguous.  */
6649   if (TREE_CODE (decl) == TREE_LIST)
6650     {
6651       tree t, tmpl = NULL_TREE;
6652       for (t = decl; t; t = TREE_CHAIN (t))
6653         {
6654           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6655           if (!tmpl)
6656             tmpl = elt;
6657           else if (tmpl != elt)
6658             break;
6659         }
6660       if (tmpl && t == NULL_TREE)
6661         return tmpl;
6662       else
6663         return decl;
6664     }
6665
6666   return (decl != NULL_TREE
6667           && DECL_SELF_REFERENCE_P (decl)
6668           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
6669     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
6670 }
6671
6672 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
6673    parameters, find the desired type.
6674
6675    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
6676
6677    IN_DECL, if non-NULL, is the template declaration we are trying to
6678    instantiate.
6679
6680    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
6681    the class we are looking up.
6682
6683    Issue error and warning messages under control of COMPLAIN.
6684
6685    If the template class is really a local class in a template
6686    function, then the FUNCTION_CONTEXT is the function in which it is
6687    being instantiated.
6688
6689    ??? Note that this function is currently called *twice* for each
6690    template-id: the first time from the parser, while creating the
6691    incomplete type (finish_template_type), and the second type during the
6692    real instantiation (instantiate_template_class). This is surely something
6693    that we want to avoid. It also causes some problems with argument
6694    coercion (see convert_nontype_argument for more information on this).  */
6695
6696 tree
6697 lookup_template_class (tree d1,
6698                        tree arglist,
6699                        tree in_decl,
6700                        tree context,
6701                        int entering_scope,
6702                        tsubst_flags_t complain)
6703 {
6704   tree templ = NULL_TREE, parmlist;
6705   tree t;
6706   spec_entry **slot;
6707   spec_entry *entry;
6708   spec_entry elt;
6709   hashval_t hash;
6710
6711   timevar_push (TV_NAME_LOOKUP);
6712
6713   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6714     {
6715       tree value = innermost_non_namespace_value (d1);
6716       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6717         templ = value;
6718       else
6719         {
6720           if (context)
6721             push_decl_namespace (context);
6722           templ = lookup_name (d1);
6723           templ = maybe_get_template_decl_from_type_decl (templ);
6724           if (context)
6725             pop_decl_namespace ();
6726         }
6727       if (templ)
6728         context = DECL_CONTEXT (templ);
6729     }
6730   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6731     {
6732       tree type = TREE_TYPE (d1);
6733
6734       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6735          an implicit typename for the second A.  Deal with it.  */
6736       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6737         type = TREE_TYPE (type);
6738
6739       if (CLASSTYPE_TEMPLATE_INFO (type))
6740         {
6741           templ = CLASSTYPE_TI_TEMPLATE (type);
6742           d1 = DECL_NAME (templ);
6743         }
6744     }
6745   else if (TREE_CODE (d1) == ENUMERAL_TYPE
6746            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6747     {
6748       templ = TYPE_TI_TEMPLATE (d1);
6749       d1 = DECL_NAME (templ);
6750     }
6751   else if (TREE_CODE (d1) == TEMPLATE_DECL
6752            && DECL_TEMPLATE_RESULT (d1)
6753            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6754     {
6755       templ = d1;
6756       d1 = DECL_NAME (templ);
6757       context = DECL_CONTEXT (templ);
6758     }
6759
6760   /* Issue an error message if we didn't find a template.  */
6761   if (! templ)
6762     {
6763       if (complain & tf_error)
6764         error ("%qT is not a template", d1);
6765       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6766     }
6767
6768   if (TREE_CODE (templ) != TEMPLATE_DECL
6769          /* Make sure it's a user visible template, if it was named by
6770             the user.  */
6771       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6772           && !PRIMARY_TEMPLATE_P (templ)))
6773     {
6774       if (complain & tf_error)
6775         {
6776           error ("non-template type %qT used as a template", d1);
6777           if (in_decl)
6778             error ("for template declaration %q+D", in_decl);
6779         }
6780       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6781     }
6782
6783   complain &= ~tf_user;
6784
6785   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6786     {
6787       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6788          template arguments */
6789
6790       tree parm;
6791       tree arglist2;
6792       tree outer;
6793
6794       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6795
6796       /* Consider an example where a template template parameter declared as
6797
6798            template <class T, class U = std::allocator<T> > class TT
6799
6800          The template parameter level of T and U are one level larger than
6801          of TT.  To proper process the default argument of U, say when an
6802          instantiation `TT<int>' is seen, we need to build the full
6803          arguments containing {int} as the innermost level.  Outer levels,
6804          available when not appearing as default template argument, can be
6805          obtained from the arguments of the enclosing template.
6806
6807          Suppose that TT is later substituted with std::vector.  The above
6808          instantiation is `TT<int, std::allocator<T> >' with TT at
6809          level 1, and T at level 2, while the template arguments at level 1
6810          becomes {std::vector} and the inner level 2 is {int}.  */
6811
6812       outer = DECL_CONTEXT (templ);
6813       if (outer)
6814         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
6815       else if (current_template_parms)
6816         /* This is an argument of the current template, so we haven't set
6817            DECL_CONTEXT yet.  */
6818         outer = current_template_args ();
6819
6820       if (outer)
6821         arglist = add_to_template_args (outer, arglist);
6822
6823       arglist2 = coerce_template_parms (parmlist, arglist, templ,
6824                                         complain,
6825                                         /*require_all_args=*/true,
6826                                         /*use_default_args=*/true);
6827       if (arglist2 == error_mark_node
6828           || (!uses_template_parms (arglist2)
6829               && check_instantiated_args (templ, arglist2, complain)))
6830         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6831
6832       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
6833       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
6834     }
6835   else
6836     {
6837       tree template_type = TREE_TYPE (templ);
6838       tree gen_tmpl;
6839       tree type_decl;
6840       tree found = NULL_TREE;
6841       int arg_depth;
6842       int parm_depth;
6843       int is_dependent_type;
6844       int use_partial_inst_tmpl = false;
6845
6846       gen_tmpl = most_general_template (templ);
6847       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
6848       parm_depth = TMPL_PARMS_DEPTH (parmlist);
6849       arg_depth = TMPL_ARGS_DEPTH (arglist);
6850
6851       if (arg_depth == 1 && parm_depth > 1)
6852         {
6853           /* We've been given an incomplete set of template arguments.
6854              For example, given:
6855
6856                template <class T> struct S1 {
6857                  template <class U> struct S2 {};
6858                  template <class U> struct S2<U*> {};
6859                 };
6860
6861              we will be called with an ARGLIST of `U*', but the
6862              TEMPLATE will be `template <class T> template
6863              <class U> struct S1<T>::S2'.  We must fill in the missing
6864              arguments.  */
6865           arglist
6866             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
6867                                            arglist);
6868           arg_depth = TMPL_ARGS_DEPTH (arglist);
6869         }
6870
6871       /* Now we should have enough arguments.  */
6872       gcc_assert (parm_depth == arg_depth);
6873
6874       /* From here on, we're only interested in the most general
6875          template.  */
6876
6877       /* Calculate the BOUND_ARGS.  These will be the args that are
6878          actually tsubst'd into the definition to create the
6879          instantiation.  */
6880       if (parm_depth > 1)
6881         {
6882           /* We have multiple levels of arguments to coerce, at once.  */
6883           int i;
6884           int saved_depth = TMPL_ARGS_DEPTH (arglist);
6885
6886           tree bound_args = make_tree_vec (parm_depth);
6887
6888           for (i = saved_depth,
6889                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
6890                i > 0 && t != NULL_TREE;
6891                --i, t = TREE_CHAIN (t))
6892             {
6893               tree a;
6894               if (i == saved_depth)
6895                 a = coerce_template_parms (TREE_VALUE (t),
6896                                            arglist, gen_tmpl,
6897                                            complain,
6898                                            /*require_all_args=*/true,
6899                                            /*use_default_args=*/true);
6900               else
6901                 /* Outer levels should have already been coerced.  */
6902                 a = TMPL_ARGS_LEVEL (arglist, i);
6903
6904               /* Don't process further if one of the levels fails.  */
6905               if (a == error_mark_node)
6906                 {
6907                   /* Restore the ARGLIST to its full size.  */
6908                   TREE_VEC_LENGTH (arglist) = saved_depth;
6909                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6910                 }
6911
6912               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6913
6914               /* We temporarily reduce the length of the ARGLIST so
6915                  that coerce_template_parms will see only the arguments
6916                  corresponding to the template parameters it is
6917                  examining.  */
6918               TREE_VEC_LENGTH (arglist)--;
6919             }
6920
6921           /* Restore the ARGLIST to its full size.  */
6922           TREE_VEC_LENGTH (arglist) = saved_depth;
6923
6924           arglist = bound_args;
6925         }
6926       else
6927         arglist
6928           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6929                                    INNERMOST_TEMPLATE_ARGS (arglist),
6930                                    gen_tmpl,
6931                                    complain,
6932                                    /*require_all_args=*/true,
6933                                    /*use_default_args=*/true);
6934
6935       if (arglist == error_mark_node)
6936         /* We were unable to bind the arguments.  */
6937         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6938
6939       /* In the scope of a template class, explicit references to the
6940          template class refer to the type of the template, not any
6941          instantiation of it.  For example, in:
6942
6943            template <class T> class C { void f(C<T>); }
6944
6945          the `C<T>' is just the same as `C'.  Outside of the
6946          class, however, such a reference is an instantiation.  */
6947       if ((entering_scope
6948            || !PRIMARY_TEMPLATE_P (gen_tmpl)
6949            || currently_open_class (template_type))
6950           /* comp_template_args is expensive, check it last.  */
6951           && comp_template_args (TYPE_TI_ARGS (template_type),
6952                                  arglist))
6953         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, template_type);
6954
6955       /* If we already have this specialization, return it.  */
6956       elt.tmpl = gen_tmpl;
6957       elt.args = arglist;
6958       hash = hash_specialization (&elt);
6959       entry = (spec_entry *) htab_find_with_hash (type_specializations,
6960                                                   &elt, hash);
6961
6962       if (entry)
6963         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->spec);
6964
6965       is_dependent_type = uses_template_parms (arglist);
6966
6967       /* If the deduced arguments are invalid, then the binding
6968          failed.  */
6969       if (!is_dependent_type
6970           && check_instantiated_args (gen_tmpl,
6971                                       INNERMOST_TEMPLATE_ARGS (arglist),
6972                                       complain))
6973         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6974
6975       if (!is_dependent_type
6976           && !PRIMARY_TEMPLATE_P (gen_tmpl)
6977           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
6978           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6979         {
6980           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6981                                       DECL_NAME (gen_tmpl),
6982                                       /*tag_scope=*/ts_global);
6983           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
6984         }
6985
6986       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
6987                         complain, in_decl);
6988       if (!context)
6989         context = global_namespace;
6990
6991       /* Create the type.  */
6992       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
6993         {
6994           if (!is_dependent_type)
6995             {
6996               set_current_access_from_decl (TYPE_NAME (template_type));
6997               t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
6998                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
6999                                       arglist, complain, in_decl),
7000                               SCOPED_ENUM_P (template_type), NULL);
7001             }
7002           else
7003             {
7004               /* We don't want to call start_enum for this type, since
7005                  the values for the enumeration constants may involve
7006                  template parameters.  And, no one should be interested
7007                  in the enumeration constants for such a type.  */
7008               t = cxx_make_type (ENUMERAL_TYPE);
7009               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
7010             }
7011           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
7012           ENUM_FIXED_UNDERLYING_TYPE_P (t)
7013             = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
7014         }
7015       else
7016         {
7017           t = make_class_type (TREE_CODE (template_type));
7018           CLASSTYPE_DECLARED_CLASS (t)
7019             = CLASSTYPE_DECLARED_CLASS (template_type);
7020           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
7021           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
7022
7023           /* A local class.  Make sure the decl gets registered properly.  */
7024           if (context == current_function_decl)
7025             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
7026
7027           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
7028             /* This instantiation is another name for the primary
7029                template type. Set the TYPE_CANONICAL field
7030                appropriately. */
7031             TYPE_CANONICAL (t) = template_type;
7032           else if (any_template_arguments_need_structural_equality_p (arglist))
7033             /* Some of the template arguments require structural
7034                equality testing, so this template class requires
7035                structural equality testing. */
7036             SET_TYPE_STRUCTURAL_EQUALITY (t);
7037         }
7038
7039       /* If we called start_enum or pushtag above, this information
7040          will already be set up.  */
7041       if (!TYPE_NAME (t))
7042         {
7043           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
7044
7045           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
7046           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
7047           DECL_SOURCE_LOCATION (type_decl)
7048             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
7049         }
7050       else
7051         type_decl = TYPE_NAME (t);
7052
7053       TREE_PRIVATE (type_decl)
7054         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
7055       TREE_PROTECTED (type_decl)
7056         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
7057       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
7058         {
7059           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
7060           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
7061         }
7062
7063       /* Let's consider the explicit specialization of a member
7064          of a class template specialization that is implicitely instantiated,
7065          e.g.:
7066              template<class T>
7067              struct S
7068              {
7069                template<class U> struct M {}; //#0
7070              };
7071
7072              template<>
7073              template<>
7074              struct S<int>::M<char> //#1
7075              {
7076                int i;
7077              };
7078         [temp.expl.spec]/4 says this is valid.
7079
7080         In this case, when we write:
7081         S<int>::M<char> m;
7082
7083         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
7084         the one of #0.
7085
7086         When we encounter #1, we want to store the partial instantiation
7087         of M (template<class T> S<int>::M<T>) in it's CLASSTYPE_TI_TEMPLATE.
7088
7089         For all cases other than this "explicit specialization of member of a
7090         class template", we just want to store the most general template into
7091         the CLASSTYPE_TI_TEMPLATE of M.
7092
7093         This case of "explicit specialization of member of a class template"
7094         only happens when:
7095         1/ the enclosing class is an instantiation of, and therefore not
7096         the same as, the context of the most general template, and
7097         2/ we aren't looking at the partial instantiation itself, i.e.
7098         the innermost arguments are not the same as the innermost parms of
7099         the most general template.
7100
7101         So it's only when 1/ and 2/ happens that we want to use the partial
7102         instantiation of the member template in lieu of its most general
7103         template.  */
7104
7105       if (PRIMARY_TEMPLATE_P (gen_tmpl)
7106           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
7107           /* the enclosing class must be an instantiation...  */
7108           && CLASS_TYPE_P (context)
7109           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
7110         {
7111           tree partial_inst_args;
7112           TREE_VEC_LENGTH (arglist)--;
7113           ++processing_template_decl;
7114           partial_inst_args =
7115             tsubst (INNERMOST_TEMPLATE_ARGS
7116                         (CLASSTYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
7117                     arglist, complain, NULL_TREE);
7118           --processing_template_decl;
7119           TREE_VEC_LENGTH (arglist)++;
7120           use_partial_inst_tmpl =
7121             /*...and we must not be looking at the partial instantiation
7122              itself. */
7123             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
7124                                  partial_inst_args);
7125         }
7126
7127       if (!use_partial_inst_tmpl)
7128         /* This case is easy; there are no member templates involved.  */
7129         found = gen_tmpl;
7130       else
7131         {
7132           /* This is a full instantiation of a member template.  Find
7133              the partial instantiation of which this is an instance.  */
7134
7135           /* Temporarily reduce by one the number of levels in the ARGLIST
7136              so as to avoid comparing the last set of arguments.  */
7137           TREE_VEC_LENGTH (arglist)--;
7138           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
7139           TREE_VEC_LENGTH (arglist)++;
7140           found = CLASSTYPE_TI_TEMPLATE (found);
7141         }
7142
7143       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
7144
7145       elt.spec = t;
7146       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
7147                                                        &elt, hash, INSERT);
7148       *slot = ggc_alloc_spec_entry ();
7149       **slot = elt;
7150
7151       /* Note this use of the partial instantiation so we can check it
7152          later in maybe_process_partial_specialization.  */
7153       DECL_TEMPLATE_INSTANTIATIONS (templ)
7154         = tree_cons (arglist, t,
7155                      DECL_TEMPLATE_INSTANTIATIONS (templ));
7156
7157       if (TREE_CODE (t) == ENUMERAL_TYPE && !is_dependent_type)
7158         /* Now that the type has been registered on the instantiations
7159            list, we set up the enumerators.  Because the enumeration
7160            constants may involve the enumeration type itself, we make
7161            sure to register the type first, and then create the
7162            constants.  That way, doing tsubst_expr for the enumeration
7163            constants won't result in recursive calls here; we'll find
7164            the instantiation and exit above.  */
7165         tsubst_enum (template_type, t, arglist);
7166
7167       if (is_dependent_type)
7168         /* If the type makes use of template parameters, the
7169            code that generates debugging information will crash.  */
7170         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
7171
7172       /* Possibly limit visibility based on template args.  */
7173       TREE_PUBLIC (type_decl) = 1;
7174       determine_visibility (type_decl);
7175
7176       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
7177     }
7178   timevar_pop (TV_NAME_LOOKUP);
7179 }
7180 \f
7181 struct pair_fn_data
7182 {
7183   tree_fn_t fn;
7184   void *data;
7185   /* True when we should also visit template parameters that occur in
7186      non-deduced contexts.  */
7187   bool include_nondeduced_p;
7188   struct pointer_set_t *visited;
7189 };
7190
7191 /* Called from for_each_template_parm via walk_tree.  */
7192
7193 static tree
7194 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
7195 {
7196   tree t = *tp;
7197   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
7198   tree_fn_t fn = pfd->fn;
7199   void *data = pfd->data;
7200
7201   if (TYPE_P (t)
7202       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
7203       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
7204                                  pfd->include_nondeduced_p))
7205     return error_mark_node;
7206
7207   switch (TREE_CODE (t))
7208     {
7209     case RECORD_TYPE:
7210       if (TYPE_PTRMEMFUNC_P (t))
7211         break;
7212       /* Fall through.  */
7213
7214     case UNION_TYPE:
7215     case ENUMERAL_TYPE:
7216       if (!TYPE_TEMPLATE_INFO (t))
7217         *walk_subtrees = 0;
7218       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
7219                                        fn, data, pfd->visited, 
7220                                        pfd->include_nondeduced_p))
7221         return error_mark_node;
7222       break;
7223
7224     case INTEGER_TYPE:
7225       if (for_each_template_parm (TYPE_MIN_VALUE (t),
7226                                   fn, data, pfd->visited, 
7227                                   pfd->include_nondeduced_p)
7228           || for_each_template_parm (TYPE_MAX_VALUE (t),
7229                                      fn, data, pfd->visited,
7230                                      pfd->include_nondeduced_p))
7231         return error_mark_node;
7232       break;
7233
7234     case METHOD_TYPE:
7235       /* Since we're not going to walk subtrees, we have to do this
7236          explicitly here.  */
7237       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
7238                                   pfd->visited, pfd->include_nondeduced_p))
7239         return error_mark_node;
7240       /* Fall through.  */
7241
7242     case FUNCTION_TYPE:
7243       /* Check the return type.  */
7244       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7245                                   pfd->include_nondeduced_p))
7246         return error_mark_node;
7247
7248       /* Check the parameter types.  Since default arguments are not
7249          instantiated until they are needed, the TYPE_ARG_TYPES may
7250          contain expressions that involve template parameters.  But,
7251          no-one should be looking at them yet.  And, once they're
7252          instantiated, they don't contain template parameters, so
7253          there's no point in looking at them then, either.  */
7254       {
7255         tree parm;
7256
7257         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
7258           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
7259                                       pfd->visited, pfd->include_nondeduced_p))
7260             return error_mark_node;
7261
7262         /* Since we've already handled the TYPE_ARG_TYPES, we don't
7263            want walk_tree walking into them itself.  */
7264         *walk_subtrees = 0;
7265       }
7266       break;
7267
7268     case TYPEOF_TYPE:
7269       if (pfd->include_nondeduced_p
7270           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
7271                                      pfd->visited, 
7272                                      pfd->include_nondeduced_p))
7273         return error_mark_node;
7274       break;
7275
7276     case FUNCTION_DECL:
7277     case VAR_DECL:
7278       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
7279           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
7280                                      pfd->visited, pfd->include_nondeduced_p))
7281         return error_mark_node;
7282       /* Fall through.  */
7283
7284     case PARM_DECL:
7285     case CONST_DECL:
7286       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
7287           && for_each_template_parm (DECL_INITIAL (t), fn, data,
7288                                      pfd->visited, pfd->include_nondeduced_p))
7289         return error_mark_node;
7290       if (DECL_CONTEXT (t)
7291           && pfd->include_nondeduced_p
7292           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
7293                                      pfd->visited, pfd->include_nondeduced_p))
7294         return error_mark_node;
7295       break;
7296
7297     case BOUND_TEMPLATE_TEMPLATE_PARM:
7298       /* Record template parameters such as `T' inside `TT<T>'.  */
7299       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
7300                                   pfd->include_nondeduced_p))
7301         return error_mark_node;
7302       /* Fall through.  */
7303
7304     case TEMPLATE_TEMPLATE_PARM:
7305     case TEMPLATE_TYPE_PARM:
7306     case TEMPLATE_PARM_INDEX:
7307       if (fn && (*fn)(t, data))
7308         return error_mark_node;
7309       else if (!fn)
7310         return error_mark_node;
7311       break;
7312
7313     case TEMPLATE_DECL:
7314       /* A template template parameter is encountered.  */
7315       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
7316           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7317                                      pfd->include_nondeduced_p))
7318         return error_mark_node;
7319
7320       /* Already substituted template template parameter */
7321       *walk_subtrees = 0;
7322       break;
7323
7324     case TYPENAME_TYPE:
7325       if (!fn
7326           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
7327                                      data, pfd->visited, 
7328                                      pfd->include_nondeduced_p))
7329         return error_mark_node;
7330       break;
7331
7332     case CONSTRUCTOR:
7333       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
7334           && pfd->include_nondeduced_p
7335           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
7336                                      (TREE_TYPE (t)), fn, data,
7337                                      pfd->visited, pfd->include_nondeduced_p))
7338         return error_mark_node;
7339       break;
7340
7341     case INDIRECT_REF:
7342     case COMPONENT_REF:
7343       /* If there's no type, then this thing must be some expression
7344          involving template parameters.  */
7345       if (!fn && !TREE_TYPE (t))
7346         return error_mark_node;
7347       break;
7348
7349     case MODOP_EXPR:
7350     case CAST_EXPR:
7351     case REINTERPRET_CAST_EXPR:
7352     case CONST_CAST_EXPR:
7353     case STATIC_CAST_EXPR:
7354     case DYNAMIC_CAST_EXPR:
7355     case ARROW_EXPR:
7356     case DOTSTAR_EXPR:
7357     case TYPEID_EXPR:
7358     case PSEUDO_DTOR_EXPR:
7359       if (!fn)
7360         return error_mark_node;
7361       break;
7362
7363     default:
7364       break;
7365     }
7366
7367   /* We didn't find any template parameters we liked.  */
7368   return NULL_TREE;
7369 }
7370
7371 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
7372    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
7373    call FN with the parameter and the DATA.
7374    If FN returns nonzero, the iteration is terminated, and
7375    for_each_template_parm returns 1.  Otherwise, the iteration
7376    continues.  If FN never returns a nonzero value, the value
7377    returned by for_each_template_parm is 0.  If FN is NULL, it is
7378    considered to be the function which always returns 1.
7379
7380    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
7381    parameters that occur in non-deduced contexts.  When false, only
7382    visits those template parameters that can be deduced.  */
7383
7384 static int
7385 for_each_template_parm (tree t, tree_fn_t fn, void* data,
7386                         struct pointer_set_t *visited,
7387                         bool include_nondeduced_p)
7388 {
7389   struct pair_fn_data pfd;
7390   int result;
7391
7392   /* Set up.  */
7393   pfd.fn = fn;
7394   pfd.data = data;
7395   pfd.include_nondeduced_p = include_nondeduced_p;
7396
7397   /* Walk the tree.  (Conceptually, we would like to walk without
7398      duplicates, but for_each_template_parm_r recursively calls
7399      for_each_template_parm, so we would need to reorganize a fair
7400      bit to use walk_tree_without_duplicates, so we keep our own
7401      visited list.)  */
7402   if (visited)
7403     pfd.visited = visited;
7404   else
7405     pfd.visited = pointer_set_create ();
7406   result = cp_walk_tree (&t,
7407                          for_each_template_parm_r,
7408                          &pfd,
7409                          pfd.visited) != NULL_TREE;
7410
7411   /* Clean up.  */
7412   if (!visited)
7413     {
7414       pointer_set_destroy (pfd.visited);
7415       pfd.visited = 0;
7416     }
7417
7418   return result;
7419 }
7420
7421 /* Returns true if T depends on any template parameter.  */
7422
7423 int
7424 uses_template_parms (tree t)
7425 {
7426   bool dependent_p;
7427   int saved_processing_template_decl;
7428
7429   saved_processing_template_decl = processing_template_decl;
7430   if (!saved_processing_template_decl)
7431     processing_template_decl = 1;
7432   if (TYPE_P (t))
7433     dependent_p = dependent_type_p (t);
7434   else if (TREE_CODE (t) == TREE_VEC)
7435     dependent_p = any_dependent_template_arguments_p (t);
7436   else if (TREE_CODE (t) == TREE_LIST)
7437     dependent_p = (uses_template_parms (TREE_VALUE (t))
7438                    || uses_template_parms (TREE_CHAIN (t)));
7439   else if (TREE_CODE (t) == TYPE_DECL)
7440     dependent_p = dependent_type_p (TREE_TYPE (t));
7441   else if (DECL_P (t)
7442            || EXPR_P (t)
7443            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
7444            || TREE_CODE (t) == OVERLOAD
7445            || TREE_CODE (t) == BASELINK
7446            || TREE_CODE (t) == IDENTIFIER_NODE
7447            || TREE_CODE (t) == TRAIT_EXPR
7448            || TREE_CODE (t) == CONSTRUCTOR
7449            || CONSTANT_CLASS_P (t))
7450     dependent_p = (type_dependent_expression_p (t)
7451                    || value_dependent_expression_p (t));
7452   else
7453     {
7454       gcc_assert (t == error_mark_node);
7455       dependent_p = false;
7456     }
7457
7458   processing_template_decl = saved_processing_template_decl;
7459
7460   return dependent_p;
7461 }
7462
7463 /* Returns true if T depends on any template parameter with level LEVEL.  */
7464
7465 int
7466 uses_template_parms_level (tree t, int level)
7467 {
7468   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
7469                                  /*include_nondeduced_p=*/true);
7470 }
7471
7472 static int tinst_depth;
7473 extern int max_tinst_depth;
7474 #ifdef GATHER_STATISTICS
7475 int depth_reached;
7476 #endif
7477 static int tinst_level_tick;
7478 static int last_template_error_tick;
7479
7480 /* We're starting to instantiate D; record the template instantiation context
7481    for diagnostics and to restore it later.  */
7482
7483 int
7484 push_tinst_level (tree d)
7485 {
7486   struct tinst_level *new_level;
7487
7488   if (tinst_depth >= max_tinst_depth)
7489     {
7490       /* If the instantiation in question still has unbound template parms,
7491          we don't really care if we can't instantiate it, so just return.
7492          This happens with base instantiation for implicit `typename'.  */
7493       if (uses_template_parms (d))
7494         return 0;
7495
7496       last_template_error_tick = tinst_level_tick;
7497       error ("template instantiation depth exceeds maximum of %d (use "
7498              "-ftemplate-depth= to increase the maximum) instantiating %qD",
7499              max_tinst_depth, d);
7500
7501       print_instantiation_context ();
7502
7503       return 0;
7504     }
7505
7506   new_level = ggc_alloc_tinst_level ();
7507   new_level->decl = d;
7508   new_level->locus = input_location;
7509   new_level->in_system_header_p = in_system_header;
7510   new_level->next = current_tinst_level;
7511   current_tinst_level = new_level;
7512
7513   ++tinst_depth;
7514 #ifdef GATHER_STATISTICS
7515   if (tinst_depth > depth_reached)
7516     depth_reached = tinst_depth;
7517 #endif
7518
7519   ++tinst_level_tick;
7520   return 1;
7521 }
7522
7523 /* We're done instantiating this template; return to the instantiation
7524    context.  */
7525
7526 void
7527 pop_tinst_level (void)
7528 {
7529   /* Restore the filename and line number stashed away when we started
7530      this instantiation.  */
7531   input_location = current_tinst_level->locus;
7532   current_tinst_level = current_tinst_level->next;
7533   --tinst_depth;
7534   ++tinst_level_tick;
7535 }
7536
7537 /* We're instantiating a deferred template; restore the template
7538    instantiation context in which the instantiation was requested, which
7539    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
7540
7541 static tree
7542 reopen_tinst_level (struct tinst_level *level)
7543 {
7544   struct tinst_level *t;
7545
7546   tinst_depth = 0;
7547   for (t = level; t; t = t->next)
7548     ++tinst_depth;
7549
7550   current_tinst_level = level;
7551   pop_tinst_level ();
7552   return level->decl;
7553 }
7554
7555 /* Returns the TINST_LEVEL which gives the original instantiation
7556    context.  */
7557
7558 struct tinst_level *
7559 outermost_tinst_level (void)
7560 {
7561   struct tinst_level *level = current_tinst_level;
7562   if (level)
7563     while (level->next)
7564       level = level->next;
7565   return level;
7566 }
7567
7568 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
7569
7570 bool
7571 parameter_of_template_p (tree parm, tree templ)
7572 {
7573   tree parms;
7574   int i;
7575
7576   if (!parm || !templ)
7577     return false;
7578
7579   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
7580   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7581
7582   parms = DECL_TEMPLATE_PARMS (templ);
7583   parms = INNERMOST_TEMPLATE_PARMS (parms);
7584
7585   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
7586     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
7587       return true;
7588
7589   return false;
7590 }
7591
7592 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
7593    vector of template arguments, as for tsubst.
7594
7595    Returns an appropriate tsubst'd friend declaration.  */
7596
7597 static tree
7598 tsubst_friend_function (tree decl, tree args)
7599 {
7600   tree new_friend;
7601
7602   if (TREE_CODE (decl) == FUNCTION_DECL
7603       && DECL_TEMPLATE_INSTANTIATION (decl)
7604       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
7605     /* This was a friend declared with an explicit template
7606        argument list, e.g.:
7607
7608        friend void f<>(T);
7609
7610        to indicate that f was a template instantiation, not a new
7611        function declaration.  Now, we have to figure out what
7612        instantiation of what template.  */
7613     {
7614       tree template_id, arglist, fns;
7615       tree new_args;
7616       tree tmpl;
7617       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
7618
7619       /* Friend functions are looked up in the containing namespace scope.
7620          We must enter that scope, to avoid finding member functions of the
7621          current class with same name.  */
7622       push_nested_namespace (ns);
7623       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
7624                          tf_warning_or_error, NULL_TREE,
7625                          /*integral_constant_expression_p=*/false);
7626       pop_nested_namespace (ns);
7627       arglist = tsubst (DECL_TI_ARGS (decl), args,
7628                         tf_warning_or_error, NULL_TREE);
7629       template_id = lookup_template_function (fns, arglist);
7630
7631       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7632       tmpl = determine_specialization (template_id, new_friend,
7633                                        &new_args,
7634                                        /*need_member_template=*/0,
7635                                        TREE_VEC_LENGTH (args),
7636                                        tsk_none);
7637       return instantiate_template (tmpl, new_args, tf_error);
7638     }
7639
7640   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7641
7642   /* The NEW_FRIEND will look like an instantiation, to the
7643      compiler, but is not an instantiation from the point of view of
7644      the language.  For example, we might have had:
7645
7646      template <class T> struct S {
7647        template <class U> friend void f(T, U);
7648      };
7649
7650      Then, in S<int>, template <class U> void f(int, U) is not an
7651      instantiation of anything.  */
7652   if (new_friend == error_mark_node)
7653     return error_mark_node;
7654
7655   DECL_USE_TEMPLATE (new_friend) = 0;
7656   if (TREE_CODE (decl) == TEMPLATE_DECL)
7657     {
7658       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
7659       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
7660         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
7661     }
7662
7663   /* The mangled name for the NEW_FRIEND is incorrect.  The function
7664      is not a template instantiation and should not be mangled like
7665      one.  Therefore, we forget the mangling here; we'll recompute it
7666      later if we need it.  */
7667   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
7668     {
7669       SET_DECL_RTL (new_friend, NULL);
7670       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
7671     }
7672
7673   if (DECL_NAMESPACE_SCOPE_P (new_friend))
7674     {
7675       tree old_decl;
7676       tree new_friend_template_info;
7677       tree new_friend_result_template_info;
7678       tree ns;
7679       int  new_friend_is_defn;
7680
7681       /* We must save some information from NEW_FRIEND before calling
7682          duplicate decls since that function will free NEW_FRIEND if
7683          possible.  */
7684       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
7685       new_friend_is_defn =
7686             (DECL_INITIAL (DECL_TEMPLATE_RESULT
7687                            (template_for_substitution (new_friend)))
7688              != NULL_TREE);
7689       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
7690         {
7691           /* This declaration is a `primary' template.  */
7692           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
7693
7694           new_friend_result_template_info
7695             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
7696         }
7697       else
7698         new_friend_result_template_info = NULL_TREE;
7699
7700       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
7701       if (new_friend_is_defn)
7702         DECL_INITIAL (new_friend) = error_mark_node;
7703
7704       /* Inside pushdecl_namespace_level, we will push into the
7705          current namespace. However, the friend function should go
7706          into the namespace of the template.  */
7707       ns = decl_namespace_context (new_friend);
7708       push_nested_namespace (ns);
7709       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
7710       pop_nested_namespace (ns);
7711
7712       if (old_decl == error_mark_node)
7713         return error_mark_node;
7714
7715       if (old_decl != new_friend)
7716         {
7717           /* This new friend declaration matched an existing
7718              declaration.  For example, given:
7719
7720                template <class T> void f(T);
7721                template <class U> class C {
7722                  template <class T> friend void f(T) {}
7723                };
7724
7725              the friend declaration actually provides the definition
7726              of `f', once C has been instantiated for some type.  So,
7727              old_decl will be the out-of-class template declaration,
7728              while new_friend is the in-class definition.
7729
7730              But, if `f' was called before this point, the
7731              instantiation of `f' will have DECL_TI_ARGS corresponding
7732              to `T' but not to `U', references to which might appear
7733              in the definition of `f'.  Previously, the most general
7734              template for an instantiation of `f' was the out-of-class
7735              version; now it is the in-class version.  Therefore, we
7736              run through all specialization of `f', adding to their
7737              DECL_TI_ARGS appropriately.  In particular, they need a
7738              new set of outer arguments, corresponding to the
7739              arguments for this class instantiation.
7740
7741              The same situation can arise with something like this:
7742
7743                friend void f(int);
7744                template <class T> class C {
7745                  friend void f(T) {}
7746                };
7747
7748              when `C<int>' is instantiated.  Now, `f(int)' is defined
7749              in the class.  */
7750
7751           if (!new_friend_is_defn)
7752             /* On the other hand, if the in-class declaration does
7753                *not* provide a definition, then we don't want to alter
7754                existing definitions.  We can just leave everything
7755                alone.  */
7756             ;
7757           else
7758             {
7759               tree new_template = TI_TEMPLATE (new_friend_template_info);
7760               tree new_args = TI_ARGS (new_friend_template_info);
7761
7762               /* Overwrite whatever template info was there before, if
7763                  any, with the new template information pertaining to
7764                  the declaration.  */
7765               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
7766
7767               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
7768                 {
7769                   /* We should have called reregister_specialization in
7770                      duplicate_decls.  */
7771                   gcc_assert (retrieve_specialization (new_template,
7772                                                        new_args, 0)
7773                               == old_decl);
7774
7775                   /* Instantiate it if the global has already been used.  */
7776                   if (DECL_ODR_USED (old_decl))
7777                     instantiate_decl (old_decl, /*defer_ok=*/true,
7778                                       /*expl_inst_class_mem_p=*/false);
7779                 }
7780               else
7781                 {
7782                   tree t;
7783
7784                   /* Indicate that the old function template is a partial
7785                      instantiation.  */
7786                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
7787                     = new_friend_result_template_info;
7788
7789                   gcc_assert (new_template
7790                               == most_general_template (new_template));
7791                   gcc_assert (new_template != old_decl);
7792
7793                   /* Reassign any specializations already in the hash table
7794                      to the new more general template, and add the
7795                      additional template args.  */
7796                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
7797                        t != NULL_TREE;
7798                        t = TREE_CHAIN (t))
7799                     {
7800                       tree spec = TREE_VALUE (t);
7801                       spec_entry elt;
7802
7803                       elt.tmpl = old_decl;
7804                       elt.args = DECL_TI_ARGS (spec);
7805                       elt.spec = NULL_TREE;
7806
7807                       htab_remove_elt (decl_specializations, &elt);
7808
7809                       DECL_TI_ARGS (spec)
7810                         = add_outermost_template_args (new_args,
7811                                                        DECL_TI_ARGS (spec));
7812
7813                       register_specialization
7814                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
7815
7816                     }
7817                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
7818                 }
7819             }
7820
7821           /* The information from NEW_FRIEND has been merged into OLD_DECL
7822              by duplicate_decls.  */
7823           new_friend = old_decl;
7824         }
7825     }
7826   else
7827     {
7828       tree context = DECL_CONTEXT (new_friend);
7829       bool dependent_p;
7830
7831       /* In the code
7832            template <class T> class C {
7833              template <class U> friend void C1<U>::f (); // case 1
7834              friend void C2<T>::f ();                    // case 2
7835            };
7836          we only need to make sure CONTEXT is a complete type for
7837          case 2.  To distinguish between the two cases, we note that
7838          CONTEXT of case 1 remains dependent type after tsubst while
7839          this isn't true for case 2.  */
7840       ++processing_template_decl;
7841       dependent_p = dependent_type_p (context);
7842       --processing_template_decl;
7843
7844       if (!dependent_p
7845           && !complete_type_or_else (context, NULL_TREE))
7846         return error_mark_node;
7847
7848       if (COMPLETE_TYPE_P (context))
7849         {
7850           /* Check to see that the declaration is really present, and,
7851              possibly obtain an improved declaration.  */
7852           tree fn = check_classfn (context,
7853                                    new_friend, NULL_TREE);
7854
7855           if (fn)
7856             new_friend = fn;
7857         }
7858     }
7859
7860   return new_friend;
7861 }
7862
7863 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
7864    template arguments, as for tsubst.
7865
7866    Returns an appropriate tsubst'd friend type or error_mark_node on
7867    failure.  */
7868
7869 static tree
7870 tsubst_friend_class (tree friend_tmpl, tree args)
7871 {
7872   tree friend_type;
7873   tree tmpl;
7874   tree context;
7875
7876   context = CP_DECL_CONTEXT (friend_tmpl);
7877
7878   if (context != global_namespace)
7879     {
7880       if (TREE_CODE (context) == NAMESPACE_DECL)
7881         push_nested_namespace (context);
7882       else
7883         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
7884     }
7885
7886   /* Look for a class template declaration.  We look for hidden names
7887      because two friend declarations of the same template are the
7888      same.  For example, in:
7889
7890        struct A { 
7891          template <typename> friend class F;
7892        };
7893        template <typename> struct B { 
7894          template <typename> friend class F;
7895        };
7896
7897      both F templates are the same.  */
7898   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
7899                            /*block_p=*/true, 0, 
7900                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
7901
7902   /* But, if we don't find one, it might be because we're in a
7903      situation like this:
7904
7905        template <class T>
7906        struct S {
7907          template <class U>
7908          friend struct S;
7909        };
7910
7911      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
7912      for `S<int>', not the TEMPLATE_DECL.  */
7913   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
7914     {
7915       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
7916       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
7917     }
7918
7919   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
7920     {
7921       /* The friend template has already been declared.  Just
7922          check to see that the declarations match, and install any new
7923          default parameters.  We must tsubst the default parameters,
7924          of course.  We only need the innermost template parameters
7925          because that is all that redeclare_class_template will look
7926          at.  */
7927       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
7928           > TMPL_ARGS_DEPTH (args))
7929         {
7930           tree parms;
7931           location_t saved_input_location;
7932           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
7933                                          args, tf_warning_or_error);
7934
7935           saved_input_location = input_location;
7936           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
7937           redeclare_class_template (TREE_TYPE (tmpl), parms);
7938           input_location = saved_input_location;
7939           
7940         }
7941
7942       friend_type = TREE_TYPE (tmpl);
7943     }
7944   else
7945     {
7946       /* The friend template has not already been declared.  In this
7947          case, the instantiation of the template class will cause the
7948          injection of this template into the global scope.  */
7949       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7950       if (tmpl == error_mark_node)
7951         return error_mark_node;
7952
7953       /* The new TMPL is not an instantiation of anything, so we
7954          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7955          the new type because that is supposed to be the corresponding
7956          template decl, i.e., TMPL.  */
7957       DECL_USE_TEMPLATE (tmpl) = 0;
7958       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7959       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7960       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7961         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7962
7963       /* Inject this template into the global scope.  */
7964       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7965     }
7966
7967   if (context != global_namespace)
7968     {
7969       if (TREE_CODE (context) == NAMESPACE_DECL)
7970         pop_nested_namespace (context);
7971       else
7972         pop_nested_class ();
7973     }
7974
7975   return friend_type;
7976 }
7977
7978 /* Returns zero if TYPE cannot be completed later due to circularity.
7979    Otherwise returns one.  */
7980
7981 static int
7982 can_complete_type_without_circularity (tree type)
7983 {
7984   if (type == NULL_TREE || type == error_mark_node)
7985     return 0;
7986   else if (COMPLETE_TYPE_P (type))
7987     return 1;
7988   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
7989     return can_complete_type_without_circularity (TREE_TYPE (type));
7990   else if (CLASS_TYPE_P (type)
7991            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
7992     return 0;
7993   else
7994     return 1;
7995 }
7996
7997 /* Apply any attributes which had to be deferred until instantiation
7998    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
7999    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
8000
8001 static void
8002 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
8003                                 tree args, tsubst_flags_t complain, tree in_decl)
8004 {
8005   tree last_dep = NULL_TREE;
8006   tree t;
8007   tree *p;
8008
8009   for (t = attributes; t; t = TREE_CHAIN (t))
8010     if (ATTR_IS_DEPENDENT (t))
8011       {
8012         last_dep = t;
8013         attributes = copy_list (attributes);
8014         break;
8015       }
8016
8017   if (DECL_P (*decl_p))
8018     {
8019       if (TREE_TYPE (*decl_p) == error_mark_node)
8020         return;
8021       p = &DECL_ATTRIBUTES (*decl_p);
8022     }
8023   else
8024     p = &TYPE_ATTRIBUTES (*decl_p);
8025
8026   if (last_dep)
8027     {
8028       tree late_attrs = NULL_TREE;
8029       tree *q = &late_attrs;
8030
8031       for (*p = attributes; *p; )
8032         {
8033           t = *p;
8034           if (ATTR_IS_DEPENDENT (t))
8035             {
8036               *p = TREE_CHAIN (t);
8037               TREE_CHAIN (t) = NULL_TREE;
8038               /* If the first attribute argument is an identifier, don't
8039                  pass it through tsubst.  Attributes like mode, format,
8040                  cleanup and several target specific attributes expect it
8041                  unmodified.  */
8042               if (TREE_VALUE (t)
8043                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
8044                   && TREE_VALUE (TREE_VALUE (t))
8045                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
8046                       == IDENTIFIER_NODE))
8047                 {
8048                   tree chain
8049                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
8050                                    in_decl,
8051                                    /*integral_constant_expression_p=*/false);
8052                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
8053                     TREE_VALUE (t)
8054                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
8055                                    chain);
8056                 }
8057               else
8058                 TREE_VALUE (t)
8059                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
8060                                  /*integral_constant_expression_p=*/false);
8061               *q = t;
8062               q = &TREE_CHAIN (t);
8063             }
8064           else
8065             p = &TREE_CHAIN (t);
8066         }
8067
8068       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
8069     }
8070 }
8071
8072 /* Perform (or defer) access check for typedefs that were referenced
8073    from within the template TMPL code.
8074    This is a subroutine of instantiate_template and instantiate_class_template.
8075    TMPL is the template to consider and TARGS is the list of arguments of
8076    that template.  */
8077
8078 static void
8079 perform_typedefs_access_check (tree tmpl, tree targs)
8080 {
8081   location_t saved_location;
8082   int i;
8083   qualified_typedef_usage_t *iter;
8084
8085   if (!tmpl
8086       || (!CLASS_TYPE_P (tmpl)
8087           && TREE_CODE (tmpl) != FUNCTION_DECL))
8088     return;
8089
8090   saved_location = input_location;
8091   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
8092                     get_types_needing_access_check (tmpl),
8093                     i, iter)
8094     {
8095       tree type_decl = iter->typedef_decl;
8096       tree type_scope = iter->context;
8097
8098       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
8099         continue;
8100
8101       if (uses_template_parms (type_decl))
8102         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
8103       if (uses_template_parms (type_scope))
8104         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
8105
8106       /* Make access check error messages point to the location
8107          of the use of the typedef.  */
8108       input_location = iter->locus;
8109       perform_or_defer_access_check (TYPE_BINFO (type_scope),
8110                                      type_decl, type_decl);
8111     }
8112     input_location = saved_location;
8113 }
8114
8115 tree
8116 instantiate_class_template (tree type)
8117 {
8118   tree templ, args, pattern, t, member;
8119   tree typedecl;
8120   tree pbinfo;
8121   tree base_list;
8122   unsigned int saved_maximum_field_alignment;
8123
8124   if (type == error_mark_node)
8125     return error_mark_node;
8126
8127   if (COMPLETE_OR_OPEN_TYPE_P (type)
8128       || uses_template_parms (type))
8129     return type;
8130
8131   /* Figure out which template is being instantiated.  */
8132   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
8133   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
8134
8135   /* Determine what specialization of the original template to
8136      instantiate.  */
8137   t = most_specialized_class (type, templ, tf_warning_or_error);
8138   if (t == error_mark_node)
8139     {
8140       TYPE_BEING_DEFINED (type) = 1;
8141       return error_mark_node;
8142     }
8143   else if (t)
8144     {
8145       /* This TYPE is actually an instantiation of a partial
8146          specialization.  We replace the innermost set of ARGS with
8147          the arguments appropriate for substitution.  For example,
8148          given:
8149
8150            template <class T> struct S {};
8151            template <class T> struct S<T*> {};
8152
8153          and supposing that we are instantiating S<int*>, ARGS will
8154          presently be {int*} -- but we need {int}.  */
8155       pattern = TREE_TYPE (t);
8156       args = TREE_PURPOSE (t);
8157     }
8158   else
8159     {
8160       pattern = TREE_TYPE (templ);
8161       args = CLASSTYPE_TI_ARGS (type);
8162     }
8163
8164   /* If the template we're instantiating is incomplete, then clearly
8165      there's nothing we can do.  */
8166   if (!COMPLETE_TYPE_P (pattern))
8167     return type;
8168
8169   /* If we've recursively instantiated too many templates, stop.  */
8170   if (! push_tinst_level (type))
8171     return type;
8172
8173   /* Now we're really doing the instantiation.  Mark the type as in
8174      the process of being defined.  */
8175   TYPE_BEING_DEFINED (type) = 1;
8176
8177   /* We may be in the middle of deferred access check.  Disable
8178      it now.  */
8179   push_deferring_access_checks (dk_no_deferred);
8180
8181   push_to_top_level ();
8182   /* Use #pragma pack from the template context.  */
8183   saved_maximum_field_alignment = maximum_field_alignment;
8184   maximum_field_alignment = TYPE_PRECISION (pattern);
8185
8186   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
8187
8188   /* Set the input location to the most specialized template definition.
8189      This is needed if tsubsting causes an error.  */
8190   typedecl = TYPE_MAIN_DECL (pattern);
8191   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
8192     DECL_SOURCE_LOCATION (typedecl);
8193
8194   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
8195   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
8196   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
8197   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
8198   TYPE_HAS_COPY_ASSIGN (type) = TYPE_HAS_COPY_ASSIGN (pattern);
8199   TYPE_HAS_CONST_COPY_ASSIGN (type) = TYPE_HAS_CONST_COPY_ASSIGN (pattern);
8200   TYPE_HAS_COPY_CTOR (type) = TYPE_HAS_COPY_CTOR (pattern);
8201   TYPE_HAS_CONST_COPY_CTOR (type) = TYPE_HAS_CONST_COPY_CTOR (pattern);
8202   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
8203   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
8204   TYPE_PACKED (type) = TYPE_PACKED (pattern);
8205   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
8206   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
8207   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
8208   if (ANON_AGGR_TYPE_P (pattern))
8209     SET_ANON_AGGR_TYPE_P (type);
8210   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
8211     {
8212       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
8213       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
8214     }
8215
8216   pbinfo = TYPE_BINFO (pattern);
8217
8218   /* We should never instantiate a nested class before its enclosing
8219      class; we need to look up the nested class by name before we can
8220      instantiate it, and that lookup should instantiate the enclosing
8221      class.  */
8222   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
8223               || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
8224
8225   base_list = NULL_TREE;
8226   if (BINFO_N_BASE_BINFOS (pbinfo))
8227     {
8228       tree pbase_binfo;
8229       tree pushed_scope;
8230       int i;
8231
8232       /* We must enter the scope containing the type, as that is where
8233          the accessibility of types named in dependent bases are
8234          looked up from.  */
8235       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
8236
8237       /* Substitute into each of the bases to determine the actual
8238          basetypes.  */
8239       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
8240         {
8241           tree base;
8242           tree access = BINFO_BASE_ACCESS (pbinfo, i);
8243           tree expanded_bases = NULL_TREE;
8244           int idx, len = 1;
8245
8246           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
8247             {
8248               expanded_bases = 
8249                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
8250                                        args, tf_error, NULL_TREE);
8251               if (expanded_bases == error_mark_node)
8252                 continue;
8253
8254               len = TREE_VEC_LENGTH (expanded_bases);
8255             }
8256
8257           for (idx = 0; idx < len; idx++)
8258             {
8259               if (expanded_bases)
8260                 /* Extract the already-expanded base class.  */
8261                 base = TREE_VEC_ELT (expanded_bases, idx);
8262               else
8263                 /* Substitute to figure out the base class.  */
8264                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
8265                                NULL_TREE);
8266
8267               if (base == error_mark_node)
8268                 continue;
8269
8270               base_list = tree_cons (access, base, base_list);
8271               if (BINFO_VIRTUAL_P (pbase_binfo))
8272                 TREE_TYPE (base_list) = integer_type_node;
8273             }
8274         }
8275
8276       /* The list is now in reverse order; correct that.  */
8277       base_list = nreverse (base_list);
8278
8279       if (pushed_scope)
8280         pop_scope (pushed_scope);
8281     }
8282   /* Now call xref_basetypes to set up all the base-class
8283      information.  */
8284   xref_basetypes (type, base_list);
8285
8286   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
8287                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
8288                                   args, tf_error, NULL_TREE);
8289   fixup_attribute_variants (type);
8290
8291   /* Now that our base classes are set up, enter the scope of the
8292      class, so that name lookups into base classes, etc. will work
8293      correctly.  This is precisely analogous to what we do in
8294      begin_class_definition when defining an ordinary non-template
8295      class, except we also need to push the enclosing classes.  */
8296   push_nested_class (type);
8297
8298   /* Now members are processed in the order of declaration.  */
8299   for (member = CLASSTYPE_DECL_LIST (pattern);
8300        member; member = TREE_CHAIN (member))
8301     {
8302       tree t = TREE_VALUE (member);
8303
8304       if (TREE_PURPOSE (member))
8305         {
8306           if (TYPE_P (t))
8307             {
8308               /* Build new CLASSTYPE_NESTED_UTDS.  */
8309
8310               tree newtag;
8311               bool class_template_p;
8312
8313               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
8314                                   && TYPE_LANG_SPECIFIC (t)
8315                                   && CLASSTYPE_IS_TEMPLATE (t));
8316               /* If the member is a class template, then -- even after
8317                  substitution -- there may be dependent types in the
8318                  template argument list for the class.  We increment
8319                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
8320                  that function will assume that no types are dependent
8321                  when outside of a template.  */
8322               if (class_template_p)
8323                 ++processing_template_decl;
8324               newtag = tsubst (t, args, tf_error, NULL_TREE);
8325               if (class_template_p)
8326                 --processing_template_decl;
8327               if (newtag == error_mark_node)
8328                 continue;
8329
8330               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
8331                 {
8332                   tree name = TYPE_IDENTIFIER (t);
8333
8334                   if (class_template_p)
8335                     /* Unfortunately, lookup_template_class sets
8336                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
8337                        instantiation (i.e., for the type of a member
8338                        template class nested within a template class.)
8339                        This behavior is required for
8340                        maybe_process_partial_specialization to work
8341                        correctly, but is not accurate in this case;
8342                        the TAG is not an instantiation of anything.
8343                        (The corresponding TEMPLATE_DECL is an
8344                        instantiation, but the TYPE is not.) */
8345                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
8346
8347                   /* Now, we call pushtag to put this NEWTAG into the scope of
8348                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
8349                      pushtag calling push_template_decl.  We don't have to do
8350                      this for enums because it will already have been done in
8351                      tsubst_enum.  */
8352                   if (name)
8353                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
8354                   pushtag (name, newtag, /*tag_scope=*/ts_current);
8355                 }
8356             }
8357           else if (TREE_CODE (t) == FUNCTION_DECL
8358                    || DECL_FUNCTION_TEMPLATE_P (t))
8359             {
8360               /* Build new TYPE_METHODS.  */
8361               tree r;
8362
8363               if (TREE_CODE (t) == TEMPLATE_DECL)
8364                 ++processing_template_decl;
8365               r = tsubst (t, args, tf_error, NULL_TREE);
8366               if (TREE_CODE (t) == TEMPLATE_DECL)
8367                 --processing_template_decl;
8368               set_current_access_from_decl (r);
8369               finish_member_declaration (r);
8370             }
8371           else
8372             {
8373               /* Build new TYPE_FIELDS.  */
8374               if (TREE_CODE (t) == STATIC_ASSERT)
8375                 {
8376                   tree condition = 
8377                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
8378                                  tf_warning_or_error, NULL_TREE,
8379                                  /*integral_constant_expression_p=*/true);
8380                   finish_static_assert (condition,
8381                                         STATIC_ASSERT_MESSAGE (t), 
8382                                         STATIC_ASSERT_SOURCE_LOCATION (t),
8383                                         /*member_p=*/true);
8384                 }
8385               else if (TREE_CODE (t) != CONST_DECL)
8386                 {
8387                   tree r;
8388
8389                   /* The file and line for this declaration, to
8390                      assist in error message reporting.  Since we
8391                      called push_tinst_level above, we don't need to
8392                      restore these.  */
8393                   input_location = DECL_SOURCE_LOCATION (t);
8394
8395                   if (TREE_CODE (t) == TEMPLATE_DECL)
8396                     ++processing_template_decl;
8397                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
8398                   if (TREE_CODE (t) == TEMPLATE_DECL)
8399                     --processing_template_decl;
8400                   if (TREE_CODE (r) == VAR_DECL)
8401                     {
8402                       /* In [temp.inst]:
8403
8404                            [t]he initialization (and any associated
8405                            side-effects) of a static data member does
8406                            not occur unless the static data member is
8407                            itself used in a way that requires the
8408                            definition of the static data member to
8409                            exist.
8410
8411                          Therefore, we do not substitute into the
8412                          initialized for the static data member here.  */
8413                       finish_static_data_member_decl
8414                         (r,
8415                          /*init=*/NULL_TREE,
8416                          /*init_const_expr_p=*/false,
8417                          /*asmspec_tree=*/NULL_TREE,
8418                          /*flags=*/0);
8419                       if (DECL_INITIALIZED_IN_CLASS_P (r))
8420                         check_static_variable_definition (r, TREE_TYPE (r));
8421                     }
8422                   else if (TREE_CODE (r) == FIELD_DECL)
8423                     {
8424                       /* Determine whether R has a valid type and can be
8425                          completed later.  If R is invalid, then it is
8426                          replaced by error_mark_node so that it will not be
8427                          added to TYPE_FIELDS.  */
8428                       tree rtype = TREE_TYPE (r);
8429                       if (can_complete_type_without_circularity (rtype))
8430                         complete_type (rtype);
8431
8432                       if (!COMPLETE_TYPE_P (rtype))
8433                         {
8434                           cxx_incomplete_type_error (r, rtype);
8435                           r = error_mark_node;
8436                         }
8437                     }
8438
8439                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
8440                      such a thing will already have been added to the field
8441                      list by tsubst_enum in finish_member_declaration in the
8442                      CLASSTYPE_NESTED_UTDS case above.  */
8443                   if (!(TREE_CODE (r) == TYPE_DECL
8444                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
8445                         && DECL_ARTIFICIAL (r)))
8446                     {
8447                       set_current_access_from_decl (r);
8448                       finish_member_declaration (r);
8449                     }
8450                 }
8451             }
8452         }
8453       else
8454         {
8455           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
8456             {
8457               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
8458
8459               tree friend_type = t;
8460               bool adjust_processing_template_decl = false;
8461
8462               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8463                 {
8464                   /* template <class T> friend class C;  */
8465                   friend_type = tsubst_friend_class (friend_type, args);
8466                   adjust_processing_template_decl = true;
8467                 }
8468               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
8469                 {
8470                   /* template <class T> friend class C::D;  */
8471                   friend_type = tsubst (friend_type, args,
8472                                         tf_warning_or_error, NULL_TREE);
8473                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8474                     friend_type = TREE_TYPE (friend_type);
8475                   adjust_processing_template_decl = true;
8476                 }
8477               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
8478                 {
8479                   /* This could be either
8480
8481                        friend class T::C;
8482
8483                      when dependent_type_p is false or
8484
8485                        template <class U> friend class T::C;
8486
8487                      otherwise.  */
8488                   friend_type = tsubst (friend_type, args,
8489                                         tf_warning_or_error, NULL_TREE);
8490                   /* Bump processing_template_decl for correct
8491                      dependent_type_p calculation.  */
8492                   ++processing_template_decl;
8493                   if (dependent_type_p (friend_type))
8494                     adjust_processing_template_decl = true;
8495                   --processing_template_decl;
8496                 }
8497               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
8498                        && hidden_name_p (TYPE_NAME (friend_type)))
8499                 {
8500                   /* friend class C;
8501
8502                      where C hasn't been declared yet.  Let's lookup name
8503                      from namespace scope directly, bypassing any name that
8504                      come from dependent base class.  */
8505                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
8506
8507                   /* The call to xref_tag_from_type does injection for friend
8508                      classes.  */
8509                   push_nested_namespace (ns);
8510                   friend_type =
8511                     xref_tag_from_type (friend_type, NULL_TREE,
8512                                         /*tag_scope=*/ts_current);
8513                   pop_nested_namespace (ns);
8514                 }
8515               else if (uses_template_parms (friend_type))
8516                 /* friend class C<T>;  */
8517                 friend_type = tsubst (friend_type, args,
8518                                       tf_warning_or_error, NULL_TREE);
8519               /* Otherwise it's
8520
8521                    friend class C;
8522
8523                  where C is already declared or
8524
8525                    friend class C<int>;
8526
8527                  We don't have to do anything in these cases.  */
8528
8529               if (adjust_processing_template_decl)
8530                 /* Trick make_friend_class into realizing that the friend
8531                    we're adding is a template, not an ordinary class.  It's
8532                    important that we use make_friend_class since it will
8533                    perform some error-checking and output cross-reference
8534                    information.  */
8535                 ++processing_template_decl;
8536
8537               if (friend_type != error_mark_node)
8538                 make_friend_class (type, friend_type, /*complain=*/false);
8539
8540               if (adjust_processing_template_decl)
8541                 --processing_template_decl;
8542             }
8543           else
8544             {
8545               /* Build new DECL_FRIENDLIST.  */
8546               tree r;
8547
8548               /* The file and line for this declaration, to
8549                  assist in error message reporting.  Since we
8550                  called push_tinst_level above, we don't need to
8551                  restore these.  */
8552               input_location = DECL_SOURCE_LOCATION (t);
8553
8554               if (TREE_CODE (t) == TEMPLATE_DECL)
8555                 {
8556                   ++processing_template_decl;
8557                   push_deferring_access_checks (dk_no_check);
8558                 }
8559
8560               r = tsubst_friend_function (t, args);
8561               add_friend (type, r, /*complain=*/false);
8562               if (TREE_CODE (t) == TEMPLATE_DECL)
8563                 {
8564                   pop_deferring_access_checks ();
8565                   --processing_template_decl;
8566                 }
8567             }
8568         }
8569     }
8570
8571   /* Set the file and line number information to whatever is given for
8572      the class itself.  This puts error messages involving generated
8573      implicit functions at a predictable point, and the same point
8574      that would be used for non-template classes.  */
8575   input_location = DECL_SOURCE_LOCATION (typedecl);
8576
8577   unreverse_member_declarations (type);
8578   finish_struct_1 (type);
8579   TYPE_BEING_DEFINED (type) = 0;
8580
8581   /* We don't instantiate default arguments for member functions.  14.7.1:
8582
8583      The implicit instantiation of a class template specialization causes
8584      the implicit instantiation of the declarations, but not of the
8585      definitions or default arguments, of the class member functions,
8586      member classes, static data members and member templates....  */
8587
8588   /* Some typedefs referenced from within the template code need to be access
8589      checked at template instantiation time, i.e now. These types were
8590      added to the template at parsing time. Let's get those and perform
8591      the access checks then.  */
8592   perform_typedefs_access_check (pattern, args);
8593   perform_deferred_access_checks ();
8594   pop_nested_class ();
8595   maximum_field_alignment = saved_maximum_field_alignment;
8596   pop_from_top_level ();
8597   pop_deferring_access_checks ();
8598   pop_tinst_level ();
8599
8600   /* The vtable for a template class can be emitted in any translation
8601      unit in which the class is instantiated.  When there is no key
8602      method, however, finish_struct_1 will already have added TYPE to
8603      the keyed_classes list.  */
8604   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
8605     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
8606
8607   return type;
8608 }
8609
8610 static tree
8611 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8612 {
8613   tree r;
8614
8615   if (!t)
8616     r = t;
8617   else if (TYPE_P (t))
8618     r = tsubst (t, args, complain, in_decl);
8619   else
8620     {
8621       if (!(complain & tf_warning))
8622         ++c_inhibit_evaluation_warnings;
8623       r = tsubst_expr (t, args, complain, in_decl,
8624                        /*integral_constant_expression_p=*/true);
8625       if (!(complain & tf_warning))
8626         --c_inhibit_evaluation_warnings;
8627     }
8628   return r;
8629 }
8630
8631 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
8632    NONTYPE_ARGUMENT_PACK.  */
8633
8634 static tree
8635 make_fnparm_pack (tree spec_parm)
8636 {
8637   /* Collect all of the extra "packed" parameters into an
8638      argument pack.  */
8639   tree parmvec;
8640   tree parmtypevec;
8641   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
8642   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
8643   int i, len = list_length (spec_parm);
8644
8645   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
8646   parmvec = make_tree_vec (len);
8647   parmtypevec = make_tree_vec (len);
8648   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
8649     {
8650       TREE_VEC_ELT (parmvec, i) = spec_parm;
8651       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
8652     }
8653
8654   /* Build the argument packs.  */
8655   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
8656   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
8657   TREE_TYPE (argpack) = argtypepack;
8658
8659   return argpack;
8660 }        
8661
8662 /* Substitute ARGS into T, which is an pack expansion
8663    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
8664    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
8665    (if only a partial substitution could be performed) or
8666    ERROR_MARK_NODE if there was an error.  */
8667 tree
8668 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
8669                        tree in_decl)
8670 {
8671   tree pattern;
8672   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
8673   int i, len = -1;
8674   tree result;
8675   int incomplete = 0;
8676   htab_t saved_local_specializations = NULL;
8677
8678   gcc_assert (PACK_EXPANSION_P (t));
8679   pattern = PACK_EXPANSION_PATTERN (t);
8680
8681   /* Determine the argument packs that will instantiate the parameter
8682      packs used in the expansion expression. While we're at it,
8683      compute the number of arguments to be expanded and make sure it
8684      is consistent.  */
8685   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
8686        pack = TREE_CHAIN (pack))
8687     {
8688       tree parm_pack = TREE_VALUE (pack);
8689       tree arg_pack = NULL_TREE;
8690       tree orig_arg = NULL_TREE;
8691
8692       if (TREE_CODE (parm_pack) == PARM_DECL)
8693         {
8694           if (!cp_unevaluated_operand)
8695             arg_pack = retrieve_local_specialization (parm_pack);
8696           else
8697             {
8698               /* We can't rely on local_specializations for a parameter
8699                  name used later in a function declaration (such as in a
8700                  late-specified return type).  Even if it exists, it might
8701                  have the wrong value for a recursive call.  Just make a
8702                  dummy decl, since it's only used for its type.  */
8703               arg_pack = tsubst_decl (parm_pack, args, complain);
8704               arg_pack = make_fnparm_pack (arg_pack);
8705             }
8706         }
8707       else
8708         {
8709           int level, idx, levels;
8710           template_parm_level_and_index (parm_pack, &level, &idx);
8711
8712           levels = TMPL_ARGS_DEPTH (args);
8713           if (level <= levels)
8714             arg_pack = TMPL_ARG (args, level, idx);
8715         }
8716
8717       orig_arg = arg_pack;
8718       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
8719         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
8720       
8721       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
8722         /* This can only happen if we forget to expand an argument
8723            pack somewhere else. Just return an error, silently.  */
8724         {
8725           result = make_tree_vec (1);
8726           TREE_VEC_ELT (result, 0) = error_mark_node;
8727           return result;
8728         }
8729
8730       /* For clarity in the comments below let's use the
8731          representation 'argument_pack<elements>' to denote an
8732          argument pack and its elements.
8733
8734          In the 'if' block below, we want to detect cases where
8735          ARG_PACK is argument_pack<PARM_PACK...>.  I.e, we want to
8736          check if ARG_PACK is an argument pack which sole element is
8737          the expansion of PARM_PACK.  That argument pack is typically
8738          created by template_parm_to_arg when passed a parameter
8739          pack.  */
8740       if (arg_pack
8741           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
8742           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
8743         {
8744           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
8745           tree pattern = PACK_EXPANSION_PATTERN (expansion);
8746           /* So we have an argument_pack<P...>.  We want to test if P
8747              is actually PARM_PACK.  We will not use cp_tree_equal to
8748              test P and PARM_PACK because during type fixup (by
8749              fixup_template_parm) P can be a pre-fixup version of a
8750              type and PARM_PACK be its post-fixup version.
8751              cp_tree_equal would consider them as different even
8752              though we would want to consider them compatible for our
8753              precise purpose here.
8754
8755              Thus we are going to consider that P and PARM_PACK are
8756              compatible if they have the same DECL.  */
8757           if ((/* If ARG_PACK is a type parameter pack named by the
8758                   same DECL as parm_pack ...  */
8759                (TYPE_P (pattern)
8760                 && TYPE_P (parm_pack)
8761                 && TYPE_NAME (pattern) == TYPE_NAME (parm_pack))
8762                /* ... or if ARG_PACK is a non-type parameter
8763                   named by the same DECL as parm_pack ...  */
8764                || (TREE_CODE (pattern) == TEMPLATE_PARM_INDEX
8765                    && TREE_CODE (parm_pack) == PARM_DECL
8766                    && TEMPLATE_PARM_DECL (pattern)
8767                    == TEMPLATE_PARM_DECL (DECL_INITIAL (parm_pack))))
8768               && template_parameter_pack_p (pattern))
8769             /* ... then the argument pack that the parameter maps to
8770                is just an expansion of the parameter itself, such as
8771                one would find in the implicit typedef of a class
8772                inside the class itself.  Consider this parameter
8773                "unsubstituted", so that we will maintain the outer
8774                pack expansion.  */
8775             arg_pack = NULL_TREE;
8776         }
8777           
8778       if (arg_pack)
8779         {
8780           int my_len = 
8781             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
8782
8783           /* It's all-or-nothing with incomplete argument packs.  */
8784           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8785             return error_mark_node;
8786           
8787           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8788             incomplete = 1;
8789
8790           if (len < 0)
8791             len = my_len;
8792           else if (len != my_len)
8793             {
8794               if (incomplete)
8795                 /* We got explicit args for some packs but not others;
8796                    do nothing now and try again after deduction.  */
8797                 return t;
8798               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
8799                 error ("mismatched argument pack lengths while expanding "
8800                        "%<%T%>",
8801                        pattern);
8802               else
8803                 error ("mismatched argument pack lengths while expanding "
8804                        "%<%E%>",
8805                        pattern);
8806               return error_mark_node;
8807             }
8808
8809           /* Keep track of the parameter packs and their corresponding
8810              argument packs.  */
8811           packs = tree_cons (parm_pack, arg_pack, packs);
8812           TREE_TYPE (packs) = orig_arg;
8813         }
8814       else
8815         /* We can't substitute for this parameter pack.  */
8816         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
8817                                          TREE_VALUE (pack),
8818                                          unsubstituted_packs);
8819     }
8820
8821   /* We cannot expand this expansion expression, because we don't have
8822      all of the argument packs we need. Substitute into the pattern
8823      and return a PACK_EXPANSION_*. The caller will need to deal with
8824      that.  */
8825   if (unsubstituted_packs)
8826     {
8827       tree new_pat;
8828       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8829         new_pat = tsubst_expr (pattern, args, complain, in_decl,
8830                                /*integral_constant_expression_p=*/false);
8831       else
8832         new_pat = tsubst (pattern, args, complain, in_decl);
8833       return make_pack_expansion (new_pat);
8834     }
8835
8836   /* We could not find any argument packs that work.  */
8837   if (len < 0)
8838     return error_mark_node;
8839
8840   if (cp_unevaluated_operand)
8841     {
8842       /* We're in a late-specified return type, so create our own local
8843          specializations table; the current table is either NULL or (in the
8844          case of recursive unification) might have bindings that we don't
8845          want to use or alter.  */
8846       saved_local_specializations = local_specializations;
8847       local_specializations = htab_create (37,
8848                                            hash_local_specialization,
8849                                            eq_local_specializations,
8850                                            NULL);
8851     }
8852
8853   /* For each argument in each argument pack, substitute into the
8854      pattern.  */
8855   result = make_tree_vec (len + incomplete);
8856   for (i = 0; i < len + incomplete; ++i)
8857     {
8858       /* For parameter pack, change the substitution of the parameter
8859          pack to the ith argument in its argument pack, then expand
8860          the pattern.  */
8861       for (pack = packs; pack; pack = TREE_CHAIN (pack))
8862         {
8863           tree parm = TREE_PURPOSE (pack);
8864
8865           if (TREE_CODE (parm) == PARM_DECL)
8866             {
8867               /* Select the Ith argument from the pack.  */
8868               tree arg = make_node (ARGUMENT_PACK_SELECT);
8869               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
8870               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
8871               mark_used (parm);
8872               register_local_specialization (arg, parm);
8873             }
8874           else
8875             {
8876               tree value = parm;
8877               int idx, level;
8878               template_parm_level_and_index (parm, &level, &idx);
8879               
8880               if (i < len) 
8881                 {
8882                   /* Select the Ith argument from the pack. */
8883                   value = make_node (ARGUMENT_PACK_SELECT);
8884                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
8885                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
8886                 }
8887
8888               /* Update the corresponding argument.  */
8889               TMPL_ARG (args, level, idx) = value;
8890             }
8891         }
8892
8893       /* Substitute into the PATTERN with the altered arguments.  */
8894       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8895         TREE_VEC_ELT (result, i) = 
8896           tsubst_expr (pattern, args, complain, in_decl,
8897                        /*integral_constant_expression_p=*/false);
8898       else
8899         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
8900
8901       if (i == len)
8902         /* When we have incomplete argument packs, the last "expanded"
8903            result is itself a pack expansion, which allows us
8904            to deduce more arguments.  */
8905         TREE_VEC_ELT (result, i) = 
8906           make_pack_expansion (TREE_VEC_ELT (result, i));
8907
8908       if (TREE_VEC_ELT (result, i) == error_mark_node)
8909         {
8910           result = error_mark_node;
8911           break;
8912         }
8913     }
8914
8915   /* Update ARGS to restore the substitution from parameter packs to
8916      their argument packs.  */
8917   for (pack = packs; pack; pack = TREE_CHAIN (pack))
8918     {
8919       tree parm = TREE_PURPOSE (pack);
8920
8921       if (TREE_CODE (parm) == PARM_DECL)
8922         register_local_specialization (TREE_TYPE (pack), parm);
8923       else
8924         {
8925           int idx, level;
8926           template_parm_level_and_index (parm, &level, &idx);
8927           
8928           /* Update the corresponding argument.  */
8929           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
8930             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
8931               TREE_TYPE (pack);
8932           else
8933             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
8934         }
8935     }
8936
8937   if (saved_local_specializations)
8938     {
8939       htab_delete (local_specializations);
8940       local_specializations = saved_local_specializations;
8941     }
8942   
8943   return result;
8944 }
8945
8946 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
8947    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
8948    parameter packs; all parms generated from a function parameter pack will
8949    have the same DECL_PARM_INDEX.  */
8950
8951 tree
8952 get_pattern_parm (tree parm, tree tmpl)
8953 {
8954   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
8955   tree patparm;
8956
8957   if (DECL_ARTIFICIAL (parm))
8958     {
8959       for (patparm = DECL_ARGUMENTS (pattern);
8960            patparm; patparm = DECL_CHAIN (patparm))
8961         if (DECL_ARTIFICIAL (patparm)
8962             && DECL_NAME (parm) == DECL_NAME (patparm))
8963           break;
8964     }
8965   else
8966     {
8967       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
8968       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
8969       gcc_assert (DECL_PARM_INDEX (patparm)
8970                   == DECL_PARM_INDEX (parm));
8971     }
8972
8973   return patparm;
8974 }
8975
8976 /* Substitute ARGS into the vector or list of template arguments T.  */
8977
8978 static tree
8979 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8980 {
8981   tree orig_t = t;
8982   int len, need_new = 0, i, expanded_len_adjust = 0, out;
8983   tree *elts;
8984
8985   if (t == error_mark_node)
8986     return error_mark_node;
8987
8988   len = TREE_VEC_LENGTH (t);
8989   elts = XALLOCAVEC (tree, len);
8990
8991   for (i = 0; i < len; i++)
8992     {
8993       tree orig_arg = TREE_VEC_ELT (t, i);
8994       tree new_arg;
8995
8996       if (TREE_CODE (orig_arg) == TREE_VEC)
8997         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
8998       else if (PACK_EXPANSION_P (orig_arg))
8999         {
9000           /* Substitute into an expansion expression.  */
9001           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
9002
9003           if (TREE_CODE (new_arg) == TREE_VEC)
9004             /* Add to the expanded length adjustment the number of
9005                expanded arguments. We subtract one from this
9006                measurement, because the argument pack expression
9007                itself is already counted as 1 in
9008                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
9009                the argument pack is empty.  */
9010             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
9011         }
9012       else if (ARGUMENT_PACK_P (orig_arg))
9013         {
9014           /* Substitute into each of the arguments.  */
9015           new_arg = TYPE_P (orig_arg)
9016             ? cxx_make_type (TREE_CODE (orig_arg))
9017             : make_node (TREE_CODE (orig_arg));
9018           
9019           SET_ARGUMENT_PACK_ARGS (
9020             new_arg,
9021             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
9022                                   args, complain, in_decl));
9023
9024           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
9025             new_arg = error_mark_node;
9026
9027           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
9028             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
9029                                           complain, in_decl);
9030             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
9031
9032             if (TREE_TYPE (new_arg) == error_mark_node)
9033               new_arg = error_mark_node;
9034           }
9035         }
9036       else
9037         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
9038
9039       if (new_arg == error_mark_node)
9040         return error_mark_node;
9041
9042       elts[i] = new_arg;
9043       if (new_arg != orig_arg)
9044         need_new = 1;
9045     }
9046
9047   if (!need_new)
9048     return t;
9049
9050   /* Make space for the expanded arguments coming from template
9051      argument packs.  */
9052   t = make_tree_vec (len + expanded_len_adjust);
9053   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
9054      arguments for a member template.
9055      In that case each TREE_VEC in ORIG_T represents a level of template
9056      arguments, and ORIG_T won't carry any non defaulted argument count.
9057      It will rather be the nested TREE_VECs that will carry one.
9058      In other words, ORIG_T carries a non defaulted argument count only
9059      if it doesn't contain any nested TREE_VEC.  */
9060   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
9061     {
9062       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
9063       count += expanded_len_adjust;
9064       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
9065     }
9066   for (i = 0, out = 0; i < len; i++)
9067     {
9068       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
9069            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
9070           && TREE_CODE (elts[i]) == TREE_VEC)
9071         {
9072           int idx;
9073
9074           /* Now expand the template argument pack "in place".  */
9075           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
9076             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
9077         }
9078       else
9079         {
9080           TREE_VEC_ELT (t, out) = elts[i];
9081           out++;
9082         }
9083     }
9084
9085   return t;
9086 }
9087
9088 /* Return the result of substituting ARGS into the template parameters
9089    given by PARMS.  If there are m levels of ARGS and m + n levels of
9090    PARMS, then the result will contain n levels of PARMS.  For
9091    example, if PARMS is `template <class T> template <class U>
9092    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
9093    result will be `template <int*, double, class V>'.  */
9094
9095 static tree
9096 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
9097 {
9098   tree r = NULL_TREE;
9099   tree* new_parms;
9100
9101   /* When substituting into a template, we must set
9102      PROCESSING_TEMPLATE_DECL as the template parameters may be
9103      dependent if they are based on one-another, and the dependency
9104      predicates are short-circuit outside of templates.  */
9105   ++processing_template_decl;
9106
9107   for (new_parms = &r;
9108        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
9109        new_parms = &(TREE_CHAIN (*new_parms)),
9110          parms = TREE_CHAIN (parms))
9111     {
9112       tree new_vec =
9113         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
9114       int i;
9115
9116       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
9117         {
9118           tree tuple;
9119
9120           if (parms == error_mark_node)
9121             continue;
9122
9123           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
9124
9125           if (tuple == error_mark_node)
9126             continue;
9127
9128           TREE_VEC_ELT (new_vec, i) =
9129             tsubst_template_parm (tuple, args, complain);
9130         }
9131
9132       *new_parms =
9133         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
9134                              - TMPL_ARGS_DEPTH (args)),
9135                    new_vec, NULL_TREE);
9136     }
9137
9138   --processing_template_decl;
9139
9140   return r;
9141 }
9142
9143 /* Return the result of substituting ARGS into one template parameter
9144    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
9145    parameter and which TREE_PURPOSE is the default argument of the
9146    template parameter.  */
9147
9148 static tree
9149 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
9150 {
9151   tree default_value, parm_decl;
9152
9153   if (args == NULL_TREE
9154       || t == NULL_TREE
9155       || t == error_mark_node)
9156     return t;
9157
9158   gcc_assert (TREE_CODE (t) == TREE_LIST);
9159
9160   default_value = TREE_PURPOSE (t);
9161   parm_decl = TREE_VALUE (t);
9162
9163   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
9164   if (TREE_CODE (parm_decl) == PARM_DECL
9165       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
9166     parm_decl = error_mark_node;
9167   default_value = tsubst_template_arg (default_value, args,
9168                                        complain, NULL_TREE);
9169
9170   return build_tree_list (default_value, parm_decl);
9171 }
9172
9173 /* Substitute the ARGS into the indicated aggregate (or enumeration)
9174    type T.  If T is not an aggregate or enumeration type, it is
9175    handled as if by tsubst.  IN_DECL is as for tsubst.  If
9176    ENTERING_SCOPE is nonzero, T is the context for a template which
9177    we are presently tsubst'ing.  Return the substituted value.  */
9178
9179 static tree
9180 tsubst_aggr_type (tree t,
9181                   tree args,
9182                   tsubst_flags_t complain,
9183                   tree in_decl,
9184                   int entering_scope)
9185 {
9186   if (t == NULL_TREE)
9187     return NULL_TREE;
9188
9189   switch (TREE_CODE (t))
9190     {
9191     case RECORD_TYPE:
9192       if (TYPE_PTRMEMFUNC_P (t))
9193         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
9194
9195       /* Else fall through.  */
9196     case ENUMERAL_TYPE:
9197     case UNION_TYPE:
9198       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
9199         {
9200           tree argvec;
9201           tree context;
9202           tree r;
9203           int saved_unevaluated_operand;
9204           int saved_inhibit_evaluation_warnings;
9205
9206           /* In "sizeof(X<I>)" we need to evaluate "I".  */
9207           saved_unevaluated_operand = cp_unevaluated_operand;
9208           cp_unevaluated_operand = 0;
9209           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
9210           c_inhibit_evaluation_warnings = 0;
9211
9212           /* First, determine the context for the type we are looking
9213              up.  */
9214           context = TYPE_CONTEXT (t);
9215           if (context)
9216             {
9217               context = tsubst_aggr_type (context, args, complain,
9218                                           in_decl, /*entering_scope=*/1);
9219               /* If context is a nested class inside a class template,
9220                  it may still need to be instantiated (c++/33959).  */
9221               if (TYPE_P (context))
9222                 context = complete_type (context);
9223             }
9224
9225           /* Then, figure out what arguments are appropriate for the
9226              type we are trying to find.  For example, given:
9227
9228                template <class T> struct S;
9229                template <class T, class U> void f(T, U) { S<U> su; }
9230
9231              and supposing that we are instantiating f<int, double>,
9232              then our ARGS will be {int, double}, but, when looking up
9233              S we only want {double}.  */
9234           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
9235                                          complain, in_decl);
9236           if (argvec == error_mark_node)
9237             r = error_mark_node;
9238           else
9239             {
9240               r = lookup_template_class (t, argvec, in_decl, context,
9241                                          entering_scope, complain);
9242               r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
9243             }
9244
9245           cp_unevaluated_operand = saved_unevaluated_operand;
9246           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
9247
9248           return r;
9249         }
9250       else
9251         /* This is not a template type, so there's nothing to do.  */
9252         return t;
9253
9254     default:
9255       return tsubst (t, args, complain, in_decl);
9256     }
9257 }
9258
9259 /* Substitute into the default argument ARG (a default argument for
9260    FN), which has the indicated TYPE.  */
9261
9262 tree
9263 tsubst_default_argument (tree fn, tree type, tree arg)
9264 {
9265   tree saved_class_ptr = NULL_TREE;
9266   tree saved_class_ref = NULL_TREE;
9267
9268   /* This can happen in invalid code.  */
9269   if (TREE_CODE (arg) == DEFAULT_ARG)
9270     return arg;
9271
9272   /* This default argument came from a template.  Instantiate the
9273      default argument here, not in tsubst.  In the case of
9274      something like:
9275
9276        template <class T>
9277        struct S {
9278          static T t();
9279          void f(T = t());
9280        };
9281
9282      we must be careful to do name lookup in the scope of S<T>,
9283      rather than in the current class.  */
9284   push_access_scope (fn);
9285   /* The "this" pointer is not valid in a default argument.  */
9286   if (cfun)
9287     {
9288       saved_class_ptr = current_class_ptr;
9289       cp_function_chain->x_current_class_ptr = NULL_TREE;
9290       saved_class_ref = current_class_ref;
9291       cp_function_chain->x_current_class_ref = NULL_TREE;
9292     }
9293
9294   push_deferring_access_checks(dk_no_deferred);
9295   /* The default argument expression may cause implicitly defined
9296      member functions to be synthesized, which will result in garbage
9297      collection.  We must treat this situation as if we were within
9298      the body of function so as to avoid collecting live data on the
9299      stack.  */
9300   ++function_depth;
9301   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
9302                      tf_warning_or_error, NULL_TREE,
9303                      /*integral_constant_expression_p=*/false);
9304   --function_depth;
9305   pop_deferring_access_checks();
9306
9307   /* Restore the "this" pointer.  */
9308   if (cfun)
9309     {
9310       cp_function_chain->x_current_class_ptr = saved_class_ptr;
9311       cp_function_chain->x_current_class_ref = saved_class_ref;
9312     }
9313
9314   /* Make sure the default argument is reasonable.  */
9315   arg = check_default_argument (type, arg);
9316
9317   pop_access_scope (fn);
9318
9319   return arg;
9320 }
9321
9322 /* Substitute into all the default arguments for FN.  */
9323
9324 static void
9325 tsubst_default_arguments (tree fn)
9326 {
9327   tree arg;
9328   tree tmpl_args;
9329
9330   tmpl_args = DECL_TI_ARGS (fn);
9331
9332   /* If this function is not yet instantiated, we certainly don't need
9333      its default arguments.  */
9334   if (uses_template_parms (tmpl_args))
9335     return;
9336   /* Don't do this again for clones.  */
9337   if (DECL_CLONED_FUNCTION_P (fn))
9338     return;
9339
9340   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
9341        arg;
9342        arg = TREE_CHAIN (arg))
9343     if (TREE_PURPOSE (arg))
9344       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
9345                                                     TREE_VALUE (arg),
9346                                                     TREE_PURPOSE (arg));
9347 }
9348
9349 /* Substitute the ARGS into the T, which is a _DECL.  Return the
9350    result of the substitution.  Issue error and warning messages under
9351    control of COMPLAIN.  */
9352
9353 static tree
9354 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
9355 {
9356 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
9357   location_t saved_loc;
9358   tree r = NULL_TREE;
9359   tree in_decl = t;
9360   hashval_t hash = 0;
9361
9362   /* Set the filename and linenumber to improve error-reporting.  */
9363   saved_loc = input_location;
9364   input_location = DECL_SOURCE_LOCATION (t);
9365
9366   switch (TREE_CODE (t))
9367     {
9368     case TEMPLATE_DECL:
9369       {
9370         /* We can get here when processing a member function template,
9371            member class template, or template template parameter.  */
9372         tree decl = DECL_TEMPLATE_RESULT (t);
9373         tree spec;
9374         tree tmpl_args;
9375         tree full_args;
9376
9377         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9378           {
9379             /* Template template parameter is treated here.  */
9380             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9381             if (new_type == error_mark_node)
9382               RETURN (error_mark_node);
9383
9384             r = copy_decl (t);
9385             DECL_CHAIN (r) = NULL_TREE;
9386             TREE_TYPE (r) = new_type;
9387             DECL_TEMPLATE_RESULT (r)
9388               = build_decl (DECL_SOURCE_LOCATION (decl),
9389                             TYPE_DECL, DECL_NAME (decl), new_type);
9390             DECL_TEMPLATE_PARMS (r)
9391               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9392                                        complain);
9393             TYPE_NAME (new_type) = r;
9394             break;
9395           }
9396
9397         /* We might already have an instance of this template.
9398            The ARGS are for the surrounding class type, so the
9399            full args contain the tsubst'd args for the context,
9400            plus the innermost args from the template decl.  */
9401         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
9402           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
9403           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
9404         /* Because this is a template, the arguments will still be
9405            dependent, even after substitution.  If
9406            PROCESSING_TEMPLATE_DECL is not set, the dependency
9407            predicates will short-circuit.  */
9408         ++processing_template_decl;
9409         full_args = tsubst_template_args (tmpl_args, args,
9410                                           complain, in_decl);
9411         --processing_template_decl;
9412         if (full_args == error_mark_node)
9413           RETURN (error_mark_node);
9414
9415         /* If this is a default template template argument,
9416            tsubst might not have changed anything.  */
9417         if (full_args == tmpl_args)
9418           RETURN (t);
9419
9420         hash = hash_tmpl_and_args (t, full_args);
9421         spec = retrieve_specialization (t, full_args, hash);
9422         if (spec != NULL_TREE)
9423           {
9424             r = spec;
9425             break;
9426           }
9427
9428         /* Make a new template decl.  It will be similar to the
9429            original, but will record the current template arguments.
9430            We also create a new function declaration, which is just
9431            like the old one, but points to this new template, rather
9432            than the old one.  */
9433         r = copy_decl (t);
9434         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
9435         DECL_CHAIN (r) = NULL_TREE;
9436
9437         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
9438
9439         if (TREE_CODE (decl) == TYPE_DECL)
9440           {
9441             tree new_type;
9442             ++processing_template_decl;
9443             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9444             --processing_template_decl;
9445             if (new_type == error_mark_node)
9446               RETURN (error_mark_node);
9447
9448             TREE_TYPE (r) = new_type;
9449             CLASSTYPE_TI_TEMPLATE (new_type) = r;
9450             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
9451             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
9452             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
9453           }
9454         else
9455           {
9456             tree new_decl;
9457             ++processing_template_decl;
9458             new_decl = tsubst (decl, args, complain, in_decl);
9459             --processing_template_decl;
9460             if (new_decl == error_mark_node)
9461               RETURN (error_mark_node);
9462
9463             DECL_TEMPLATE_RESULT (r) = new_decl;
9464             DECL_TI_TEMPLATE (new_decl) = r;
9465             TREE_TYPE (r) = TREE_TYPE (new_decl);
9466             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
9467             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
9468           }
9469
9470         SET_DECL_IMPLICIT_INSTANTIATION (r);
9471         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
9472         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
9473
9474         /* The template parameters for this new template are all the
9475            template parameters for the old template, except the
9476            outermost level of parameters.  */
9477         DECL_TEMPLATE_PARMS (r)
9478           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9479                                    complain);
9480
9481         if (PRIMARY_TEMPLATE_P (t))
9482           DECL_PRIMARY_TEMPLATE (r) = r;
9483
9484         if (TREE_CODE (decl) != TYPE_DECL)
9485           /* Record this non-type partial instantiation.  */
9486           register_specialization (r, t,
9487                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
9488                                    false, hash);
9489       }
9490       break;
9491
9492     case FUNCTION_DECL:
9493       {
9494         tree ctx;
9495         tree argvec = NULL_TREE;
9496         tree *friends;
9497         tree gen_tmpl;
9498         tree type;
9499         int member;
9500         int args_depth;
9501         int parms_depth;
9502
9503         /* Nobody should be tsubst'ing into non-template functions.  */
9504         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
9505
9506         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
9507           {
9508             tree spec;
9509             bool dependent_p;
9510
9511             /* If T is not dependent, just return it.  We have to
9512                increment PROCESSING_TEMPLATE_DECL because
9513                value_dependent_expression_p assumes that nothing is
9514                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
9515             ++processing_template_decl;
9516             dependent_p = value_dependent_expression_p (t);
9517             --processing_template_decl;
9518             if (!dependent_p)
9519               RETURN (t);
9520
9521             /* Calculate the most general template of which R is a
9522                specialization, and the complete set of arguments used to
9523                specialize R.  */
9524             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
9525             argvec = tsubst_template_args (DECL_TI_ARGS
9526                                           (DECL_TEMPLATE_RESULT
9527                                                  (DECL_TI_TEMPLATE (t))),
9528                                            args, complain, in_decl);
9529
9530             /* Check to see if we already have this specialization.  */
9531             hash = hash_tmpl_and_args (gen_tmpl, argvec);
9532             spec = retrieve_specialization (gen_tmpl, argvec, hash);
9533
9534             if (spec)
9535               {
9536                 r = spec;
9537                 break;
9538               }
9539
9540             /* We can see more levels of arguments than parameters if
9541                there was a specialization of a member template, like
9542                this:
9543
9544                  template <class T> struct S { template <class U> void f(); }
9545                  template <> template <class U> void S<int>::f(U);
9546
9547                Here, we'll be substituting into the specialization,
9548                because that's where we can find the code we actually
9549                want to generate, but we'll have enough arguments for
9550                the most general template.
9551
9552                We also deal with the peculiar case:
9553
9554                  template <class T> struct S {
9555                    template <class U> friend void f();
9556                  };
9557                  template <class U> void f() {}
9558                  template S<int>;
9559                  template void f<double>();
9560
9561                Here, the ARGS for the instantiation of will be {int,
9562                double}.  But, we only need as many ARGS as there are
9563                levels of template parameters in CODE_PATTERN.  We are
9564                careful not to get fooled into reducing the ARGS in
9565                situations like:
9566
9567                  template <class T> struct S { template <class U> void f(U); }
9568                  template <class T> template <> void S<T>::f(int) {}
9569
9570                which we can spot because the pattern will be a
9571                specialization in this case.  */
9572             args_depth = TMPL_ARGS_DEPTH (args);
9573             parms_depth =
9574               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
9575             if (args_depth > parms_depth
9576                 && !DECL_TEMPLATE_SPECIALIZATION (t))
9577               args = get_innermost_template_args (args, parms_depth);
9578           }
9579         else
9580           {
9581             /* This special case arises when we have something like this:
9582
9583                  template <class T> struct S {
9584                    friend void f<int>(int, double);
9585                  };
9586
9587                Here, the DECL_TI_TEMPLATE for the friend declaration
9588                will be an IDENTIFIER_NODE.  We are being called from
9589                tsubst_friend_function, and we want only to create a
9590                new decl (R) with appropriate types so that we can call
9591                determine_specialization.  */
9592             gen_tmpl = NULL_TREE;
9593           }
9594
9595         if (DECL_CLASS_SCOPE_P (t))
9596           {
9597             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
9598               member = 2;
9599             else
9600               member = 1;
9601             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
9602                                     complain, t, /*entering_scope=*/1);
9603           }
9604         else
9605           {
9606             member = 0;
9607             ctx = DECL_CONTEXT (t);
9608           }
9609         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9610         if (type == error_mark_node)
9611           RETURN (error_mark_node);
9612
9613         /* We do NOT check for matching decls pushed separately at this
9614            point, as they may not represent instantiations of this
9615            template, and in any case are considered separate under the
9616            discrete model.  */
9617         r = copy_decl (t);
9618         DECL_USE_TEMPLATE (r) = 0;
9619         TREE_TYPE (r) = type;
9620         /* Clear out the mangled name and RTL for the instantiation.  */
9621         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9622         SET_DECL_RTL (r, NULL);
9623         /* Leave DECL_INITIAL set on deleted instantiations.  */
9624         if (!DECL_DELETED_FN (r))
9625           DECL_INITIAL (r) = NULL_TREE;
9626         DECL_CONTEXT (r) = ctx;
9627
9628         if (member && DECL_CONV_FN_P (r))
9629           /* Type-conversion operator.  Reconstruct the name, in
9630              case it's the name of one of the template's parameters.  */
9631           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
9632
9633         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
9634                                      complain, t);
9635         DECL_RESULT (r) = NULL_TREE;
9636
9637         TREE_STATIC (r) = 0;
9638         TREE_PUBLIC (r) = TREE_PUBLIC (t);
9639         DECL_EXTERNAL (r) = 1;
9640         /* If this is an instantiation of a function with internal
9641            linkage, we already know what object file linkage will be
9642            assigned to the instantiation.  */
9643         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
9644         DECL_DEFER_OUTPUT (r) = 0;
9645         DECL_CHAIN (r) = NULL_TREE;
9646         DECL_PENDING_INLINE_INFO (r) = 0;
9647         DECL_PENDING_INLINE_P (r) = 0;
9648         DECL_SAVED_TREE (r) = NULL_TREE;
9649         DECL_STRUCT_FUNCTION (r) = NULL;
9650         TREE_USED (r) = 0;
9651         /* We'll re-clone as appropriate in instantiate_template.  */
9652         DECL_CLONED_FUNCTION (r) = NULL_TREE;
9653
9654         /* If we aren't complaining now, return on error before we register
9655            the specialization so that we'll complain eventually.  */
9656         if ((complain & tf_error) == 0
9657             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9658             && !grok_op_properties (r, /*complain=*/false))
9659           RETURN (error_mark_node);
9660
9661         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
9662            this in the special friend case mentioned above where
9663            GEN_TMPL is NULL.  */
9664         if (gen_tmpl)
9665           {
9666             DECL_TEMPLATE_INFO (r)
9667               = build_template_info (gen_tmpl, argvec);
9668             SET_DECL_IMPLICIT_INSTANTIATION (r);
9669             register_specialization (r, gen_tmpl, argvec, false, hash);
9670
9671             /* We're not supposed to instantiate default arguments
9672                until they are called, for a template.  But, for a
9673                declaration like:
9674
9675                  template <class T> void f ()
9676                  { extern void g(int i = T()); }
9677
9678                we should do the substitution when the template is
9679                instantiated.  We handle the member function case in
9680                instantiate_class_template since the default arguments
9681                might refer to other members of the class.  */
9682             if (!member
9683                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
9684                 && !uses_template_parms (argvec))
9685               tsubst_default_arguments (r);
9686           }
9687         else
9688           DECL_TEMPLATE_INFO (r) = NULL_TREE;
9689
9690         /* Copy the list of befriending classes.  */
9691         for (friends = &DECL_BEFRIENDING_CLASSES (r);
9692              *friends;
9693              friends = &TREE_CHAIN (*friends))
9694           {
9695             *friends = copy_node (*friends);
9696             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
9697                                             args, complain,
9698                                             in_decl);
9699           }
9700
9701         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
9702           {
9703             maybe_retrofit_in_chrg (r);
9704             if (DECL_CONSTRUCTOR_P (r))
9705               grok_ctor_properties (ctx, r);
9706             /* If this is an instantiation of a member template, clone it.
9707                If it isn't, that'll be handled by
9708                clone_constructors_and_destructors.  */
9709             if (PRIMARY_TEMPLATE_P (gen_tmpl))
9710               clone_function_decl (r, /*update_method_vec_p=*/0);
9711           }
9712         else if ((complain & tf_error) != 0
9713                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9714                  && !grok_op_properties (r, /*complain=*/true))
9715           RETURN (error_mark_node);
9716
9717         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
9718           SET_DECL_FRIEND_CONTEXT (r,
9719                                    tsubst (DECL_FRIEND_CONTEXT (t),
9720                                             args, complain, in_decl));
9721
9722         /* Possibly limit visibility based on template args.  */
9723         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9724         if (DECL_VISIBILITY_SPECIFIED (t))
9725           {
9726             DECL_VISIBILITY_SPECIFIED (r) = 0;
9727             DECL_ATTRIBUTES (r)
9728               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9729           }
9730         determine_visibility (r);
9731         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
9732             && !processing_template_decl)
9733           defaulted_late_check (r);
9734
9735         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9736                                         args, complain, in_decl);
9737       }
9738       break;
9739
9740     case PARM_DECL:
9741       {
9742         tree type = NULL_TREE;
9743         int i, len = 1;
9744         tree expanded_types = NULL_TREE;
9745         tree prev_r = NULL_TREE;
9746         tree first_r = NULL_TREE;
9747
9748         if (FUNCTION_PARAMETER_PACK_P (t))
9749           {
9750             /* If there is a local specialization that isn't a
9751                parameter pack, it means that we're doing a "simple"
9752                substitution from inside tsubst_pack_expansion. Just
9753                return the local specialization (which will be a single
9754                parm).  */
9755             tree spec = retrieve_local_specialization (t);
9756             if (spec 
9757                 && TREE_CODE (spec) == PARM_DECL
9758                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
9759               RETURN (spec);
9760
9761             /* Expand the TYPE_PACK_EXPANSION that provides the types for
9762                the parameters in this function parameter pack.  */
9763             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
9764                                                     complain, in_decl);
9765             if (TREE_CODE (expanded_types) == TREE_VEC)
9766               {
9767                 len = TREE_VEC_LENGTH (expanded_types);
9768
9769                 /* Zero-length parameter packs are boring. Just substitute
9770                    into the chain.  */
9771                 if (len == 0)
9772                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
9773                                   TREE_CHAIN (t)));
9774               }
9775             else
9776               {
9777                 /* All we did was update the type. Make a note of that.  */
9778                 type = expanded_types;
9779                 expanded_types = NULL_TREE;
9780               }
9781           }
9782
9783         /* Loop through all of the parameter's we'll build. When T is
9784            a function parameter pack, LEN is the number of expanded
9785            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
9786         r = NULL_TREE;
9787         for (i = 0; i < len; ++i)
9788           {
9789             prev_r = r;
9790             r = copy_node (t);
9791             if (DECL_TEMPLATE_PARM_P (t))
9792               SET_DECL_TEMPLATE_PARM_P (r);
9793
9794             /* An argument of a function parameter pack is not a parameter
9795                pack.  */
9796             FUNCTION_PARAMETER_PACK_P (r) = false;
9797
9798             if (expanded_types)
9799               /* We're on the Ith parameter of the function parameter
9800                  pack.  */
9801               {
9802                 /* Get the Ith type.  */
9803                 type = TREE_VEC_ELT (expanded_types, i);
9804
9805                 if (DECL_NAME (r))
9806                   /* Rename the parameter to include the index.  */
9807                   DECL_NAME (r) =
9808                     make_ith_pack_parameter_name (DECL_NAME (r), i);
9809               }
9810             else if (!type)
9811               /* We're dealing with a normal parameter.  */
9812               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9813
9814             type = type_decays_to (type);
9815             TREE_TYPE (r) = type;
9816             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9817
9818             if (DECL_INITIAL (r))
9819               {
9820                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
9821                   DECL_INITIAL (r) = TREE_TYPE (r);
9822                 else
9823                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
9824                                              complain, in_decl);
9825               }
9826
9827             DECL_CONTEXT (r) = NULL_TREE;
9828
9829             if (!DECL_TEMPLATE_PARM_P (r))
9830               DECL_ARG_TYPE (r) = type_passed_as (type);
9831
9832             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9833                                             args, complain, in_decl);
9834
9835             /* Keep track of the first new parameter we
9836                generate. That's what will be returned to the
9837                caller.  */
9838             if (!first_r)
9839               first_r = r;
9840
9841             /* Build a proper chain of parameters when substituting
9842                into a function parameter pack.  */
9843             if (prev_r)
9844               DECL_CHAIN (prev_r) = r;
9845           }
9846
9847         if (DECL_CHAIN (t))
9848           DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
9849                                    complain, DECL_CHAIN (t));
9850
9851         /* FIRST_R contains the start of the chain we've built.  */
9852         r = first_r;
9853       }
9854       break;
9855
9856     case FIELD_DECL:
9857       {
9858         tree type;
9859
9860         r = copy_decl (t);
9861         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9862         if (type == error_mark_node)
9863           RETURN (error_mark_node);
9864         TREE_TYPE (r) = type;
9865         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9866
9867         /* DECL_INITIAL gives the number of bits in a bit-field.  */
9868         DECL_INITIAL (r)
9869           = tsubst_expr (DECL_INITIAL (t), args,
9870                          complain, in_decl,
9871                          /*integral_constant_expression_p=*/true);
9872         /* We don't have to set DECL_CONTEXT here; it is set by
9873            finish_member_declaration.  */
9874         DECL_CHAIN (r) = NULL_TREE;
9875         if (VOID_TYPE_P (type))
9876           error ("instantiation of %q+D as type %qT", r, type);
9877
9878         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9879                                         args, complain, in_decl);
9880       }
9881       break;
9882
9883     case USING_DECL:
9884       /* We reach here only for member using decls.  */
9885       if (DECL_DEPENDENT_P (t))
9886         {
9887           r = do_class_using_decl
9888             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
9889              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
9890           if (!r)
9891             r = error_mark_node;
9892           else
9893             {
9894               TREE_PROTECTED (r) = TREE_PROTECTED (t);
9895               TREE_PRIVATE (r) = TREE_PRIVATE (t);
9896             }
9897         }
9898       else
9899         {
9900           r = copy_node (t);
9901           DECL_CHAIN (r) = NULL_TREE;
9902         }
9903       break;
9904
9905     case TYPE_DECL:
9906     case VAR_DECL:
9907       {
9908         tree argvec = NULL_TREE;
9909         tree gen_tmpl = NULL_TREE;
9910         tree spec;
9911         tree tmpl = NULL_TREE;
9912         tree ctx;
9913         tree type = NULL_TREE;
9914         bool local_p;
9915
9916         if (TREE_CODE (t) == TYPE_DECL
9917             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
9918           {
9919             /* If this is the canonical decl, we don't have to
9920                mess with instantiations, and often we can't (for
9921                typename, template type parms and such).  Note that
9922                TYPE_NAME is not correct for the above test if
9923                we've copied the type for a typedef.  */
9924             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9925             if (type == error_mark_node)
9926               RETURN (error_mark_node);
9927             r = TYPE_NAME (type);
9928             break;
9929           }
9930
9931         /* Check to see if we already have the specialization we
9932            need.  */
9933         spec = NULL_TREE;
9934         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
9935           {
9936             /* T is a static data member or namespace-scope entity.
9937                We have to substitute into namespace-scope variables
9938                (even though such entities are never templates) because
9939                of cases like:
9940                
9941                  template <class T> void f() { extern T t; }
9942
9943                where the entity referenced is not known until
9944                instantiation time.  */
9945             local_p = false;
9946             ctx = DECL_CONTEXT (t);
9947             if (DECL_CLASS_SCOPE_P (t))
9948               {
9949                 ctx = tsubst_aggr_type (ctx, args,
9950                                         complain,
9951                                         in_decl, /*entering_scope=*/1);
9952                 /* If CTX is unchanged, then T is in fact the
9953                    specialization we want.  That situation occurs when
9954                    referencing a static data member within in its own
9955                    class.  We can use pointer equality, rather than
9956                    same_type_p, because DECL_CONTEXT is always
9957                    canonical.  */
9958                 if (ctx == DECL_CONTEXT (t))
9959                   spec = t;
9960               }
9961
9962             if (!spec)
9963               {
9964                 tmpl = DECL_TI_TEMPLATE (t);
9965                 gen_tmpl = most_general_template (tmpl);
9966                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
9967                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
9968                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
9969               }
9970           }
9971         else
9972           {
9973             /* A local variable.  */
9974             local_p = true;
9975             /* Subsequent calls to pushdecl will fill this in.  */
9976             ctx = NULL_TREE;
9977             spec = retrieve_local_specialization (t);
9978           }
9979         /* If we already have the specialization we need, there is
9980            nothing more to do.  */ 
9981         if (spec)
9982           {
9983             r = spec;
9984             break;
9985           }
9986
9987         /* Create a new node for the specialization we need.  */
9988         r = copy_decl (t);
9989         if (type == NULL_TREE)
9990           {
9991             if (is_typedef_decl (t))
9992               type = DECL_ORIGINAL_TYPE (t);
9993             else
9994               type = TREE_TYPE (t);
9995             if (TREE_CODE (t) == VAR_DECL && VAR_HAD_UNKNOWN_BOUND (t))
9996               type = strip_array_domain (type);
9997             type = tsubst (type, args, complain, in_decl);
9998           }
9999         if (TREE_CODE (r) == VAR_DECL)
10000           {
10001             /* Even if the original location is out of scope, the
10002                newly substituted one is not.  */
10003             DECL_DEAD_FOR_LOCAL (r) = 0;
10004             DECL_INITIALIZED_P (r) = 0;
10005             DECL_TEMPLATE_INSTANTIATED (r) = 0;
10006             if (type == error_mark_node)
10007               RETURN (error_mark_node);
10008             if (TREE_CODE (type) == FUNCTION_TYPE)
10009               {
10010                 /* It may seem that this case cannot occur, since:
10011
10012                      typedef void f();
10013                      void g() { f x; }
10014
10015                    declares a function, not a variable.  However:
10016       
10017                      typedef void f();
10018                      template <typename T> void g() { T t; }
10019                      template void g<f>();
10020
10021                    is an attempt to declare a variable with function
10022                    type.  */
10023                 error ("variable %qD has function type",
10024                        /* R is not yet sufficiently initialized, so we
10025                           just use its name.  */
10026                        DECL_NAME (r));
10027                 RETURN (error_mark_node);
10028               }
10029             type = complete_type (type);
10030             /* Wait until cp_finish_decl to set this again, to handle
10031                circular dependency (template/instantiate6.C). */
10032             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
10033             type = check_var_type (DECL_NAME (r), type);
10034
10035             if (DECL_HAS_VALUE_EXPR_P (t))
10036               {
10037                 tree ve = DECL_VALUE_EXPR (t);
10038                 ve = tsubst_expr (ve, args, complain, in_decl,
10039                                   /*constant_expression_p=*/false);
10040                 SET_DECL_VALUE_EXPR (r, ve);
10041               }
10042           }
10043         else if (DECL_SELF_REFERENCE_P (t))
10044           SET_DECL_SELF_REFERENCE_P (r);
10045         TREE_TYPE (r) = type;
10046         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10047         DECL_CONTEXT (r) = ctx;
10048         /* Clear out the mangled name and RTL for the instantiation.  */
10049         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
10050         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10051           SET_DECL_RTL (r, NULL);
10052         /* The initializer must not be expanded until it is required;
10053            see [temp.inst].  */
10054         DECL_INITIAL (r) = NULL_TREE;
10055         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10056           SET_DECL_RTL (r, NULL);
10057         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
10058         if (TREE_CODE (r) == VAR_DECL)
10059           {
10060             /* Possibly limit visibility based on template args.  */
10061             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10062             if (DECL_VISIBILITY_SPECIFIED (t))
10063               {
10064                 DECL_VISIBILITY_SPECIFIED (r) = 0;
10065                 DECL_ATTRIBUTES (r)
10066                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10067               }
10068             determine_visibility (r);
10069           }
10070
10071         if (!local_p)
10072           {
10073             /* A static data member declaration is always marked
10074                external when it is declared in-class, even if an
10075                initializer is present.  We mimic the non-template
10076                processing here.  */
10077             DECL_EXTERNAL (r) = 1;
10078
10079             register_specialization (r, gen_tmpl, argvec, false, hash);
10080             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
10081             SET_DECL_IMPLICIT_INSTANTIATION (r);
10082           }
10083         else if (cp_unevaluated_operand)
10084           {
10085             /* We're substituting this var in a decltype outside of its
10086                scope, such as for a lambda return type.  Don't add it to
10087                local_specializations, do perform auto deduction.  */
10088             tree auto_node = type_uses_auto (type);
10089             tree init
10090               = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
10091                              /*constant_expression_p=*/false);
10092
10093             if (auto_node && init)
10094               {
10095                 init = resolve_nondeduced_context (init);
10096                 if (describable_type (init))
10097                   {
10098                     type = do_auto_deduction (type, init, auto_node);
10099                     TREE_TYPE (r) = type;
10100                   }
10101               }
10102           }
10103         else
10104           register_local_specialization (r, t);
10105
10106         DECL_CHAIN (r) = NULL_TREE;
10107
10108         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
10109                                         /*flags=*/0,
10110                                         args, complain, in_decl);
10111
10112         /* Preserve a typedef that names a type.  */
10113         if (is_typedef_decl (r))
10114           {
10115             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
10116             set_underlying_type (r);
10117           }
10118
10119         layout_decl (r, 0);
10120       }
10121       break;
10122
10123     default:
10124       gcc_unreachable ();
10125     }
10126 #undef RETURN
10127
10128  out:
10129   /* Restore the file and line information.  */
10130   input_location = saved_loc;
10131
10132   return r;
10133 }
10134
10135 /* Substitute into the ARG_TYPES of a function type.  */
10136
10137 static tree
10138 tsubst_arg_types (tree arg_types,
10139                   tree args,
10140                   tsubst_flags_t complain,
10141                   tree in_decl)
10142 {
10143   tree remaining_arg_types;
10144   tree type = NULL_TREE;
10145   int i = 1;
10146   tree expanded_args = NULL_TREE;
10147   tree default_arg;
10148
10149   if (!arg_types || arg_types == void_list_node)
10150     return arg_types;
10151
10152   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
10153                                           args, complain, in_decl);
10154   if (remaining_arg_types == error_mark_node)
10155     return error_mark_node;
10156
10157   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
10158     {
10159       /* For a pack expansion, perform substitution on the
10160          entire expression. Later on, we'll handle the arguments
10161          one-by-one.  */
10162       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
10163                                             args, complain, in_decl);
10164
10165       if (TREE_CODE (expanded_args) == TREE_VEC)
10166         /* So that we'll spin through the parameters, one by one.  */
10167         i = TREE_VEC_LENGTH (expanded_args);
10168       else
10169         {
10170           /* We only partially substituted into the parameter
10171              pack. Our type is TYPE_PACK_EXPANSION.  */
10172           type = expanded_args;
10173           expanded_args = NULL_TREE;
10174         }
10175     }
10176
10177   while (i > 0) {
10178     --i;
10179     
10180     if (expanded_args)
10181       type = TREE_VEC_ELT (expanded_args, i);
10182     else if (!type)
10183       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
10184
10185     if (type == error_mark_node)
10186       return error_mark_node;
10187     if (VOID_TYPE_P (type))
10188       {
10189         if (complain & tf_error)
10190           {
10191             error ("invalid parameter type %qT", type);
10192             if (in_decl)
10193               error ("in declaration %q+D", in_decl);
10194           }
10195         return error_mark_node;
10196     }
10197     
10198     /* Do array-to-pointer, function-to-pointer conversion, and ignore
10199        top-level qualifiers as required.  */
10200     type = TYPE_MAIN_VARIANT (type_decays_to (type));
10201
10202     /* We do not substitute into default arguments here.  The standard
10203        mandates that they be instantiated only when needed, which is
10204        done in build_over_call.  */
10205     default_arg = TREE_PURPOSE (arg_types);
10206
10207     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
10208       {
10209         /* We've instantiated a template before its default arguments
10210            have been parsed.  This can happen for a nested template
10211            class, and is not an error unless we require the default
10212            argument in a call of this function.  */
10213         remaining_arg_types = 
10214           tree_cons (default_arg, type, remaining_arg_types);
10215         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
10216                        remaining_arg_types);
10217       }
10218     else
10219       remaining_arg_types = 
10220         hash_tree_cons (default_arg, type, remaining_arg_types);
10221   }
10222         
10223   return remaining_arg_types;
10224 }
10225
10226 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
10227    *not* handle the exception-specification for FNTYPE, because the
10228    initial substitution of explicitly provided template parameters
10229    during argument deduction forbids substitution into the
10230    exception-specification:
10231
10232      [temp.deduct]
10233
10234      All references in the function type of the function template to  the
10235      corresponding template parameters are replaced by the specified tem-
10236      plate argument values.  If a substitution in a template parameter or
10237      in  the function type of the function template results in an invalid
10238      type, type deduction fails.  [Note: The equivalent  substitution  in
10239      exception specifications is done only when the function is instanti-
10240      ated, at which point a program is  ill-formed  if  the  substitution
10241      results in an invalid type.]  */
10242
10243 static tree
10244 tsubst_function_type (tree t,
10245                       tree args,
10246                       tsubst_flags_t complain,
10247                       tree in_decl)
10248 {
10249   tree return_type;
10250   tree arg_types;
10251   tree fntype;
10252
10253   /* The TYPE_CONTEXT is not used for function/method types.  */
10254   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
10255
10256   /* Substitute the return type.  */
10257   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10258   if (return_type == error_mark_node)
10259     return error_mark_node;
10260   /* The standard does not presently indicate that creation of a
10261      function type with an invalid return type is a deduction failure.
10262      However, that is clearly analogous to creating an array of "void"
10263      or a reference to a reference.  This is core issue #486.  */
10264   if (TREE_CODE (return_type) == ARRAY_TYPE
10265       || TREE_CODE (return_type) == FUNCTION_TYPE)
10266     {
10267       if (complain & tf_error)
10268         {
10269           if (TREE_CODE (return_type) == ARRAY_TYPE)
10270             error ("function returning an array");
10271           else
10272             error ("function returning a function");
10273         }
10274       return error_mark_node;
10275     }
10276
10277   /* Substitute the argument types.  */
10278   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
10279                                 complain, in_decl);
10280   if (arg_types == error_mark_node)
10281     return error_mark_node;
10282
10283   /* Construct a new type node and return it.  */
10284   if (TREE_CODE (t) == FUNCTION_TYPE)
10285     {
10286       fntype = build_function_type (return_type, arg_types);
10287       fntype = apply_memfn_quals (fntype, type_memfn_quals (t));
10288     }
10289   else
10290     {
10291       tree r = TREE_TYPE (TREE_VALUE (arg_types));
10292       if (! MAYBE_CLASS_TYPE_P (r))
10293         {
10294           /* [temp.deduct]
10295
10296              Type deduction may fail for any of the following
10297              reasons:
10298
10299              -- Attempting to create "pointer to member of T" when T
10300              is not a class type.  */
10301           if (complain & tf_error)
10302             error ("creating pointer to member function of non-class type %qT",
10303                       r);
10304           return error_mark_node;
10305         }
10306
10307       fntype = build_method_type_directly (r, return_type,
10308                                            TREE_CHAIN (arg_types));
10309     }
10310   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
10311
10312   return fntype;
10313 }
10314
10315 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
10316    ARGS into that specification, and return the substituted
10317    specification.  If there is no specification, return NULL_TREE.  */
10318
10319 static tree
10320 tsubst_exception_specification (tree fntype,
10321                                 tree args,
10322                                 tsubst_flags_t complain,
10323                                 tree in_decl)
10324 {
10325   tree specs;
10326   tree new_specs;
10327
10328   specs = TYPE_RAISES_EXCEPTIONS (fntype);
10329   new_specs = NULL_TREE;
10330   if (specs && TREE_PURPOSE (specs))
10331     {
10332       /* A noexcept-specifier.  */
10333       new_specs = tsubst_copy_and_build
10334         (TREE_PURPOSE (specs), args, complain, in_decl, /*function_p=*/false,
10335          /*integral_constant_expression_p=*/true);
10336       new_specs = build_noexcept_spec (new_specs, complain);
10337     }
10338   else if (specs)
10339     {
10340       if (! TREE_VALUE (specs))
10341         new_specs = specs;
10342       else
10343         while (specs)
10344           {
10345             tree spec;
10346             int i, len = 1;
10347             tree expanded_specs = NULL_TREE;
10348
10349             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
10350               {
10351                 /* Expand the pack expansion type.  */
10352                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
10353                                                        args, complain,
10354                                                        in_decl);
10355
10356                 if (expanded_specs == error_mark_node)
10357                   return error_mark_node;
10358                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
10359                   len = TREE_VEC_LENGTH (expanded_specs);
10360                 else
10361                   {
10362                     /* We're substituting into a member template, so
10363                        we got a TYPE_PACK_EXPANSION back.  Add that
10364                        expansion and move on.  */
10365                     gcc_assert (TREE_CODE (expanded_specs) 
10366                                 == TYPE_PACK_EXPANSION);
10367                     new_specs = add_exception_specifier (new_specs,
10368                                                          expanded_specs,
10369                                                          complain);
10370                     specs = TREE_CHAIN (specs);
10371                     continue;
10372                   }
10373               }
10374
10375             for (i = 0; i < len; ++i)
10376               {
10377                 if (expanded_specs)
10378                   spec = TREE_VEC_ELT (expanded_specs, i);
10379                 else
10380                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
10381                 if (spec == error_mark_node)
10382                   return spec;
10383                 new_specs = add_exception_specifier (new_specs, spec, 
10384                                                      complain);
10385               }
10386
10387             specs = TREE_CHAIN (specs);
10388           }
10389     }
10390   return new_specs;
10391 }
10392
10393 /* Take the tree structure T and replace template parameters used
10394    therein with the argument vector ARGS.  IN_DECL is an associated
10395    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
10396    Issue error and warning messages under control of COMPLAIN.  Note
10397    that we must be relatively non-tolerant of extensions here, in
10398    order to preserve conformance; if we allow substitutions that
10399    should not be allowed, we may allow argument deductions that should
10400    not succeed, and therefore report ambiguous overload situations
10401    where there are none.  In theory, we could allow the substitution,
10402    but indicate that it should have failed, and allow our caller to
10403    make sure that the right thing happens, but we don't try to do this
10404    yet.
10405
10406    This function is used for dealing with types, decls and the like;
10407    for expressions, use tsubst_expr or tsubst_copy.  */
10408
10409 tree
10410 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10411 {
10412   enum tree_code code;
10413   tree type, r;
10414
10415   if (t == NULL_TREE || t == error_mark_node
10416       || t == integer_type_node
10417       || t == void_type_node
10418       || t == char_type_node
10419       || t == unknown_type_node
10420       || TREE_CODE (t) == NAMESPACE_DECL
10421       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
10422     return t;
10423
10424   if (DECL_P (t))
10425     return tsubst_decl (t, args, complain);
10426
10427   if (args == NULL_TREE)
10428     return t;
10429
10430   code = TREE_CODE (t);
10431
10432   if (code == IDENTIFIER_NODE)
10433     type = IDENTIFIER_TYPE_VALUE (t);
10434   else
10435     type = TREE_TYPE (t);
10436
10437   gcc_assert (type != unknown_type_node);
10438
10439   /* Reuse typedefs.  We need to do this to handle dependent attributes,
10440      such as attribute aligned.  */
10441   if (TYPE_P (t)
10442       && typedef_variant_p (t))
10443     {
10444       tree decl = TYPE_NAME (t);
10445       
10446       if (DECL_CLASS_SCOPE_P (decl)
10447           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
10448           && uses_template_parms (DECL_CONTEXT (decl)))
10449         {
10450           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
10451           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
10452           r = retrieve_specialization (tmpl, gen_args, 0);
10453         }
10454       else if (DECL_FUNCTION_SCOPE_P (decl)
10455                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
10456                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
10457         r = retrieve_local_specialization (decl);
10458       else
10459         /* The typedef is from a non-template context.  */
10460         return t;
10461
10462       if (r)
10463         {
10464           r = TREE_TYPE (r);
10465           r = cp_build_qualified_type_real
10466             (r, cp_type_quals (t) | cp_type_quals (r),
10467              complain | tf_ignore_bad_quals);
10468           return r;
10469         }
10470       /* Else we must be instantiating the typedef, so fall through.  */
10471     }
10472
10473   if (type
10474       && code != TYPENAME_TYPE
10475       && code != TEMPLATE_TYPE_PARM
10476       && code != IDENTIFIER_NODE
10477       && code != FUNCTION_TYPE
10478       && code != METHOD_TYPE)
10479     type = tsubst (type, args, complain, in_decl);
10480   if (type == error_mark_node)
10481     return error_mark_node;
10482
10483   switch (code)
10484     {
10485     case RECORD_TYPE:
10486     case UNION_TYPE:
10487     case ENUMERAL_TYPE:
10488       return tsubst_aggr_type (t, args, complain, in_decl,
10489                                /*entering_scope=*/0);
10490
10491     case ERROR_MARK:
10492     case IDENTIFIER_NODE:
10493     case VOID_TYPE:
10494     case REAL_TYPE:
10495     case COMPLEX_TYPE:
10496     case VECTOR_TYPE:
10497     case BOOLEAN_TYPE:
10498     case NULLPTR_TYPE:
10499     case LANG_TYPE:
10500       return t;
10501
10502     case INTEGER_TYPE:
10503       if (t == integer_type_node)
10504         return t;
10505
10506       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
10507           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
10508         return t;
10509
10510       {
10511         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
10512
10513         max = tsubst_expr (omax, args, complain, in_decl,
10514                            /*integral_constant_expression_p=*/false);
10515
10516         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
10517            needed.  */
10518         if (TREE_CODE (max) == NOP_EXPR
10519             && TREE_SIDE_EFFECTS (omax)
10520             && !TREE_TYPE (max))
10521           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
10522
10523         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
10524            with TREE_SIDE_EFFECTS that indicates this is not an integral
10525            constant expression.  */
10526         if (processing_template_decl
10527             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
10528           {
10529             gcc_assert (TREE_CODE (max) == NOP_EXPR);
10530             TREE_SIDE_EFFECTS (max) = 1;
10531           }
10532
10533         return compute_array_index_type (NULL_TREE, max, complain);
10534       }
10535
10536     case TEMPLATE_TYPE_PARM:
10537     case TEMPLATE_TEMPLATE_PARM:
10538     case BOUND_TEMPLATE_TEMPLATE_PARM:
10539     case TEMPLATE_PARM_INDEX:
10540       {
10541         int idx;
10542         int level;
10543         int levels;
10544         tree arg = NULL_TREE;
10545
10546         r = NULL_TREE;
10547
10548         gcc_assert (TREE_VEC_LENGTH (args) > 0);
10549         template_parm_level_and_index (t, &level, &idx); 
10550
10551         levels = TMPL_ARGS_DEPTH (args);
10552         if (level <= levels)
10553           {
10554             arg = TMPL_ARG (args, level, idx);
10555
10556             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
10557               /* See through ARGUMENT_PACK_SELECT arguments. */
10558               arg = ARGUMENT_PACK_SELECT_ARG (arg);
10559           }
10560
10561         if (arg == error_mark_node)
10562           return error_mark_node;
10563         else if (arg != NULL_TREE)
10564           {
10565             if (ARGUMENT_PACK_P (arg))
10566               /* If ARG is an argument pack, we don't actually want to
10567                  perform a substitution here, because substitutions
10568                  for argument packs are only done
10569                  element-by-element. We can get to this point when
10570                  substituting the type of a non-type template
10571                  parameter pack, when that type actually contains
10572                  template parameter packs from an outer template, e.g.,
10573
10574                  template<typename... Types> struct A {
10575                    template<Types... Values> struct B { };
10576                  };  */
10577               return t;
10578
10579             if (code == TEMPLATE_TYPE_PARM)
10580               {
10581                 int quals;
10582                 gcc_assert (TYPE_P (arg));
10583
10584                 quals = cp_type_quals (arg) | cp_type_quals (t);
10585                   
10586                 return cp_build_qualified_type_real
10587                   (arg, quals, complain | tf_ignore_bad_quals);
10588               }
10589             else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
10590               {
10591                 /* We are processing a type constructed from a
10592                    template template parameter.  */
10593                 tree argvec = tsubst (TYPE_TI_ARGS (t),
10594                                       args, complain, in_decl);
10595                 if (argvec == error_mark_node)
10596                   return error_mark_node;
10597
10598                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
10599                    are resolving nested-types in the signature of a
10600                    member function templates.  Otherwise ARG is a
10601                    TEMPLATE_DECL and is the real template to be
10602                    instantiated.  */
10603                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
10604                   arg = TYPE_NAME (arg);
10605
10606                 r = lookup_template_class (arg,
10607                                            argvec, in_decl,
10608                                            DECL_CONTEXT (arg),
10609                                             /*entering_scope=*/0,
10610                                            complain);
10611                 return cp_build_qualified_type_real
10612                   (r, cp_type_quals (t), complain);
10613               }
10614             else
10615               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
10616               return unshare_expr (arg);
10617           }
10618
10619         if (level == 1)
10620           /* This can happen during the attempted tsubst'ing in
10621              unify.  This means that we don't yet have any information
10622              about the template parameter in question.  */
10623           return t;
10624
10625         /* If we get here, we must have been looking at a parm for a
10626            more deeply nested template.  Make a new version of this
10627            template parameter, but with a lower level.  */
10628         switch (code)
10629           {
10630           case TEMPLATE_TYPE_PARM:
10631           case TEMPLATE_TEMPLATE_PARM:
10632           case BOUND_TEMPLATE_TEMPLATE_PARM:
10633             if (cp_type_quals (t))
10634               {
10635                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
10636                 r = cp_build_qualified_type_real
10637                   (r, cp_type_quals (t),
10638                    complain | (code == TEMPLATE_TYPE_PARM
10639                                ? tf_ignore_bad_quals : 0));
10640               }
10641             else
10642               {
10643                 r = copy_type (t);
10644                 TEMPLATE_TYPE_PARM_INDEX (r)
10645                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
10646                                                 r, levels, args, complain);
10647                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
10648                 TYPE_MAIN_VARIANT (r) = r;
10649                 TYPE_POINTER_TO (r) = NULL_TREE;
10650                 TYPE_REFERENCE_TO (r) = NULL_TREE;
10651
10652                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
10653                   /* We have reduced the level of the template
10654                      template parameter, but not the levels of its
10655                      template parameters, so canonical_type_parameter
10656                      will not be able to find the canonical template
10657                      template parameter for this level. Thus, we
10658                      require structural equality checking to compare
10659                      TEMPLATE_TEMPLATE_PARMs. */
10660                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10661                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
10662                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10663                 else
10664                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
10665
10666                 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
10667                   {
10668                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
10669                                           complain, in_decl);
10670                     if (argvec == error_mark_node)
10671                       return error_mark_node;
10672
10673                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
10674                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
10675                   }
10676               }
10677             break;
10678
10679           case TEMPLATE_PARM_INDEX:
10680             r = reduce_template_parm_level (t, type, levels, args, complain);
10681             break;
10682
10683           default:
10684             gcc_unreachable ();
10685           }
10686
10687         return r;
10688       }
10689
10690     case TREE_LIST:
10691       {
10692         tree purpose, value, chain;
10693
10694         if (t == void_list_node)
10695           return t;
10696
10697         purpose = TREE_PURPOSE (t);
10698         if (purpose)
10699           {
10700             purpose = tsubst (purpose, args, complain, in_decl);
10701             if (purpose == error_mark_node)
10702               return error_mark_node;
10703           }
10704         value = TREE_VALUE (t);
10705         if (value)
10706           {
10707             value = tsubst (value, args, complain, in_decl);
10708             if (value == error_mark_node)
10709               return error_mark_node;
10710           }
10711         chain = TREE_CHAIN (t);
10712         if (chain && chain != void_type_node)
10713           {
10714             chain = tsubst (chain, args, complain, in_decl);
10715             if (chain == error_mark_node)
10716               return error_mark_node;
10717           }
10718         if (purpose == TREE_PURPOSE (t)
10719             && value == TREE_VALUE (t)
10720             && chain == TREE_CHAIN (t))
10721           return t;
10722         return hash_tree_cons (purpose, value, chain);
10723       }
10724
10725     case TREE_BINFO:
10726       /* We should never be tsubsting a binfo.  */
10727       gcc_unreachable ();
10728
10729     case TREE_VEC:
10730       /* A vector of template arguments.  */
10731       gcc_assert (!type);
10732       return tsubst_template_args (t, args, complain, in_decl);
10733
10734     case POINTER_TYPE:
10735     case REFERENCE_TYPE:
10736       {
10737         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
10738           return t;
10739
10740         /* [temp.deduct]
10741
10742            Type deduction may fail for any of the following
10743            reasons:
10744
10745            -- Attempting to create a pointer to reference type.
10746            -- Attempting to create a reference to a reference type or
10747               a reference to void.
10748
10749           Core issue 106 says that creating a reference to a reference
10750           during instantiation is no longer a cause for failure. We
10751           only enforce this check in strict C++98 mode.  */
10752         if ((TREE_CODE (type) == REFERENCE_TYPE
10753              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
10754             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
10755           {
10756             static location_t last_loc;
10757
10758             /* We keep track of the last time we issued this error
10759                message to avoid spewing a ton of messages during a
10760                single bad template instantiation.  */
10761             if (complain & tf_error
10762                 && last_loc != input_location)
10763               {
10764                 if (TREE_CODE (type) == VOID_TYPE)
10765                   error ("forming reference to void");
10766                else if (code == POINTER_TYPE)
10767                  error ("forming pointer to reference type %qT", type);
10768                else
10769                   error ("forming reference to reference type %qT", type);
10770                 last_loc = input_location;
10771               }
10772
10773             return error_mark_node;
10774           }
10775         else if (code == POINTER_TYPE)
10776           {
10777             r = build_pointer_type (type);
10778             if (TREE_CODE (type) == METHOD_TYPE)
10779               r = build_ptrmemfunc_type (r);
10780           }
10781         else if (TREE_CODE (type) == REFERENCE_TYPE)
10782           /* In C++0x, during template argument substitution, when there is an
10783              attempt to create a reference to a reference type, reference
10784              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
10785
10786              "If a template-argument for a template-parameter T names a type
10787              that is a reference to a type A, an attempt to create the type
10788              'lvalue reference to cv T' creates the type 'lvalue reference to
10789              A,' while an attempt to create the type type rvalue reference to
10790              cv T' creates the type T"
10791           */
10792           r = cp_build_reference_type
10793               (TREE_TYPE (type),
10794                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
10795         else
10796           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
10797         r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
10798
10799         if (r != error_mark_node)
10800           /* Will this ever be needed for TYPE_..._TO values?  */
10801           layout_type (r);
10802
10803         return r;
10804       }
10805     case OFFSET_TYPE:
10806       {
10807         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
10808         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
10809           {
10810             /* [temp.deduct]
10811
10812                Type deduction may fail for any of the following
10813                reasons:
10814
10815                -- Attempting to create "pointer to member of T" when T
10816                   is not a class type.  */
10817             if (complain & tf_error)
10818               error ("creating pointer to member of non-class type %qT", r);
10819             return error_mark_node;
10820           }
10821         if (TREE_CODE (type) == REFERENCE_TYPE)
10822           {
10823             if (complain & tf_error)
10824               error ("creating pointer to member reference type %qT", type);
10825             return error_mark_node;
10826           }
10827         if (TREE_CODE (type) == VOID_TYPE)
10828           {
10829             if (complain & tf_error)
10830               error ("creating pointer to member of type void");
10831             return error_mark_node;
10832           }
10833         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
10834         if (TREE_CODE (type) == FUNCTION_TYPE)
10835           {
10836             /* The type of the implicit object parameter gets its
10837                cv-qualifiers from the FUNCTION_TYPE. */
10838             tree memptr;
10839             tree method_type = build_memfn_type (type, r, type_memfn_quals (type));
10840             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
10841             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
10842                                                  complain);
10843           }
10844         else
10845           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
10846                                                cp_type_quals (t),
10847                                                complain);
10848       }
10849     case FUNCTION_TYPE:
10850     case METHOD_TYPE:
10851       {
10852         tree fntype;
10853         tree specs;
10854         fntype = tsubst_function_type (t, args, complain, in_decl);
10855         if (fntype == error_mark_node)
10856           return error_mark_node;
10857
10858         /* Substitute the exception specification.  */
10859         specs = tsubst_exception_specification (t, args, complain,
10860                                                 in_decl);
10861         if (specs == error_mark_node)
10862           return error_mark_node;
10863         if (specs)
10864           fntype = build_exception_variant (fntype, specs);
10865         return fntype;
10866       }
10867     case ARRAY_TYPE:
10868       {
10869         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
10870         if (domain == error_mark_node)
10871           return error_mark_node;
10872
10873         /* As an optimization, we avoid regenerating the array type if
10874            it will obviously be the same as T.  */
10875         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
10876           return t;
10877
10878         /* These checks should match the ones in grokdeclarator.
10879
10880            [temp.deduct]
10881
10882            The deduction may fail for any of the following reasons:
10883
10884            -- Attempting to create an array with an element type that
10885               is void, a function type, or a reference type, or [DR337]
10886               an abstract class type.  */
10887         if (TREE_CODE (type) == VOID_TYPE
10888             || TREE_CODE (type) == FUNCTION_TYPE
10889             || TREE_CODE (type) == REFERENCE_TYPE)
10890           {
10891             if (complain & tf_error)
10892               error ("creating array of %qT", type);
10893             return error_mark_node;
10894           }
10895         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
10896           {
10897             if (complain & tf_error)
10898               error ("creating array of %qT, which is an abstract class type",
10899                      type);
10900             return error_mark_node;
10901           }
10902
10903         r = build_cplus_array_type (type, domain);
10904
10905         if (TYPE_USER_ALIGN (t))
10906           {
10907             TYPE_ALIGN (r) = TYPE_ALIGN (t);
10908             TYPE_USER_ALIGN (r) = 1;
10909           }
10910
10911         return r;
10912       }
10913
10914     case TYPENAME_TYPE:
10915       {
10916         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10917                                      in_decl, /*entering_scope=*/1);
10918         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
10919                               complain, in_decl);
10920
10921         if (ctx == error_mark_node || f == error_mark_node)
10922           return error_mark_node;
10923
10924         if (!MAYBE_CLASS_TYPE_P (ctx))
10925           {
10926             if (complain & tf_error)
10927               error ("%qT is not a class, struct, or union type", ctx);
10928             return error_mark_node;
10929           }
10930         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
10931           {
10932             /* Normally, make_typename_type does not require that the CTX
10933                have complete type in order to allow things like:
10934
10935                  template <class T> struct S { typename S<T>::X Y; };
10936
10937                But, such constructs have already been resolved by this
10938                point, so here CTX really should have complete type, unless
10939                it's a partial instantiation.  */
10940             ctx = complete_type (ctx);
10941             if (!COMPLETE_TYPE_P (ctx))
10942               {
10943                 if (complain & tf_error)
10944                   cxx_incomplete_type_error (NULL_TREE, ctx);
10945                 return error_mark_node;
10946               }
10947           }
10948
10949         f = make_typename_type (ctx, f, typename_type,
10950                                 (complain & tf_error) | tf_keep_type_decl);
10951         if (f == error_mark_node)
10952           return f;
10953         if (TREE_CODE (f) == TYPE_DECL)
10954           {
10955             complain |= tf_ignore_bad_quals;
10956             f = TREE_TYPE (f);
10957           }
10958
10959         if (TREE_CODE (f) != TYPENAME_TYPE)
10960           {
10961             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
10962               error ("%qT resolves to %qT, which is not an enumeration type",
10963                      t, f);
10964             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
10965               error ("%qT resolves to %qT, which is is not a class type",
10966                      t, f);
10967           }
10968
10969         return cp_build_qualified_type_real
10970           (f, cp_type_quals (f) | cp_type_quals (t), complain);
10971       }
10972
10973     case UNBOUND_CLASS_TEMPLATE:
10974       {
10975         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10976                                      in_decl, /*entering_scope=*/1);
10977         tree name = TYPE_IDENTIFIER (t);
10978         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
10979
10980         if (ctx == error_mark_node || name == error_mark_node)
10981           return error_mark_node;
10982
10983         if (parm_list)
10984           parm_list = tsubst_template_parms (parm_list, args, complain);
10985         return make_unbound_class_template (ctx, name, parm_list, complain);
10986       }
10987
10988     case TYPEOF_TYPE:
10989       {
10990         tree type;
10991
10992         ++cp_unevaluated_operand;
10993         ++c_inhibit_evaluation_warnings;
10994
10995         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
10996                             complain, in_decl,
10997                             /*integral_constant_expression_p=*/false);
10998
10999         --cp_unevaluated_operand;
11000         --c_inhibit_evaluation_warnings;
11001
11002         type = finish_typeof (type);
11003         return cp_build_qualified_type_real (type,
11004                                              cp_type_quals (t)
11005                                              | cp_type_quals (type),
11006                                              complain);
11007       }
11008
11009     case DECLTYPE_TYPE:
11010       {
11011         tree type;
11012
11013         ++cp_unevaluated_operand;
11014         ++c_inhibit_evaluation_warnings;
11015
11016         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
11017                             complain, in_decl,
11018                             /*integral_constant_expression_p=*/false);
11019
11020         --cp_unevaluated_operand;
11021         --c_inhibit_evaluation_warnings;
11022
11023         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
11024           type = lambda_capture_field_type (type);
11025         else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
11026           type = lambda_return_type (type);
11027         else
11028           type = finish_decltype_type
11029             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
11030         return cp_build_qualified_type_real (type,
11031                                              cp_type_quals (t)
11032                                              | cp_type_quals (type),
11033                                              complain);
11034       }
11035
11036     case TYPE_ARGUMENT_PACK:
11037     case NONTYPE_ARGUMENT_PACK:
11038       {
11039         tree r = TYPE_P (t) ? cxx_make_type (code) : make_node (code);
11040         tree packed_out = 
11041           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
11042                                 args,
11043                                 complain,
11044                                 in_decl);
11045         SET_ARGUMENT_PACK_ARGS (r, packed_out);
11046
11047         /* For template nontype argument packs, also substitute into
11048            the type.  */
11049         if (code == NONTYPE_ARGUMENT_PACK)
11050           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
11051
11052         return r;
11053       }
11054       break;
11055
11056     case INTEGER_CST:
11057     case REAL_CST:
11058     case STRING_CST:
11059     case PLUS_EXPR:
11060     case MINUS_EXPR:
11061     case NEGATE_EXPR:
11062     case NOP_EXPR:
11063     case INDIRECT_REF:
11064     case ADDR_EXPR:
11065     case CALL_EXPR:
11066     case ARRAY_REF:
11067     case SCOPE_REF:
11068       /* We should use one of the expression tsubsts for these codes.  */
11069       gcc_unreachable ();
11070
11071     default:
11072       sorry ("use of %qs in template", tree_code_name [(int) code]);
11073       return error_mark_node;
11074     }
11075 }
11076
11077 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
11078    type of the expression on the left-hand side of the "." or "->"
11079    operator.  */
11080
11081 static tree
11082 tsubst_baselink (tree baselink, tree object_type,
11083                  tree args, tsubst_flags_t complain, tree in_decl)
11084 {
11085     tree name;
11086     tree qualifying_scope;
11087     tree fns;
11088     tree optype;
11089     tree template_args = 0;
11090     bool template_id_p = false;
11091
11092     /* A baselink indicates a function from a base class.  Both the
11093        BASELINK_ACCESS_BINFO and the base class referenced may
11094        indicate bases of the template class, rather than the
11095        instantiated class.  In addition, lookups that were not
11096        ambiguous before may be ambiguous now.  Therefore, we perform
11097        the lookup again.  */
11098     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
11099     qualifying_scope = tsubst (qualifying_scope, args,
11100                                complain, in_decl);
11101     fns = BASELINK_FUNCTIONS (baselink);
11102     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
11103     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
11104       {
11105         template_id_p = true;
11106         template_args = TREE_OPERAND (fns, 1);
11107         fns = TREE_OPERAND (fns, 0);
11108         if (template_args)
11109           template_args = tsubst_template_args (template_args, args,
11110                                                 complain, in_decl);
11111       }
11112     name = DECL_NAME (get_first_fn (fns));
11113     if (IDENTIFIER_TYPENAME_P (name))
11114       name = mangle_conv_op_name_for_type (optype);
11115     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
11116     if (!baselink)
11117       return error_mark_node;
11118
11119     /* If lookup found a single function, mark it as used at this
11120        point.  (If it lookup found multiple functions the one selected
11121        later by overload resolution will be marked as used at that
11122        point.)  */
11123     if (BASELINK_P (baselink))
11124       fns = BASELINK_FUNCTIONS (baselink);
11125     if (!template_id_p && !really_overloaded_fn (fns))
11126       mark_used (OVL_CURRENT (fns));
11127
11128     /* Add back the template arguments, if present.  */
11129     if (BASELINK_P (baselink) && template_id_p)
11130       BASELINK_FUNCTIONS (baselink)
11131         = build_nt (TEMPLATE_ID_EXPR,
11132                     BASELINK_FUNCTIONS (baselink),
11133                     template_args);
11134     /* Update the conversion operator type.  */
11135     BASELINK_OPTYPE (baselink) = optype;
11136
11137     if (!object_type)
11138       object_type = current_class_type;
11139     return adjust_result_of_qualified_name_lookup (baselink,
11140                                                    qualifying_scope,
11141                                                    object_type);
11142 }
11143
11144 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
11145    true if the qualified-id will be a postfix-expression in-and-of
11146    itself; false if more of the postfix-expression follows the
11147    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
11148    of "&".  */
11149
11150 static tree
11151 tsubst_qualified_id (tree qualified_id, tree args,
11152                      tsubst_flags_t complain, tree in_decl,
11153                      bool done, bool address_p)
11154 {
11155   tree expr;
11156   tree scope;
11157   tree name;
11158   bool is_template;
11159   tree template_args;
11160
11161   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
11162
11163   /* Figure out what name to look up.  */
11164   name = TREE_OPERAND (qualified_id, 1);
11165   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
11166     {
11167       is_template = true;
11168       template_args = TREE_OPERAND (name, 1);
11169       if (template_args)
11170         template_args = tsubst_template_args (template_args, args,
11171                                               complain, in_decl);
11172       name = TREE_OPERAND (name, 0);
11173     }
11174   else
11175     {
11176       is_template = false;
11177       template_args = NULL_TREE;
11178     }
11179
11180   /* Substitute into the qualifying scope.  When there are no ARGS, we
11181      are just trying to simplify a non-dependent expression.  In that
11182      case the qualifying scope may be dependent, and, in any case,
11183      substituting will not help.  */
11184   scope = TREE_OPERAND (qualified_id, 0);
11185   if (args)
11186     {
11187       scope = tsubst (scope, args, complain, in_decl);
11188       expr = tsubst_copy (name, args, complain, in_decl);
11189     }
11190   else
11191     expr = name;
11192
11193   if (dependent_scope_p (scope))
11194     return build_qualified_name (NULL_TREE, scope, expr,
11195                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
11196
11197   if (!BASELINK_P (name) && !DECL_P (expr))
11198     {
11199       if (TREE_CODE (expr) == BIT_NOT_EXPR)
11200         {
11201           /* A BIT_NOT_EXPR is used to represent a destructor.  */
11202           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
11203             {
11204               error ("qualifying type %qT does not match destructor name ~%qT",
11205                      scope, TREE_OPERAND (expr, 0));
11206               expr = error_mark_node;
11207             }
11208           else
11209             expr = lookup_qualified_name (scope, complete_dtor_identifier,
11210                                           /*is_type_p=*/0, false);
11211         }
11212       else
11213         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
11214       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
11215                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
11216         {
11217           if (complain & tf_error)
11218             {
11219               error ("dependent-name %qE is parsed as a non-type, but "
11220                      "instantiation yields a type", qualified_id);
11221               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
11222             }
11223           return error_mark_node;
11224         }
11225     }
11226
11227   if (DECL_P (expr))
11228     {
11229       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
11230                                            scope);
11231       /* Remember that there was a reference to this entity.  */
11232       mark_used (expr);
11233     }
11234
11235   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
11236     {
11237       if (complain & tf_error)
11238         qualified_name_lookup_error (scope,
11239                                      TREE_OPERAND (qualified_id, 1),
11240                                      expr, input_location);
11241       return error_mark_node;
11242     }
11243
11244   if (is_template)
11245     expr = lookup_template_function (expr, template_args);
11246
11247   if (expr == error_mark_node && complain & tf_error)
11248     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
11249                                  expr, input_location);
11250   else if (TYPE_P (scope))
11251     {
11252       expr = (adjust_result_of_qualified_name_lookup
11253               (expr, scope, current_class_type));
11254       expr = (finish_qualified_id_expr
11255               (scope, expr, done, address_p,
11256                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
11257                /*template_arg_p=*/false));
11258     }
11259
11260   /* Expressions do not generally have reference type.  */
11261   if (TREE_CODE (expr) != SCOPE_REF
11262       /* However, if we're about to form a pointer-to-member, we just
11263          want the referenced member referenced.  */
11264       && TREE_CODE (expr) != OFFSET_REF)
11265     expr = convert_from_reference (expr);
11266
11267   return expr;
11268 }
11269
11270 /* Like tsubst, but deals with expressions.  This function just replaces
11271    template parms; to finish processing the resultant expression, use
11272    tsubst_expr.  */
11273
11274 static tree
11275 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11276 {
11277   enum tree_code code;
11278   tree r;
11279
11280   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
11281     return t;
11282
11283   code = TREE_CODE (t);
11284
11285   switch (code)
11286     {
11287     case PARM_DECL:
11288       r = retrieve_local_specialization (t);
11289
11290       if (r == NULL)
11291         {
11292           tree c;
11293           /* This can happen for a parameter name used later in a function
11294              declaration (such as in a late-specified return type).  Just
11295              make a dummy decl, since it's only used for its type.  */
11296           gcc_assert (cp_unevaluated_operand != 0);
11297           /* We copy T because want to tsubst the PARM_DECL only,
11298              not the following PARM_DECLs that are chained to T.  */
11299           c = copy_node (t);
11300           r = tsubst_decl (c, args, complain);
11301           /* Give it the template pattern as its context; its true context
11302              hasn't been instantiated yet and this is good enough for
11303              mangling.  */
11304           DECL_CONTEXT (r) = DECL_CONTEXT (t);
11305         }
11306       
11307       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
11308         r = ARGUMENT_PACK_SELECT_ARG (r);
11309       mark_used (r);
11310       return r;
11311
11312     case CONST_DECL:
11313       {
11314         tree enum_type;
11315         tree v;
11316
11317         if (DECL_TEMPLATE_PARM_P (t))
11318           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
11319         /* There is no need to substitute into namespace-scope
11320            enumerators.  */
11321         if (DECL_NAMESPACE_SCOPE_P (t))
11322           return t;
11323         /* If ARGS is NULL, then T is known to be non-dependent.  */
11324         if (args == NULL_TREE)
11325           return integral_constant_value (t);
11326
11327         /* Unfortunately, we cannot just call lookup_name here.
11328            Consider:
11329
11330              template <int I> int f() {
11331              enum E { a = I };
11332              struct S { void g() { E e = a; } };
11333              };
11334
11335            When we instantiate f<7>::S::g(), say, lookup_name is not
11336            clever enough to find f<7>::a.  */
11337         enum_type
11338           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
11339                               /*entering_scope=*/0);
11340
11341         for (v = TYPE_VALUES (enum_type);
11342              v != NULL_TREE;
11343              v = TREE_CHAIN (v))
11344           if (TREE_PURPOSE (v) == DECL_NAME (t))
11345             return TREE_VALUE (v);
11346
11347           /* We didn't find the name.  That should never happen; if
11348              name-lookup found it during preliminary parsing, we
11349              should find it again here during instantiation.  */
11350         gcc_unreachable ();
11351       }
11352       return t;
11353
11354     case FIELD_DECL:
11355       if (DECL_CONTEXT (t))
11356         {
11357           tree ctx;
11358
11359           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
11360                                   /*entering_scope=*/1);
11361           if (ctx != DECL_CONTEXT (t))
11362             {
11363               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
11364               if (!r)
11365                 {
11366                   if (complain & tf_error)
11367                     error ("using invalid field %qD", t);
11368                   return error_mark_node;
11369                 }
11370               return r;
11371             }
11372         }
11373
11374       return t;
11375
11376     case VAR_DECL:
11377     case FUNCTION_DECL:
11378       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
11379           || local_variable_p (t))
11380         t = tsubst (t, args, complain, in_decl);
11381       mark_used (t);
11382       return t;
11383
11384     case OVERLOAD:
11385       /* An OVERLOAD will always be a non-dependent overload set; an
11386          overload set from function scope will just be represented with an
11387          IDENTIFIER_NODE, and from class scope with a BASELINK.  */
11388       gcc_assert (!uses_template_parms (t));
11389       return t;
11390
11391     case BASELINK:
11392       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
11393
11394     case TEMPLATE_DECL:
11395       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11396         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
11397                        args, complain, in_decl);
11398       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
11399         return tsubst (t, args, complain, in_decl);
11400       else if (DECL_CLASS_SCOPE_P (t)
11401                && uses_template_parms (DECL_CONTEXT (t)))
11402         {
11403           /* Template template argument like the following example need
11404              special treatment:
11405
11406                template <template <class> class TT> struct C {};
11407                template <class T> struct D {
11408                  template <class U> struct E {};
11409                  C<E> c;                                // #1
11410                };
11411                D<int> d;                                // #2
11412
11413              We are processing the template argument `E' in #1 for
11414              the template instantiation #2.  Originally, `E' is a
11415              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
11416              have to substitute this with one having context `D<int>'.  */
11417
11418           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
11419           return lookup_field (context, DECL_NAME(t), 0, false);
11420         }
11421       else
11422         /* Ordinary template template argument.  */
11423         return t;
11424
11425     case CAST_EXPR:
11426     case REINTERPRET_CAST_EXPR:
11427     case CONST_CAST_EXPR:
11428     case STATIC_CAST_EXPR:
11429     case DYNAMIC_CAST_EXPR:
11430     case NOP_EXPR:
11431       return build1
11432         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11433          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11434
11435     case SIZEOF_EXPR:
11436       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11437         {
11438
11439           tree expanded;
11440           int len = 0;
11441
11442           ++cp_unevaluated_operand;
11443           ++c_inhibit_evaluation_warnings;
11444           /* We only want to compute the number of arguments.  */
11445           expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
11446                                             complain, in_decl);
11447           --cp_unevaluated_operand;
11448           --c_inhibit_evaluation_warnings;
11449
11450           if (TREE_CODE (expanded) == TREE_VEC)
11451             len = TREE_VEC_LENGTH (expanded);
11452
11453           if (expanded == error_mark_node)
11454             return error_mark_node;
11455           else if (PACK_EXPANSION_P (expanded)
11456                    || (TREE_CODE (expanded) == TREE_VEC
11457                        && len > 0
11458                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
11459             {
11460               if (TREE_CODE (expanded) == TREE_VEC)
11461                 expanded = TREE_VEC_ELT (expanded, len - 1);
11462
11463               if (TYPE_P (expanded))
11464                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
11465                                                    complain & tf_error);
11466               else
11467                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
11468                                                    complain & tf_error);
11469             }
11470           else
11471             return build_int_cst (size_type_node, len);
11472         }
11473       /* Fall through */
11474
11475     case INDIRECT_REF:
11476     case NEGATE_EXPR:
11477     case TRUTH_NOT_EXPR:
11478     case BIT_NOT_EXPR:
11479     case ADDR_EXPR:
11480     case UNARY_PLUS_EXPR:      /* Unary + */
11481     case ALIGNOF_EXPR:
11482     case AT_ENCODE_EXPR:
11483     case ARROW_EXPR:
11484     case THROW_EXPR:
11485     case TYPEID_EXPR:
11486     case REALPART_EXPR:
11487     case IMAGPART_EXPR:
11488       return build1
11489         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11490          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11491
11492     case COMPONENT_REF:
11493       {
11494         tree object;
11495         tree name;
11496
11497         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
11498         name = TREE_OPERAND (t, 1);
11499         if (TREE_CODE (name) == BIT_NOT_EXPR)
11500           {
11501             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11502                                 complain, in_decl);
11503             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11504           }
11505         else if (TREE_CODE (name) == SCOPE_REF
11506                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
11507           {
11508             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
11509                                      complain, in_decl);
11510             name = TREE_OPERAND (name, 1);
11511             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11512                                 complain, in_decl);
11513             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11514             name = build_qualified_name (/*type=*/NULL_TREE,
11515                                          base, name,
11516                                          /*template_p=*/false);
11517           }
11518         else if (TREE_CODE (name) == BASELINK)
11519           name = tsubst_baselink (name,
11520                                   non_reference (TREE_TYPE (object)),
11521                                   args, complain,
11522                                   in_decl);
11523         else
11524           name = tsubst_copy (name, args, complain, in_decl);
11525         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
11526       }
11527
11528     case PLUS_EXPR:
11529     case MINUS_EXPR:
11530     case MULT_EXPR:
11531     case TRUNC_DIV_EXPR:
11532     case CEIL_DIV_EXPR:
11533     case FLOOR_DIV_EXPR:
11534     case ROUND_DIV_EXPR:
11535     case EXACT_DIV_EXPR:
11536     case BIT_AND_EXPR:
11537     case BIT_IOR_EXPR:
11538     case BIT_XOR_EXPR:
11539     case TRUNC_MOD_EXPR:
11540     case FLOOR_MOD_EXPR:
11541     case TRUTH_ANDIF_EXPR:
11542     case TRUTH_ORIF_EXPR:
11543     case TRUTH_AND_EXPR:
11544     case TRUTH_OR_EXPR:
11545     case RSHIFT_EXPR:
11546     case LSHIFT_EXPR:
11547     case RROTATE_EXPR:
11548     case LROTATE_EXPR:
11549     case EQ_EXPR:
11550     case NE_EXPR:
11551     case MAX_EXPR:
11552     case MIN_EXPR:
11553     case LE_EXPR:
11554     case GE_EXPR:
11555     case LT_EXPR:
11556     case GT_EXPR:
11557     case COMPOUND_EXPR:
11558     case DOTSTAR_EXPR:
11559     case MEMBER_REF:
11560     case PREDECREMENT_EXPR:
11561     case PREINCREMENT_EXPR:
11562     case POSTDECREMENT_EXPR:
11563     case POSTINCREMENT_EXPR:
11564       return build_nt
11565         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11566          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11567
11568     case SCOPE_REF:
11569       return build_qualified_name (/*type=*/NULL_TREE,
11570                                    tsubst_copy (TREE_OPERAND (t, 0),
11571                                                 args, complain, in_decl),
11572                                    tsubst_copy (TREE_OPERAND (t, 1),
11573                                                 args, complain, in_decl),
11574                                    QUALIFIED_NAME_IS_TEMPLATE (t));
11575
11576     case ARRAY_REF:
11577       return build_nt
11578         (ARRAY_REF,
11579          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11580          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11581          NULL_TREE, NULL_TREE);
11582
11583     case CALL_EXPR:
11584       {
11585         int n = VL_EXP_OPERAND_LENGTH (t);
11586         tree result = build_vl_exp (CALL_EXPR, n);
11587         int i;
11588         for (i = 0; i < n; i++)
11589           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
11590                                              complain, in_decl);
11591         return result;
11592       }
11593
11594     case COND_EXPR:
11595     case MODOP_EXPR:
11596     case PSEUDO_DTOR_EXPR:
11597       {
11598         r = build_nt
11599           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11600            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11601            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11602         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11603         return r;
11604       }
11605
11606     case NEW_EXPR:
11607       {
11608         r = build_nt
11609         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11610          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11611          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11612         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
11613         return r;
11614       }
11615
11616     case DELETE_EXPR:
11617       {
11618         r = build_nt
11619         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11620          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11621         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
11622         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
11623         return r;
11624       }
11625
11626     case TEMPLATE_ID_EXPR:
11627       {
11628         /* Substituted template arguments */
11629         tree fn = TREE_OPERAND (t, 0);
11630         tree targs = TREE_OPERAND (t, 1);
11631
11632         fn = tsubst_copy (fn, args, complain, in_decl);
11633         if (targs)
11634           targs = tsubst_template_args (targs, args, complain, in_decl);
11635
11636         return lookup_template_function (fn, targs);
11637       }
11638
11639     case TREE_LIST:
11640       {
11641         tree purpose, value, chain;
11642
11643         if (t == void_list_node)
11644           return t;
11645
11646         purpose = TREE_PURPOSE (t);
11647         if (purpose)
11648           purpose = tsubst_copy (purpose, args, complain, in_decl);
11649         value = TREE_VALUE (t);
11650         if (value)
11651           value = tsubst_copy (value, args, complain, in_decl);
11652         chain = TREE_CHAIN (t);
11653         if (chain && chain != void_type_node)
11654           chain = tsubst_copy (chain, args, complain, in_decl);
11655         if (purpose == TREE_PURPOSE (t)
11656             && value == TREE_VALUE (t)
11657             && chain == TREE_CHAIN (t))
11658           return t;
11659         return tree_cons (purpose, value, chain);
11660       }
11661
11662     case RECORD_TYPE:
11663     case UNION_TYPE:
11664     case ENUMERAL_TYPE:
11665     case INTEGER_TYPE:
11666     case TEMPLATE_TYPE_PARM:
11667     case TEMPLATE_TEMPLATE_PARM:
11668     case BOUND_TEMPLATE_TEMPLATE_PARM:
11669     case TEMPLATE_PARM_INDEX:
11670     case POINTER_TYPE:
11671     case REFERENCE_TYPE:
11672     case OFFSET_TYPE:
11673     case FUNCTION_TYPE:
11674     case METHOD_TYPE:
11675     case ARRAY_TYPE:
11676     case TYPENAME_TYPE:
11677     case UNBOUND_CLASS_TEMPLATE:
11678     case TYPEOF_TYPE:
11679     case DECLTYPE_TYPE:
11680     case TYPE_DECL:
11681       return tsubst (t, args, complain, in_decl);
11682
11683     case IDENTIFIER_NODE:
11684       if (IDENTIFIER_TYPENAME_P (t))
11685         {
11686           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11687           return mangle_conv_op_name_for_type (new_type);
11688         }
11689       else
11690         return t;
11691
11692     case CONSTRUCTOR:
11693       /* This is handled by tsubst_copy_and_build.  */
11694       gcc_unreachable ();
11695
11696     case VA_ARG_EXPR:
11697       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
11698                                           in_decl),
11699                              tsubst (TREE_TYPE (t), args, complain, in_decl));
11700
11701     case CLEANUP_POINT_EXPR:
11702       /* We shouldn't have built any of these during initial template
11703          generation.  Instead, they should be built during instantiation
11704          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
11705       gcc_unreachable ();
11706
11707     case OFFSET_REF:
11708       r = build2
11709         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11710          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11711          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11712       PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
11713       mark_used (TREE_OPERAND (r, 1));
11714       return r;
11715
11716     case EXPR_PACK_EXPANSION:
11717       error ("invalid use of pack expansion expression");
11718       return error_mark_node;
11719
11720     case NONTYPE_ARGUMENT_PACK:
11721       error ("use %<...%> to expand argument pack");
11722       return error_mark_node;
11723
11724     case INTEGER_CST:
11725     case REAL_CST:
11726     case STRING_CST:
11727     case COMPLEX_CST:
11728       {
11729         /* Instantiate any typedefs in the type.  */
11730         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11731         r = fold_convert (type, t);
11732         gcc_assert (TREE_CODE (r) == code);
11733         return r;
11734       }
11735
11736     case PTRMEM_CST:
11737       /* These can sometimes show up in a partial instantiation, but never
11738          involve template parms.  */
11739       gcc_assert (!uses_template_parms (t));
11740       return t;
11741
11742     default:
11743       /* We shouldn't get here, but keep going if !ENABLE_CHECKING.  */
11744       gcc_checking_assert (false);
11745       return t;
11746     }
11747 }
11748
11749 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
11750
11751 static tree
11752 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
11753                     tree in_decl)
11754 {
11755   tree new_clauses = NULL, nc, oc;
11756
11757   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
11758     {
11759       nc = copy_node (oc);
11760       OMP_CLAUSE_CHAIN (nc) = new_clauses;
11761       new_clauses = nc;
11762
11763       switch (OMP_CLAUSE_CODE (nc))
11764         {
11765         case OMP_CLAUSE_LASTPRIVATE:
11766           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
11767             {
11768               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
11769               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
11770                            in_decl, /*integral_constant_expression_p=*/false);
11771               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
11772                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
11773             }
11774           /* FALLTHRU */
11775         case OMP_CLAUSE_PRIVATE:
11776         case OMP_CLAUSE_SHARED:
11777         case OMP_CLAUSE_FIRSTPRIVATE:
11778         case OMP_CLAUSE_REDUCTION:
11779         case OMP_CLAUSE_COPYIN:
11780         case OMP_CLAUSE_COPYPRIVATE:
11781         case OMP_CLAUSE_IF:
11782         case OMP_CLAUSE_NUM_THREADS:
11783         case OMP_CLAUSE_SCHEDULE:
11784         case OMP_CLAUSE_COLLAPSE:
11785           OMP_CLAUSE_OPERAND (nc, 0)
11786             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
11787                            in_decl, /*integral_constant_expression_p=*/false);
11788           break;
11789         case OMP_CLAUSE_NOWAIT:
11790         case OMP_CLAUSE_ORDERED:
11791         case OMP_CLAUSE_DEFAULT:
11792         case OMP_CLAUSE_UNTIED:
11793           break;
11794         default:
11795           gcc_unreachable ();
11796         }
11797     }
11798
11799   return finish_omp_clauses (nreverse (new_clauses));
11800 }
11801
11802 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
11803
11804 static tree
11805 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
11806                           tree in_decl)
11807 {
11808 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
11809
11810   tree purpose, value, chain;
11811
11812   if (t == NULL)
11813     return t;
11814
11815   if (TREE_CODE (t) != TREE_LIST)
11816     return tsubst_copy_and_build (t, args, complain, in_decl,
11817                                   /*function_p=*/false,
11818                                   /*integral_constant_expression_p=*/false);
11819
11820   if (t == void_list_node)
11821     return t;
11822
11823   purpose = TREE_PURPOSE (t);
11824   if (purpose)
11825     purpose = RECUR (purpose);
11826   value = TREE_VALUE (t);
11827   if (value && TREE_CODE (value) != LABEL_DECL)
11828     value = RECUR (value);
11829   chain = TREE_CHAIN (t);
11830   if (chain && chain != void_type_node)
11831     chain = RECUR (chain);
11832   return tree_cons (purpose, value, chain);
11833 #undef RECUR
11834 }
11835
11836 /* Substitute one OMP_FOR iterator.  */
11837
11838 static void
11839 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
11840                          tree condv, tree incrv, tree *clauses,
11841                          tree args, tsubst_flags_t complain, tree in_decl,
11842                          bool integral_constant_expression_p)
11843 {
11844 #define RECUR(NODE)                             \
11845   tsubst_expr ((NODE), args, complain, in_decl, \
11846                integral_constant_expression_p)
11847   tree decl, init, cond, incr, auto_node;
11848
11849   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
11850   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
11851   decl = RECUR (TREE_OPERAND (init, 0));
11852   init = TREE_OPERAND (init, 1);
11853   auto_node = type_uses_auto (TREE_TYPE (decl));
11854   if (auto_node && init)
11855     {
11856       tree init_expr = init;
11857       if (TREE_CODE (init_expr) == DECL_EXPR)
11858         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
11859       init_expr = RECUR (init_expr);
11860       TREE_TYPE (decl)
11861         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
11862     }
11863   gcc_assert (!type_dependent_expression_p (decl));
11864
11865   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
11866     {
11867       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
11868       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11869       if (TREE_CODE (incr) == MODIFY_EXPR)
11870         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
11871                                     RECUR (TREE_OPERAND (incr, 1)),
11872                                     complain);
11873       else
11874         incr = RECUR (incr);
11875       TREE_VEC_ELT (declv, i) = decl;
11876       TREE_VEC_ELT (initv, i) = init;
11877       TREE_VEC_ELT (condv, i) = cond;
11878       TREE_VEC_ELT (incrv, i) = incr;
11879       return;
11880     }
11881
11882   if (init && TREE_CODE (init) != DECL_EXPR)
11883     {
11884       tree c;
11885       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
11886         {
11887           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
11888                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
11889               && OMP_CLAUSE_DECL (c) == decl)
11890             break;
11891           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
11892                    && OMP_CLAUSE_DECL (c) == decl)
11893             error ("iteration variable %qD should not be firstprivate", decl);
11894           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
11895                    && OMP_CLAUSE_DECL (c) == decl)
11896             error ("iteration variable %qD should not be reduction", decl);
11897         }
11898       if (c == NULL)
11899         {
11900           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
11901           OMP_CLAUSE_DECL (c) = decl;
11902           c = finish_omp_clauses (c);
11903           if (c)
11904             {
11905               OMP_CLAUSE_CHAIN (c) = *clauses;
11906               *clauses = c;
11907             }
11908         }
11909     }
11910   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
11911   if (COMPARISON_CLASS_P (cond))
11912     cond = build2 (TREE_CODE (cond), boolean_type_node,
11913                    RECUR (TREE_OPERAND (cond, 0)),
11914                    RECUR (TREE_OPERAND (cond, 1)));
11915   else
11916     cond = RECUR (cond);
11917   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11918   switch (TREE_CODE (incr))
11919     {
11920     case PREINCREMENT_EXPR:
11921     case PREDECREMENT_EXPR:
11922     case POSTINCREMENT_EXPR:
11923     case POSTDECREMENT_EXPR:
11924       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
11925                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
11926       break;
11927     case MODIFY_EXPR:
11928       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11929           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11930         {
11931           tree rhs = TREE_OPERAND (incr, 1);
11932           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11933                          RECUR (TREE_OPERAND (incr, 0)),
11934                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11935                                  RECUR (TREE_OPERAND (rhs, 0)),
11936                                  RECUR (TREE_OPERAND (rhs, 1))));
11937         }
11938       else
11939         incr = RECUR (incr);
11940       break;
11941     case MODOP_EXPR:
11942       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11943           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11944         {
11945           tree lhs = RECUR (TREE_OPERAND (incr, 0));
11946           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
11947                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
11948                                  TREE_TYPE (decl), lhs,
11949                                  RECUR (TREE_OPERAND (incr, 2))));
11950         }
11951       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
11952                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
11953                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
11954         {
11955           tree rhs = TREE_OPERAND (incr, 2);
11956           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11957                          RECUR (TREE_OPERAND (incr, 0)),
11958                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11959                                  RECUR (TREE_OPERAND (rhs, 0)),
11960                                  RECUR (TREE_OPERAND (rhs, 1))));
11961         }
11962       else
11963         incr = RECUR (incr);
11964       break;
11965     default:
11966       incr = RECUR (incr);
11967       break;
11968     }
11969
11970   TREE_VEC_ELT (declv, i) = decl;
11971   TREE_VEC_ELT (initv, i) = init;
11972   TREE_VEC_ELT (condv, i) = cond;
11973   TREE_VEC_ELT (incrv, i) = incr;
11974 #undef RECUR
11975 }
11976
11977 /* Like tsubst_copy for expressions, etc. but also does semantic
11978    processing.  */
11979
11980 static tree
11981 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
11982              bool integral_constant_expression_p)
11983 {
11984 #define RECUR(NODE)                             \
11985   tsubst_expr ((NODE), args, complain, in_decl, \
11986                integral_constant_expression_p)
11987
11988   tree stmt, tmp;
11989
11990   if (t == NULL_TREE || t == error_mark_node)
11991     return t;
11992
11993   if (EXPR_HAS_LOCATION (t))
11994     input_location = EXPR_LOCATION (t);
11995   if (STATEMENT_CODE_P (TREE_CODE (t)))
11996     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
11997
11998   switch (TREE_CODE (t))
11999     {
12000     case STATEMENT_LIST:
12001       {
12002         tree_stmt_iterator i;
12003         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
12004           RECUR (tsi_stmt (i));
12005         break;
12006       }
12007
12008     case CTOR_INITIALIZER:
12009       finish_mem_initializers (tsubst_initializer_list
12010                                (TREE_OPERAND (t, 0), args));
12011       break;
12012
12013     case RETURN_EXPR:
12014       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
12015       break;
12016
12017     case EXPR_STMT:
12018       tmp = RECUR (EXPR_STMT_EXPR (t));
12019       if (EXPR_STMT_STMT_EXPR_RESULT (t))
12020         finish_stmt_expr_expr (tmp, cur_stmt_expr);
12021       else
12022         finish_expr_stmt (tmp);
12023       break;
12024
12025     case USING_STMT:
12026       do_using_directive (USING_STMT_NAMESPACE (t));
12027       break;
12028
12029     case DECL_EXPR:
12030       {
12031         tree decl, pattern_decl;
12032         tree init;
12033
12034         pattern_decl = decl = DECL_EXPR_DECL (t);
12035         if (TREE_CODE (decl) == LABEL_DECL)
12036           finish_label_decl (DECL_NAME (decl));
12037         else if (TREE_CODE (decl) == USING_DECL)
12038           {
12039             tree scope = USING_DECL_SCOPE (decl);
12040             tree name = DECL_NAME (decl);
12041             tree decl;
12042
12043             scope = tsubst (scope, args, complain, in_decl);
12044             decl = lookup_qualified_name (scope, name,
12045                                           /*is_type_p=*/false,
12046                                           /*complain=*/false);
12047             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
12048               qualified_name_lookup_error (scope, name, decl, input_location);
12049             else
12050               do_local_using_decl (decl, scope, name);
12051           }
12052         else
12053           {
12054             init = DECL_INITIAL (decl);
12055             decl = tsubst (decl, args, complain, in_decl);
12056             if (decl != error_mark_node)
12057               {
12058                 /* By marking the declaration as instantiated, we avoid
12059                    trying to instantiate it.  Since instantiate_decl can't
12060                    handle local variables, and since we've already done
12061                    all that needs to be done, that's the right thing to
12062                    do.  */
12063                 if (TREE_CODE (decl) == VAR_DECL)
12064                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12065                 if (TREE_CODE (decl) == VAR_DECL
12066                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
12067                   /* Anonymous aggregates are a special case.  */
12068                   finish_anon_union (decl);
12069                 else
12070                   {
12071                     int const_init = false;
12072                     maybe_push_decl (decl);
12073                     if (TREE_CODE (decl) == VAR_DECL
12074                         && DECL_PRETTY_FUNCTION_P (decl))
12075                       {
12076                         /* For __PRETTY_FUNCTION__ we have to adjust the
12077                            initializer.  */
12078                         const char *const name
12079                           = cxx_printable_name (current_function_decl, 2);
12080                         init = cp_fname_init (name, &TREE_TYPE (decl));
12081                       }
12082                     else
12083                       {
12084                         tree t = RECUR (init);
12085
12086                         if (init && !t)
12087                           {
12088                             /* If we had an initializer but it
12089                                instantiated to nothing,
12090                                value-initialize the object.  This will
12091                                only occur when the initializer was a
12092                                pack expansion where the parameter packs
12093                                used in that expansion were of length
12094                                zero.  */
12095                             init = build_value_init (TREE_TYPE (decl),
12096                                                      complain);
12097                             if (TREE_CODE (init) == AGGR_INIT_EXPR)
12098                               init = get_target_expr (init);
12099                           }
12100                         else
12101                           init = t;
12102                       }
12103
12104                     if (TREE_CODE (decl) == VAR_DECL)
12105                       const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
12106                                     (pattern_decl));
12107                     cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
12108                   }
12109               }
12110           }
12111
12112         /* A DECL_EXPR can also be used as an expression, in the condition
12113            clause of an if/for/while construct.  */
12114         return decl;
12115       }
12116
12117     case FOR_STMT:
12118       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12119       RECUR (FOR_INIT_STMT (t));
12120       finish_for_init_stmt (stmt);
12121       tmp = RECUR (FOR_COND (t));
12122       finish_for_cond (tmp, stmt);
12123       tmp = RECUR (FOR_EXPR (t));
12124       finish_for_expr (tmp, stmt);
12125       RECUR (FOR_BODY (t));
12126       finish_for_stmt (stmt);
12127       break;
12128
12129     case RANGE_FOR_STMT:
12130       {
12131         tree decl, expr;
12132         stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12133         decl = RANGE_FOR_DECL (t);
12134         decl = tsubst (decl, args, complain, in_decl);
12135         maybe_push_decl (decl);
12136         expr = RECUR (RANGE_FOR_EXPR (t));
12137         stmt = cp_convert_range_for (stmt, decl, expr);
12138         RECUR (RANGE_FOR_BODY (t));
12139         finish_for_stmt (stmt);
12140       }
12141       break;
12142
12143     case WHILE_STMT:
12144       stmt = begin_while_stmt ();
12145       tmp = RECUR (WHILE_COND (t));
12146       finish_while_stmt_cond (tmp, stmt);
12147       RECUR (WHILE_BODY (t));
12148       finish_while_stmt (stmt);
12149       break;
12150
12151     case DO_STMT:
12152       stmt = begin_do_stmt ();
12153       RECUR (DO_BODY (t));
12154       finish_do_body (stmt);
12155       tmp = RECUR (DO_COND (t));
12156       finish_do_stmt (tmp, stmt);
12157       break;
12158
12159     case IF_STMT:
12160       stmt = begin_if_stmt ();
12161       tmp = RECUR (IF_COND (t));
12162       finish_if_stmt_cond (tmp, stmt);
12163       RECUR (THEN_CLAUSE (t));
12164       finish_then_clause (stmt);
12165
12166       if (ELSE_CLAUSE (t))
12167         {
12168           begin_else_clause (stmt);
12169           RECUR (ELSE_CLAUSE (t));
12170           finish_else_clause (stmt);
12171         }
12172
12173       finish_if_stmt (stmt);
12174       break;
12175
12176     case BIND_EXPR:
12177       if (BIND_EXPR_BODY_BLOCK (t))
12178         stmt = begin_function_body ();
12179       else
12180         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
12181                                     ? BCS_TRY_BLOCK : 0);
12182
12183       RECUR (BIND_EXPR_BODY (t));
12184
12185       if (BIND_EXPR_BODY_BLOCK (t))
12186         finish_function_body (stmt);
12187       else
12188         finish_compound_stmt (stmt);
12189       break;
12190
12191     case BREAK_STMT:
12192       finish_break_stmt ();
12193       break;
12194
12195     case CONTINUE_STMT:
12196       finish_continue_stmt ();
12197       break;
12198
12199     case SWITCH_STMT:
12200       stmt = begin_switch_stmt ();
12201       tmp = RECUR (SWITCH_STMT_COND (t));
12202       finish_switch_cond (tmp, stmt);
12203       RECUR (SWITCH_STMT_BODY (t));
12204       finish_switch_stmt (stmt);
12205       break;
12206
12207     case CASE_LABEL_EXPR:
12208       finish_case_label (EXPR_LOCATION (t),
12209                          RECUR (CASE_LOW (t)),
12210                          RECUR (CASE_HIGH (t)));
12211       break;
12212
12213     case LABEL_EXPR:
12214       {
12215         tree decl = LABEL_EXPR_LABEL (t);
12216         tree label;
12217
12218         label = finish_label_stmt (DECL_NAME (decl));
12219         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
12220           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
12221       }
12222       break;
12223
12224     case GOTO_EXPR:
12225       tmp = GOTO_DESTINATION (t);
12226       if (TREE_CODE (tmp) != LABEL_DECL)
12227         /* Computed goto's must be tsubst'd into.  On the other hand,
12228            non-computed gotos must not be; the identifier in question
12229            will have no binding.  */
12230         tmp = RECUR (tmp);
12231       else
12232         tmp = DECL_NAME (tmp);
12233       finish_goto_stmt (tmp);
12234       break;
12235
12236     case ASM_EXPR:
12237       tmp = finish_asm_stmt
12238         (ASM_VOLATILE_P (t),
12239          RECUR (ASM_STRING (t)),
12240          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
12241          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
12242          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
12243          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
12244       {
12245         tree asm_expr = tmp;
12246         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
12247           asm_expr = TREE_OPERAND (asm_expr, 0);
12248         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
12249       }
12250       break;
12251
12252     case TRY_BLOCK:
12253       if (CLEANUP_P (t))
12254         {
12255           stmt = begin_try_block ();
12256           RECUR (TRY_STMTS (t));
12257           finish_cleanup_try_block (stmt);
12258           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
12259         }
12260       else
12261         {
12262           tree compound_stmt = NULL_TREE;
12263
12264           if (FN_TRY_BLOCK_P (t))
12265             stmt = begin_function_try_block (&compound_stmt);
12266           else
12267             stmt = begin_try_block ();
12268
12269           RECUR (TRY_STMTS (t));
12270
12271           if (FN_TRY_BLOCK_P (t))
12272             finish_function_try_block (stmt);
12273           else
12274             finish_try_block (stmt);
12275
12276           RECUR (TRY_HANDLERS (t));
12277           if (FN_TRY_BLOCK_P (t))
12278             finish_function_handler_sequence (stmt, compound_stmt);
12279           else
12280             finish_handler_sequence (stmt);
12281         }
12282       break;
12283
12284     case HANDLER:
12285       {
12286         tree decl = HANDLER_PARMS (t);
12287
12288         if (decl)
12289           {
12290             decl = tsubst (decl, args, complain, in_decl);
12291             /* Prevent instantiate_decl from trying to instantiate
12292                this variable.  We've already done all that needs to be
12293                done.  */
12294             if (decl != error_mark_node)
12295               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12296           }
12297         stmt = begin_handler ();
12298         finish_handler_parms (decl, stmt);
12299         RECUR (HANDLER_BODY (t));
12300         finish_handler (stmt);
12301       }
12302       break;
12303
12304     case TAG_DEFN:
12305       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12306       break;
12307
12308     case STATIC_ASSERT:
12309       {
12310         tree condition = 
12311           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
12312                        args,
12313                        complain, in_decl,
12314                        /*integral_constant_expression_p=*/true);
12315         finish_static_assert (condition,
12316                               STATIC_ASSERT_MESSAGE (t),
12317                               STATIC_ASSERT_SOURCE_LOCATION (t),
12318                               /*member_p=*/false);
12319       }
12320       break;
12321
12322     case OMP_PARALLEL:
12323       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
12324                                 args, complain, in_decl);
12325       stmt = begin_omp_parallel ();
12326       RECUR (OMP_PARALLEL_BODY (t));
12327       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
12328         = OMP_PARALLEL_COMBINED (t);
12329       break;
12330
12331     case OMP_TASK:
12332       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
12333                                 args, complain, in_decl);
12334       stmt = begin_omp_task ();
12335       RECUR (OMP_TASK_BODY (t));
12336       finish_omp_task (tmp, stmt);
12337       break;
12338
12339     case OMP_FOR:
12340       {
12341         tree clauses, body, pre_body;
12342         tree declv, initv, condv, incrv;
12343         int i;
12344
12345         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
12346                                       args, complain, in_decl);
12347         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12348         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12349         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12350         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12351
12352         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
12353           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
12354                                    &clauses, args, complain, in_decl,
12355                                    integral_constant_expression_p);
12356
12357         stmt = begin_omp_structured_block ();
12358
12359         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
12360           if (TREE_VEC_ELT (initv, i) == NULL
12361               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
12362             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
12363           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
12364             {
12365               tree init = RECUR (TREE_VEC_ELT (initv, i));
12366               gcc_assert (init == TREE_VEC_ELT (declv, i));
12367               TREE_VEC_ELT (initv, i) = NULL_TREE;
12368             }
12369           else
12370             {
12371               tree decl_expr = TREE_VEC_ELT (initv, i);
12372               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
12373               gcc_assert (init != NULL);
12374               TREE_VEC_ELT (initv, i) = RECUR (init);
12375               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
12376               RECUR (decl_expr);
12377               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
12378             }
12379
12380         pre_body = push_stmt_list ();
12381         RECUR (OMP_FOR_PRE_BODY (t));
12382         pre_body = pop_stmt_list (pre_body);
12383
12384         body = push_stmt_list ();
12385         RECUR (OMP_FOR_BODY (t));
12386         body = pop_stmt_list (body);
12387
12388         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
12389                             body, pre_body, clauses);
12390
12391         add_stmt (finish_omp_structured_block (stmt));
12392       }
12393       break;
12394
12395     case OMP_SECTIONS:
12396     case OMP_SINGLE:
12397       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
12398       stmt = push_stmt_list ();
12399       RECUR (OMP_BODY (t));
12400       stmt = pop_stmt_list (stmt);
12401
12402       t = copy_node (t);
12403       OMP_BODY (t) = stmt;
12404       OMP_CLAUSES (t) = tmp;
12405       add_stmt (t);
12406       break;
12407
12408     case OMP_SECTION:
12409     case OMP_CRITICAL:
12410     case OMP_MASTER:
12411     case OMP_ORDERED:
12412       stmt = push_stmt_list ();
12413       RECUR (OMP_BODY (t));
12414       stmt = pop_stmt_list (stmt);
12415
12416       t = copy_node (t);
12417       OMP_BODY (t) = stmt;
12418       add_stmt (t);
12419       break;
12420
12421     case OMP_ATOMIC:
12422       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
12423       {
12424         tree op1 = TREE_OPERAND (t, 1);
12425         tree lhs = RECUR (TREE_OPERAND (op1, 0));
12426         tree rhs = RECUR (TREE_OPERAND (op1, 1));
12427         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
12428       }
12429       break;
12430
12431     case EXPR_PACK_EXPANSION:
12432       error ("invalid use of pack expansion expression");
12433       return error_mark_node;
12434
12435     case NONTYPE_ARGUMENT_PACK:
12436       error ("use %<...%> to expand argument pack");
12437       return error_mark_node;
12438
12439     default:
12440       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
12441
12442       return tsubst_copy_and_build (t, args, complain, in_decl,
12443                                     /*function_p=*/false,
12444                                     integral_constant_expression_p);
12445     }
12446
12447   return NULL_TREE;
12448 #undef RECUR
12449 }
12450
12451 /* T is a postfix-expression that is not being used in a function
12452    call.  Return the substituted version of T.  */
12453
12454 static tree
12455 tsubst_non_call_postfix_expression (tree t, tree args,
12456                                     tsubst_flags_t complain,
12457                                     tree in_decl)
12458 {
12459   if (TREE_CODE (t) == SCOPE_REF)
12460     t = tsubst_qualified_id (t, args, complain, in_decl,
12461                              /*done=*/false, /*address_p=*/false);
12462   else
12463     t = tsubst_copy_and_build (t, args, complain, in_decl,
12464                                /*function_p=*/false,
12465                                /*integral_constant_expression_p=*/false);
12466
12467   return t;
12468 }
12469
12470 /* Like tsubst but deals with expressions and performs semantic
12471    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
12472
12473 tree
12474 tsubst_copy_and_build (tree t,
12475                        tree args,
12476                        tsubst_flags_t complain,
12477                        tree in_decl,
12478                        bool function_p,
12479                        bool integral_constant_expression_p)
12480 {
12481 #define RECUR(NODE)                                             \
12482   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
12483                          /*function_p=*/false,                  \
12484                          integral_constant_expression_p)
12485
12486   tree op1;
12487
12488   if (t == NULL_TREE || t == error_mark_node)
12489     return t;
12490
12491   switch (TREE_CODE (t))
12492     {
12493     case USING_DECL:
12494       t = DECL_NAME (t);
12495       /* Fall through.  */
12496     case IDENTIFIER_NODE:
12497       {
12498         tree decl;
12499         cp_id_kind idk;
12500         bool non_integral_constant_expression_p;
12501         const char *error_msg;
12502
12503         if (IDENTIFIER_TYPENAME_P (t))
12504           {
12505             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12506             t = mangle_conv_op_name_for_type (new_type);
12507           }
12508
12509         /* Look up the name.  */
12510         decl = lookup_name (t);
12511
12512         /* By convention, expressions use ERROR_MARK_NODE to indicate
12513            failure, not NULL_TREE.  */
12514         if (decl == NULL_TREE)
12515           decl = error_mark_node;
12516
12517         decl = finish_id_expression (t, decl, NULL_TREE,
12518                                      &idk,
12519                                      integral_constant_expression_p,
12520                                      /*allow_non_integral_constant_expression_p=*/false,
12521                                      &non_integral_constant_expression_p,
12522                                      /*template_p=*/false,
12523                                      /*done=*/true,
12524                                      /*address_p=*/false,
12525                                      /*template_arg_p=*/false,
12526                                      &error_msg,
12527                                      input_location);
12528         if (error_msg)
12529           error (error_msg);
12530         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
12531           decl = unqualified_name_lookup_error (decl);
12532         return decl;
12533       }
12534
12535     case TEMPLATE_ID_EXPR:
12536       {
12537         tree object;
12538         tree templ = RECUR (TREE_OPERAND (t, 0));
12539         tree targs = TREE_OPERAND (t, 1);
12540
12541         if (targs)
12542           targs = tsubst_template_args (targs, args, complain, in_decl);
12543
12544         if (TREE_CODE (templ) == COMPONENT_REF)
12545           {
12546             object = TREE_OPERAND (templ, 0);
12547             templ = TREE_OPERAND (templ, 1);
12548           }
12549         else
12550           object = NULL_TREE;
12551         templ = lookup_template_function (templ, targs);
12552
12553         if (object)
12554           return build3 (COMPONENT_REF, TREE_TYPE (templ),
12555                          object, templ, NULL_TREE);
12556         else
12557           return baselink_for_fns (templ);
12558       }
12559
12560     case INDIRECT_REF:
12561       {
12562         tree r = RECUR (TREE_OPERAND (t, 0));
12563
12564         if (REFERENCE_REF_P (t))
12565           {
12566             /* A type conversion to reference type will be enclosed in
12567                such an indirect ref, but the substitution of the cast
12568                will have also added such an indirect ref.  */
12569             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
12570               r = convert_from_reference (r);
12571           }
12572         else
12573           r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
12574         return r;
12575       }
12576
12577     case NOP_EXPR:
12578       return build_nop
12579         (tsubst (TREE_TYPE (t), args, complain, in_decl),
12580          RECUR (TREE_OPERAND (t, 0)));
12581
12582     case CAST_EXPR:
12583     case REINTERPRET_CAST_EXPR:
12584     case CONST_CAST_EXPR:
12585     case DYNAMIC_CAST_EXPR:
12586     case STATIC_CAST_EXPR:
12587       {
12588         tree type;
12589         tree op;
12590
12591         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12592         if (integral_constant_expression_p
12593             && !cast_valid_in_integral_constant_expression_p (type))
12594           {
12595             if (complain & tf_error)
12596               error ("a cast to a type other than an integral or "
12597                      "enumeration type cannot appear in a constant-expression");
12598             return error_mark_node; 
12599           }
12600
12601         op = RECUR (TREE_OPERAND (t, 0));
12602
12603         switch (TREE_CODE (t))
12604           {
12605           case CAST_EXPR:
12606             return build_functional_cast (type, op, complain);
12607           case REINTERPRET_CAST_EXPR:
12608             return build_reinterpret_cast (type, op, complain);
12609           case CONST_CAST_EXPR:
12610             return build_const_cast (type, op, complain);
12611           case DYNAMIC_CAST_EXPR:
12612             return build_dynamic_cast (type, op, complain);
12613           case STATIC_CAST_EXPR:
12614             return build_static_cast (type, op, complain);
12615           default:
12616             gcc_unreachable ();
12617           }
12618       }
12619
12620     case POSTDECREMENT_EXPR:
12621     case POSTINCREMENT_EXPR:
12622       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12623                                                 args, complain, in_decl);
12624       return build_x_unary_op (TREE_CODE (t), op1, complain);
12625
12626     case PREDECREMENT_EXPR:
12627     case PREINCREMENT_EXPR:
12628     case NEGATE_EXPR:
12629     case BIT_NOT_EXPR:
12630     case ABS_EXPR:
12631     case TRUTH_NOT_EXPR:
12632     case UNARY_PLUS_EXPR:  /* Unary + */
12633     case REALPART_EXPR:
12634     case IMAGPART_EXPR:
12635       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
12636                                complain);
12637
12638     case ADDR_EXPR:
12639       op1 = TREE_OPERAND (t, 0);
12640       if (TREE_CODE (op1) == LABEL_DECL)
12641         return finish_label_address_expr (DECL_NAME (op1),
12642                                           EXPR_LOCATION (op1));
12643       if (TREE_CODE (op1) == SCOPE_REF)
12644         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
12645                                    /*done=*/true, /*address_p=*/true);
12646       else
12647         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
12648                                                   in_decl);
12649       return build_x_unary_op (ADDR_EXPR, op1, complain);
12650
12651     case PLUS_EXPR:
12652     case MINUS_EXPR:
12653     case MULT_EXPR:
12654     case TRUNC_DIV_EXPR:
12655     case CEIL_DIV_EXPR:
12656     case FLOOR_DIV_EXPR:
12657     case ROUND_DIV_EXPR:
12658     case EXACT_DIV_EXPR:
12659     case BIT_AND_EXPR:
12660     case BIT_IOR_EXPR:
12661     case BIT_XOR_EXPR:
12662     case TRUNC_MOD_EXPR:
12663     case FLOOR_MOD_EXPR:
12664     case TRUTH_ANDIF_EXPR:
12665     case TRUTH_ORIF_EXPR:
12666     case TRUTH_AND_EXPR:
12667     case TRUTH_OR_EXPR:
12668     case RSHIFT_EXPR:
12669     case LSHIFT_EXPR:
12670     case RROTATE_EXPR:
12671     case LROTATE_EXPR:
12672     case EQ_EXPR:
12673     case NE_EXPR:
12674     case MAX_EXPR:
12675     case MIN_EXPR:
12676     case LE_EXPR:
12677     case GE_EXPR:
12678     case LT_EXPR:
12679     case GT_EXPR:
12680     case MEMBER_REF:
12681     case DOTSTAR_EXPR:
12682       return build_x_binary_op
12683         (TREE_CODE (t),
12684          RECUR (TREE_OPERAND (t, 0)),
12685          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
12686           ? ERROR_MARK
12687           : TREE_CODE (TREE_OPERAND (t, 0))),
12688          RECUR (TREE_OPERAND (t, 1)),
12689          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
12690           ? ERROR_MARK
12691           : TREE_CODE (TREE_OPERAND (t, 1))),
12692          /*overloaded_p=*/NULL,
12693          complain);
12694
12695     case SCOPE_REF:
12696       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
12697                                   /*address_p=*/false);
12698     case ARRAY_REF:
12699       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12700                                                 args, complain, in_decl);
12701       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
12702
12703     case SIZEOF_EXPR:
12704       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
12705         return tsubst_copy (t, args, complain, in_decl);
12706       /* Fall through */
12707       
12708     case ALIGNOF_EXPR:
12709       op1 = TREE_OPERAND (t, 0);
12710       if (!args)
12711         {
12712           /* When there are no ARGS, we are trying to evaluate a
12713              non-dependent expression from the parser.  Trying to do
12714              the substitutions may not work.  */
12715           if (!TYPE_P (op1))
12716             op1 = TREE_TYPE (op1);
12717         }
12718       else
12719         {
12720           ++cp_unevaluated_operand;
12721           ++c_inhibit_evaluation_warnings;
12722           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12723                                        /*function_p=*/false,
12724                                        /*integral_constant_expression_p=*/false);
12725           --cp_unevaluated_operand;
12726           --c_inhibit_evaluation_warnings;
12727         }
12728       if (TYPE_P (op1))
12729         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
12730                                            complain & tf_error);
12731       else
12732         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
12733                                            complain & tf_error);
12734
12735     case AT_ENCODE_EXPR:
12736       {
12737         op1 = TREE_OPERAND (t, 0);
12738         ++cp_unevaluated_operand;
12739         ++c_inhibit_evaluation_warnings;
12740         op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12741                                      /*function_p=*/false,
12742                                      /*integral_constant_expression_p=*/false);
12743         --cp_unevaluated_operand;
12744         --c_inhibit_evaluation_warnings;
12745         return objc_build_encode_expr (op1);
12746       }
12747
12748     case NOEXCEPT_EXPR:
12749       op1 = TREE_OPERAND (t, 0);
12750       ++cp_unevaluated_operand;
12751       ++c_inhibit_evaluation_warnings;
12752       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12753                                    /*function_p=*/false,
12754                                    /*integral_constant_expression_p=*/false);
12755       --cp_unevaluated_operand;
12756       --c_inhibit_evaluation_warnings;
12757       return finish_noexcept_expr (op1, complain);
12758
12759     case MODOP_EXPR:
12760       {
12761         tree r = build_x_modify_expr
12762           (RECUR (TREE_OPERAND (t, 0)),
12763            TREE_CODE (TREE_OPERAND (t, 1)),
12764            RECUR (TREE_OPERAND (t, 2)),
12765            complain);
12766         /* TREE_NO_WARNING must be set if either the expression was
12767            parenthesized or it uses an operator such as >>= rather
12768            than plain assignment.  In the former case, it was already
12769            set and must be copied.  In the latter case,
12770            build_x_modify_expr sets it and it must not be reset
12771            here.  */
12772         if (TREE_NO_WARNING (t))
12773           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12774         return r;
12775       }
12776
12777     case ARROW_EXPR:
12778       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12779                                                 args, complain, in_decl);
12780       /* Remember that there was a reference to this entity.  */
12781       if (DECL_P (op1))
12782         mark_used (op1);
12783       return build_x_arrow (op1);
12784
12785     case NEW_EXPR:
12786       {
12787         tree placement = RECUR (TREE_OPERAND (t, 0));
12788         tree init = RECUR (TREE_OPERAND (t, 3));
12789         VEC(tree,gc) *placement_vec;
12790         VEC(tree,gc) *init_vec;
12791         tree ret;
12792
12793         if (placement == NULL_TREE)
12794           placement_vec = NULL;
12795         else
12796           {
12797             placement_vec = make_tree_vector ();
12798             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
12799               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
12800           }
12801
12802         /* If there was an initializer in the original tree, but it
12803            instantiated to an empty list, then we should pass a
12804            non-NULL empty vector to tell build_new that it was an
12805            empty initializer() rather than no initializer.  This can
12806            only happen when the initializer is a pack expansion whose
12807            parameter packs are of length zero.  */
12808         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
12809           init_vec = NULL;
12810         else
12811           {
12812             init_vec = make_tree_vector ();
12813             if (init == void_zero_node)
12814               gcc_assert (init_vec != NULL);
12815             else
12816               {
12817                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
12818                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
12819               }
12820           }
12821
12822         ret = build_new (&placement_vec,
12823                          tsubst (TREE_OPERAND (t, 1), args, complain, in_decl),
12824                          RECUR (TREE_OPERAND (t, 2)),
12825                          &init_vec,
12826                          NEW_EXPR_USE_GLOBAL (t),
12827                          complain);
12828
12829         if (placement_vec != NULL)
12830           release_tree_vector (placement_vec);
12831         if (init_vec != NULL)
12832           release_tree_vector (init_vec);
12833
12834         return ret;
12835       }
12836
12837     case DELETE_EXPR:
12838      return delete_sanity
12839        (RECUR (TREE_OPERAND (t, 0)),
12840         RECUR (TREE_OPERAND (t, 1)),
12841         DELETE_EXPR_USE_VEC (t),
12842         DELETE_EXPR_USE_GLOBAL (t));
12843
12844     case COMPOUND_EXPR:
12845       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
12846                                     RECUR (TREE_OPERAND (t, 1)),
12847                                     complain);
12848
12849     case CALL_EXPR:
12850       {
12851         tree function;
12852         VEC(tree,gc) *call_args;
12853         unsigned int nargs, i;
12854         bool qualified_p;
12855         bool koenig_p;
12856         tree ret;
12857
12858         function = CALL_EXPR_FN (t);
12859         /* When we parsed the expression,  we determined whether or
12860            not Koenig lookup should be performed.  */
12861         koenig_p = KOENIG_LOOKUP_P (t);
12862         if (TREE_CODE (function) == SCOPE_REF)
12863           {
12864             qualified_p = true;
12865             function = tsubst_qualified_id (function, args, complain, in_decl,
12866                                             /*done=*/false,
12867                                             /*address_p=*/false);
12868           }
12869         else
12870           {
12871             if (TREE_CODE (function) == COMPONENT_REF)
12872               {
12873                 tree op = TREE_OPERAND (function, 1);
12874
12875                 qualified_p = (TREE_CODE (op) == SCOPE_REF
12876                                || (BASELINK_P (op)
12877                                    && BASELINK_QUALIFIED_P (op)));
12878               }
12879             else
12880               qualified_p = false;
12881
12882             function = tsubst_copy_and_build (function, args, complain,
12883                                               in_decl,
12884                                               !qualified_p,
12885                                               integral_constant_expression_p);
12886
12887             if (BASELINK_P (function))
12888               qualified_p = true;
12889           }
12890
12891         nargs = call_expr_nargs (t);
12892         call_args = make_tree_vector ();
12893         for (i = 0; i < nargs; ++i)
12894           {
12895             tree arg = CALL_EXPR_ARG (t, i);
12896
12897             if (!PACK_EXPANSION_P (arg))
12898               VEC_safe_push (tree, gc, call_args,
12899                              RECUR (CALL_EXPR_ARG (t, i)));
12900             else
12901               {
12902                 /* Expand the pack expansion and push each entry onto
12903                    CALL_ARGS.  */
12904                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
12905                 if (TREE_CODE (arg) == TREE_VEC)
12906                   {
12907                     unsigned int len, j;
12908
12909                     len = TREE_VEC_LENGTH (arg);
12910                     for (j = 0; j < len; ++j)
12911                       {
12912                         tree value = TREE_VEC_ELT (arg, j);
12913                         if (value != NULL_TREE)
12914                           value = convert_from_reference (value);
12915                         VEC_safe_push (tree, gc, call_args, value);
12916                       }
12917                   }
12918                 else
12919                   {
12920                     /* A partial substitution.  Add one entry.  */
12921                     VEC_safe_push (tree, gc, call_args, arg);
12922                   }
12923               }
12924           }
12925
12926         /* We do not perform argument-dependent lookup if normal
12927            lookup finds a non-function, in accordance with the
12928            expected resolution of DR 218.  */
12929         if (koenig_p
12930             && ((is_overloaded_fn (function)
12931                  /* If lookup found a member function, the Koenig lookup is
12932                     not appropriate, even if an unqualified-name was used
12933                     to denote the function.  */
12934                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
12935                 || TREE_CODE (function) == IDENTIFIER_NODE)
12936             /* Only do this when substitution turns a dependent call
12937                into a non-dependent call.  */
12938             && type_dependent_expression_p_push (t)
12939             && !any_type_dependent_arguments_p (call_args))
12940           function = perform_koenig_lookup (function, call_args, false);
12941
12942         if (TREE_CODE (function) == IDENTIFIER_NODE)
12943           {
12944             unqualified_name_lookup_error (function);
12945             release_tree_vector (call_args);
12946             return error_mark_node;
12947           }
12948
12949         /* Remember that there was a reference to this entity.  */
12950         if (DECL_P (function))
12951           mark_used (function);
12952
12953         if (TREE_CODE (function) == OFFSET_REF)
12954           ret = build_offset_ref_call_from_tree (function, &call_args);
12955         else if (TREE_CODE (function) == COMPONENT_REF)
12956           {
12957             tree instance = TREE_OPERAND (function, 0);
12958             tree fn = TREE_OPERAND (function, 1);
12959
12960             if (processing_template_decl
12961                 && (type_dependent_expression_p (instance)
12962                     || (!BASELINK_P (fn)
12963                         && TREE_CODE (fn) != FIELD_DECL)
12964                     || type_dependent_expression_p (fn)
12965                     || any_type_dependent_arguments_p (call_args)))
12966               ret = build_nt_call_vec (function, call_args);
12967             else if (!BASELINK_P (fn))
12968               ret = finish_call_expr (function, &call_args,
12969                                        /*disallow_virtual=*/false,
12970                                        /*koenig_p=*/false,
12971                                        complain);
12972             else
12973               ret = (build_new_method_call
12974                       (instance, fn,
12975                        &call_args, NULL_TREE,
12976                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
12977                        /*fn_p=*/NULL,
12978                        complain));
12979           }
12980         else
12981           ret = finish_call_expr (function, &call_args,
12982                                   /*disallow_virtual=*/qualified_p,
12983                                   koenig_p,
12984                                   complain);
12985
12986         release_tree_vector (call_args);
12987
12988         return ret;
12989       }
12990
12991     case COND_EXPR:
12992       return build_x_conditional_expr
12993         (RECUR (TREE_OPERAND (t, 0)),
12994          RECUR (TREE_OPERAND (t, 1)),
12995          RECUR (TREE_OPERAND (t, 2)),
12996          complain);
12997
12998     case PSEUDO_DTOR_EXPR:
12999       return finish_pseudo_destructor_expr
13000         (RECUR (TREE_OPERAND (t, 0)),
13001          RECUR (TREE_OPERAND (t, 1)),
13002          tsubst (TREE_OPERAND (t, 2), args, complain, in_decl));
13003
13004     case TREE_LIST:
13005       {
13006         tree purpose, value, chain;
13007
13008         if (t == void_list_node)
13009           return t;
13010
13011         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
13012             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
13013           {
13014             /* We have pack expansions, so expand those and
13015                create a new list out of it.  */
13016             tree purposevec = NULL_TREE;
13017             tree valuevec = NULL_TREE;
13018             tree chain;
13019             int i, len = -1;
13020
13021             /* Expand the argument expressions.  */
13022             if (TREE_PURPOSE (t))
13023               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
13024                                                  complain, in_decl);
13025             if (TREE_VALUE (t))
13026               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
13027                                                complain, in_decl);
13028
13029             /* Build the rest of the list.  */
13030             chain = TREE_CHAIN (t);
13031             if (chain && chain != void_type_node)
13032               chain = RECUR (chain);
13033
13034             /* Determine the number of arguments.  */
13035             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
13036               {
13037                 len = TREE_VEC_LENGTH (purposevec);
13038                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
13039               }
13040             else if (TREE_CODE (valuevec) == TREE_VEC)
13041               len = TREE_VEC_LENGTH (valuevec);
13042             else
13043               {
13044                 /* Since we only performed a partial substitution into
13045                    the argument pack, we only return a single list
13046                    node.  */
13047                 if (purposevec == TREE_PURPOSE (t)
13048                     && valuevec == TREE_VALUE (t)
13049                     && chain == TREE_CHAIN (t))
13050                   return t;
13051
13052                 return tree_cons (purposevec, valuevec, chain);
13053               }
13054             
13055             /* Convert the argument vectors into a TREE_LIST */
13056             i = len;
13057             while (i > 0)
13058               {
13059                 /* Grab the Ith values.  */
13060                 i--;
13061                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
13062                                      : NULL_TREE;
13063                 value 
13064                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
13065                              : NULL_TREE;
13066
13067                 /* Build the list (backwards).  */
13068                 chain = tree_cons (purpose, value, chain);
13069               }
13070
13071             return chain;
13072           }
13073
13074         purpose = TREE_PURPOSE (t);
13075         if (purpose)
13076           purpose = RECUR (purpose);
13077         value = TREE_VALUE (t);
13078         if (value)
13079           value = RECUR (value);
13080         chain = TREE_CHAIN (t);
13081         if (chain && chain != void_type_node)
13082           chain = RECUR (chain);
13083         if (purpose == TREE_PURPOSE (t)
13084             && value == TREE_VALUE (t)
13085             && chain == TREE_CHAIN (t))
13086           return t;
13087         return tree_cons (purpose, value, chain);
13088       }
13089
13090     case COMPONENT_REF:
13091       {
13092         tree object;
13093         tree object_type;
13094         tree member;
13095
13096         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13097                                                      args, complain, in_decl);
13098         /* Remember that there was a reference to this entity.  */
13099         if (DECL_P (object))
13100           mark_used (object);
13101         object_type = TREE_TYPE (object);
13102
13103         member = TREE_OPERAND (t, 1);
13104         if (BASELINK_P (member))
13105           member = tsubst_baselink (member,
13106                                     non_reference (TREE_TYPE (object)),
13107                                     args, complain, in_decl);
13108         else
13109           member = tsubst_copy (member, args, complain, in_decl);
13110         if (member == error_mark_node)
13111           return error_mark_node;
13112
13113         if (object_type && !CLASS_TYPE_P (object_type))
13114           {
13115             if (SCALAR_TYPE_P (object_type))
13116               {
13117                 tree s = NULL_TREE;
13118                 tree dtor = member;
13119
13120                 if (TREE_CODE (dtor) == SCOPE_REF)
13121                   {
13122                     s = TREE_OPERAND (dtor, 0);
13123                     dtor = TREE_OPERAND (dtor, 1);
13124                   }
13125                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
13126                   {
13127                     dtor = TREE_OPERAND (dtor, 0);
13128                     if (TYPE_P (dtor))
13129                       return finish_pseudo_destructor_expr (object, s, dtor);
13130                   }
13131               }
13132           }
13133         else if (TREE_CODE (member) == SCOPE_REF
13134                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
13135           {
13136             tree tmpl;
13137             tree args;
13138
13139             /* Lookup the template functions now that we know what the
13140                scope is.  */
13141             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
13142             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
13143             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
13144                                             /*is_type_p=*/false,
13145                                             /*complain=*/false);
13146             if (BASELINK_P (member))
13147               {
13148                 BASELINK_FUNCTIONS (member)
13149                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
13150                               args);
13151                 member = (adjust_result_of_qualified_name_lookup
13152                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
13153                            object_type));
13154               }
13155             else
13156               {
13157                 qualified_name_lookup_error (object_type, tmpl, member,
13158                                              input_location);
13159                 return error_mark_node;
13160               }
13161           }
13162         else if (TREE_CODE (member) == SCOPE_REF
13163                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
13164                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
13165           {
13166             if (complain & tf_error)
13167               {
13168                 if (TYPE_P (TREE_OPERAND (member, 0)))
13169                   error ("%qT is not a class or namespace",
13170                          TREE_OPERAND (member, 0));
13171                 else
13172                   error ("%qD is not a class or namespace",
13173                          TREE_OPERAND (member, 0));
13174               }
13175             return error_mark_node;
13176           }
13177         else if (TREE_CODE (member) == FIELD_DECL)
13178           return finish_non_static_data_member (member, object, NULL_TREE);
13179
13180         return finish_class_member_access_expr (object, member,
13181                                                 /*template_p=*/false,
13182                                                 complain);
13183       }
13184
13185     case THROW_EXPR:
13186       return build_throw
13187         (RECUR (TREE_OPERAND (t, 0)));
13188
13189     case CONSTRUCTOR:
13190       {
13191         VEC(constructor_elt,gc) *n;
13192         constructor_elt *ce;
13193         unsigned HOST_WIDE_INT idx;
13194         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13195         bool process_index_p;
13196         int newlen;
13197         bool need_copy_p = false;
13198         tree r;
13199
13200         if (type == error_mark_node)
13201           return error_mark_node;
13202
13203         /* digest_init will do the wrong thing if we let it.  */
13204         if (type && TYPE_PTRMEMFUNC_P (type))
13205           return t;
13206
13207         /* We do not want to process the index of aggregate
13208            initializers as they are identifier nodes which will be
13209            looked up by digest_init.  */
13210         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
13211
13212         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
13213         newlen = VEC_length (constructor_elt, n);
13214         FOR_EACH_VEC_ELT (constructor_elt, n, idx, ce)
13215           {
13216             if (ce->index && process_index_p)
13217               ce->index = RECUR (ce->index);
13218
13219             if (PACK_EXPANSION_P (ce->value))
13220               {
13221                 /* Substitute into the pack expansion.  */
13222                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
13223                                                   in_decl);
13224
13225                 if (ce->value == error_mark_node)
13226                   ;
13227                 else if (TREE_VEC_LENGTH (ce->value) == 1)
13228                   /* Just move the argument into place.  */
13229                   ce->value = TREE_VEC_ELT (ce->value, 0);
13230                 else
13231                   {
13232                     /* Update the length of the final CONSTRUCTOR
13233                        arguments vector, and note that we will need to
13234                        copy.*/
13235                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
13236                     need_copy_p = true;
13237                   }
13238               }
13239             else
13240               ce->value = RECUR (ce->value);
13241           }
13242
13243         if (need_copy_p)
13244           {
13245             VEC(constructor_elt,gc) *old_n = n;
13246
13247             n = VEC_alloc (constructor_elt, gc, newlen);
13248             FOR_EACH_VEC_ELT (constructor_elt, old_n, idx, ce)
13249               {
13250                 if (TREE_CODE (ce->value) == TREE_VEC)
13251                   {
13252                     int i, len = TREE_VEC_LENGTH (ce->value);
13253                     for (i = 0; i < len; ++i)
13254                       CONSTRUCTOR_APPEND_ELT (n, 0,
13255                                               TREE_VEC_ELT (ce->value, i));
13256                   }
13257                 else
13258                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
13259               }
13260           }
13261
13262         r = build_constructor (init_list_type_node, n);
13263         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
13264
13265         if (TREE_HAS_CONSTRUCTOR (t))
13266           return finish_compound_literal (type, r);
13267
13268         TREE_TYPE (r) = type;
13269         return r;
13270       }
13271
13272     case TYPEID_EXPR:
13273       {
13274         tree operand_0 = TREE_OPERAND (t, 0);
13275         if (TYPE_P (operand_0))
13276           {
13277             operand_0 = tsubst (operand_0, args, complain, in_decl);
13278             return get_typeid (operand_0);
13279           }
13280         else
13281           {
13282             operand_0 = RECUR (operand_0);
13283             return build_typeid (operand_0);
13284           }
13285       }
13286
13287     case VAR_DECL:
13288       if (!args)
13289         return t;
13290       /* Fall through */
13291
13292     case PARM_DECL:
13293       {
13294         tree r = tsubst_copy (t, args, complain, in_decl);
13295
13296         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
13297           /* If the original type was a reference, we'll be wrapped in
13298              the appropriate INDIRECT_REF.  */
13299           r = convert_from_reference (r);
13300         return r;
13301       }
13302
13303     case VA_ARG_EXPR:
13304       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
13305                              tsubst (TREE_TYPE (t), args, complain, in_decl));
13306
13307     case OFFSETOF_EXPR:
13308       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
13309
13310     case TRAIT_EXPR:
13311       {
13312         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
13313                                   complain, in_decl);
13314
13315         tree type2 = TRAIT_EXPR_TYPE2 (t);
13316         if (type2)
13317           type2 = tsubst_copy (type2, args, complain, in_decl);
13318         
13319         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
13320       }
13321
13322     case STMT_EXPR:
13323       {
13324         tree old_stmt_expr = cur_stmt_expr;
13325         tree stmt_expr = begin_stmt_expr ();
13326
13327         cur_stmt_expr = stmt_expr;
13328         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
13329                      integral_constant_expression_p);
13330         stmt_expr = finish_stmt_expr (stmt_expr, false);
13331         cur_stmt_expr = old_stmt_expr;
13332
13333         /* If the resulting list of expression statement is empty,
13334            fold it further into void_zero_node.  */
13335         if (empty_expr_stmt_p (stmt_expr))
13336           stmt_expr = void_zero_node;
13337
13338         return stmt_expr;
13339       }
13340
13341     case CONST_DECL:
13342       t = tsubst_copy (t, args, complain, in_decl);
13343       /* As in finish_id_expression, we resolve enumeration constants
13344          to their underlying values.  */
13345       if (TREE_CODE (t) == CONST_DECL)
13346         {
13347           used_types_insert (TREE_TYPE (t));
13348           return DECL_INITIAL (t);
13349         }
13350       return t;
13351
13352     case LAMBDA_EXPR:
13353       {
13354         tree r = build_lambda_expr ();
13355
13356         tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
13357         TREE_TYPE (r) = type;
13358         CLASSTYPE_LAMBDA_EXPR (type) = r;
13359
13360         LAMBDA_EXPR_LOCATION (r)
13361           = LAMBDA_EXPR_LOCATION (t);
13362         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
13363           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
13364         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
13365         LAMBDA_EXPR_DISCRIMINATOR (r)
13366           = (LAMBDA_EXPR_DISCRIMINATOR (t));
13367         LAMBDA_EXPR_CAPTURE_LIST (r)
13368           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
13369         LAMBDA_EXPR_THIS_CAPTURE (r)
13370           = RECUR (LAMBDA_EXPR_THIS_CAPTURE (t));
13371         LAMBDA_EXPR_EXTRA_SCOPE (r)
13372           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
13373
13374         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
13375         determine_visibility (TYPE_NAME (type));
13376         /* Now that we know visibility, instantiate the type so we have a
13377            declaration of the op() for later calls to lambda_function.  */
13378         complete_type (type);
13379
13380         type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
13381         if (type)
13382           apply_lambda_return_type (r, type);
13383
13384         return build_lambda_object (r);
13385       }
13386
13387     case TARGET_EXPR:
13388       /* We can get here for a constant initializer of non-dependent type.
13389          FIXME stop folding in cp_parser_initializer_clause.  */
13390       gcc_assert (TREE_CONSTANT (t));
13391       {
13392         tree r = get_target_expr (RECUR (TARGET_EXPR_INITIAL (t)));
13393         TREE_CONSTANT (r) = true;
13394         return r;
13395       }
13396
13397     default:
13398       /* Handle Objective-C++ constructs, if appropriate.  */
13399       {
13400         tree subst
13401           = objcp_tsubst_copy_and_build (t, args, complain,
13402                                          in_decl, /*function_p=*/false);
13403         if (subst)
13404           return subst;
13405       }
13406       return tsubst_copy (t, args, complain, in_decl);
13407     }
13408
13409 #undef RECUR
13410 }
13411
13412 /* Verify that the instantiated ARGS are valid. For type arguments,
13413    make sure that the type's linkage is ok. For non-type arguments,
13414    make sure they are constants if they are integral or enumerations.
13415    Emit an error under control of COMPLAIN, and return TRUE on error.  */
13416
13417 static bool
13418 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
13419 {
13420   if (ARGUMENT_PACK_P (t))
13421     {
13422       tree vec = ARGUMENT_PACK_ARGS (t);
13423       int len = TREE_VEC_LENGTH (vec);
13424       bool result = false;
13425       int i;
13426
13427       for (i = 0; i < len; ++i)
13428         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
13429           result = true;
13430       return result;
13431     }
13432   else if (TYPE_P (t))
13433     {
13434       /* [basic.link]: A name with no linkage (notably, the name
13435          of a class or enumeration declared in a local scope)
13436          shall not be used to declare an entity with linkage.
13437          This implies that names with no linkage cannot be used as
13438          template arguments
13439
13440          DR 757 relaxes this restriction for C++0x.  */
13441       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
13442                  : no_linkage_check (t, /*relaxed_p=*/false));
13443
13444       if (nt)
13445         {
13446           /* DR 488 makes use of a type with no linkage cause
13447              type deduction to fail.  */
13448           if (complain & tf_error)
13449             {
13450               if (TYPE_ANONYMOUS_P (nt))
13451                 error ("%qT is/uses anonymous type", t);
13452               else
13453                 error ("template argument for %qD uses local type %qT",
13454                        tmpl, t);
13455             }
13456           return true;
13457         }
13458       /* In order to avoid all sorts of complications, we do not
13459          allow variably-modified types as template arguments.  */
13460       else if (variably_modified_type_p (t, NULL_TREE))
13461         {
13462           if (complain & tf_error)
13463             error ("%qT is a variably modified type", t);
13464           return true;
13465         }
13466     }
13467   /* A non-type argument of integral or enumerated type must be a
13468      constant.  */
13469   else if (TREE_TYPE (t)
13470            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
13471            && !TREE_CONSTANT (t))
13472     {
13473       if (complain & tf_error)
13474         error ("integral expression %qE is not constant", t);
13475       return true;
13476     }
13477   return false;
13478 }
13479
13480 static bool
13481 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
13482 {
13483   int ix, len = DECL_NTPARMS (tmpl);
13484   bool result = false;
13485
13486   for (ix = 0; ix != len; ix++)
13487     {
13488       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
13489         result = true;
13490     }
13491   if (result && (complain & tf_error))
13492     error ("  trying to instantiate %qD", tmpl);
13493   return result;
13494 }
13495
13496 /* Instantiate the indicated variable or function template TMPL with
13497    the template arguments in TARG_PTR.  */
13498
13499 tree
13500 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
13501 {
13502   tree targ_ptr = orig_args;
13503   tree fndecl;
13504   tree gen_tmpl;
13505   tree spec;
13506   HOST_WIDE_INT saved_processing_template_decl;
13507
13508   if (tmpl == error_mark_node)
13509     return error_mark_node;
13510
13511   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
13512
13513   /* If this function is a clone, handle it specially.  */
13514   if (DECL_CLONED_FUNCTION_P (tmpl))
13515     {
13516       tree spec;
13517       tree clone;
13518
13519       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
13520          DECL_CLONED_FUNCTION.  */
13521       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
13522                                    targ_ptr, complain);
13523       if (spec == error_mark_node)
13524         return error_mark_node;
13525
13526       /* Look for the clone.  */
13527       FOR_EACH_CLONE (clone, spec)
13528         if (DECL_NAME (clone) == DECL_NAME (tmpl))
13529           return clone;
13530       /* We should always have found the clone by now.  */
13531       gcc_unreachable ();
13532       return NULL_TREE;
13533     }
13534
13535   /* Check to see if we already have this specialization.  */
13536   gen_tmpl = most_general_template (tmpl);
13537   if (tmpl != gen_tmpl)
13538     /* The TMPL is a partial instantiation.  To get a full set of
13539        arguments we must add the arguments used to perform the
13540        partial instantiation.  */
13541     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
13542                                             targ_ptr);
13543
13544   /* It would be nice to avoid hashing here and then again in tsubst_decl,
13545      but it doesn't seem to be on the hot path.  */
13546   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
13547
13548   gcc_assert (tmpl == gen_tmpl
13549               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
13550                   == spec)
13551               || fndecl == NULL_TREE);
13552
13553   if (spec != NULL_TREE)
13554     return spec;
13555
13556   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
13557                                complain))
13558     return error_mark_node;
13559
13560   /* We are building a FUNCTION_DECL, during which the access of its
13561      parameters and return types have to be checked.  However this
13562      FUNCTION_DECL which is the desired context for access checking
13563      is not built yet.  We solve this chicken-and-egg problem by
13564      deferring all checks until we have the FUNCTION_DECL.  */
13565   push_deferring_access_checks (dk_deferred);
13566
13567   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
13568      (because, for example, we have encountered a non-dependent
13569      function call in the body of a template function and must now
13570      determine which of several overloaded functions will be called),
13571      within the instantiation itself we are not processing a
13572      template.  */  
13573   saved_processing_template_decl = processing_template_decl;
13574   processing_template_decl = 0;
13575   /* Substitute template parameters to obtain the specialization.  */
13576   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
13577                    targ_ptr, complain, gen_tmpl);
13578   processing_template_decl = saved_processing_template_decl;
13579   if (fndecl == error_mark_node)
13580     return error_mark_node;
13581
13582   /* Now we know the specialization, compute access previously
13583      deferred.  */
13584   push_access_scope (fndecl);
13585
13586   /* Some typedefs referenced from within the template code need to be access
13587      checked at template instantiation time, i.e now. These types were
13588      added to the template at parsing time. Let's get those and perfom
13589      the acces checks then.  */
13590   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
13591   perform_deferred_access_checks ();
13592   pop_access_scope (fndecl);
13593   pop_deferring_access_checks ();
13594
13595   /* The DECL_TI_TEMPLATE should always be the immediate parent
13596      template, not the most general template.  */
13597   DECL_TI_TEMPLATE (fndecl) = tmpl;
13598
13599   /* If we've just instantiated the main entry point for a function,
13600      instantiate all the alternate entry points as well.  We do this
13601      by cloning the instantiation of the main entry point, not by
13602      instantiating the template clones.  */
13603   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
13604     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
13605
13606   return fndecl;
13607 }
13608
13609 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
13610    NARGS elements of the arguments that are being used when calling
13611    it.  TARGS is a vector into which the deduced template arguments
13612    are placed.
13613
13614    Return zero for success, 2 for an incomplete match that doesn't resolve
13615    all the types, and 1 for complete failure.  An error message will be
13616    printed only for an incomplete match.
13617
13618    If FN is a conversion operator, or we are trying to produce a specific
13619    specialization, RETURN_TYPE is the return type desired.
13620
13621    The EXPLICIT_TARGS are explicit template arguments provided via a
13622    template-id.
13623
13624    The parameter STRICT is one of:
13625
13626    DEDUCE_CALL:
13627      We are deducing arguments for a function call, as in
13628      [temp.deduct.call].
13629
13630    DEDUCE_CONV:
13631      We are deducing arguments for a conversion function, as in
13632      [temp.deduct.conv].
13633
13634    DEDUCE_EXACT:
13635      We are deducing arguments when doing an explicit instantiation
13636      as in [temp.explicit], when determining an explicit specialization
13637      as in [temp.expl.spec], or when taking the address of a function
13638      template, as in [temp.deduct.funcaddr].  */
13639
13640 int
13641 fn_type_unification (tree fn,
13642                      tree explicit_targs,
13643                      tree targs,
13644                      const tree *args,
13645                      unsigned int nargs,
13646                      tree return_type,
13647                      unification_kind_t strict,
13648                      int flags)
13649 {
13650   tree parms;
13651   tree fntype;
13652   int result;
13653   bool incomplete_argument_packs_p = false;
13654
13655   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
13656
13657   fntype = TREE_TYPE (fn);
13658   if (explicit_targs)
13659     {
13660       /* [temp.deduct]
13661
13662          The specified template arguments must match the template
13663          parameters in kind (i.e., type, nontype, template), and there
13664          must not be more arguments than there are parameters;
13665          otherwise type deduction fails.
13666
13667          Nontype arguments must match the types of the corresponding
13668          nontype template parameters, or must be convertible to the
13669          types of the corresponding nontype parameters as specified in
13670          _temp.arg.nontype_, otherwise type deduction fails.
13671
13672          All references in the function type of the function template
13673          to the corresponding template parameters are replaced by the
13674          specified template argument values.  If a substitution in a
13675          template parameter or in the function type of the function
13676          template results in an invalid type, type deduction fails.  */
13677       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
13678       int i, len = TREE_VEC_LENGTH (tparms);
13679       tree converted_args;
13680       bool incomplete = false;
13681
13682       if (explicit_targs == error_mark_node)
13683         return 1;
13684
13685       converted_args
13686         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
13687                                   /*require_all_args=*/false,
13688                                   /*use_default_args=*/false));
13689       if (converted_args == error_mark_node)
13690         return 1;
13691
13692       /* Substitute the explicit args into the function type.  This is
13693          necessary so that, for instance, explicitly declared function
13694          arguments can match null pointed constants.  If we were given
13695          an incomplete set of explicit args, we must not do semantic
13696          processing during substitution as we could create partial
13697          instantiations.  */
13698       for (i = 0; i < len; i++)
13699         {
13700           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13701           bool parameter_pack = false;
13702
13703           /* Dig out the actual parm.  */
13704           if (TREE_CODE (parm) == TYPE_DECL
13705               || TREE_CODE (parm) == TEMPLATE_DECL)
13706             {
13707               parm = TREE_TYPE (parm);
13708               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
13709             }
13710           else if (TREE_CODE (parm) == PARM_DECL)
13711             {
13712               parm = DECL_INITIAL (parm);
13713               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
13714             }
13715
13716           if (parameter_pack)
13717             {
13718               int level, idx;
13719               tree targ;
13720               template_parm_level_and_index (parm, &level, &idx);
13721
13722               /* Mark the argument pack as "incomplete". We could
13723                  still deduce more arguments during unification.  */
13724               targ = TMPL_ARG (converted_args, level, idx);
13725               if (targ)
13726                 {
13727                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
13728                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
13729                     = ARGUMENT_PACK_ARGS (targ);
13730                 }
13731
13732               /* We have some incomplete argument packs.  */
13733               incomplete_argument_packs_p = true;
13734             }
13735         }
13736
13737       if (incomplete_argument_packs_p)
13738         /* Any substitution is guaranteed to be incomplete if there
13739            are incomplete argument packs, because we can still deduce
13740            more arguments.  */
13741         incomplete = 1;
13742       else
13743         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
13744
13745       processing_template_decl += incomplete;
13746       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
13747       processing_template_decl -= incomplete;
13748
13749       if (fntype == error_mark_node)
13750         return 1;
13751
13752       /* Place the explicitly specified arguments in TARGS.  */
13753       for (i = NUM_TMPL_ARGS (converted_args); i--;)
13754         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
13755     }
13756
13757   /* Never do unification on the 'this' parameter.  */
13758   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
13759
13760   if (return_type)
13761     {
13762       tree *new_args;
13763
13764       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
13765       new_args = XALLOCAVEC (tree, nargs + 1);
13766       new_args[0] = return_type;
13767       memcpy (new_args + 1, args, nargs * sizeof (tree));
13768       args = new_args;
13769       ++nargs;
13770     }
13771
13772   /* We allow incomplete unification without an error message here
13773      because the standard doesn't seem to explicitly prohibit it.  Our
13774      callers must be ready to deal with unification failures in any
13775      event.  */
13776   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
13777                                   targs, parms, args, nargs, /*subr=*/0,
13778                                   strict, flags);
13779
13780   if (result == 0 && incomplete_argument_packs_p)
13781     {
13782       int i, len = NUM_TMPL_ARGS (targs);
13783
13784       /* Clear the "incomplete" flags on all argument packs.  */
13785       for (i = 0; i < len; i++)
13786         {
13787           tree arg = TREE_VEC_ELT (targs, i);
13788           if (ARGUMENT_PACK_P (arg))
13789             {
13790               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
13791               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
13792             }
13793         }
13794     }
13795
13796   /* Now that we have bindings for all of the template arguments,
13797      ensure that the arguments deduced for the template template
13798      parameters have compatible template parameter lists.  We cannot
13799      check this property before we have deduced all template
13800      arguments, because the template parameter types of a template
13801      template parameter might depend on prior template parameters
13802      deduced after the template template parameter.  The following
13803      ill-formed example illustrates this issue:
13804
13805        template<typename T, template<T> class C> void f(C<5>, T);
13806
13807        template<int N> struct X {};
13808
13809        void g() {
13810          f(X<5>(), 5l); // error: template argument deduction fails
13811        }
13812
13813      The template parameter list of 'C' depends on the template type
13814      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
13815      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
13816      time that we deduce 'C'.  */
13817   if (result == 0
13818       && !template_template_parm_bindings_ok_p 
13819            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
13820     return 1;
13821
13822   if (result == 0)
13823     /* All is well so far.  Now, check:
13824
13825        [temp.deduct]
13826
13827        When all template arguments have been deduced, all uses of
13828        template parameters in nondeduced contexts are replaced with
13829        the corresponding deduced argument values.  If the
13830        substitution results in an invalid type, as described above,
13831        type deduction fails.  */
13832     {
13833       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
13834       if (substed == error_mark_node)
13835         return 1;
13836
13837       /* If we're looking for an exact match, check that what we got
13838          is indeed an exact match.  It might not be if some template
13839          parameters are used in non-deduced contexts.  */
13840       if (strict == DEDUCE_EXACT)
13841         {
13842           unsigned int i;
13843
13844           tree sarg
13845             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
13846           if (return_type)
13847             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
13848           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
13849             if (!same_type_p (args[i], TREE_VALUE (sarg)))
13850               return 1;
13851         }
13852     }
13853
13854   return result;
13855 }
13856
13857 /* Adjust types before performing type deduction, as described in
13858    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
13859    sections are symmetric.  PARM is the type of a function parameter
13860    or the return type of the conversion function.  ARG is the type of
13861    the argument passed to the call, or the type of the value
13862    initialized with the result of the conversion function.
13863    ARG_EXPR is the original argument expression, which may be null.  */
13864
13865 static int
13866 maybe_adjust_types_for_deduction (unification_kind_t strict,
13867                                   tree* parm,
13868                                   tree* arg,
13869                                   tree arg_expr)
13870 {
13871   int result = 0;
13872
13873   switch (strict)
13874     {
13875     case DEDUCE_CALL:
13876       break;
13877
13878     case DEDUCE_CONV:
13879       {
13880         /* Swap PARM and ARG throughout the remainder of this
13881            function; the handling is precisely symmetric since PARM
13882            will initialize ARG rather than vice versa.  */
13883         tree* temp = parm;
13884         parm = arg;
13885         arg = temp;
13886         break;
13887       }
13888
13889     case DEDUCE_EXACT:
13890       /* Core issue #873: Do the DR606 thing (see below) for these cases,
13891          too, but here handle it by stripping the reference from PARM
13892          rather than by adding it to ARG.  */
13893       if (TREE_CODE (*parm) == REFERENCE_TYPE
13894           && TYPE_REF_IS_RVALUE (*parm)
13895           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13896           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13897           && TREE_CODE (*arg) == REFERENCE_TYPE
13898           && !TYPE_REF_IS_RVALUE (*arg))
13899         *parm = TREE_TYPE (*parm);
13900       /* Nothing else to do in this case.  */
13901       return 0;
13902
13903     default:
13904       gcc_unreachable ();
13905     }
13906
13907   if (TREE_CODE (*parm) != REFERENCE_TYPE)
13908     {
13909       /* [temp.deduct.call]
13910
13911          If P is not a reference type:
13912
13913          --If A is an array type, the pointer type produced by the
13914          array-to-pointer standard conversion (_conv.array_) is
13915          used in place of A for type deduction; otherwise,
13916
13917          --If A is a function type, the pointer type produced by
13918          the function-to-pointer standard conversion
13919          (_conv.func_) is used in place of A for type deduction;
13920          otherwise,
13921
13922          --If A is a cv-qualified type, the top level
13923          cv-qualifiers of A's type are ignored for type
13924          deduction.  */
13925       if (TREE_CODE (*arg) == ARRAY_TYPE)
13926         *arg = build_pointer_type (TREE_TYPE (*arg));
13927       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
13928         *arg = build_pointer_type (*arg);
13929       else
13930         *arg = TYPE_MAIN_VARIANT (*arg);
13931     }
13932
13933   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
13934      of the form T&&, where T is a template parameter, and the argument
13935      is an lvalue, T is deduced as A& */
13936   if (TREE_CODE (*parm) == REFERENCE_TYPE
13937       && TYPE_REF_IS_RVALUE (*parm)
13938       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13939       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13940       && arg_expr && real_lvalue_p (arg_expr))
13941     *arg = build_reference_type (*arg);
13942
13943   /* [temp.deduct.call]
13944
13945      If P is a cv-qualified type, the top level cv-qualifiers
13946      of P's type are ignored for type deduction.  If P is a
13947      reference type, the type referred to by P is used for
13948      type deduction.  */
13949   *parm = TYPE_MAIN_VARIANT (*parm);
13950   if (TREE_CODE (*parm) == REFERENCE_TYPE)
13951     {
13952       *parm = TREE_TYPE (*parm);
13953       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13954     }
13955
13956   /* DR 322. For conversion deduction, remove a reference type on parm
13957      too (which has been swapped into ARG).  */
13958   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
13959     *arg = TREE_TYPE (*arg);
13960
13961   return result;
13962 }
13963
13964 /* Most parms like fn_type_unification.
13965
13966    If SUBR is 1, we're being called recursively (to unify the
13967    arguments of a function or method parameter of a function
13968    template). */
13969
13970 static int
13971 type_unification_real (tree tparms,
13972                        tree targs,
13973                        tree xparms,
13974                        const tree *xargs,
13975                        unsigned int xnargs,
13976                        int subr,
13977                        unification_kind_t strict,
13978                        int flags)
13979 {
13980   tree parm, arg, arg_expr;
13981   int i;
13982   int ntparms = TREE_VEC_LENGTH (tparms);
13983   int sub_strict;
13984   int saw_undeduced = 0;
13985   tree parms;
13986   const tree *args;
13987   unsigned int nargs;
13988   unsigned int ia;
13989
13990   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
13991   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
13992   gcc_assert (ntparms > 0);
13993
13994   /* Reset the number of non-defaulted template arguments contained
13995      in in TARGS.  */
13996   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
13997
13998   switch (strict)
13999     {
14000     case DEDUCE_CALL:
14001       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
14002                     | UNIFY_ALLOW_DERIVED);
14003       break;
14004
14005     case DEDUCE_CONV:
14006       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14007       break;
14008
14009     case DEDUCE_EXACT:
14010       sub_strict = UNIFY_ALLOW_NONE;
14011       break;
14012
14013     default:
14014       gcc_unreachable ();
14015     }
14016
14017  again:
14018   parms = xparms;
14019   args = xargs;
14020   nargs = xnargs;
14021
14022   ia = 0;
14023   while (parms && parms != void_list_node
14024          && ia < nargs)
14025     {
14026       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
14027         break;
14028
14029       parm = TREE_VALUE (parms);
14030       parms = TREE_CHAIN (parms);
14031       arg = args[ia];
14032       ++ia;
14033       arg_expr = NULL;
14034
14035       if (arg == error_mark_node)
14036         return 1;
14037       if (arg == unknown_type_node)
14038         /* We can't deduce anything from this, but we might get all the
14039            template args from other function args.  */
14040         continue;
14041
14042       /* Conversions will be performed on a function argument that
14043          corresponds with a function parameter that contains only
14044          non-deducible template parameters and explicitly specified
14045          template parameters.  */
14046       if (!uses_template_parms (parm))
14047         {
14048           tree type;
14049
14050           if (!TYPE_P (arg))
14051             type = TREE_TYPE (arg);
14052           else
14053             type = arg;
14054
14055           if (same_type_p (parm, type))
14056             continue;
14057           if (strict != DEDUCE_EXACT
14058               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
14059                                   flags))
14060             continue;
14061
14062           return 1;
14063         }
14064
14065       if (!TYPE_P (arg))
14066         {
14067           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14068           if (type_unknown_p (arg))
14069             {
14070               /* [temp.deduct.type] 
14071
14072                  A template-argument can be deduced from a pointer to
14073                  function or pointer to member function argument if
14074                  the set of overloaded functions does not contain
14075                  function templates and at most one of a set of
14076                  overloaded functions provides a unique match.  */
14077               if (resolve_overloaded_unification
14078                   (tparms, targs, parm, arg, strict, sub_strict))
14079                 continue;
14080
14081               return 1;
14082             }
14083           arg_expr = arg;
14084           arg = unlowered_expr_type (arg);
14085           if (arg == error_mark_node)
14086             return 1;
14087         }
14088
14089       {
14090         int arg_strict = sub_strict;
14091
14092         if (!subr)
14093           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
14094                                                           arg_expr);
14095
14096         if (arg == init_list_type_node && arg_expr)
14097           arg = arg_expr;
14098         if (unify (tparms, targs, parm, arg, arg_strict))
14099           return 1;
14100       }
14101     }
14102
14103
14104   if (parms 
14105       && parms != void_list_node
14106       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
14107     {
14108       /* Unify the remaining arguments with the pack expansion type.  */
14109       tree argvec;
14110       tree parmvec = make_tree_vec (1);
14111
14112       /* Allocate a TREE_VEC and copy in all of the arguments */ 
14113       argvec = make_tree_vec (nargs - ia);
14114       for (i = 0; ia < nargs; ++ia, ++i)
14115         TREE_VEC_ELT (argvec, i) = args[ia];
14116
14117       /* Copy the parameter into parmvec.  */
14118       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
14119       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
14120                                 /*call_args_p=*/true, /*subr=*/subr))
14121         return 1;
14122
14123       /* Advance to the end of the list of parameters.  */
14124       parms = TREE_CHAIN (parms);
14125     }
14126
14127   /* Fail if we've reached the end of the parm list, and more args
14128      are present, and the parm list isn't variadic.  */
14129   if (ia < nargs && parms == void_list_node)
14130     return 1;
14131   /* Fail if parms are left and they don't have default values.  */
14132   if (parms && parms != void_list_node
14133       && TREE_PURPOSE (parms) == NULL_TREE)
14134     return 1;
14135
14136   if (!subr)
14137     for (i = 0; i < ntparms; i++)
14138       if (!TREE_VEC_ELT (targs, i))
14139         {
14140           tree tparm;
14141
14142           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
14143             continue;
14144
14145           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
14146
14147           /* If this is an undeduced nontype parameter that depends on
14148              a type parameter, try another pass; its type may have been
14149              deduced from a later argument than the one from which
14150              this parameter can be deduced.  */
14151           if (TREE_CODE (tparm) == PARM_DECL
14152               && uses_template_parms (TREE_TYPE (tparm))
14153               && !saw_undeduced++)
14154             goto again;
14155
14156           /* Core issue #226 (C++0x) [temp.deduct]:
14157
14158                If a template argument has not been deduced, its
14159                default template argument, if any, is used. 
14160
14161              When we are in C++98 mode, TREE_PURPOSE will either
14162              be NULL_TREE or ERROR_MARK_NODE, so we do not need
14163              to explicitly check cxx_dialect here.  */
14164           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
14165             {
14166               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
14167               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
14168               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
14169               arg = convert_template_argument (parm, arg, targs, tf_none,
14170                                                i, NULL_TREE);
14171               if (arg == error_mark_node)
14172                 return 1;
14173               else
14174                 {
14175                   TREE_VEC_ELT (targs, i) = arg;
14176                   /* The position of the first default template argument,
14177                      is also the number of non-defaulted arguments in TARGS.
14178                      Record that.  */
14179                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
14180                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
14181                   continue;
14182                 }
14183             }
14184
14185           /* If the type parameter is a parameter pack, then it will
14186              be deduced to an empty parameter pack.  */
14187           if (template_parameter_pack_p (tparm))
14188             {
14189               tree arg;
14190
14191               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
14192                 {
14193                   arg = make_node (NONTYPE_ARGUMENT_PACK);
14194                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
14195                   TREE_CONSTANT (arg) = 1;
14196                 }
14197               else
14198                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
14199
14200               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
14201
14202               TREE_VEC_ELT (targs, i) = arg;
14203               continue;
14204             }
14205
14206           return 2;
14207         }
14208 #ifdef ENABLE_CHECKING
14209   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
14210     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
14211 #endif
14212
14213   return 0;
14214 }
14215
14216 /* Subroutine of type_unification_real.  Args are like the variables
14217    at the call site.  ARG is an overloaded function (or template-id);
14218    we try deducing template args from each of the overloads, and if
14219    only one succeeds, we go with that.  Modifies TARGS and returns
14220    true on success.  */
14221
14222 static bool
14223 resolve_overloaded_unification (tree tparms,
14224                                 tree targs,
14225                                 tree parm,
14226                                 tree arg,
14227                                 unification_kind_t strict,
14228                                 int sub_strict)
14229 {
14230   tree tempargs = copy_node (targs);
14231   int good = 0;
14232   tree goodfn = NULL_TREE;
14233   bool addr_p;
14234
14235   if (TREE_CODE (arg) == ADDR_EXPR)
14236     {
14237       arg = TREE_OPERAND (arg, 0);
14238       addr_p = true;
14239     }
14240   else
14241     addr_p = false;
14242
14243   if (TREE_CODE (arg) == COMPONENT_REF)
14244     /* Handle `&x' where `x' is some static or non-static member
14245        function name.  */
14246     arg = TREE_OPERAND (arg, 1);
14247
14248   if (TREE_CODE (arg) == OFFSET_REF)
14249     arg = TREE_OPERAND (arg, 1);
14250
14251   /* Strip baselink information.  */
14252   if (BASELINK_P (arg))
14253     arg = BASELINK_FUNCTIONS (arg);
14254
14255   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
14256     {
14257       /* If we got some explicit template args, we need to plug them into
14258          the affected templates before we try to unify, in case the
14259          explicit args will completely resolve the templates in question.  */
14260
14261       tree expl_subargs = TREE_OPERAND (arg, 1);
14262       arg = TREE_OPERAND (arg, 0);
14263
14264       for (; arg; arg = OVL_NEXT (arg))
14265         {
14266           tree fn = OVL_CURRENT (arg);
14267           tree subargs, elem;
14268
14269           if (TREE_CODE (fn) != TEMPLATE_DECL)
14270             continue;
14271
14272           ++processing_template_decl;
14273           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
14274                                   expl_subargs, /*check_ret=*/false);
14275           if (subargs)
14276             {
14277               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
14278               if (try_one_overload (tparms, targs, tempargs, parm,
14279                                     elem, strict, sub_strict, addr_p)
14280                   && (!goodfn || !decls_match (goodfn, elem)))
14281                 {
14282                   goodfn = elem;
14283                   ++good;
14284                 }
14285             }
14286           --processing_template_decl;
14287         }
14288     }
14289   else if (TREE_CODE (arg) != OVERLOAD
14290            && TREE_CODE (arg) != FUNCTION_DECL)
14291     /* If ARG is, for example, "(0, &f)" then its type will be unknown
14292        -- but the deduction does not succeed because the expression is
14293        not just the function on its own.  */
14294     return false;
14295   else
14296     for (; arg; arg = OVL_NEXT (arg))
14297       if (try_one_overload (tparms, targs, tempargs, parm,
14298                             TREE_TYPE (OVL_CURRENT (arg)),
14299                             strict, sub_strict, addr_p)
14300           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
14301         {
14302           goodfn = OVL_CURRENT (arg);
14303           ++good;
14304         }
14305
14306   /* [temp.deduct.type] A template-argument can be deduced from a pointer
14307      to function or pointer to member function argument if the set of
14308      overloaded functions does not contain function templates and at most
14309      one of a set of overloaded functions provides a unique match.
14310
14311      So if we found multiple possibilities, we return success but don't
14312      deduce anything.  */
14313
14314   if (good == 1)
14315     {
14316       int i = TREE_VEC_LENGTH (targs);
14317       for (; i--; )
14318         if (TREE_VEC_ELT (tempargs, i))
14319           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
14320     }
14321   if (good)
14322     return true;
14323
14324   return false;
14325 }
14326
14327 /* Core DR 115: In contexts where deduction is done and fails, or in
14328    contexts where deduction is not done, if a template argument list is
14329    specified and it, along with any default template arguments, identifies
14330    a single function template specialization, then the template-id is an
14331    lvalue for the function template specialization.  */
14332
14333 tree
14334 resolve_nondeduced_context (tree orig_expr)
14335 {
14336   tree expr, offset, baselink;
14337   bool addr;
14338
14339   if (!type_unknown_p (orig_expr))
14340     return orig_expr;
14341
14342   expr = orig_expr;
14343   addr = false;
14344   offset = NULL_TREE;
14345   baselink = NULL_TREE;
14346
14347   if (TREE_CODE (expr) == ADDR_EXPR)
14348     {
14349       expr = TREE_OPERAND (expr, 0);
14350       addr = true;
14351     }
14352   if (TREE_CODE (expr) == OFFSET_REF)
14353     {
14354       offset = expr;
14355       expr = TREE_OPERAND (expr, 1);
14356     }
14357   if (TREE_CODE (expr) == BASELINK)
14358     {
14359       baselink = expr;
14360       expr = BASELINK_FUNCTIONS (expr);
14361     }
14362
14363   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
14364     {
14365       int good = 0;
14366       tree goodfn = NULL_TREE;
14367
14368       /* If we got some explicit template args, we need to plug them into
14369          the affected templates before we try to unify, in case the
14370          explicit args will completely resolve the templates in question.  */
14371
14372       tree expl_subargs = TREE_OPERAND (expr, 1);
14373       tree arg = TREE_OPERAND (expr, 0);
14374       tree badfn = NULL_TREE;
14375       tree badargs = NULL_TREE;
14376
14377       for (; arg; arg = OVL_NEXT (arg))
14378         {
14379           tree fn = OVL_CURRENT (arg);
14380           tree subargs, elem;
14381
14382           if (TREE_CODE (fn) != TEMPLATE_DECL)
14383             continue;
14384
14385           ++processing_template_decl;
14386           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
14387                                   expl_subargs, /*check_ret=*/false);
14388           if (subargs && !any_dependent_template_arguments_p (subargs))
14389             {
14390               elem = instantiate_template (fn, subargs, tf_none);
14391               if (elem == error_mark_node)
14392                 {
14393                   badfn = fn;
14394                   badargs = subargs;
14395                 }
14396               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
14397                 {
14398                   goodfn = elem;
14399                   ++good;
14400                 }
14401             }
14402           --processing_template_decl;
14403         }
14404       if (good == 1)
14405         {
14406           expr = goodfn;
14407           if (baselink)
14408             expr = build_baselink (BASELINK_BINFO (baselink),
14409                                    BASELINK_ACCESS_BINFO (baselink),
14410                                    expr, BASELINK_OPTYPE (baselink));
14411           if (offset)
14412             {
14413               tree base
14414                 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
14415               expr = build_offset_ref (base, expr, addr);
14416             }
14417           if (addr)
14418             expr = cp_build_addr_expr (expr, tf_warning_or_error);
14419           return expr;
14420         }
14421       else if (good == 0 && badargs)
14422         /* There were no good options and at least one bad one, so let the
14423            user know what the problem is.  */
14424         instantiate_template (badfn, badargs, tf_warning_or_error);
14425     }
14426   return orig_expr;
14427 }
14428
14429 /* Subroutine of resolve_overloaded_unification; does deduction for a single
14430    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
14431    different overloads deduce different arguments for a given parm.
14432    ADDR_P is true if the expression for which deduction is being
14433    performed was of the form "& fn" rather than simply "fn".
14434
14435    Returns 1 on success.  */
14436
14437 static int
14438 try_one_overload (tree tparms,
14439                   tree orig_targs,
14440                   tree targs,
14441                   tree parm,
14442                   tree arg,
14443                   unification_kind_t strict,
14444                   int sub_strict,
14445                   bool addr_p)
14446 {
14447   int nargs;
14448   tree tempargs;
14449   int i;
14450
14451   /* [temp.deduct.type] A template-argument can be deduced from a pointer
14452      to function or pointer to member function argument if the set of
14453      overloaded functions does not contain function templates and at most
14454      one of a set of overloaded functions provides a unique match.
14455
14456      So if this is a template, just return success.  */
14457
14458   if (uses_template_parms (arg))
14459     return 1;
14460
14461   if (TREE_CODE (arg) == METHOD_TYPE)
14462     arg = build_ptrmemfunc_type (build_pointer_type (arg));
14463   else if (addr_p)
14464     arg = build_pointer_type (arg);
14465
14466   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
14467
14468   /* We don't copy orig_targs for this because if we have already deduced
14469      some template args from previous args, unify would complain when we
14470      try to deduce a template parameter for the same argument, even though
14471      there isn't really a conflict.  */
14472   nargs = TREE_VEC_LENGTH (targs);
14473   tempargs = make_tree_vec (nargs);
14474
14475   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
14476     return 0;
14477
14478   /* First make sure we didn't deduce anything that conflicts with
14479      explicitly specified args.  */
14480   for (i = nargs; i--; )
14481     {
14482       tree elt = TREE_VEC_ELT (tempargs, i);
14483       tree oldelt = TREE_VEC_ELT (orig_targs, i);
14484
14485       if (!elt)
14486         /*NOP*/;
14487       else if (uses_template_parms (elt))
14488         /* Since we're unifying against ourselves, we will fill in
14489            template args used in the function parm list with our own
14490            template parms.  Discard them.  */
14491         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
14492       else if (oldelt && !template_args_equal (oldelt, elt))
14493         return 0;
14494     }
14495
14496   for (i = nargs; i--; )
14497     {
14498       tree elt = TREE_VEC_ELT (tempargs, i);
14499
14500       if (elt)
14501         TREE_VEC_ELT (targs, i) = elt;
14502     }
14503
14504   return 1;
14505 }
14506
14507 /* PARM is a template class (perhaps with unbound template
14508    parameters).  ARG is a fully instantiated type.  If ARG can be
14509    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
14510    TARGS are as for unify.  */
14511
14512 static tree
14513 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
14514 {
14515   tree copy_of_targs;
14516
14517   if (!CLASSTYPE_TEMPLATE_INFO (arg)
14518       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
14519           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
14520     return NULL_TREE;
14521
14522   /* We need to make a new template argument vector for the call to
14523      unify.  If we used TARGS, we'd clutter it up with the result of
14524      the attempted unification, even if this class didn't work out.
14525      We also don't want to commit ourselves to all the unifications
14526      we've already done, since unification is supposed to be done on
14527      an argument-by-argument basis.  In other words, consider the
14528      following pathological case:
14529
14530        template <int I, int J, int K>
14531        struct S {};
14532
14533        template <int I, int J>
14534        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
14535
14536        template <int I, int J, int K>
14537        void f(S<I, J, K>, S<I, I, I>);
14538
14539        void g() {
14540          S<0, 0, 0> s0;
14541          S<0, 1, 2> s2;
14542
14543          f(s0, s2);
14544        }
14545
14546      Now, by the time we consider the unification involving `s2', we
14547      already know that we must have `f<0, 0, 0>'.  But, even though
14548      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
14549      because there are two ways to unify base classes of S<0, 1, 2>
14550      with S<I, I, I>.  If we kept the already deduced knowledge, we
14551      would reject the possibility I=1.  */
14552   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
14553
14554   /* If unification failed, we're done.  */
14555   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
14556              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
14557     return NULL_TREE;
14558
14559   return arg;
14560 }
14561
14562 /* Given a template type PARM and a class type ARG, find the unique
14563    base type in ARG that is an instance of PARM.  We do not examine
14564    ARG itself; only its base-classes.  If there is not exactly one
14565    appropriate base class, return NULL_TREE.  PARM may be the type of
14566    a partial specialization, as well as a plain template type.  Used
14567    by unify.  */
14568
14569 static tree
14570 get_template_base (tree tparms, tree targs, tree parm, tree arg)
14571 {
14572   tree rval = NULL_TREE;
14573   tree binfo;
14574
14575   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
14576
14577   binfo = TYPE_BINFO (complete_type (arg));
14578   if (!binfo)
14579     /* The type could not be completed.  */
14580     return NULL_TREE;
14581
14582   /* Walk in inheritance graph order.  The search order is not
14583      important, and this avoids multiple walks of virtual bases.  */
14584   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
14585     {
14586       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
14587
14588       if (r)
14589         {
14590           /* If there is more than one satisfactory baseclass, then:
14591
14592                [temp.deduct.call]
14593
14594               If they yield more than one possible deduced A, the type
14595               deduction fails.
14596
14597              applies.  */
14598           if (rval && !same_type_p (r, rval))
14599             return NULL_TREE;
14600
14601           rval = r;
14602         }
14603     }
14604
14605   return rval;
14606 }
14607
14608 /* Returns the level of DECL, which declares a template parameter.  */
14609
14610 static int
14611 template_decl_level (tree decl)
14612 {
14613   switch (TREE_CODE (decl))
14614     {
14615     case TYPE_DECL:
14616     case TEMPLATE_DECL:
14617       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
14618
14619     case PARM_DECL:
14620       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
14621
14622     default:
14623       gcc_unreachable ();
14624     }
14625   return 0;
14626 }
14627
14628 /* Decide whether ARG can be unified with PARM, considering only the
14629    cv-qualifiers of each type, given STRICT as documented for unify.
14630    Returns nonzero iff the unification is OK on that basis.  */
14631
14632 static int
14633 check_cv_quals_for_unify (int strict, tree arg, tree parm)
14634 {
14635   int arg_quals = cp_type_quals (arg);
14636   int parm_quals = cp_type_quals (parm);
14637
14638   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14639       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14640     {
14641       /*  Although a CVR qualifier is ignored when being applied to a
14642           substituted template parameter ([8.3.2]/1 for example), that
14643           does not allow us to unify "const T" with "int&" because both
14644           types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
14645           It is ok when we're allowing additional CV qualifiers
14646           at the outer level [14.8.2.1]/3,1st bullet.  */
14647       if ((TREE_CODE (arg) == REFERENCE_TYPE
14648            || TREE_CODE (arg) == FUNCTION_TYPE
14649            || TREE_CODE (arg) == METHOD_TYPE)
14650           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
14651         return 0;
14652
14653       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
14654           && (parm_quals & TYPE_QUAL_RESTRICT))
14655         return 0;
14656     }
14657
14658   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14659       && (arg_quals & parm_quals) != parm_quals)
14660     return 0;
14661
14662   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
14663       && (parm_quals & arg_quals) != arg_quals)
14664     return 0;
14665
14666   return 1;
14667 }
14668
14669 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
14670 void 
14671 template_parm_level_and_index (tree parm, int* level, int* index)
14672 {
14673   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14674       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14675       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14676     {
14677       *index = TEMPLATE_TYPE_IDX (parm);
14678       *level = TEMPLATE_TYPE_LEVEL (parm);
14679     }
14680   else
14681     {
14682       *index = TEMPLATE_PARM_IDX (parm);
14683       *level = TEMPLATE_PARM_LEVEL (parm);
14684     }
14685 }
14686
14687 /* Unifies the remaining arguments in PACKED_ARGS with the pack
14688    expansion at the end of PACKED_PARMS. Returns 0 if the type
14689    deduction succeeds, 1 otherwise. STRICT is the same as in
14690    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
14691    call argument list. We'll need to adjust the arguments to make them
14692    types. SUBR tells us if this is from a recursive call to
14693    type_unification_real.  */
14694 int
14695 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
14696                       tree packed_args, int strict, bool call_args_p,
14697                       bool subr)
14698 {
14699   tree parm 
14700     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
14701   tree pattern = PACK_EXPANSION_PATTERN (parm);
14702   tree pack, packs = NULL_TREE;
14703   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
14704   int len = TREE_VEC_LENGTH (packed_args);
14705
14706   /* Determine the parameter packs we will be deducing from the
14707      pattern, and record their current deductions.  */
14708   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
14709        pack; pack = TREE_CHAIN (pack))
14710     {
14711       tree parm_pack = TREE_VALUE (pack);
14712       int idx, level;
14713
14714       /* Determine the index and level of this parameter pack.  */
14715       template_parm_level_and_index (parm_pack, &level, &idx);
14716
14717       /* Keep track of the parameter packs and their corresponding
14718          argument packs.  */
14719       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
14720       TREE_TYPE (packs) = make_tree_vec (len - start);
14721     }
14722   
14723   /* Loop through all of the arguments that have not yet been
14724      unified and unify each with the pattern.  */
14725   for (i = start; i < len; i++)
14726     {
14727       tree parm = pattern;
14728
14729       /* For each parameter pack, clear out the deduced value so that
14730          we can deduce it again.  */
14731       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14732         {
14733           int idx, level;
14734           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14735
14736           TMPL_ARG (targs, level, idx) = NULL_TREE;
14737         }
14738
14739       /* Unify the pattern with the current argument.  */
14740       {
14741         tree arg = TREE_VEC_ELT (packed_args, i);
14742         tree arg_expr = NULL_TREE;
14743         int arg_strict = strict;
14744         bool skip_arg_p = false;
14745
14746         if (call_args_p)
14747           {
14748             int sub_strict;
14749
14750             /* This mirrors what we do in type_unification_real.  */
14751             switch (strict)
14752               {
14753               case DEDUCE_CALL:
14754                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
14755                               | UNIFY_ALLOW_MORE_CV_QUAL
14756                               | UNIFY_ALLOW_DERIVED);
14757                 break;
14758                 
14759               case DEDUCE_CONV:
14760                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14761                 break;
14762                 
14763               case DEDUCE_EXACT:
14764                 sub_strict = UNIFY_ALLOW_NONE;
14765                 break;
14766                 
14767               default:
14768                 gcc_unreachable ();
14769               }
14770
14771             if (!TYPE_P (arg))
14772               {
14773                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14774                 if (type_unknown_p (arg))
14775                   {
14776                     /* [temp.deduct.type] A template-argument can be
14777                        deduced from a pointer to function or pointer
14778                        to member function argument if the set of
14779                        overloaded functions does not contain function
14780                        templates and at most one of a set of
14781                        overloaded functions provides a unique
14782                        match.  */
14783
14784                     if (resolve_overloaded_unification
14785                         (tparms, targs, parm, arg,
14786                          (unification_kind_t) strict,
14787                          sub_strict)
14788                         != 0)
14789                       return 1;
14790                     skip_arg_p = true;
14791                   }
14792
14793                 if (!skip_arg_p)
14794                   {
14795                     arg_expr = arg;
14796                     arg = unlowered_expr_type (arg);
14797                     if (arg == error_mark_node)
14798                       return 1;
14799                   }
14800               }
14801       
14802             arg_strict = sub_strict;
14803
14804             if (!subr)
14805               arg_strict |= 
14806                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
14807                                                   &parm, &arg, arg_expr);
14808           }
14809
14810         if (!skip_arg_p)
14811           {
14812             /* For deduction from an init-list we need the actual list.  */
14813             if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
14814               arg = arg_expr;
14815             if (unify (tparms, targs, parm, arg, arg_strict))
14816               return 1;
14817           }
14818       }
14819
14820       /* For each parameter pack, collect the deduced value.  */
14821       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14822         {
14823           int idx, level;
14824           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14825
14826           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
14827             TMPL_ARG (targs, level, idx);
14828         }
14829     }
14830
14831   /* Verify that the results of unification with the parameter packs
14832      produce results consistent with what we've seen before, and make
14833      the deduced argument packs available.  */
14834   for (pack = packs; pack; pack = TREE_CHAIN (pack))
14835     {
14836       tree old_pack = TREE_VALUE (pack);
14837       tree new_args = TREE_TYPE (pack);
14838       int i, len = TREE_VEC_LENGTH (new_args);
14839       int idx, level;
14840       bool nondeduced_p = false;
14841
14842       /* By default keep the original deduced argument pack.
14843          If necessary, more specific code is going to update the
14844          resulting deduced argument later down in this function.  */
14845       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14846       TMPL_ARG (targs, level, idx) = old_pack;
14847
14848       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
14849          actually deduce anything.  */
14850       for (i = 0; i < len && !nondeduced_p; ++i)
14851         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
14852           nondeduced_p = true;
14853       if (nondeduced_p)
14854         continue;
14855
14856       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
14857         {
14858           /* Prepend the explicit arguments onto NEW_ARGS.  */
14859           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14860           tree old_args = new_args;
14861           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
14862           int len = explicit_len + TREE_VEC_LENGTH (old_args);
14863
14864           /* Copy the explicit arguments.  */
14865           new_args = make_tree_vec (len);
14866           for (i = 0; i < explicit_len; i++)
14867             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
14868
14869           /* Copy the deduced arguments.  */
14870           for (; i < len; i++)
14871             TREE_VEC_ELT (new_args, i) =
14872               TREE_VEC_ELT (old_args, i - explicit_len);
14873         }
14874
14875       if (!old_pack)
14876         {
14877           tree result;
14878           /* Build the deduced *_ARGUMENT_PACK.  */
14879           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
14880             {
14881               result = make_node (NONTYPE_ARGUMENT_PACK);
14882               TREE_TYPE (result) = 
14883                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
14884               TREE_CONSTANT (result) = 1;
14885             }
14886           else
14887             result = cxx_make_type (TYPE_ARGUMENT_PACK);
14888
14889           SET_ARGUMENT_PACK_ARGS (result, new_args);
14890
14891           /* Note the deduced argument packs for this parameter
14892              pack.  */
14893           TMPL_ARG (targs, level, idx) = result;
14894         }
14895       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
14896                && (ARGUMENT_PACK_ARGS (old_pack) 
14897                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
14898         {
14899           /* We only had the explicitly-provided arguments before, but
14900              now we have a complete set of arguments.  */
14901           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14902
14903           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
14904           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
14905           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
14906         }
14907       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
14908                                     new_args))
14909         /* Inconsistent unification of this parameter pack.  */
14910         return 1;
14911     }
14912
14913   return 0;
14914 }
14915
14916 /* Deduce the value of template parameters.  TPARMS is the (innermost)
14917    set of template parameters to a template.  TARGS is the bindings
14918    for those template parameters, as determined thus far; TARGS may
14919    include template arguments for outer levels of template parameters
14920    as well.  PARM is a parameter to a template function, or a
14921    subcomponent of that parameter; ARG is the corresponding argument.
14922    This function attempts to match PARM with ARG in a manner
14923    consistent with the existing assignments in TARGS.  If more values
14924    are deduced, then TARGS is updated.
14925
14926    Returns 0 if the type deduction succeeds, 1 otherwise.  The
14927    parameter STRICT is a bitwise or of the following flags:
14928
14929      UNIFY_ALLOW_NONE:
14930        Require an exact match between PARM and ARG.
14931      UNIFY_ALLOW_MORE_CV_QUAL:
14932        Allow the deduced ARG to be more cv-qualified (by qualification
14933        conversion) than ARG.
14934      UNIFY_ALLOW_LESS_CV_QUAL:
14935        Allow the deduced ARG to be less cv-qualified than ARG.
14936      UNIFY_ALLOW_DERIVED:
14937        Allow the deduced ARG to be a template base class of ARG,
14938        or a pointer to a template base class of the type pointed to by
14939        ARG.
14940      UNIFY_ALLOW_INTEGER:
14941        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
14942        case for more information.
14943      UNIFY_ALLOW_OUTER_LEVEL:
14944        This is the outermost level of a deduction. Used to determine validity
14945        of qualification conversions. A valid qualification conversion must
14946        have const qualified pointers leading up to the inner type which
14947        requires additional CV quals, except at the outer level, where const
14948        is not required [conv.qual]. It would be normal to set this flag in
14949        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
14950      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
14951        This is the outermost level of a deduction, and PARM can be more CV
14952        qualified at this point.
14953      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
14954        This is the outermost level of a deduction, and PARM can be less CV
14955        qualified at this point.  */
14956
14957 static int
14958 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
14959 {
14960   int idx;
14961   tree targ;
14962   tree tparm;
14963   int strict_in = strict;
14964
14965   /* I don't think this will do the right thing with respect to types.
14966      But the only case I've seen it in so far has been array bounds, where
14967      signedness is the only information lost, and I think that will be
14968      okay.  */
14969   while (TREE_CODE (parm) == NOP_EXPR)
14970     parm = TREE_OPERAND (parm, 0);
14971
14972   if (arg == error_mark_node)
14973     return 1;
14974   if (arg == unknown_type_node
14975       || arg == init_list_type_node)
14976     /* We can't deduce anything from this, but we might get all the
14977        template args from other function args.  */
14978     return 0;
14979
14980   /* If PARM uses template parameters, then we can't bail out here,
14981      even if ARG == PARM, since we won't record unifications for the
14982      template parameters.  We might need them if we're trying to
14983      figure out which of two things is more specialized.  */
14984   if (arg == parm && !uses_template_parms (parm))
14985     return 0;
14986
14987   /* Handle init lists early, so the rest of the function can assume
14988      we're dealing with a type. */
14989   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
14990     {
14991       tree elt, elttype;
14992       unsigned i;
14993       tree orig_parm = parm;
14994
14995       /* Replace T with std::initializer_list<T> for deduction.  */
14996       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14997           && flag_deduce_init_list)
14998         parm = listify (parm);
14999
15000       if (!is_std_init_list (parm))
15001         /* We can only deduce from an initializer list argument if the
15002            parameter is std::initializer_list; otherwise this is a
15003            non-deduced context. */
15004         return 0;
15005
15006       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
15007
15008       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
15009         {
15010           int elt_strict = strict;
15011
15012           if (elt == error_mark_node)
15013             return 1;
15014
15015           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
15016             {
15017               tree type = TREE_TYPE (elt);
15018               /* It should only be possible to get here for a call.  */
15019               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
15020               elt_strict |= maybe_adjust_types_for_deduction
15021                 (DEDUCE_CALL, &elttype, &type, elt);
15022               elt = type;
15023             }
15024
15025           if (unify (tparms, targs, elttype, elt, elt_strict))
15026             return 1;
15027         }
15028
15029       /* If the std::initializer_list<T> deduction worked, replace the
15030          deduced A with std::initializer_list<A>.  */
15031       if (orig_parm != parm)
15032         {
15033           idx = TEMPLATE_TYPE_IDX (orig_parm);
15034           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15035           targ = listify (targ);
15036           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
15037         }
15038       return 0;
15039     }
15040
15041   /* Immediately reject some pairs that won't unify because of
15042      cv-qualification mismatches.  */
15043   if (TREE_CODE (arg) == TREE_CODE (parm)
15044       && TYPE_P (arg)
15045       /* It is the elements of the array which hold the cv quals of an array
15046          type, and the elements might be template type parms. We'll check
15047          when we recurse.  */
15048       && TREE_CODE (arg) != ARRAY_TYPE
15049       /* We check the cv-qualifiers when unifying with template type
15050          parameters below.  We want to allow ARG `const T' to unify with
15051          PARM `T' for example, when computing which of two templates
15052          is more specialized, for example.  */
15053       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
15054       && !check_cv_quals_for_unify (strict_in, arg, parm))
15055     return 1;
15056
15057   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
15058       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
15059     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
15060   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
15061   strict &= ~UNIFY_ALLOW_DERIVED;
15062   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
15063   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
15064
15065   switch (TREE_CODE (parm))
15066     {
15067     case TYPENAME_TYPE:
15068     case SCOPE_REF:
15069     case UNBOUND_CLASS_TEMPLATE:
15070       /* In a type which contains a nested-name-specifier, template
15071          argument values cannot be deduced for template parameters used
15072          within the nested-name-specifier.  */
15073       return 0;
15074
15075     case TEMPLATE_TYPE_PARM:
15076     case TEMPLATE_TEMPLATE_PARM:
15077     case BOUND_TEMPLATE_TEMPLATE_PARM:
15078       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
15079       if (tparm == error_mark_node)
15080         return 1;
15081
15082       if (TEMPLATE_TYPE_LEVEL (parm)
15083           != template_decl_level (tparm))
15084         /* The PARM is not one we're trying to unify.  Just check
15085            to see if it matches ARG.  */
15086         return (TREE_CODE (arg) == TREE_CODE (parm)
15087                 && same_type_p (parm, arg)) ? 0 : 1;
15088       idx = TEMPLATE_TYPE_IDX (parm);
15089       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15090       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
15091
15092       /* Check for mixed types and values.  */
15093       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15094            && TREE_CODE (tparm) != TYPE_DECL)
15095           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15096               && TREE_CODE (tparm) != TEMPLATE_DECL))
15097         return 1;
15098
15099       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15100         {
15101           /* ARG must be constructed from a template class or a template
15102              template parameter.  */
15103           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
15104               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
15105             return 1;
15106
15107           {
15108             tree parmvec = TYPE_TI_ARGS (parm);
15109             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
15110             tree full_argvec = add_to_template_args (targs, argvec);
15111             tree parm_parms 
15112               = DECL_INNERMOST_TEMPLATE_PARMS
15113                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
15114             int i, len;
15115             int parm_variadic_p = 0;
15116
15117             /* The resolution to DR150 makes clear that default
15118                arguments for an N-argument may not be used to bind T
15119                to a template template parameter with fewer than N
15120                parameters.  It is not safe to permit the binding of
15121                default arguments as an extension, as that may change
15122                the meaning of a conforming program.  Consider:
15123
15124                   struct Dense { static const unsigned int dim = 1; };
15125
15126                   template <template <typename> class View,
15127                             typename Block>
15128                   void operator+(float, View<Block> const&);
15129
15130                   template <typename Block,
15131                             unsigned int Dim = Block::dim>
15132                   struct Lvalue_proxy { operator float() const; };
15133
15134                   void
15135                   test_1d (void) {
15136                     Lvalue_proxy<Dense> p;
15137                     float b;
15138                     b + p;
15139                   }
15140
15141               Here, if Lvalue_proxy is permitted to bind to View, then
15142               the global operator+ will be used; if they are not, the
15143               Lvalue_proxy will be converted to float.  */
15144             if (coerce_template_parms (parm_parms,
15145                                        full_argvec,
15146                                        TYPE_TI_TEMPLATE (parm),
15147                                        tf_none,
15148                                        /*require_all_args=*/true,
15149                                        /*use_default_args=*/false)
15150                 == error_mark_node)
15151               return 1;
15152
15153             /* Deduce arguments T, i from TT<T> or TT<i>.
15154                We check each element of PARMVEC and ARGVEC individually
15155                rather than the whole TREE_VEC since they can have
15156                different number of elements.  */
15157
15158             parmvec = expand_template_argument_pack (parmvec);
15159             argvec = expand_template_argument_pack (argvec);
15160
15161             len = TREE_VEC_LENGTH (parmvec);
15162
15163             /* Check if the parameters end in a pack, making them
15164                variadic.  */
15165             if (len > 0
15166                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
15167               parm_variadic_p = 1;
15168             
15169             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
15170               return 1;
15171
15172              for (i = 0; i < len - parm_variadic_p; ++i)
15173               {
15174                 if (unify (tparms, targs,
15175                            TREE_VEC_ELT (parmvec, i),
15176                            TREE_VEC_ELT (argvec, i),
15177                            UNIFY_ALLOW_NONE))
15178                   return 1;
15179               }
15180
15181             if (parm_variadic_p
15182                 && unify_pack_expansion (tparms, targs,
15183                                          parmvec, argvec,
15184                                          UNIFY_ALLOW_NONE,
15185                                          /*call_args_p=*/false,
15186                                          /*subr=*/false))
15187               return 1;
15188           }
15189           arg = TYPE_TI_TEMPLATE (arg);
15190
15191           /* Fall through to deduce template name.  */
15192         }
15193
15194       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15195           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15196         {
15197           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
15198
15199           /* Simple cases: Value already set, does match or doesn't.  */
15200           if (targ != NULL_TREE && template_args_equal (targ, arg))
15201             return 0;
15202           else if (targ)
15203             return 1;
15204         }
15205       else
15206         {
15207           /* If PARM is `const T' and ARG is only `int', we don't have
15208              a match unless we are allowing additional qualification.
15209              If ARG is `const int' and PARM is just `T' that's OK;
15210              that binds `const int' to `T'.  */
15211           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
15212                                          arg, parm))
15213             return 1;
15214
15215           /* Consider the case where ARG is `const volatile int' and
15216              PARM is `const T'.  Then, T should be `volatile int'.  */
15217           arg = cp_build_qualified_type_real
15218             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
15219           if (arg == error_mark_node)
15220             return 1;
15221
15222           /* Simple cases: Value already set, does match or doesn't.  */
15223           if (targ != NULL_TREE && same_type_p (targ, arg))
15224             return 0;
15225           else if (targ)
15226             return 1;
15227
15228           /* Make sure that ARG is not a variable-sized array.  (Note
15229              that were talking about variable-sized arrays (like
15230              `int[n]'), rather than arrays of unknown size (like
15231              `int[]').)  We'll get very confused by such a type since
15232              the bound of the array will not be computable in an
15233              instantiation.  Besides, such types are not allowed in
15234              ISO C++, so we can do as we please here.  */
15235           if (variably_modified_type_p (arg, NULL_TREE))
15236             return 1;
15237
15238           /* Strip typedefs as in convert_template_argument.  */
15239           arg = strip_typedefs (arg);
15240         }
15241
15242       /* If ARG is a parameter pack or an expansion, we cannot unify
15243          against it unless PARM is also a parameter pack.  */
15244       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
15245           && !template_parameter_pack_p (parm))
15246         return 1;
15247
15248       /* If the argument deduction results is a METHOD_TYPE,
15249          then there is a problem.
15250          METHOD_TYPE doesn't map to any real C++ type the result of
15251          the deduction can not be of that type.  */
15252       if (TREE_CODE (arg) == METHOD_TYPE)
15253         return 1;
15254
15255       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
15256       return 0;
15257
15258     case TEMPLATE_PARM_INDEX:
15259       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
15260       if (tparm == error_mark_node)
15261         return 1;
15262
15263       if (TEMPLATE_PARM_LEVEL (parm)
15264           != template_decl_level (tparm))
15265         /* The PARM is not one we're trying to unify.  Just check
15266            to see if it matches ARG.  */
15267         return !(TREE_CODE (arg) == TREE_CODE (parm)
15268                  && cp_tree_equal (parm, arg));
15269
15270       idx = TEMPLATE_PARM_IDX (parm);
15271       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15272
15273       if (targ)
15274         return !cp_tree_equal (targ, arg);
15275
15276       /* [temp.deduct.type] If, in the declaration of a function template
15277          with a non-type template-parameter, the non-type
15278          template-parameter is used in an expression in the function
15279          parameter-list and, if the corresponding template-argument is
15280          deduced, the template-argument type shall match the type of the
15281          template-parameter exactly, except that a template-argument
15282          deduced from an array bound may be of any integral type.
15283          The non-type parameter might use already deduced type parameters.  */
15284       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
15285       if (!TREE_TYPE (arg))
15286         /* Template-parameter dependent expression.  Just accept it for now.
15287            It will later be processed in convert_template_argument.  */
15288         ;
15289       else if (same_type_p (TREE_TYPE (arg), tparm))
15290         /* OK */;
15291       else if ((strict & UNIFY_ALLOW_INTEGER)
15292                && (TREE_CODE (tparm) == INTEGER_TYPE
15293                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
15294         /* Convert the ARG to the type of PARM; the deduced non-type
15295            template argument must exactly match the types of the
15296            corresponding parameter.  */
15297         arg = fold (build_nop (tparm, arg));
15298       else if (uses_template_parms (tparm))
15299         /* We haven't deduced the type of this parameter yet.  Try again
15300            later.  */
15301         return 0;
15302       else
15303         return 1;
15304
15305       /* If ARG is a parameter pack or an expansion, we cannot unify
15306          against it unless PARM is also a parameter pack.  */
15307       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
15308           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
15309         return 1;
15310
15311       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
15312       return 0;
15313
15314     case PTRMEM_CST:
15315      {
15316         /* A pointer-to-member constant can be unified only with
15317          another constant.  */
15318       if (TREE_CODE (arg) != PTRMEM_CST)
15319         return 1;
15320
15321       /* Just unify the class member. It would be useless (and possibly
15322          wrong, depending on the strict flags) to unify also
15323          PTRMEM_CST_CLASS, because we want to be sure that both parm and
15324          arg refer to the same variable, even if through different
15325          classes. For instance:
15326
15327          struct A { int x; };
15328          struct B : A { };
15329
15330          Unification of &A::x and &B::x must succeed.  */
15331       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
15332                     PTRMEM_CST_MEMBER (arg), strict);
15333      }
15334
15335     case POINTER_TYPE:
15336       {
15337         if (TREE_CODE (arg) != POINTER_TYPE)
15338           return 1;
15339
15340         /* [temp.deduct.call]
15341
15342            A can be another pointer or pointer to member type that can
15343            be converted to the deduced A via a qualification
15344            conversion (_conv.qual_).
15345
15346            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
15347            This will allow for additional cv-qualification of the
15348            pointed-to types if appropriate.  */
15349
15350         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
15351           /* The derived-to-base conversion only persists through one
15352              level of pointers.  */
15353           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
15354
15355         return unify (tparms, targs, TREE_TYPE (parm),
15356                       TREE_TYPE (arg), strict);
15357       }
15358
15359     case REFERENCE_TYPE:
15360       if (TREE_CODE (arg) != REFERENCE_TYPE)
15361         return 1;
15362       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15363                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
15364
15365     case ARRAY_TYPE:
15366       if (TREE_CODE (arg) != ARRAY_TYPE)
15367         return 1;
15368       if ((TYPE_DOMAIN (parm) == NULL_TREE)
15369           != (TYPE_DOMAIN (arg) == NULL_TREE))
15370         return 1;
15371       if (TYPE_DOMAIN (parm) != NULL_TREE)
15372         {
15373           tree parm_max;
15374           tree arg_max;
15375           bool parm_cst;
15376           bool arg_cst;
15377
15378           /* Our representation of array types uses "N - 1" as the
15379              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
15380              not an integer constant.  We cannot unify arbitrarily
15381              complex expressions, so we eliminate the MINUS_EXPRs
15382              here.  */
15383           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
15384           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
15385           if (!parm_cst)
15386             {
15387               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
15388               parm_max = TREE_OPERAND (parm_max, 0);
15389             }
15390           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
15391           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
15392           if (!arg_cst)
15393             {
15394               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
15395                  trying to unify the type of a variable with the type
15396                  of a template parameter.  For example:
15397
15398                    template <unsigned int N>
15399                    void f (char (&) [N]);
15400                    int g(); 
15401                    void h(int i) {
15402                      char a[g(i)];
15403                      f(a); 
15404                    }
15405
15406                 Here, the type of the ARG will be "int [g(i)]", and
15407                 may be a SAVE_EXPR, etc.  */
15408               if (TREE_CODE (arg_max) != MINUS_EXPR)
15409                 return 1;
15410               arg_max = TREE_OPERAND (arg_max, 0);
15411             }
15412
15413           /* If only one of the bounds used a MINUS_EXPR, compensate
15414              by adding one to the other bound.  */
15415           if (parm_cst && !arg_cst)
15416             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
15417                                     integer_type_node,
15418                                     parm_max,
15419                                     integer_one_node);
15420           else if (arg_cst && !parm_cst)
15421             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
15422                                    integer_type_node,
15423                                    arg_max,
15424                                    integer_one_node);
15425
15426           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
15427             return 1;
15428         }
15429       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15430                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
15431
15432     case REAL_TYPE:
15433     case COMPLEX_TYPE:
15434     case VECTOR_TYPE:
15435     case INTEGER_TYPE:
15436     case BOOLEAN_TYPE:
15437     case ENUMERAL_TYPE:
15438     case VOID_TYPE:
15439       if (TREE_CODE (arg) != TREE_CODE (parm))
15440         return 1;
15441
15442       /* We have already checked cv-qualification at the top of the
15443          function.  */
15444       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
15445         return 1;
15446
15447       /* As far as unification is concerned, this wins.  Later checks
15448          will invalidate it if necessary.  */
15449       return 0;
15450
15451       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
15452       /* Type INTEGER_CST can come from ordinary constant template args.  */
15453     case INTEGER_CST:
15454       while (TREE_CODE (arg) == NOP_EXPR)
15455         arg = TREE_OPERAND (arg, 0);
15456
15457       if (TREE_CODE (arg) != INTEGER_CST)
15458         return 1;
15459       return !tree_int_cst_equal (parm, arg);
15460
15461     case TREE_VEC:
15462       {
15463         int i;
15464         if (TREE_CODE (arg) != TREE_VEC)
15465           return 1;
15466         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
15467           return 1;
15468         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
15469           if (unify (tparms, targs,
15470                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
15471                      UNIFY_ALLOW_NONE))
15472             return 1;
15473         return 0;
15474       }
15475
15476     case RECORD_TYPE:
15477     case UNION_TYPE:
15478       if (TREE_CODE (arg) != TREE_CODE (parm))
15479         return 1;
15480
15481       if (TYPE_PTRMEMFUNC_P (parm))
15482         {
15483           if (!TYPE_PTRMEMFUNC_P (arg))
15484             return 1;
15485
15486           return unify (tparms, targs,
15487                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
15488                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
15489                         strict);
15490         }
15491
15492       if (CLASSTYPE_TEMPLATE_INFO (parm))
15493         {
15494           tree t = NULL_TREE;
15495
15496           if (strict_in & UNIFY_ALLOW_DERIVED)
15497             {
15498               /* First, we try to unify the PARM and ARG directly.  */
15499               t = try_class_unification (tparms, targs,
15500                                          parm, arg);
15501
15502               if (!t)
15503                 {
15504                   /* Fallback to the special case allowed in
15505                      [temp.deduct.call]:
15506
15507                        If P is a class, and P has the form
15508                        template-id, then A can be a derived class of
15509                        the deduced A.  Likewise, if P is a pointer to
15510                        a class of the form template-id, A can be a
15511                        pointer to a derived class pointed to by the
15512                        deduced A.  */
15513                   t = get_template_base (tparms, targs, parm, arg);
15514
15515                   if (!t)
15516                     return 1;
15517                 }
15518             }
15519           else if (CLASSTYPE_TEMPLATE_INFO (arg)
15520                    && (CLASSTYPE_TI_TEMPLATE (parm)
15521                        == CLASSTYPE_TI_TEMPLATE (arg)))
15522             /* Perhaps PARM is something like S<U> and ARG is S<int>.
15523                Then, we should unify `int' and `U'.  */
15524             t = arg;
15525           else
15526             /* There's no chance of unification succeeding.  */
15527             return 1;
15528
15529           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
15530                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
15531         }
15532       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
15533         return 1;
15534       return 0;
15535
15536     case METHOD_TYPE:
15537     case FUNCTION_TYPE:
15538       {
15539         unsigned int nargs;
15540         tree *args;
15541         tree a;
15542         unsigned int i;
15543
15544         if (TREE_CODE (arg) != TREE_CODE (parm))
15545           return 1;
15546
15547         /* CV qualifications for methods can never be deduced, they must
15548            match exactly.  We need to check them explicitly here,
15549            because type_unification_real treats them as any other
15550            cv-qualified parameter.  */
15551         if (TREE_CODE (parm) == METHOD_TYPE
15552             && (!check_cv_quals_for_unify
15553                 (UNIFY_ALLOW_NONE,
15554                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
15555                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
15556           return 1;
15557
15558         if (unify (tparms, targs, TREE_TYPE (parm),
15559                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
15560           return 1;
15561
15562         nargs = list_length (TYPE_ARG_TYPES (arg));
15563         args = XALLOCAVEC (tree, nargs);
15564         for (a = TYPE_ARG_TYPES (arg), i = 0;
15565              a != NULL_TREE && a != void_list_node;
15566              a = TREE_CHAIN (a), ++i)
15567           args[i] = TREE_VALUE (a);
15568         nargs = i;
15569
15570         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
15571                                       args, nargs, 1, DEDUCE_EXACT,
15572                                       LOOKUP_NORMAL);
15573       }
15574
15575     case OFFSET_TYPE:
15576       /* Unify a pointer to member with a pointer to member function, which
15577          deduces the type of the member as a function type. */
15578       if (TYPE_PTRMEMFUNC_P (arg))
15579         {
15580           tree method_type;
15581           tree fntype;
15582
15583           /* Check top-level cv qualifiers */
15584           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
15585             return 1;
15586
15587           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15588                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
15589             return 1;
15590
15591           /* Determine the type of the function we are unifying against. */
15592           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
15593           fntype =
15594             build_function_type (TREE_TYPE (method_type),
15595                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
15596
15597           /* Extract the cv-qualifiers of the member function from the
15598              implicit object parameter and place them on the function
15599              type to be restored later. */
15600           fntype = apply_memfn_quals (fntype, type_memfn_quals (method_type));
15601           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
15602         }
15603
15604       if (TREE_CODE (arg) != OFFSET_TYPE)
15605         return 1;
15606       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15607                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
15608         return 1;
15609       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15610                     strict);
15611
15612     case CONST_DECL:
15613       if (DECL_TEMPLATE_PARM_P (parm))
15614         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
15615       if (arg != integral_constant_value (parm))
15616         return 1;
15617       return 0;
15618
15619     case FIELD_DECL:
15620     case TEMPLATE_DECL:
15621       /* Matched cases are handled by the ARG == PARM test above.  */
15622       return 1;
15623
15624     case VAR_DECL:
15625       /* A non-type template parameter that is a variable should be a
15626          an integral constant, in which case, it whould have been
15627          folded into its (constant) value. So we should not be getting
15628          a variable here.  */
15629       gcc_unreachable ();
15630
15631     case TYPE_ARGUMENT_PACK:
15632     case NONTYPE_ARGUMENT_PACK:
15633       {
15634         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
15635         tree packed_args = ARGUMENT_PACK_ARGS (arg);
15636         int i, len = TREE_VEC_LENGTH (packed_parms);
15637         int argslen = TREE_VEC_LENGTH (packed_args);
15638         int parm_variadic_p = 0;
15639
15640         for (i = 0; i < len; ++i)
15641           {
15642             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
15643               {
15644                 if (i == len - 1)
15645                   /* We can unify against something with a trailing
15646                      parameter pack.  */
15647                   parm_variadic_p = 1;
15648                 else
15649                   /* Since there is something following the pack
15650                      expansion, we cannot unify this template argument
15651                      list.  */
15652                   return 0;
15653               }
15654           }
15655           
15656
15657         /* If we don't have enough arguments to satisfy the parameters
15658            (not counting the pack expression at the end), or we have
15659            too many arguments for a parameter list that doesn't end in
15660            a pack expression, we can't unify.  */
15661         if (argslen < (len - parm_variadic_p)
15662             || (argslen > len && !parm_variadic_p))
15663           return 1;
15664
15665         /* Unify all of the parameters that precede the (optional)
15666            pack expression.  */
15667         for (i = 0; i < len - parm_variadic_p; ++i)
15668           {
15669             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
15670                        TREE_VEC_ELT (packed_args, i), strict))
15671               return 1;
15672           }
15673
15674         if (parm_variadic_p)
15675           return unify_pack_expansion (tparms, targs, 
15676                                        packed_parms, packed_args,
15677                                        strict, /*call_args_p=*/false,
15678                                        /*subr=*/false);
15679         return 0;
15680       }
15681
15682       break;
15683
15684     case TYPEOF_TYPE:
15685     case DECLTYPE_TYPE:
15686       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
15687          nodes.  */
15688       return 0;
15689
15690     case ERROR_MARK:
15691       /* Unification fails if we hit an error node.  */
15692       return 1;
15693
15694     default:
15695       gcc_assert (EXPR_P (parm));
15696
15697       /* We must be looking at an expression.  This can happen with
15698          something like:
15699
15700            template <int I>
15701            void foo(S<I>, S<I + 2>);
15702
15703          This is a "nondeduced context":
15704
15705            [deduct.type]
15706
15707            The nondeduced contexts are:
15708
15709            --A type that is a template-id in which one or more of
15710              the template-arguments is an expression that references
15711              a template-parameter.
15712
15713          In these cases, we assume deduction succeeded, but don't
15714          actually infer any unifications.  */
15715
15716       if (!uses_template_parms (parm)
15717           && !template_args_equal (parm, arg))
15718         return 1;
15719       else
15720         return 0;
15721     }
15722 }
15723 \f
15724 /* Note that DECL can be defined in this translation unit, if
15725    required.  */
15726
15727 static void
15728 mark_definable (tree decl)
15729 {
15730   tree clone;
15731   DECL_NOT_REALLY_EXTERN (decl) = 1;
15732   FOR_EACH_CLONE (clone, decl)
15733     DECL_NOT_REALLY_EXTERN (clone) = 1;
15734 }
15735
15736 /* Called if RESULT is explicitly instantiated, or is a member of an
15737    explicitly instantiated class.  */
15738
15739 void
15740 mark_decl_instantiated (tree result, int extern_p)
15741 {
15742   SET_DECL_EXPLICIT_INSTANTIATION (result);
15743
15744   /* If this entity has already been written out, it's too late to
15745      make any modifications.  */
15746   if (TREE_ASM_WRITTEN (result))
15747     return;
15748
15749   if (TREE_CODE (result) != FUNCTION_DECL)
15750     /* The TREE_PUBLIC flag for function declarations will have been
15751        set correctly by tsubst.  */
15752     TREE_PUBLIC (result) = 1;
15753
15754   /* This might have been set by an earlier implicit instantiation.  */
15755   DECL_COMDAT (result) = 0;
15756
15757   if (extern_p)
15758     DECL_NOT_REALLY_EXTERN (result) = 0;
15759   else
15760     {
15761       mark_definable (result);
15762       /* Always make artificials weak.  */
15763       if (DECL_ARTIFICIAL (result) && flag_weak)
15764         comdat_linkage (result);
15765       /* For WIN32 we also want to put explicit instantiations in
15766          linkonce sections.  */
15767       else if (TREE_PUBLIC (result))
15768         maybe_make_one_only (result);
15769     }
15770
15771   /* If EXTERN_P, then this function will not be emitted -- unless
15772      followed by an explicit instantiation, at which point its linkage
15773      will be adjusted.  If !EXTERN_P, then this function will be
15774      emitted here.  In neither circumstance do we want
15775      import_export_decl to adjust the linkage.  */
15776   DECL_INTERFACE_KNOWN (result) = 1;
15777 }
15778
15779 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
15780    important template arguments.  If any are missing, we check whether
15781    they're important by using error_mark_node for substituting into any
15782    args that were used for partial ordering (the ones between ARGS and END)
15783    and seeing if it bubbles up.  */
15784
15785 static bool
15786 check_undeduced_parms (tree targs, tree args, tree end)
15787 {
15788   bool found = false;
15789   int i;
15790   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
15791     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
15792       {
15793         found = true;
15794         TREE_VEC_ELT (targs, i) = error_mark_node;
15795       }
15796   if (found)
15797     {
15798       for (; args != end; args = TREE_CHAIN (args))
15799         {
15800           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
15801           if (substed == error_mark_node)
15802             return true;
15803         }
15804     }
15805   return false;
15806 }
15807
15808 /* Given two function templates PAT1 and PAT2, return:
15809
15810    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
15811    -1 if PAT2 is more specialized than PAT1.
15812    0 if neither is more specialized.
15813
15814    LEN indicates the number of parameters we should consider
15815    (defaulted parameters should not be considered).
15816
15817    The 1998 std underspecified function template partial ordering, and
15818    DR214 addresses the issue.  We take pairs of arguments, one from
15819    each of the templates, and deduce them against each other.  One of
15820    the templates will be more specialized if all the *other*
15821    template's arguments deduce against its arguments and at least one
15822    of its arguments *does* *not* deduce against the other template's
15823    corresponding argument.  Deduction is done as for class templates.
15824    The arguments used in deduction have reference and top level cv
15825    qualifiers removed.  Iff both arguments were originally reference
15826    types *and* deduction succeeds in both directions, the template
15827    with the more cv-qualified argument wins for that pairing (if
15828    neither is more cv-qualified, they both are equal).  Unlike regular
15829    deduction, after all the arguments have been deduced in this way,
15830    we do *not* verify the deduced template argument values can be
15831    substituted into non-deduced contexts.
15832
15833    The logic can be a bit confusing here, because we look at deduce1 and
15834    targs1 to see if pat2 is at least as specialized, and vice versa; if we
15835    can find template arguments for pat1 to make arg1 look like arg2, that
15836    means that arg2 is at least as specialized as arg1.  */
15837
15838 int
15839 more_specialized_fn (tree pat1, tree pat2, int len)
15840 {
15841   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
15842   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
15843   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
15844   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
15845   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
15846   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
15847   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
15848   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
15849   tree origs1, origs2;
15850   bool lose1 = false;
15851   bool lose2 = false;
15852
15853   /* Remove the this parameter from non-static member functions.  If
15854      one is a non-static member function and the other is not a static
15855      member function, remove the first parameter from that function
15856      also.  This situation occurs for operator functions where we
15857      locate both a member function (with this pointer) and non-member
15858      operator (with explicit first operand).  */
15859   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
15860     {
15861       len--; /* LEN is the number of significant arguments for DECL1 */
15862       args1 = TREE_CHAIN (args1);
15863       if (!DECL_STATIC_FUNCTION_P (decl2))
15864         args2 = TREE_CHAIN (args2);
15865     }
15866   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
15867     {
15868       args2 = TREE_CHAIN (args2);
15869       if (!DECL_STATIC_FUNCTION_P (decl1))
15870         {
15871           len--;
15872           args1 = TREE_CHAIN (args1);
15873         }
15874     }
15875
15876   /* If only one is a conversion operator, they are unordered.  */
15877   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
15878     return 0;
15879
15880   /* Consider the return type for a conversion function */
15881   if (DECL_CONV_FN_P (decl1))
15882     {
15883       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
15884       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
15885       len++;
15886     }
15887
15888   processing_template_decl++;
15889
15890   origs1 = args1;
15891   origs2 = args2;
15892
15893   while (len--
15894          /* Stop when an ellipsis is seen.  */
15895          && args1 != NULL_TREE && args2 != NULL_TREE)
15896     {
15897       tree arg1 = TREE_VALUE (args1);
15898       tree arg2 = TREE_VALUE (args2);
15899       int deduce1, deduce2;
15900       int quals1 = -1;
15901       int quals2 = -1;
15902
15903       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15904           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15905         {
15906           /* When both arguments are pack expansions, we need only
15907              unify the patterns themselves.  */
15908           arg1 = PACK_EXPANSION_PATTERN (arg1);
15909           arg2 = PACK_EXPANSION_PATTERN (arg2);
15910
15911           /* This is the last comparison we need to do.  */
15912           len = 0;
15913         }
15914
15915       if (TREE_CODE (arg1) == REFERENCE_TYPE)
15916         {
15917           arg1 = TREE_TYPE (arg1);
15918           quals1 = cp_type_quals (arg1);
15919         }
15920
15921       if (TREE_CODE (arg2) == REFERENCE_TYPE)
15922         {
15923           arg2 = TREE_TYPE (arg2);
15924           quals2 = cp_type_quals (arg2);
15925         }
15926
15927       if ((quals1 < 0) != (quals2 < 0))
15928         {
15929           /* Only of the args is a reference, see if we should apply
15930              array/function pointer decay to it.  This is not part of
15931              DR214, but is, IMHO, consistent with the deduction rules
15932              for the function call itself, and with our earlier
15933              implementation of the underspecified partial ordering
15934              rules.  (nathan).  */
15935           if (quals1 >= 0)
15936             {
15937               switch (TREE_CODE (arg1))
15938                 {
15939                 case ARRAY_TYPE:
15940                   arg1 = TREE_TYPE (arg1);
15941                   /* FALLTHROUGH. */
15942                 case FUNCTION_TYPE:
15943                   arg1 = build_pointer_type (arg1);
15944                   break;
15945
15946                 default:
15947                   break;
15948                 }
15949             }
15950           else
15951             {
15952               switch (TREE_CODE (arg2))
15953                 {
15954                 case ARRAY_TYPE:
15955                   arg2 = TREE_TYPE (arg2);
15956                   /* FALLTHROUGH. */
15957                 case FUNCTION_TYPE:
15958                   arg2 = build_pointer_type (arg2);
15959                   break;
15960
15961                 default:
15962                   break;
15963                 }
15964             }
15965         }
15966
15967       arg1 = TYPE_MAIN_VARIANT (arg1);
15968       arg2 = TYPE_MAIN_VARIANT (arg2);
15969
15970       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
15971         {
15972           int i, len2 = list_length (args2);
15973           tree parmvec = make_tree_vec (1);
15974           tree argvec = make_tree_vec (len2);
15975           tree ta = args2;
15976
15977           /* Setup the parameter vector, which contains only ARG1.  */
15978           TREE_VEC_ELT (parmvec, 0) = arg1;
15979
15980           /* Setup the argument vector, which contains the remaining
15981              arguments.  */
15982           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
15983             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15984
15985           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
15986                                            argvec, UNIFY_ALLOW_NONE, 
15987                                            /*call_args_p=*/false, 
15988                                            /*subr=*/0);
15989
15990           /* We cannot deduce in the other direction, because ARG1 is
15991              a pack expansion but ARG2 is not.  */
15992           deduce2 = 0;
15993         }
15994       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15995         {
15996           int i, len1 = list_length (args1);
15997           tree parmvec = make_tree_vec (1);
15998           tree argvec = make_tree_vec (len1);
15999           tree ta = args1;
16000
16001           /* Setup the parameter vector, which contains only ARG1.  */
16002           TREE_VEC_ELT (parmvec, 0) = arg2;
16003
16004           /* Setup the argument vector, which contains the remaining
16005              arguments.  */
16006           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
16007             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
16008
16009           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
16010                                            argvec, UNIFY_ALLOW_NONE, 
16011                                            /*call_args_p=*/false, 
16012                                            /*subr=*/0);
16013
16014           /* We cannot deduce in the other direction, because ARG2 is
16015              a pack expansion but ARG1 is not.*/
16016           deduce1 = 0;
16017         }
16018
16019       else
16020         {
16021           /* The normal case, where neither argument is a pack
16022              expansion.  */
16023           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
16024           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
16025         }
16026
16027       /* If we couldn't deduce arguments for tparms1 to make arg1 match
16028          arg2, then arg2 is not as specialized as arg1.  */
16029       if (!deduce1)
16030         lose2 = true;
16031       if (!deduce2)
16032         lose1 = true;
16033
16034       /* "If, for a given type, deduction succeeds in both directions
16035          (i.e., the types are identical after the transformations above)
16036          and if the type from the argument template is more cv-qualified
16037          than the type from the parameter template (as described above)
16038          that type is considered to be more specialized than the other. If
16039          neither type is more cv-qualified than the other then neither type
16040          is more specialized than the other."  */
16041
16042       if (deduce1 && deduce2
16043           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
16044         {
16045           if ((quals1 & quals2) == quals2)
16046             lose2 = true;
16047           if ((quals1 & quals2) == quals1)
16048             lose1 = true;
16049         }
16050
16051       if (lose1 && lose2)
16052         /* We've failed to deduce something in either direction.
16053            These must be unordered.  */
16054         break;
16055
16056       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
16057           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16058         /* We have already processed all of the arguments in our
16059            handing of the pack expansion type.  */
16060         len = 0;
16061
16062       args1 = TREE_CHAIN (args1);
16063       args2 = TREE_CHAIN (args2);
16064     }
16065
16066   /* "In most cases, all template parameters must have values in order for
16067      deduction to succeed, but for partial ordering purposes a template
16068      parameter may remain without a value provided it is not used in the
16069      types being used for partial ordering."
16070
16071      Thus, if we are missing any of the targs1 we need to substitute into
16072      origs1, then pat2 is not as specialized as pat1.  This can happen when
16073      there is a nondeduced context.  */
16074   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
16075     lose2 = true;
16076   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
16077     lose1 = true;
16078
16079   processing_template_decl--;
16080
16081   /* All things being equal, if the next argument is a pack expansion
16082      for one function but not for the other, prefer the
16083      non-variadic function.  FIXME this is bogus; see c++/41958.  */
16084   if (lose1 == lose2
16085       && args1 && TREE_VALUE (args1)
16086       && args2 && TREE_VALUE (args2))
16087     {
16088       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
16089       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
16090     }
16091
16092   if (lose1 == lose2)
16093     return 0;
16094   else if (!lose1)
16095     return 1;
16096   else
16097     return -1;
16098 }
16099
16100 /* Determine which of two partial specializations is more specialized.
16101
16102    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
16103    to the first partial specialization.  The TREE_VALUE is the
16104    innermost set of template parameters for the partial
16105    specialization.  PAT2 is similar, but for the second template.
16106
16107    Return 1 if the first partial specialization is more specialized;
16108    -1 if the second is more specialized; 0 if neither is more
16109    specialized.
16110
16111    See [temp.class.order] for information about determining which of
16112    two templates is more specialized.  */
16113
16114 static int
16115 more_specialized_class (tree pat1, tree pat2)
16116 {
16117   tree targs;
16118   tree tmpl1, tmpl2;
16119   int winner = 0;
16120   bool any_deductions = false;
16121
16122   tmpl1 = TREE_TYPE (pat1);
16123   tmpl2 = TREE_TYPE (pat2);
16124
16125   /* Just like what happens for functions, if we are ordering between
16126      different class template specializations, we may encounter dependent
16127      types in the arguments, and we need our dependency check functions
16128      to behave correctly.  */
16129   ++processing_template_decl;
16130   targs = get_class_bindings (TREE_VALUE (pat1),
16131                               CLASSTYPE_TI_ARGS (tmpl1),
16132                               CLASSTYPE_TI_ARGS (tmpl2));
16133   if (targs)
16134     {
16135       --winner;
16136       any_deductions = true;
16137     }
16138
16139   targs = get_class_bindings (TREE_VALUE (pat2),
16140                               CLASSTYPE_TI_ARGS (tmpl2),
16141                               CLASSTYPE_TI_ARGS (tmpl1));
16142   if (targs)
16143     {
16144       ++winner;
16145       any_deductions = true;
16146     }
16147   --processing_template_decl;
16148
16149   /* In the case of a tie where at least one of the class templates
16150      has a parameter pack at the end, the template with the most
16151      non-packed parameters wins.  */
16152   if (winner == 0
16153       && any_deductions
16154       && (template_args_variadic_p (TREE_PURPOSE (pat1))
16155           || template_args_variadic_p (TREE_PURPOSE (pat2))))
16156     {
16157       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
16158       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
16159       int len1 = TREE_VEC_LENGTH (args1);
16160       int len2 = TREE_VEC_LENGTH (args2);
16161
16162       /* We don't count the pack expansion at the end.  */
16163       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
16164         --len1;
16165       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
16166         --len2;
16167
16168       if (len1 > len2)
16169         return 1;
16170       else if (len1 < len2)
16171         return -1;
16172     }
16173
16174   return winner;
16175 }
16176
16177 /* Return the template arguments that will produce the function signature
16178    DECL from the function template FN, with the explicit template
16179    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
16180    also match.  Return NULL_TREE if no satisfactory arguments could be
16181    found.  */
16182
16183 static tree
16184 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
16185 {
16186   int ntparms = DECL_NTPARMS (fn);
16187   tree targs = make_tree_vec (ntparms);
16188   tree decl_type;
16189   tree decl_arg_types;
16190   tree *args;
16191   unsigned int nargs, ix;
16192   tree arg;
16193
16194   /* Substitute the explicit template arguments into the type of DECL.
16195      The call to fn_type_unification will handle substitution into the
16196      FN.  */
16197   decl_type = TREE_TYPE (decl);
16198   if (explicit_args && uses_template_parms (decl_type))
16199     {
16200       tree tmpl;
16201       tree converted_args;
16202
16203       if (DECL_TEMPLATE_INFO (decl))
16204         tmpl = DECL_TI_TEMPLATE (decl);
16205       else
16206         /* We can get here for some invalid specializations.  */
16207         return NULL_TREE;
16208
16209       converted_args
16210         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
16211                                  explicit_args, NULL_TREE,
16212                                  tf_none,
16213                                  /*require_all_args=*/false,
16214                                  /*use_default_args=*/false);
16215       if (converted_args == error_mark_node)
16216         return NULL_TREE;
16217
16218       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
16219       if (decl_type == error_mark_node)
16220         return NULL_TREE;
16221     }
16222
16223   /* Never do unification on the 'this' parameter.  */
16224   decl_arg_types = skip_artificial_parms_for (decl, 
16225                                               TYPE_ARG_TYPES (decl_type));
16226
16227   nargs = list_length (decl_arg_types);
16228   args = XALLOCAVEC (tree, nargs);
16229   for (arg = decl_arg_types, ix = 0;
16230        arg != NULL_TREE && arg != void_list_node;
16231        arg = TREE_CHAIN (arg), ++ix)
16232     args[ix] = TREE_VALUE (arg);
16233
16234   if (fn_type_unification (fn, explicit_args, targs,
16235                            args, ix,
16236                            (check_rettype || DECL_CONV_FN_P (fn)
16237                             ? TREE_TYPE (decl_type) : NULL_TREE),
16238                            DEDUCE_EXACT, LOOKUP_NORMAL))
16239     return NULL_TREE;
16240
16241   return targs;
16242 }
16243
16244 /* Return the innermost template arguments that, when applied to a
16245    template specialization whose innermost template parameters are
16246    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
16247    ARGS.
16248
16249    For example, suppose we have:
16250
16251      template <class T, class U> struct S {};
16252      template <class T> struct S<T*, int> {};
16253
16254    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
16255    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
16256    int}.  The resulting vector will be {double}, indicating that `T'
16257    is bound to `double'.  */
16258
16259 static tree
16260 get_class_bindings (tree tparms, tree spec_args, tree args)
16261 {
16262   int i, ntparms = TREE_VEC_LENGTH (tparms);
16263   tree deduced_args;
16264   tree innermost_deduced_args;
16265
16266   innermost_deduced_args = make_tree_vec (ntparms);
16267   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
16268     {
16269       deduced_args = copy_node (args);
16270       SET_TMPL_ARGS_LEVEL (deduced_args,
16271                            TMPL_ARGS_DEPTH (deduced_args),
16272                            innermost_deduced_args);
16273     }
16274   else
16275     deduced_args = innermost_deduced_args;
16276
16277   if (unify (tparms, deduced_args,
16278              INNERMOST_TEMPLATE_ARGS (spec_args),
16279              INNERMOST_TEMPLATE_ARGS (args),
16280              UNIFY_ALLOW_NONE))
16281     return NULL_TREE;
16282
16283   for (i =  0; i < ntparms; ++i)
16284     if (! TREE_VEC_ELT (innermost_deduced_args, i))
16285       return NULL_TREE;
16286
16287   /* Verify that nondeduced template arguments agree with the type
16288      obtained from argument deduction.
16289
16290      For example:
16291
16292        struct A { typedef int X; };
16293        template <class T, class U> struct C {};
16294        template <class T> struct C<T, typename T::X> {};
16295
16296      Then with the instantiation `C<A, int>', we can deduce that
16297      `T' is `A' but unify () does not check whether `typename T::X'
16298      is `int'.  */
16299   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
16300   if (spec_args == error_mark_node
16301       /* We only need to check the innermost arguments; the other
16302          arguments will always agree.  */
16303       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
16304                               INNERMOST_TEMPLATE_ARGS (args)))
16305     return NULL_TREE;
16306
16307   /* Now that we have bindings for all of the template arguments,
16308      ensure that the arguments deduced for the template template
16309      parameters have compatible template parameter lists.  See the use
16310      of template_template_parm_bindings_ok_p in fn_type_unification
16311      for more information.  */
16312   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
16313     return NULL_TREE;
16314
16315   return deduced_args;
16316 }
16317
16318 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
16319    Return the TREE_LIST node with the most specialized template, if
16320    any.  If there is no most specialized template, the error_mark_node
16321    is returned.
16322
16323    Note that this function does not look at, or modify, the
16324    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
16325    returned is one of the elements of INSTANTIATIONS, callers may
16326    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
16327    and retrieve it from the value returned.  */
16328
16329 tree
16330 most_specialized_instantiation (tree templates)
16331 {
16332   tree fn, champ;
16333
16334   ++processing_template_decl;
16335
16336   champ = templates;
16337   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
16338     {
16339       int fate = 0;
16340
16341       if (get_bindings (TREE_VALUE (champ),
16342                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
16343                         NULL_TREE, /*check_ret=*/false))
16344         fate--;
16345
16346       if (get_bindings (TREE_VALUE (fn),
16347                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
16348                         NULL_TREE, /*check_ret=*/false))
16349         fate++;
16350
16351       if (fate == -1)
16352         champ = fn;
16353       else if (!fate)
16354         {
16355           /* Equally specialized, move to next function.  If there
16356              is no next function, nothing's most specialized.  */
16357           fn = TREE_CHAIN (fn);
16358           champ = fn;
16359           if (!fn)
16360             break;
16361         }
16362     }
16363
16364   if (champ)
16365     /* Now verify that champ is better than everything earlier in the
16366        instantiation list.  */
16367     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
16368       if (get_bindings (TREE_VALUE (champ),
16369                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
16370                         NULL_TREE, /*check_ret=*/false)
16371           || !get_bindings (TREE_VALUE (fn),
16372                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
16373                             NULL_TREE, /*check_ret=*/false))
16374         {
16375           champ = NULL_TREE;
16376           break;
16377         }
16378
16379   processing_template_decl--;
16380
16381   if (!champ)
16382     return error_mark_node;
16383
16384   return champ;
16385 }
16386
16387 /* If DECL is a specialization of some template, return the most
16388    general such template.  Otherwise, returns NULL_TREE.
16389
16390    For example, given:
16391
16392      template <class T> struct S { template <class U> void f(U); };
16393
16394    if TMPL is `template <class U> void S<int>::f(U)' this will return
16395    the full template.  This function will not trace past partial
16396    specializations, however.  For example, given in addition:
16397
16398      template <class T> struct S<T*> { template <class U> void f(U); };
16399
16400    if TMPL is `template <class U> void S<int*>::f(U)' this will return
16401    `template <class T> template <class U> S<T*>::f(U)'.  */
16402
16403 tree
16404 most_general_template (tree decl)
16405 {
16406   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
16407      an immediate specialization.  */
16408   if (TREE_CODE (decl) == FUNCTION_DECL)
16409     {
16410       if (DECL_TEMPLATE_INFO (decl)) {
16411         decl = DECL_TI_TEMPLATE (decl);
16412
16413         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
16414            template friend.  */
16415         if (TREE_CODE (decl) != TEMPLATE_DECL)
16416           return NULL_TREE;
16417       } else
16418         return NULL_TREE;
16419     }
16420
16421   /* Look for more and more general templates.  */
16422   while (DECL_TEMPLATE_INFO (decl))
16423     {
16424       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
16425          (See cp-tree.h for details.)  */
16426       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
16427         break;
16428
16429       if (CLASS_TYPE_P (TREE_TYPE (decl))
16430           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
16431         break;
16432
16433       /* Stop if we run into an explicitly specialized class template.  */
16434       if (!DECL_NAMESPACE_SCOPE_P (decl)
16435           && DECL_CONTEXT (decl)
16436           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
16437         break;
16438
16439       decl = DECL_TI_TEMPLATE (decl);
16440     }
16441
16442   return decl;
16443 }
16444
16445 /* Return the most specialized of the class template partial
16446    specializations of TMPL which can produce TYPE, a specialization of
16447    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
16448    a _TYPE node corresponding to the partial specialization, while the
16449    TREE_PURPOSE is the set of template arguments that must be
16450    substituted into the TREE_TYPE in order to generate TYPE.
16451
16452    If the choice of partial specialization is ambiguous, a diagnostic
16453    is issued, and the error_mark_node is returned.  If there are no
16454    partial specializations of TMPL matching TYPE, then NULL_TREE is
16455    returned.  */
16456
16457 static tree
16458 most_specialized_class (tree type, tree tmpl, tsubst_flags_t complain)
16459 {
16460   tree list = NULL_TREE;
16461   tree t;
16462   tree champ;
16463   int fate;
16464   bool ambiguous_p;
16465   tree args;
16466   tree outer_args = NULL_TREE;
16467
16468   tmpl = most_general_template (tmpl);
16469   args = CLASSTYPE_TI_ARGS (type);
16470
16471   /* For determining which partial specialization to use, only the
16472      innermost args are interesting.  */
16473   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
16474     {
16475       outer_args = strip_innermost_template_args (args, 1);
16476       args = INNERMOST_TEMPLATE_ARGS (args);
16477     }
16478
16479   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
16480     {
16481       tree partial_spec_args;
16482       tree spec_args;
16483       tree parms = TREE_VALUE (t);
16484
16485       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
16486
16487       ++processing_template_decl;
16488
16489       if (outer_args)
16490         {
16491           int i;
16492
16493           /* Discard the outer levels of args, and then substitute in the
16494              template args from the enclosing class.  */
16495           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
16496           partial_spec_args = tsubst_template_args
16497             (partial_spec_args, outer_args, tf_none, NULL_TREE);
16498
16499           /* PARMS already refers to just the innermost parms, but the
16500              template parms in partial_spec_args had their levels lowered
16501              by tsubst, so we need to do the same for the parm list.  We
16502              can't just tsubst the TREE_VEC itself, as tsubst wants to
16503              treat a TREE_VEC as an argument vector.  */
16504           parms = copy_node (parms);
16505           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
16506             TREE_VEC_ELT (parms, i) =
16507               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
16508
16509         }
16510
16511       partial_spec_args =
16512           coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
16513                                  add_to_template_args (outer_args,
16514                                                        partial_spec_args),
16515                                  tmpl, tf_none,
16516                                  /*require_all_args=*/true,
16517                                  /*use_default_args=*/true);
16518
16519       --processing_template_decl;
16520
16521       if (partial_spec_args == error_mark_node)
16522         return error_mark_node;
16523
16524       spec_args = get_class_bindings (parms,
16525                                       partial_spec_args,
16526                                       args);
16527       if (spec_args)
16528         {
16529           if (outer_args)
16530             spec_args = add_to_template_args (outer_args, spec_args);
16531           list = tree_cons (spec_args, TREE_VALUE (t), list);
16532           TREE_TYPE (list) = TREE_TYPE (t);
16533         }
16534     }
16535
16536   if (! list)
16537     return NULL_TREE;
16538
16539   ambiguous_p = false;
16540   t = list;
16541   champ = t;
16542   t = TREE_CHAIN (t);
16543   for (; t; t = TREE_CHAIN (t))
16544     {
16545       fate = more_specialized_class (champ, t);
16546       if (fate == 1)
16547         ;
16548       else
16549         {
16550           if (fate == 0)
16551             {
16552               t = TREE_CHAIN (t);
16553               if (! t)
16554                 {
16555                   ambiguous_p = true;
16556                   break;
16557                 }
16558             }
16559           champ = t;
16560         }
16561     }
16562
16563   if (!ambiguous_p)
16564     for (t = list; t && t != champ; t = TREE_CHAIN (t))
16565       {
16566         fate = more_specialized_class (champ, t);
16567         if (fate != 1)
16568           {
16569             ambiguous_p = true;
16570             break;
16571           }
16572       }
16573
16574   if (ambiguous_p)
16575     {
16576       const char *str;
16577       char *spaces = NULL;
16578       if (!(complain & tf_error))
16579         return error_mark_node;
16580       error ("ambiguous class template instantiation for %q#T", type);
16581       str = ngettext ("candidate is:", "candidates are:", list_length (list));
16582       for (t = list; t; t = TREE_CHAIN (t))
16583         {
16584           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
16585           spaces = spaces ? spaces : get_spaces (str);
16586         }
16587       free (spaces);
16588       return error_mark_node;
16589     }
16590
16591   return champ;
16592 }
16593
16594 /* Explicitly instantiate DECL.  */
16595
16596 void
16597 do_decl_instantiation (tree decl, tree storage)
16598 {
16599   tree result = NULL_TREE;
16600   int extern_p = 0;
16601
16602   if (!decl || decl == error_mark_node)
16603     /* An error occurred, for which grokdeclarator has already issued
16604        an appropriate message.  */
16605     return;
16606   else if (! DECL_LANG_SPECIFIC (decl))
16607     {
16608       error ("explicit instantiation of non-template %q#D", decl);
16609       return;
16610     }
16611   else if (TREE_CODE (decl) == VAR_DECL)
16612     {
16613       /* There is an asymmetry here in the way VAR_DECLs and
16614          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
16615          the latter, the DECL we get back will be marked as a
16616          template instantiation, and the appropriate
16617          DECL_TEMPLATE_INFO will be set up.  This does not happen for
16618          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
16619          should handle VAR_DECLs as it currently handles
16620          FUNCTION_DECLs.  */
16621       if (!DECL_CLASS_SCOPE_P (decl))
16622         {
16623           error ("%qD is not a static data member of a class template", decl);
16624           return;
16625         }
16626       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
16627       if (!result || TREE_CODE (result) != VAR_DECL)
16628         {
16629           error ("no matching template for %qD found", decl);
16630           return;
16631         }
16632       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
16633         {
16634           error ("type %qT for explicit instantiation %qD does not match "
16635                  "declared type %qT", TREE_TYPE (result), decl,
16636                  TREE_TYPE (decl));
16637           return;
16638         }
16639     }
16640   else if (TREE_CODE (decl) != FUNCTION_DECL)
16641     {
16642       error ("explicit instantiation of %q#D", decl);
16643       return;
16644     }
16645   else
16646     result = decl;
16647
16648   /* Check for various error cases.  Note that if the explicit
16649      instantiation is valid the RESULT will currently be marked as an
16650      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
16651      until we get here.  */
16652
16653   if (DECL_TEMPLATE_SPECIALIZATION (result))
16654     {
16655       /* DR 259 [temp.spec].
16656
16657          Both an explicit instantiation and a declaration of an explicit
16658          specialization shall not appear in a program unless the explicit
16659          instantiation follows a declaration of the explicit specialization.
16660
16661          For a given set of template parameters, if an explicit
16662          instantiation of a template appears after a declaration of an
16663          explicit specialization for that template, the explicit
16664          instantiation has no effect.  */
16665       return;
16666     }
16667   else if (DECL_EXPLICIT_INSTANTIATION (result))
16668     {
16669       /* [temp.spec]
16670
16671          No program shall explicitly instantiate any template more
16672          than once.
16673
16674          We check DECL_NOT_REALLY_EXTERN so as not to complain when
16675          the first instantiation was `extern' and the second is not,
16676          and EXTERN_P for the opposite case.  */
16677       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
16678         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
16679       /* If an "extern" explicit instantiation follows an ordinary
16680          explicit instantiation, the template is instantiated.  */
16681       if (extern_p)
16682         return;
16683     }
16684   else if (!DECL_IMPLICIT_INSTANTIATION (result))
16685     {
16686       error ("no matching template for %qD found", result);
16687       return;
16688     }
16689   else if (!DECL_TEMPLATE_INFO (result))
16690     {
16691       permerror (input_location, "explicit instantiation of non-template %q#D", result);
16692       return;
16693     }
16694
16695   if (storage == NULL_TREE)
16696     ;
16697   else if (storage == ridpointers[(int) RID_EXTERN])
16698     {
16699       if (!in_system_header && (cxx_dialect == cxx98))
16700         pedwarn (input_location, OPT_pedantic, 
16701                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
16702                  "instantiations");
16703       extern_p = 1;
16704     }
16705   else
16706     error ("storage class %qD applied to template instantiation", storage);
16707
16708   check_explicit_instantiation_namespace (result);
16709   mark_decl_instantiated (result, extern_p);
16710   if (! extern_p)
16711     instantiate_decl (result, /*defer_ok=*/1,
16712                       /*expl_inst_class_mem_p=*/false);
16713 }
16714
16715 static void
16716 mark_class_instantiated (tree t, int extern_p)
16717 {
16718   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
16719   SET_CLASSTYPE_INTERFACE_KNOWN (t);
16720   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
16721   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
16722   if (! extern_p)
16723     {
16724       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
16725       rest_of_type_compilation (t, 1);
16726     }
16727 }
16728
16729 /* Called from do_type_instantiation through binding_table_foreach to
16730    do recursive instantiation for the type bound in ENTRY.  */
16731 static void
16732 bt_instantiate_type_proc (binding_entry entry, void *data)
16733 {
16734   tree storage = *(tree *) data;
16735
16736   if (MAYBE_CLASS_TYPE_P (entry->type)
16737       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
16738     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
16739 }
16740
16741 /* Called from do_type_instantiation to instantiate a member
16742    (a member function or a static member variable) of an
16743    explicitly instantiated class template.  */
16744 static void
16745 instantiate_class_member (tree decl, int extern_p)
16746 {
16747   mark_decl_instantiated (decl, extern_p);
16748   if (! extern_p)
16749     instantiate_decl (decl, /*defer_ok=*/1,
16750                       /*expl_inst_class_mem_p=*/true);
16751 }
16752
16753 /* Perform an explicit instantiation of template class T.  STORAGE, if
16754    non-null, is the RID for extern, inline or static.  COMPLAIN is
16755    nonzero if this is called from the parser, zero if called recursively,
16756    since the standard is unclear (as detailed below).  */
16757
16758 void
16759 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
16760 {
16761   int extern_p = 0;
16762   int nomem_p = 0;
16763   int static_p = 0;
16764   int previous_instantiation_extern_p = 0;
16765
16766   if (TREE_CODE (t) == TYPE_DECL)
16767     t = TREE_TYPE (t);
16768
16769   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
16770     {
16771       error ("explicit instantiation of non-template type %qT", t);
16772       return;
16773     }
16774
16775   complete_type (t);
16776
16777   if (!COMPLETE_TYPE_P (t))
16778     {
16779       if (complain & tf_error)
16780         error ("explicit instantiation of %q#T before definition of template",
16781                t);
16782       return;
16783     }
16784
16785   if (storage != NULL_TREE)
16786     {
16787       if (!in_system_header)
16788         {
16789           if (storage == ridpointers[(int) RID_EXTERN])
16790             {
16791               if (cxx_dialect == cxx98)
16792                 pedwarn (input_location, OPT_pedantic, 
16793                          "ISO C++ 1998 forbids the use of %<extern%> on "
16794                          "explicit instantiations");
16795             }
16796           else
16797             pedwarn (input_location, OPT_pedantic, 
16798                      "ISO C++ forbids the use of %qE"
16799                      " on explicit instantiations", storage);
16800         }
16801
16802       if (storage == ridpointers[(int) RID_INLINE])
16803         nomem_p = 1;
16804       else if (storage == ridpointers[(int) RID_EXTERN])
16805         extern_p = 1;
16806       else if (storage == ridpointers[(int) RID_STATIC])
16807         static_p = 1;
16808       else
16809         {
16810           error ("storage class %qD applied to template instantiation",
16811                  storage);
16812           extern_p = 0;
16813         }
16814     }
16815
16816   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
16817     {
16818       /* DR 259 [temp.spec].
16819
16820          Both an explicit instantiation and a declaration of an explicit
16821          specialization shall not appear in a program unless the explicit
16822          instantiation follows a declaration of the explicit specialization.
16823
16824          For a given set of template parameters, if an explicit
16825          instantiation of a template appears after a declaration of an
16826          explicit specialization for that template, the explicit
16827          instantiation has no effect.  */
16828       return;
16829     }
16830   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
16831     {
16832       /* [temp.spec]
16833
16834          No program shall explicitly instantiate any template more
16835          than once.
16836
16837          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
16838          instantiation was `extern'.  If EXTERN_P then the second is.
16839          These cases are OK.  */
16840       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
16841
16842       if (!previous_instantiation_extern_p && !extern_p
16843           && (complain & tf_error))
16844         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
16845
16846       /* If we've already instantiated the template, just return now.  */
16847       if (!CLASSTYPE_INTERFACE_ONLY (t))
16848         return;
16849     }
16850
16851   check_explicit_instantiation_namespace (TYPE_NAME (t));
16852   mark_class_instantiated (t, extern_p);
16853
16854   if (nomem_p)
16855     return;
16856
16857   {
16858     tree tmp;
16859
16860     /* In contrast to implicit instantiation, where only the
16861        declarations, and not the definitions, of members are
16862        instantiated, we have here:
16863
16864          [temp.explicit]
16865
16866          The explicit instantiation of a class template specialization
16867          implies the instantiation of all of its members not
16868          previously explicitly specialized in the translation unit
16869          containing the explicit instantiation.
16870
16871        Of course, we can't instantiate member template classes, since
16872        we don't have any arguments for them.  Note that the standard
16873        is unclear on whether the instantiation of the members are
16874        *explicit* instantiations or not.  However, the most natural
16875        interpretation is that it should be an explicit instantiation.  */
16876
16877     if (! static_p)
16878       for (tmp = TYPE_METHODS (t); tmp; tmp = DECL_CHAIN (tmp))
16879         if (TREE_CODE (tmp) == FUNCTION_DECL
16880             && DECL_TEMPLATE_INSTANTIATION (tmp))
16881           instantiate_class_member (tmp, extern_p);
16882
16883     for (tmp = TYPE_FIELDS (t); tmp; tmp = DECL_CHAIN (tmp))
16884       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
16885         instantiate_class_member (tmp, extern_p);
16886
16887     if (CLASSTYPE_NESTED_UTDS (t))
16888       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
16889                              bt_instantiate_type_proc, &storage);
16890   }
16891 }
16892
16893 /* Given a function DECL, which is a specialization of TMPL, modify
16894    DECL to be a re-instantiation of TMPL with the same template
16895    arguments.  TMPL should be the template into which tsubst'ing
16896    should occur for DECL, not the most general template.
16897
16898    One reason for doing this is a scenario like this:
16899
16900      template <class T>
16901      void f(const T&, int i);
16902
16903      void g() { f(3, 7); }
16904
16905      template <class T>
16906      void f(const T& t, const int i) { }
16907
16908    Note that when the template is first instantiated, with
16909    instantiate_template, the resulting DECL will have no name for the
16910    first parameter, and the wrong type for the second.  So, when we go
16911    to instantiate the DECL, we regenerate it.  */
16912
16913 static void
16914 regenerate_decl_from_template (tree decl, tree tmpl)
16915 {
16916   /* The arguments used to instantiate DECL, from the most general
16917      template.  */
16918   tree args;
16919   tree code_pattern;
16920
16921   args = DECL_TI_ARGS (decl);
16922   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
16923
16924   /* Make sure that we can see identifiers, and compute access
16925      correctly.  */
16926   push_access_scope (decl);
16927
16928   if (TREE_CODE (decl) == FUNCTION_DECL)
16929     {
16930       tree decl_parm;
16931       tree pattern_parm;
16932       tree specs;
16933       int args_depth;
16934       int parms_depth;
16935
16936       args_depth = TMPL_ARGS_DEPTH (args);
16937       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
16938       if (args_depth > parms_depth)
16939         args = get_innermost_template_args (args, parms_depth);
16940
16941       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
16942                                               args, tf_error, NULL_TREE);
16943       if (specs)
16944         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
16945                                                     specs);
16946
16947       /* Merge parameter declarations.  */
16948       decl_parm = skip_artificial_parms_for (decl,
16949                                              DECL_ARGUMENTS (decl));
16950       pattern_parm
16951         = skip_artificial_parms_for (code_pattern,
16952                                      DECL_ARGUMENTS (code_pattern));
16953       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
16954         {
16955           tree parm_type;
16956           tree attributes;
16957           
16958           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16959             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
16960           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
16961                               NULL_TREE);
16962           parm_type = type_decays_to (parm_type);
16963           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16964             TREE_TYPE (decl_parm) = parm_type;
16965           attributes = DECL_ATTRIBUTES (pattern_parm);
16966           if (DECL_ATTRIBUTES (decl_parm) != attributes)
16967             {
16968               DECL_ATTRIBUTES (decl_parm) = attributes;
16969               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16970             }
16971           decl_parm = DECL_CHAIN (decl_parm);
16972           pattern_parm = DECL_CHAIN (pattern_parm);
16973         }
16974       /* Merge any parameters that match with the function parameter
16975          pack.  */
16976       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
16977         {
16978           int i, len;
16979           tree expanded_types;
16980           /* Expand the TYPE_PACK_EXPANSION that provides the types for
16981              the parameters in this function parameter pack.  */
16982           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
16983                                                  args, tf_error, NULL_TREE);
16984           len = TREE_VEC_LENGTH (expanded_types);
16985           for (i = 0; i < len; i++)
16986             {
16987               tree parm_type;
16988               tree attributes;
16989           
16990               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16991                 /* Rename the parameter to include the index.  */
16992                 DECL_NAME (decl_parm) = 
16993                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
16994               parm_type = TREE_VEC_ELT (expanded_types, i);
16995               parm_type = type_decays_to (parm_type);
16996               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16997                 TREE_TYPE (decl_parm) = parm_type;
16998               attributes = DECL_ATTRIBUTES (pattern_parm);
16999               if (DECL_ATTRIBUTES (decl_parm) != attributes)
17000                 {
17001                   DECL_ATTRIBUTES (decl_parm) = attributes;
17002                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
17003                 }
17004               decl_parm = DECL_CHAIN (decl_parm);
17005             }
17006         }
17007       /* Merge additional specifiers from the CODE_PATTERN.  */
17008       if (DECL_DECLARED_INLINE_P (code_pattern)
17009           && !DECL_DECLARED_INLINE_P (decl))
17010         DECL_DECLARED_INLINE_P (decl) = 1;
17011     }
17012   else if (TREE_CODE (decl) == VAR_DECL)
17013     {
17014       DECL_INITIAL (decl) =
17015         tsubst_expr (DECL_INITIAL (code_pattern), args,
17016                      tf_error, DECL_TI_TEMPLATE (decl),
17017                      /*integral_constant_expression_p=*/false);
17018       if (VAR_HAD_UNKNOWN_BOUND (decl))
17019         TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
17020                                    tf_error, DECL_TI_TEMPLATE (decl));
17021     }
17022   else
17023     gcc_unreachable ();
17024
17025   pop_access_scope (decl);
17026 }
17027
17028 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
17029    substituted to get DECL.  */
17030
17031 tree
17032 template_for_substitution (tree decl)
17033 {
17034   tree tmpl = DECL_TI_TEMPLATE (decl);
17035
17036   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
17037      for the instantiation.  This is not always the most general
17038      template.  Consider, for example:
17039
17040         template <class T>
17041         struct S { template <class U> void f();
17042                    template <> void f<int>(); };
17043
17044      and an instantiation of S<double>::f<int>.  We want TD to be the
17045      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
17046   while (/* An instantiation cannot have a definition, so we need a
17047             more general template.  */
17048          DECL_TEMPLATE_INSTANTIATION (tmpl)
17049            /* We must also deal with friend templates.  Given:
17050
17051                 template <class T> struct S {
17052                   template <class U> friend void f() {};
17053                 };
17054
17055               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
17056               so far as the language is concerned, but that's still
17057               where we get the pattern for the instantiation from.  On
17058               other hand, if the definition comes outside the class, say:
17059
17060                 template <class T> struct S {
17061                   template <class U> friend void f();
17062                 };
17063                 template <class U> friend void f() {}
17064
17065               we don't need to look any further.  That's what the check for
17066               DECL_INITIAL is for.  */
17067           || (TREE_CODE (decl) == FUNCTION_DECL
17068               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
17069               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
17070     {
17071       /* The present template, TD, should not be a definition.  If it
17072          were a definition, we should be using it!  Note that we
17073          cannot restructure the loop to just keep going until we find
17074          a template with a definition, since that might go too far if
17075          a specialization was declared, but not defined.  */
17076       gcc_assert (TREE_CODE (decl) != VAR_DECL
17077                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
17078
17079       /* Fetch the more general template.  */
17080       tmpl = DECL_TI_TEMPLATE (tmpl);
17081     }
17082
17083   return tmpl;
17084 }
17085
17086 /* Returns true if we need to instantiate this template instance even if we
17087    know we aren't going to emit it..  */
17088
17089 bool
17090 always_instantiate_p (tree decl)
17091 {
17092   /* We always instantiate inline functions so that we can inline them.  An
17093      explicit instantiation declaration prohibits implicit instantiation of
17094      non-inline functions.  With high levels of optimization, we would
17095      normally inline non-inline functions -- but we're not allowed to do
17096      that for "extern template" functions.  Therefore, we check
17097      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
17098   return ((TREE_CODE (decl) == FUNCTION_DECL
17099            && DECL_DECLARED_INLINE_P (decl))
17100           /* And we need to instantiate static data members so that
17101              their initializers are available in integral constant
17102              expressions.  */
17103           || (TREE_CODE (decl) == VAR_DECL
17104               && decl_maybe_constant_var_p (decl)));
17105 }
17106
17107 /* Produce the definition of D, a _DECL generated from a template.  If
17108    DEFER_OK is nonzero, then we don't have to actually do the
17109    instantiation now; we just have to do it sometime.  Normally it is
17110    an error if this is an explicit instantiation but D is undefined.
17111    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
17112    explicitly instantiated class template.  */
17113
17114 tree
17115 instantiate_decl (tree d, int defer_ok,
17116                   bool expl_inst_class_mem_p)
17117 {
17118   tree tmpl = DECL_TI_TEMPLATE (d);
17119   tree gen_args;
17120   tree args;
17121   tree td;
17122   tree code_pattern;
17123   tree spec;
17124   tree gen_tmpl;
17125   bool pattern_defined;
17126   int need_push;
17127   location_t saved_loc = input_location;
17128   bool external_p;
17129
17130   /* This function should only be used to instantiate templates for
17131      functions and static member variables.  */
17132   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
17133               || TREE_CODE (d) == VAR_DECL);
17134
17135   /* Variables are never deferred; if instantiation is required, they
17136      are instantiated right away.  That allows for better code in the
17137      case that an expression refers to the value of the variable --
17138      if the variable has a constant value the referring expression can
17139      take advantage of that fact.  */
17140   if (TREE_CODE (d) == VAR_DECL
17141       || DECL_DECLARED_CONSTEXPR_P (d))
17142     defer_ok = 0;
17143
17144   /* Don't instantiate cloned functions.  Instead, instantiate the
17145      functions they cloned.  */
17146   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
17147     d = DECL_CLONED_FUNCTION (d);
17148
17149   if (DECL_TEMPLATE_INSTANTIATED (d)
17150       || DECL_TEMPLATE_SPECIALIZATION (d))
17151     /* D has already been instantiated or explicitly specialized, so
17152        there's nothing for us to do here.
17153
17154        It might seem reasonable to check whether or not D is an explicit
17155        instantiation, and, if so, stop here.  But when an explicit
17156        instantiation is deferred until the end of the compilation,
17157        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
17158        the instantiation.  */
17159     return d;
17160
17161   /* Check to see whether we know that this template will be
17162      instantiated in some other file, as with "extern template"
17163      extension.  */
17164   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
17165
17166   /* In general, we do not instantiate such templates.  */
17167   if (external_p && !always_instantiate_p (d))
17168     return d;
17169
17170   gen_tmpl = most_general_template (tmpl);
17171   gen_args = DECL_TI_ARGS (d);
17172
17173   if (tmpl != gen_tmpl)
17174     /* We should already have the extra args.  */
17175     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
17176                 == TMPL_ARGS_DEPTH (gen_args));
17177   /* And what's in the hash table should match D.  */
17178   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
17179               || spec == NULL_TREE);
17180
17181   /* This needs to happen before any tsubsting.  */
17182   if (! push_tinst_level (d))
17183     return d;
17184
17185   timevar_push (TV_PARSE);
17186
17187   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
17188      for the instantiation.  */
17189   td = template_for_substitution (d);
17190   code_pattern = DECL_TEMPLATE_RESULT (td);
17191
17192   /* We should never be trying to instantiate a member of a class
17193      template or partial specialization.  */
17194   gcc_assert (d != code_pattern);
17195
17196   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
17197       || DECL_TEMPLATE_SPECIALIZATION (td))
17198     /* In the case of a friend template whose definition is provided
17199        outside the class, we may have too many arguments.  Drop the
17200        ones we don't need.  The same is true for specializations.  */
17201     args = get_innermost_template_args
17202       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
17203   else
17204     args = gen_args;
17205
17206   if (TREE_CODE (d) == FUNCTION_DECL)
17207     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
17208   else
17209     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
17210
17211   /* We may be in the middle of deferred access check.  Disable it now.  */
17212   push_deferring_access_checks (dk_no_deferred);
17213
17214   /* Unless an explicit instantiation directive has already determined
17215      the linkage of D, remember that a definition is available for
17216      this entity.  */
17217   if (pattern_defined
17218       && !DECL_INTERFACE_KNOWN (d)
17219       && !DECL_NOT_REALLY_EXTERN (d))
17220     mark_definable (d);
17221
17222   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
17223   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
17224   input_location = DECL_SOURCE_LOCATION (d);
17225
17226   /* If D is a member of an explicitly instantiated class template,
17227      and no definition is available, treat it like an implicit
17228      instantiation.  */
17229   if (!pattern_defined && expl_inst_class_mem_p
17230       && DECL_EXPLICIT_INSTANTIATION (d))
17231     {
17232       /* Leave linkage flags alone on instantiations with anonymous
17233          visibility.  */
17234       if (TREE_PUBLIC (d))
17235         {
17236           DECL_NOT_REALLY_EXTERN (d) = 0;
17237           DECL_INTERFACE_KNOWN (d) = 0;
17238         }
17239       SET_DECL_IMPLICIT_INSTANTIATION (d);
17240     }
17241
17242   /* Recheck the substitutions to obtain any warning messages
17243      about ignoring cv qualifiers.  Don't do this for artificial decls,
17244      as it breaks the context-sensitive substitution for lambda op(). */
17245   if (!defer_ok && !DECL_ARTIFICIAL (d))
17246     {
17247       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
17248       tree type = TREE_TYPE (gen);
17249
17250       /* Make sure that we can see identifiers, and compute access
17251          correctly.  D is already the target FUNCTION_DECL with the
17252          right context.  */
17253       push_access_scope (d);
17254
17255       if (TREE_CODE (gen) == FUNCTION_DECL)
17256         {
17257           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
17258           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
17259                                           d);
17260           /* Don't simply tsubst the function type, as that will give
17261              duplicate warnings about poor parameter qualifications.
17262              The function arguments are the same as the decl_arguments
17263              without the top level cv qualifiers.  */
17264           type = TREE_TYPE (type);
17265         }
17266       tsubst (type, gen_args, tf_warning_or_error, d);
17267
17268       pop_access_scope (d);
17269     }
17270
17271   /* Defer all other templates, unless we have been explicitly
17272      forbidden from doing so.  */
17273   if (/* If there is no definition, we cannot instantiate the
17274          template.  */
17275       ! pattern_defined
17276       /* If it's OK to postpone instantiation, do so.  */
17277       || defer_ok
17278       /* If this is a static data member that will be defined
17279          elsewhere, we don't want to instantiate the entire data
17280          member, but we do want to instantiate the initializer so that
17281          we can substitute that elsewhere.  */
17282       || (external_p && TREE_CODE (d) == VAR_DECL))
17283     {
17284       /* The definition of the static data member is now required so
17285          we must substitute the initializer.  */
17286       if (TREE_CODE (d) == VAR_DECL
17287           && !DECL_INITIAL (d)
17288           && DECL_INITIAL (code_pattern))
17289         {
17290           tree ns;
17291           tree init;
17292           bool const_init = false;
17293
17294           ns = decl_namespace_context (d);
17295           push_nested_namespace (ns);
17296           push_nested_class (DECL_CONTEXT (d));
17297           init = tsubst_expr (DECL_INITIAL (code_pattern),
17298                               args,
17299                               tf_warning_or_error, NULL_TREE,
17300                               /*integral_constant_expression_p=*/false);
17301           /* Make sure the initializer is still constant, in case of
17302              circular dependency (template/instantiate6.C). */
17303           const_init
17304             = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
17305           cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
17306                           /*asmspec_tree=*/NULL_TREE,
17307                           LOOKUP_ONLYCONVERTING);
17308           pop_nested_class ();
17309           pop_nested_namespace (ns);
17310         }
17311
17312       /* We restore the source position here because it's used by
17313          add_pending_template.  */
17314       input_location = saved_loc;
17315
17316       if (at_eof && !pattern_defined
17317           && DECL_EXPLICIT_INSTANTIATION (d)
17318           && DECL_NOT_REALLY_EXTERN (d))
17319         /* [temp.explicit]
17320
17321            The definition of a non-exported function template, a
17322            non-exported member function template, or a non-exported
17323            member function or static data member of a class template
17324            shall be present in every translation unit in which it is
17325            explicitly instantiated.  */
17326         permerror (input_location,  "explicit instantiation of %qD "
17327                    "but no definition available", d);
17328
17329       /* If we're in unevaluated context, we just wanted to get the
17330          constant value; this isn't an odr use, so don't queue
17331          a full instantiation.  */
17332       if (cp_unevaluated_operand != 0)
17333         goto out;
17334       /* ??? Historically, we have instantiated inline functions, even
17335          when marked as "extern template".  */
17336       if (!(external_p && TREE_CODE (d) == VAR_DECL))
17337         add_pending_template (d);
17338       goto out;
17339     }
17340   /* Tell the repository that D is available in this translation unit
17341      -- and see if it is supposed to be instantiated here.  */
17342   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
17343     {
17344       /* In a PCH file, despite the fact that the repository hasn't
17345          requested instantiation in the PCH it is still possible that
17346          an instantiation will be required in a file that includes the
17347          PCH.  */
17348       if (pch_file)
17349         add_pending_template (d);
17350       /* Instantiate inline functions so that the inliner can do its
17351          job, even though we'll not be emitting a copy of this
17352          function.  */
17353       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
17354         goto out;
17355     }
17356
17357   need_push = !cfun || !global_bindings_p ();
17358   if (need_push)
17359     push_to_top_level ();
17360
17361   /* Mark D as instantiated so that recursive calls to
17362      instantiate_decl do not try to instantiate it again.  */
17363   DECL_TEMPLATE_INSTANTIATED (d) = 1;
17364
17365   /* Regenerate the declaration in case the template has been modified
17366      by a subsequent redeclaration.  */
17367   regenerate_decl_from_template (d, td);
17368
17369   /* We already set the file and line above.  Reset them now in case
17370      they changed as a result of calling regenerate_decl_from_template.  */
17371   input_location = DECL_SOURCE_LOCATION (d);
17372
17373   if (TREE_CODE (d) == VAR_DECL)
17374     {
17375       tree init;
17376       bool const_init = false;
17377
17378       /* Clear out DECL_RTL; whatever was there before may not be right
17379          since we've reset the type of the declaration.  */
17380       SET_DECL_RTL (d, NULL);
17381       DECL_IN_AGGR_P (d) = 0;
17382
17383       /* The initializer is placed in DECL_INITIAL by
17384          regenerate_decl_from_template so we don't need to
17385          push/pop_access_scope again here.  Pull it out so that
17386          cp_finish_decl can process it.  */
17387       init = DECL_INITIAL (d);
17388       DECL_INITIAL (d) = NULL_TREE;
17389       DECL_INITIALIZED_P (d) = 0;
17390
17391       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
17392          initializer.  That function will defer actual emission until
17393          we have a chance to determine linkage.  */
17394       DECL_EXTERNAL (d) = 0;
17395
17396       /* Enter the scope of D so that access-checking works correctly.  */
17397       push_nested_class (DECL_CONTEXT (d));
17398       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
17399       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
17400       pop_nested_class ();
17401     }
17402   else if (TREE_CODE (d) == FUNCTION_DECL)
17403     {
17404       htab_t saved_local_specializations;
17405       tree subst_decl;
17406       tree tmpl_parm;
17407       tree spec_parm;
17408
17409       /* Save away the current list, in case we are instantiating one
17410          template from within the body of another.  */
17411       saved_local_specializations = local_specializations;
17412
17413       /* Set up the list of local specializations.  */
17414       local_specializations = htab_create (37,
17415                                            hash_local_specialization,
17416                                            eq_local_specializations,
17417                                            NULL);
17418
17419       /* Set up context.  */
17420       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
17421
17422       /* Create substitution entries for the parameters.  */
17423       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
17424       tmpl_parm = DECL_ARGUMENTS (subst_decl);
17425       spec_parm = DECL_ARGUMENTS (d);
17426       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
17427         {
17428           register_local_specialization (spec_parm, tmpl_parm);
17429           spec_parm = skip_artificial_parms_for (d, spec_parm);
17430           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
17431         }
17432       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
17433         {
17434           register_local_specialization (spec_parm, tmpl_parm);
17435           tmpl_parm = DECL_CHAIN (tmpl_parm);
17436           spec_parm = DECL_CHAIN (spec_parm);
17437         }
17438       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
17439         {
17440           /* Register the (value) argument pack as a specialization of
17441              TMPL_PARM, then move on.  */
17442           tree argpack = make_fnparm_pack (spec_parm);
17443           register_local_specialization (argpack, tmpl_parm);
17444           tmpl_parm = DECL_CHAIN (tmpl_parm);
17445           spec_parm = NULL_TREE;
17446         }
17447       gcc_assert (!spec_parm);
17448
17449       /* Substitute into the body of the function.  */
17450       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
17451                    tf_warning_or_error, tmpl,
17452                    /*integral_constant_expression_p=*/false);
17453
17454       /* Set the current input_location to the end of the function
17455          so that finish_function knows where we are.  */
17456       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
17457
17458       /* We don't need the local specializations any more.  */
17459       htab_delete (local_specializations);
17460       local_specializations = saved_local_specializations;
17461
17462       /* Finish the function.  */
17463       d = finish_function (0);
17464       expand_or_defer_fn (d);
17465     }
17466
17467   /* We're not deferring instantiation any more.  */
17468   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
17469
17470   if (need_push)
17471     pop_from_top_level ();
17472
17473 out:
17474   input_location = saved_loc;
17475   pop_deferring_access_checks ();
17476   pop_tinst_level ();
17477
17478   timevar_pop (TV_PARSE);
17479
17480   return d;
17481 }
17482
17483 /* Run through the list of templates that we wish we could
17484    instantiate, and instantiate any we can.  RETRIES is the
17485    number of times we retry pending template instantiation.  */
17486
17487 void
17488 instantiate_pending_templates (int retries)
17489 {
17490   int reconsider;
17491   location_t saved_loc = input_location;
17492
17493   /* Instantiating templates may trigger vtable generation.  This in turn
17494      may require further template instantiations.  We place a limit here
17495      to avoid infinite loop.  */
17496   if (pending_templates && retries >= max_tinst_depth)
17497     {
17498       tree decl = pending_templates->tinst->decl;
17499
17500       error ("template instantiation depth exceeds maximum of %d"
17501              " instantiating %q+D, possibly from virtual table generation"
17502              " (use -ftemplate-depth= to increase the maximum)",
17503              max_tinst_depth, decl);
17504       if (TREE_CODE (decl) == FUNCTION_DECL)
17505         /* Pretend that we defined it.  */
17506         DECL_INITIAL (decl) = error_mark_node;
17507       return;
17508     }
17509
17510   do
17511     {
17512       struct pending_template **t = &pending_templates;
17513       struct pending_template *last = NULL;
17514       reconsider = 0;
17515       while (*t)
17516         {
17517           tree instantiation = reopen_tinst_level ((*t)->tinst);
17518           bool complete = false;
17519
17520           if (TYPE_P (instantiation))
17521             {
17522               tree fn;
17523
17524               if (!COMPLETE_TYPE_P (instantiation))
17525                 {
17526                   instantiate_class_template (instantiation);
17527                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
17528                     for (fn = TYPE_METHODS (instantiation);
17529                          fn;
17530                          fn = TREE_CHAIN (fn))
17531                       if (! DECL_ARTIFICIAL (fn))
17532                         instantiate_decl (fn,
17533                                           /*defer_ok=*/0,
17534                                           /*expl_inst_class_mem_p=*/false);
17535                   if (COMPLETE_TYPE_P (instantiation))
17536                     reconsider = 1;
17537                 }
17538
17539               complete = COMPLETE_TYPE_P (instantiation);
17540             }
17541           else
17542             {
17543               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
17544                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
17545                 {
17546                   instantiation
17547                     = instantiate_decl (instantiation,
17548                                         /*defer_ok=*/0,
17549                                         /*expl_inst_class_mem_p=*/false);
17550                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
17551                     reconsider = 1;
17552                 }
17553
17554               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
17555                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
17556             }
17557
17558           if (complete)
17559             /* If INSTANTIATION has been instantiated, then we don't
17560                need to consider it again in the future.  */
17561             *t = (*t)->next;
17562           else
17563             {
17564               last = *t;
17565               t = &(*t)->next;
17566             }
17567           tinst_depth = 0;
17568           current_tinst_level = NULL;
17569         }
17570       last_pending_template = last;
17571     }
17572   while (reconsider);
17573
17574   input_location = saved_loc;
17575 }
17576
17577 /* Substitute ARGVEC into T, which is a list of initializers for
17578    either base class or a non-static data member.  The TREE_PURPOSEs
17579    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
17580    instantiate_decl.  */
17581
17582 static tree
17583 tsubst_initializer_list (tree t, tree argvec)
17584 {
17585   tree inits = NULL_TREE;
17586
17587   for (; t; t = TREE_CHAIN (t))
17588     {
17589       tree decl;
17590       tree init;
17591       tree expanded_bases = NULL_TREE;
17592       tree expanded_arguments = NULL_TREE;
17593       int i, len = 1;
17594
17595       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
17596         {
17597           tree expr;
17598           tree arg;
17599
17600           /* Expand the base class expansion type into separate base
17601              classes.  */
17602           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
17603                                                  tf_warning_or_error,
17604                                                  NULL_TREE);
17605           if (expanded_bases == error_mark_node)
17606             continue;
17607           
17608           /* We'll be building separate TREE_LISTs of arguments for
17609              each base.  */
17610           len = TREE_VEC_LENGTH (expanded_bases);
17611           expanded_arguments = make_tree_vec (len);
17612           for (i = 0; i < len; i++)
17613             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
17614
17615           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
17616              expand each argument in the TREE_VALUE of t.  */
17617           expr = make_node (EXPR_PACK_EXPANSION);
17618           PACK_EXPANSION_PARAMETER_PACKS (expr) =
17619             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
17620
17621           if (TREE_VALUE (t) == void_type_node)
17622             /* VOID_TYPE_NODE is used to indicate
17623                value-initialization.  */
17624             {
17625               for (i = 0; i < len; i++)
17626                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
17627             }
17628           else
17629             {
17630               /* Substitute parameter packs into each argument in the
17631                  TREE_LIST.  */
17632               in_base_initializer = 1;
17633               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
17634                 {
17635                   tree expanded_exprs;
17636
17637                   /* Expand the argument.  */
17638                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
17639                   expanded_exprs 
17640                     = tsubst_pack_expansion (expr, argvec,
17641                                              tf_warning_or_error,
17642                                              NULL_TREE);
17643                   if (expanded_exprs == error_mark_node)
17644                     continue;
17645
17646                   /* Prepend each of the expanded expressions to the
17647                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
17648                   for (i = 0; i < len; i++)
17649                     {
17650                       TREE_VEC_ELT (expanded_arguments, i) = 
17651                         tree_cons (NULL_TREE, 
17652                                    TREE_VEC_ELT (expanded_exprs, i),
17653                                    TREE_VEC_ELT (expanded_arguments, i));
17654                     }
17655                 }
17656               in_base_initializer = 0;
17657
17658               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
17659                  since we built them backwards.  */
17660               for (i = 0; i < len; i++)
17661                 {
17662                   TREE_VEC_ELT (expanded_arguments, i) = 
17663                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
17664                 }
17665             }
17666         }
17667
17668       for (i = 0; i < len; ++i)
17669         {
17670           if (expanded_bases)
17671             {
17672               decl = TREE_VEC_ELT (expanded_bases, i);
17673               decl = expand_member_init (decl);
17674               init = TREE_VEC_ELT (expanded_arguments, i);
17675             }
17676           else
17677             {
17678               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
17679                                   tf_warning_or_error, NULL_TREE);
17680
17681               decl = expand_member_init (decl);
17682               if (decl && !DECL_P (decl))
17683                 in_base_initializer = 1;
17684
17685               init = TREE_VALUE (t);
17686               if (init != void_type_node)
17687                 init = tsubst_expr (init, argvec,
17688                                     tf_warning_or_error, NULL_TREE,
17689                                     /*integral_constant_expression_p=*/false);
17690               in_base_initializer = 0;
17691             }
17692
17693           if (decl)
17694             {
17695               init = build_tree_list (decl, init);
17696               TREE_CHAIN (init) = inits;
17697               inits = init;
17698             }
17699         }
17700     }
17701   return inits;
17702 }
17703
17704 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
17705
17706 static void
17707 set_current_access_from_decl (tree decl)
17708 {
17709   if (TREE_PRIVATE (decl))
17710     current_access_specifier = access_private_node;
17711   else if (TREE_PROTECTED (decl))
17712     current_access_specifier = access_protected_node;
17713   else
17714     current_access_specifier = access_public_node;
17715 }
17716
17717 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
17718    is the instantiation (which should have been created with
17719    start_enum) and ARGS are the template arguments to use.  */
17720
17721 static void
17722 tsubst_enum (tree tag, tree newtag, tree args)
17723 {
17724   tree e;
17725
17726   if (SCOPED_ENUM_P (newtag))
17727     begin_scope (sk_scoped_enum, newtag);
17728
17729   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
17730     {
17731       tree value;
17732       tree decl;
17733
17734       decl = TREE_VALUE (e);
17735       /* Note that in a template enum, the TREE_VALUE is the
17736          CONST_DECL, not the corresponding INTEGER_CST.  */
17737       value = tsubst_expr (DECL_INITIAL (decl),
17738                            args, tf_warning_or_error, NULL_TREE,
17739                            /*integral_constant_expression_p=*/true);
17740
17741       /* Give this enumeration constant the correct access.  */
17742       set_current_access_from_decl (decl);
17743
17744       /* Actually build the enumerator itself.  */
17745       build_enumerator
17746         (DECL_NAME (decl), value, newtag, DECL_SOURCE_LOCATION (decl));
17747     }
17748
17749   if (SCOPED_ENUM_P (newtag))
17750     finish_scope ();
17751
17752   finish_enum_value_list (newtag);
17753   finish_enum (newtag);
17754
17755   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
17756     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
17757 }
17758
17759 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
17760    its type -- but without substituting the innermost set of template
17761    arguments.  So, innermost set of template parameters will appear in
17762    the type.  */
17763
17764 tree
17765 get_mostly_instantiated_function_type (tree decl)
17766 {
17767   tree fn_type;
17768   tree tmpl;
17769   tree targs;
17770   tree tparms;
17771   int parm_depth;
17772
17773   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
17774   targs = DECL_TI_ARGS (decl);
17775   tparms = DECL_TEMPLATE_PARMS (tmpl);
17776   parm_depth = TMPL_PARMS_DEPTH (tparms);
17777
17778   /* There should be as many levels of arguments as there are levels
17779      of parameters.  */
17780   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
17781
17782   fn_type = TREE_TYPE (tmpl);
17783
17784   if (parm_depth == 1)
17785     /* No substitution is necessary.  */
17786     ;
17787   else
17788     {
17789       int i, save_access_control;
17790       tree partial_args;
17791
17792       /* Replace the innermost level of the TARGS with NULL_TREEs to
17793          let tsubst know not to substitute for those parameters.  */
17794       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
17795       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
17796         SET_TMPL_ARGS_LEVEL (partial_args, i,
17797                              TMPL_ARGS_LEVEL (targs, i));
17798       SET_TMPL_ARGS_LEVEL (partial_args,
17799                            TMPL_ARGS_DEPTH (targs),
17800                            make_tree_vec (DECL_NTPARMS (tmpl)));
17801
17802       /* Disable access control as this function is used only during
17803          name-mangling.  */
17804       save_access_control = flag_access_control;
17805       flag_access_control = 0;
17806
17807       ++processing_template_decl;
17808       /* Now, do the (partial) substitution to figure out the
17809          appropriate function type.  */
17810       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
17811       --processing_template_decl;
17812
17813       /* Substitute into the template parameters to obtain the real
17814          innermost set of parameters.  This step is important if the
17815          innermost set of template parameters contains value
17816          parameters whose types depend on outer template parameters.  */
17817       TREE_VEC_LENGTH (partial_args)--;
17818       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
17819
17820       flag_access_control = save_access_control;
17821     }
17822
17823   return fn_type;
17824 }
17825
17826 /* Return truthvalue if we're processing a template different from
17827    the last one involved in diagnostics.  */
17828 int
17829 problematic_instantiation_changed (void)
17830 {
17831   return last_template_error_tick != tinst_level_tick;
17832 }
17833
17834 /* Remember current template involved in diagnostics.  */
17835 void
17836 record_last_problematic_instantiation (void)
17837 {
17838   last_template_error_tick = tinst_level_tick;
17839 }
17840
17841 struct tinst_level *
17842 current_instantiation (void)
17843 {
17844   return current_tinst_level;
17845 }
17846
17847 /* [temp.param] Check that template non-type parm TYPE is of an allowable
17848    type. Return zero for ok, nonzero for disallowed. Issue error and
17849    warning messages under control of COMPLAIN.  */
17850
17851 static int
17852 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
17853 {
17854   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
17855     return 0;
17856   else if (POINTER_TYPE_P (type))
17857     return 0;
17858   else if (TYPE_PTR_TO_MEMBER_P (type))
17859     return 0;
17860   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
17861     return 0;
17862   else if (TREE_CODE (type) == TYPENAME_TYPE)
17863     return 0;
17864
17865   if (complain & tf_error)
17866     error ("%q#T is not a valid type for a template constant parameter", type);
17867   return 1;
17868 }
17869
17870 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
17871    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
17872
17873 static bool
17874 dependent_type_p_r (tree type)
17875 {
17876   tree scope;
17877
17878   /* [temp.dep.type]
17879
17880      A type is dependent if it is:
17881
17882      -- a template parameter. Template template parameters are types
17883         for us (since TYPE_P holds true for them) so we handle
17884         them here.  */
17885   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17886       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
17887     return true;
17888   /* -- a qualified-id with a nested-name-specifier which contains a
17889         class-name that names a dependent type or whose unqualified-id
17890         names a dependent type.  */
17891   if (TREE_CODE (type) == TYPENAME_TYPE)
17892     return true;
17893   /* -- a cv-qualified type where the cv-unqualified type is
17894         dependent.  */
17895   type = TYPE_MAIN_VARIANT (type);
17896   /* -- a compound type constructed from any dependent type.  */
17897   if (TYPE_PTR_TO_MEMBER_P (type))
17898     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
17899             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
17900                                            (type)));
17901   else if (TREE_CODE (type) == POINTER_TYPE
17902            || TREE_CODE (type) == REFERENCE_TYPE)
17903     return dependent_type_p (TREE_TYPE (type));
17904   else if (TREE_CODE (type) == FUNCTION_TYPE
17905            || TREE_CODE (type) == METHOD_TYPE)
17906     {
17907       tree arg_type;
17908
17909       if (dependent_type_p (TREE_TYPE (type)))
17910         return true;
17911       for (arg_type = TYPE_ARG_TYPES (type);
17912            arg_type;
17913            arg_type = TREE_CHAIN (arg_type))
17914         if (dependent_type_p (TREE_VALUE (arg_type)))
17915           return true;
17916       return false;
17917     }
17918   /* -- an array type constructed from any dependent type or whose
17919         size is specified by a constant expression that is
17920         value-dependent.
17921
17922         We checked for type- and value-dependence of the bounds in
17923         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
17924   if (TREE_CODE (type) == ARRAY_TYPE)
17925     {
17926       if (TYPE_DOMAIN (type)
17927           && dependent_type_p (TYPE_DOMAIN (type)))
17928         return true;
17929       return dependent_type_p (TREE_TYPE (type));
17930     }
17931
17932   /* -- a template-id in which either the template name is a template
17933      parameter ...  */
17934   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
17935     return true;
17936   /* ... or any of the template arguments is a dependent type or
17937         an expression that is type-dependent or value-dependent.  */
17938   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
17939            && (any_dependent_template_arguments_p
17940                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
17941     return true;
17942
17943   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
17944      argument of the `typeof' expression is not type-dependent, then
17945      it should already been have resolved.  */
17946   if (TREE_CODE (type) == TYPEOF_TYPE
17947       || TREE_CODE (type) == DECLTYPE_TYPE)
17948     return true;
17949
17950   /* A template argument pack is dependent if any of its packed
17951      arguments are.  */
17952   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
17953     {
17954       tree args = ARGUMENT_PACK_ARGS (type);
17955       int i, len = TREE_VEC_LENGTH (args);
17956       for (i = 0; i < len; ++i)
17957         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17958           return true;
17959     }
17960
17961   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
17962      be template parameters.  */
17963   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
17964     return true;
17965
17966   /* The standard does not specifically mention types that are local
17967      to template functions or local classes, but they should be
17968      considered dependent too.  For example:
17969
17970        template <int I> void f() {
17971          enum E { a = I };
17972          S<sizeof (E)> s;
17973        }
17974
17975      The size of `E' cannot be known until the value of `I' has been
17976      determined.  Therefore, `E' must be considered dependent.  */
17977   scope = TYPE_CONTEXT (type);
17978   if (scope && TYPE_P (scope))
17979     return dependent_type_p (scope);
17980   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
17981     return type_dependent_expression_p (scope);
17982
17983   /* Other types are non-dependent.  */
17984   return false;
17985 }
17986
17987 /* Returns TRUE if TYPE is dependent, in the sense of
17988    [temp.dep.type].  Note that a NULL type is considered dependent.  */
17989
17990 bool
17991 dependent_type_p (tree type)
17992 {
17993   /* If there are no template parameters in scope, then there can't be
17994      any dependent types.  */
17995   if (!processing_template_decl)
17996     {
17997       /* If we are not processing a template, then nobody should be
17998          providing us with a dependent type.  */
17999       gcc_assert (type);
18000       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
18001       return false;
18002     }
18003
18004   /* If the type is NULL, we have not computed a type for the entity
18005      in question; in that case, the type is dependent.  */
18006   if (!type)
18007     return true;
18008
18009   /* Erroneous types can be considered non-dependent.  */
18010   if (type == error_mark_node)
18011     return false;
18012
18013   /* If we have not already computed the appropriate value for TYPE,
18014      do so now.  */
18015   if (!TYPE_DEPENDENT_P_VALID (type))
18016     {
18017       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
18018       TYPE_DEPENDENT_P_VALID (type) = 1;
18019     }
18020
18021   return TYPE_DEPENDENT_P (type);
18022 }
18023
18024 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
18025    lookup.  In other words, a dependent type that is not the current
18026    instantiation.  */
18027
18028 bool
18029 dependent_scope_p (tree scope)
18030 {
18031   return (scope && TYPE_P (scope) && dependent_type_p (scope)
18032           && !currently_open_class (scope));
18033 }
18034
18035 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
18036    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
18037    expression.  */
18038
18039 /* Note that this predicate is not appropriate for general expressions;
18040    only constant expressions (that satisfy potential_constant_expression)
18041    can be tested for value dependence.
18042
18043    We should really also have a predicate for "instantiation-dependent".
18044
18045    fold_non_dependent_expr: fold if constant and not type-dependent and not value-dependent.
18046      (what about instantiation-dependent constant-expressions?)
18047    is_late_template_attribute: defer if instantiation-dependent.
18048    compute_array_index_type: proceed if constant and not t- or v-dependent
18049      if instantiation-dependent, need to remember full expression
18050    uses_template_parms: FIXME - need to audit callers
18051    tsubst_decl [function_decl]: Why is this using value_dependent_expression_p?
18052    dependent_type_p [array_type]: dependent if index type is dependent
18053      (or non-constant?)
18054    static_assert - instantiation-dependent */
18055
18056 bool
18057 value_dependent_expression_p (tree expression)
18058 {
18059   if (!processing_template_decl)
18060     return false;
18061
18062   /* A name declared with a dependent type.  */
18063   if (DECL_P (expression) && type_dependent_expression_p (expression))
18064     return true;
18065
18066   switch (TREE_CODE (expression))
18067     {
18068     case IDENTIFIER_NODE:
18069       /* A name that has not been looked up -- must be dependent.  */
18070       return true;
18071
18072     case TEMPLATE_PARM_INDEX:
18073       /* A non-type template parm.  */
18074       return true;
18075
18076     case CONST_DECL:
18077       /* A non-type template parm.  */
18078       if (DECL_TEMPLATE_PARM_P (expression))
18079         return true;
18080       return value_dependent_expression_p (DECL_INITIAL (expression));
18081
18082     case VAR_DECL:
18083        /* A constant with integral or enumeration type and is initialized
18084           with an expression that is value-dependent.  */
18085       if (DECL_INITIAL (expression)
18086           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
18087           && value_dependent_expression_p (DECL_INITIAL (expression)))
18088         return true;
18089       return false;
18090
18091     case DYNAMIC_CAST_EXPR:
18092     case STATIC_CAST_EXPR:
18093     case CONST_CAST_EXPR:
18094     case REINTERPRET_CAST_EXPR:
18095     case CAST_EXPR:
18096       /* These expressions are value-dependent if the type to which
18097          the cast occurs is dependent or the expression being casted
18098          is value-dependent.  */
18099       {
18100         tree type = TREE_TYPE (expression);
18101
18102         if (dependent_type_p (type))
18103           return true;
18104
18105         /* A functional cast has a list of operands.  */
18106         expression = TREE_OPERAND (expression, 0);
18107         if (!expression)
18108           {
18109             /* If there are no operands, it must be an expression such
18110                as "int()". This should not happen for aggregate types
18111                because it would form non-constant expressions.  */
18112             gcc_assert (cxx_dialect >= cxx0x
18113                         || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
18114
18115             return false;
18116           }
18117
18118         if (TREE_CODE (expression) == TREE_LIST)
18119           return any_value_dependent_elements_p (expression);
18120
18121         return value_dependent_expression_p (expression);
18122       }
18123
18124     case SIZEOF_EXPR:
18125     case ALIGNOF_EXPR:
18126     case TYPEID_EXPR:
18127       /* A `sizeof' expression is value-dependent if the operand is
18128          type-dependent or is a pack expansion.  */
18129       expression = TREE_OPERAND (expression, 0);
18130       if (PACK_EXPANSION_P (expression))
18131         return true;
18132       else if (TYPE_P (expression))
18133         return dependent_type_p (expression);
18134       return type_dependent_expression_p (expression);
18135
18136     case AT_ENCODE_EXPR:
18137       /* An 'encode' expression is value-dependent if the operand is
18138          type-dependent.  */
18139       expression = TREE_OPERAND (expression, 0);
18140       return dependent_type_p (expression);
18141
18142     case NOEXCEPT_EXPR:
18143       expression = TREE_OPERAND (expression, 0);
18144       /* FIXME why check value-dependency?  */
18145       return (type_dependent_expression_p (expression)
18146               || value_dependent_expression_p (expression));
18147
18148     case SCOPE_REF:
18149       {
18150         tree name = TREE_OPERAND (expression, 1);
18151         return value_dependent_expression_p (name);
18152       }
18153
18154     case COMPONENT_REF:
18155       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
18156               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
18157
18158     case NONTYPE_ARGUMENT_PACK:
18159       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
18160          is value-dependent.  */
18161       {
18162         tree values = ARGUMENT_PACK_ARGS (expression);
18163         int i, len = TREE_VEC_LENGTH (values);
18164         
18165         for (i = 0; i < len; ++i)
18166           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
18167             return true;
18168         
18169         return false;
18170       }
18171
18172     case TRAIT_EXPR:
18173       {
18174         tree type2 = TRAIT_EXPR_TYPE2 (expression);
18175         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
18176                 || (type2 ? dependent_type_p (type2) : false));
18177       }
18178
18179     case MODOP_EXPR:
18180       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
18181               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
18182
18183     case ARRAY_REF:
18184       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
18185               || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
18186
18187     case ADDR_EXPR:
18188       {
18189         tree op = TREE_OPERAND (expression, 0);
18190         return (value_dependent_expression_p (op)
18191                 || has_value_dependent_address (op));
18192       }
18193
18194     case CALL_EXPR:
18195       {
18196         tree fn = get_callee_fndecl (expression);
18197         int i, nargs;
18198         if (!fn && value_dependent_expression_p (CALL_EXPR_FN (expression)))
18199           return true;
18200         nargs = call_expr_nargs (expression);
18201         for (i = 0; i < nargs; ++i)
18202           {
18203             tree op = CALL_EXPR_ARG (expression, i);
18204             /* In a call to a constexpr member function, look through the
18205                implicit ADDR_EXPR on the object argument so that it doesn't
18206                cause the call to be considered value-dependent.  We also
18207                look through it in potential_constant_expression.  */
18208             if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
18209                 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
18210                 && TREE_CODE (op) == ADDR_EXPR)
18211               op = TREE_OPERAND (op, 0);
18212             if (value_dependent_expression_p (op))
18213               return true;
18214           }
18215         return false;
18216       }
18217
18218     default:
18219       /* A constant expression is value-dependent if any subexpression is
18220          value-dependent.  */
18221       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
18222         {
18223         case tcc_reference:
18224         case tcc_unary:
18225           return (value_dependent_expression_p
18226                   (TREE_OPERAND (expression, 0)));
18227
18228         case tcc_comparison:
18229         case tcc_binary:
18230           return ((value_dependent_expression_p
18231                    (TREE_OPERAND (expression, 0)))
18232                   || (value_dependent_expression_p
18233                       (TREE_OPERAND (expression, 1))));
18234
18235         case tcc_expression:
18236         case tcc_vl_exp:
18237           {
18238             int i;
18239             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
18240               /* In some cases, some of the operands may be missing.
18241                  (For example, in the case of PREDECREMENT_EXPR, the
18242                  amount to increment by may be missing.)  That doesn't
18243                  make the expression dependent.  */
18244               if (TREE_OPERAND (expression, i)
18245                   && (value_dependent_expression_p
18246                       (TREE_OPERAND (expression, i))))
18247                 return true;
18248             return false;
18249           }
18250
18251         default:
18252           break;
18253         }
18254     }
18255
18256   /* The expression is not value-dependent.  */
18257   return false;
18258 }
18259
18260 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
18261    [temp.dep.expr].  Note that an expression with no type is
18262    considered dependent.  Other parts of the compiler arrange for an
18263    expression with type-dependent subexpressions to have no type, so
18264    this function doesn't have to be fully recursive.  */
18265
18266 bool
18267 type_dependent_expression_p (tree expression)
18268 {
18269   if (!processing_template_decl)
18270     return false;
18271
18272   if (expression == error_mark_node)
18273     return false;
18274
18275   /* An unresolved name is always dependent.  */
18276   if (TREE_CODE (expression) == IDENTIFIER_NODE
18277       || TREE_CODE (expression) == USING_DECL)
18278     return true;
18279
18280   /* Some expression forms are never type-dependent.  */
18281   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
18282       || TREE_CODE (expression) == SIZEOF_EXPR
18283       || TREE_CODE (expression) == ALIGNOF_EXPR
18284       || TREE_CODE (expression) == AT_ENCODE_EXPR
18285       || TREE_CODE (expression) == NOEXCEPT_EXPR
18286       || TREE_CODE (expression) == TRAIT_EXPR
18287       || TREE_CODE (expression) == TYPEID_EXPR
18288       || TREE_CODE (expression) == DELETE_EXPR
18289       || TREE_CODE (expression) == VEC_DELETE_EXPR
18290       || TREE_CODE (expression) == THROW_EXPR)
18291     return false;
18292
18293   /* The types of these expressions depends only on the type to which
18294      the cast occurs.  */
18295   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
18296       || TREE_CODE (expression) == STATIC_CAST_EXPR
18297       || TREE_CODE (expression) == CONST_CAST_EXPR
18298       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
18299       || TREE_CODE (expression) == CAST_EXPR)
18300     return dependent_type_p (TREE_TYPE (expression));
18301
18302   /* The types of these expressions depends only on the type created
18303      by the expression.  */
18304   if (TREE_CODE (expression) == NEW_EXPR
18305       || TREE_CODE (expression) == VEC_NEW_EXPR)
18306     {
18307       /* For NEW_EXPR tree nodes created inside a template, either
18308          the object type itself or a TREE_LIST may appear as the
18309          operand 1.  */
18310       tree type = TREE_OPERAND (expression, 1);
18311       if (TREE_CODE (type) == TREE_LIST)
18312         /* This is an array type.  We need to check array dimensions
18313            as well.  */
18314         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
18315                || value_dependent_expression_p
18316                     (TREE_OPERAND (TREE_VALUE (type), 1));
18317       else
18318         return dependent_type_p (type);
18319     }
18320
18321   if (TREE_CODE (expression) == SCOPE_REF)
18322     {
18323       tree scope = TREE_OPERAND (expression, 0);
18324       tree name = TREE_OPERAND (expression, 1);
18325
18326       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
18327          contains an identifier associated by name lookup with one or more
18328          declarations declared with a dependent type, or...a
18329          nested-name-specifier or qualified-id that names a member of an
18330          unknown specialization.  */
18331       return (type_dependent_expression_p (name)
18332               || dependent_scope_p (scope));
18333     }
18334
18335   if (TREE_CODE (expression) == FUNCTION_DECL
18336       && DECL_LANG_SPECIFIC (expression)
18337       && DECL_TEMPLATE_INFO (expression)
18338       && (any_dependent_template_arguments_p
18339           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
18340     return true;
18341
18342   if (TREE_CODE (expression) == TEMPLATE_DECL
18343       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
18344     return false;
18345
18346   if (TREE_CODE (expression) == STMT_EXPR)
18347     expression = stmt_expr_value_expr (expression);
18348
18349   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
18350     {
18351       tree elt;
18352       unsigned i;
18353
18354       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
18355         {
18356           if (type_dependent_expression_p (elt))
18357             return true;
18358         }
18359       return false;
18360     }
18361
18362   /* A static data member of the current instantiation with incomplete
18363      array type is type-dependent, as the definition and specializations
18364      can have different bounds.  */
18365   if (TREE_CODE (expression) == VAR_DECL
18366       && DECL_CLASS_SCOPE_P (expression)
18367       && dependent_type_p (DECL_CONTEXT (expression))
18368       && VAR_HAD_UNKNOWN_BOUND (expression))
18369     return true;
18370
18371   if (TREE_TYPE (expression) == unknown_type_node)
18372     {
18373       if (TREE_CODE (expression) == ADDR_EXPR)
18374         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
18375       if (TREE_CODE (expression) == COMPONENT_REF
18376           || TREE_CODE (expression) == OFFSET_REF)
18377         {
18378           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
18379             return true;
18380           expression = TREE_OPERAND (expression, 1);
18381           if (TREE_CODE (expression) == IDENTIFIER_NODE)
18382             return false;
18383         }
18384       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
18385       if (TREE_CODE (expression) == SCOPE_REF)
18386         return false;
18387
18388       if (TREE_CODE (expression) == BASELINK)
18389         expression = BASELINK_FUNCTIONS (expression);
18390
18391       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
18392         {
18393           if (any_dependent_template_arguments_p
18394               (TREE_OPERAND (expression, 1)))
18395             return true;
18396           expression = TREE_OPERAND (expression, 0);
18397         }
18398       gcc_assert (TREE_CODE (expression) == OVERLOAD
18399                   || TREE_CODE (expression) == FUNCTION_DECL);
18400
18401       while (expression)
18402         {
18403           if (type_dependent_expression_p (OVL_CURRENT (expression)))
18404             return true;
18405           expression = OVL_NEXT (expression);
18406         }
18407       return false;
18408     }
18409
18410   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
18411
18412   return (dependent_type_p (TREE_TYPE (expression)));
18413 }
18414
18415 /* Like type_dependent_expression_p, but it also works while not processing
18416    a template definition, i.e. during substitution or mangling.  */
18417
18418 bool
18419 type_dependent_expression_p_push (tree expr)
18420 {
18421   bool b;
18422   ++processing_template_decl;
18423   b = type_dependent_expression_p (expr);
18424   --processing_template_decl;
18425   return b;
18426 }
18427
18428 /* Returns TRUE if ARGS contains a type-dependent expression.  */
18429
18430 bool
18431 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
18432 {
18433   unsigned int i;
18434   tree arg;
18435
18436   FOR_EACH_VEC_ELT (tree, args, i, arg)
18437     {
18438       if (type_dependent_expression_p (arg))
18439         return true;
18440     }
18441   return false;
18442 }
18443
18444 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
18445    expressions) contains any value-dependent expressions.  */
18446
18447 bool
18448 any_value_dependent_elements_p (const_tree list)
18449 {
18450   for (; list; list = TREE_CHAIN (list))
18451     if (value_dependent_expression_p (TREE_VALUE (list)))
18452       return true;
18453
18454   return false;
18455 }
18456
18457 /* Returns TRUE if the ARG (a template argument) is dependent.  */
18458
18459 bool
18460 dependent_template_arg_p (tree arg)
18461 {
18462   if (!processing_template_decl)
18463     return false;
18464
18465   /* Assume a template argument that was wrongly written by the user
18466      is dependent. This is consistent with what
18467      any_dependent_template_arguments_p [that calls this function]
18468      does.  */
18469   if (arg == error_mark_node)
18470     return true;
18471
18472   if (TREE_CODE (arg) == TEMPLATE_DECL
18473       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
18474     return dependent_template_p (arg);
18475   else if (ARGUMENT_PACK_P (arg))
18476     {
18477       tree args = ARGUMENT_PACK_ARGS (arg);
18478       int i, len = TREE_VEC_LENGTH (args);
18479       for (i = 0; i < len; ++i)
18480         {
18481           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
18482             return true;
18483         }
18484
18485       return false;
18486     }
18487   else if (TYPE_P (arg))
18488     return dependent_type_p (arg);
18489   else
18490     return (type_dependent_expression_p (arg)
18491             || value_dependent_expression_p (arg));
18492 }
18493
18494 /* Returns true if ARGS (a collection of template arguments) contains
18495    any types that require structural equality testing.  */
18496
18497 bool
18498 any_template_arguments_need_structural_equality_p (tree args)
18499 {
18500   int i;
18501   int j;
18502
18503   if (!args)
18504     return false;
18505   if (args == error_mark_node)
18506     return true;
18507
18508   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
18509     {
18510       tree level = TMPL_ARGS_LEVEL (args, i + 1);
18511       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
18512         {
18513           tree arg = TREE_VEC_ELT (level, j);
18514           tree packed_args = NULL_TREE;
18515           int k, len = 1;
18516
18517           if (ARGUMENT_PACK_P (arg))
18518             {
18519               /* Look inside the argument pack.  */
18520               packed_args = ARGUMENT_PACK_ARGS (arg);
18521               len = TREE_VEC_LENGTH (packed_args);
18522             }
18523
18524           for (k = 0; k < len; ++k)
18525             {
18526               if (packed_args)
18527                 arg = TREE_VEC_ELT (packed_args, k);
18528
18529               if (error_operand_p (arg))
18530                 return true;
18531               else if (TREE_CODE (arg) == TEMPLATE_DECL
18532                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
18533                 continue;
18534               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
18535                 return true;
18536               else if (!TYPE_P (arg) && TREE_TYPE (arg)
18537                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
18538                 return true;
18539             }
18540         }
18541     }
18542
18543   return false;
18544 }
18545
18546 /* Returns true if ARGS (a collection of template arguments) contains
18547    any dependent arguments.  */
18548
18549 bool
18550 any_dependent_template_arguments_p (const_tree args)
18551 {
18552   int i;
18553   int j;
18554
18555   if (!args)
18556     return false;
18557   if (args == error_mark_node)
18558     return true;
18559
18560   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
18561     {
18562       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
18563       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
18564         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
18565           return true;
18566     }
18567
18568   return false;
18569 }
18570
18571 /* Returns TRUE if the template TMPL is dependent.  */
18572
18573 bool
18574 dependent_template_p (tree tmpl)
18575 {
18576   if (TREE_CODE (tmpl) == OVERLOAD)
18577     {
18578       while (tmpl)
18579         {
18580           if (dependent_template_p (OVL_FUNCTION (tmpl)))
18581             return true;
18582           tmpl = OVL_CHAIN (tmpl);
18583         }
18584       return false;
18585     }
18586
18587   /* Template template parameters are dependent.  */
18588   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
18589       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
18590     return true;
18591   /* So are names that have not been looked up.  */
18592   if (TREE_CODE (tmpl) == SCOPE_REF
18593       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
18594     return true;
18595   /* So are member templates of dependent classes.  */
18596   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
18597     return dependent_type_p (DECL_CONTEXT (tmpl));
18598   return false;
18599 }
18600
18601 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
18602
18603 bool
18604 dependent_template_id_p (tree tmpl, tree args)
18605 {
18606   return (dependent_template_p (tmpl)
18607           || any_dependent_template_arguments_p (args));
18608 }
18609
18610 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
18611    is dependent.  */
18612
18613 bool
18614 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
18615 {
18616   int i;
18617
18618   if (!processing_template_decl)
18619     return false;
18620
18621   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
18622     {
18623       tree decl = TREE_VEC_ELT (declv, i);
18624       tree init = TREE_VEC_ELT (initv, i);
18625       tree cond = TREE_VEC_ELT (condv, i);
18626       tree incr = TREE_VEC_ELT (incrv, i);
18627
18628       if (type_dependent_expression_p (decl))
18629         return true;
18630
18631       if (init && type_dependent_expression_p (init))
18632         return true;
18633
18634       if (type_dependent_expression_p (cond))
18635         return true;
18636
18637       if (COMPARISON_CLASS_P (cond)
18638           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
18639               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
18640         return true;
18641
18642       if (TREE_CODE (incr) == MODOP_EXPR)
18643         {
18644           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
18645               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
18646             return true;
18647         }
18648       else if (type_dependent_expression_p (incr))
18649         return true;
18650       else if (TREE_CODE (incr) == MODIFY_EXPR)
18651         {
18652           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
18653             return true;
18654           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
18655             {
18656               tree t = TREE_OPERAND (incr, 1);
18657               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
18658                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
18659                 return true;
18660             }
18661         }
18662     }
18663
18664   return false;
18665 }
18666
18667 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
18668    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
18669    no such TYPE can be found.  Note that this function peers inside
18670    uninstantiated templates and therefore should be used only in
18671    extremely limited situations.  ONLY_CURRENT_P restricts this
18672    peering to the currently open classes hierarchy (which is required
18673    when comparing types).  */
18674
18675 tree
18676 resolve_typename_type (tree type, bool only_current_p)
18677 {
18678   tree scope;
18679   tree name;
18680   tree decl;
18681   int quals;
18682   tree pushed_scope;
18683   tree result;
18684
18685   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
18686
18687   scope = TYPE_CONTEXT (type);
18688   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
18689      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
18690      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
18691      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
18692      identifier  of the TYPENAME_TYPE anymore.
18693      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
18694      TYPENAME_TYPE instead, we avoid messing up with a possible
18695      typedef variant case.  */
18696   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
18697
18698   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
18699      it first before we can figure out what NAME refers to.  */
18700   if (TREE_CODE (scope) == TYPENAME_TYPE)
18701     scope = resolve_typename_type (scope, only_current_p);
18702   /* If we don't know what SCOPE refers to, then we cannot resolve the
18703      TYPENAME_TYPE.  */
18704   if (TREE_CODE (scope) == TYPENAME_TYPE)
18705     return type;
18706   /* If the SCOPE is a template type parameter, we have no way of
18707      resolving the name.  */
18708   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
18709     return type;
18710   /* If the SCOPE is not the current instantiation, there's no reason
18711      to look inside it.  */
18712   if (only_current_p && !currently_open_class (scope))
18713     return type;
18714   /* If this is a typedef, we don't want to look inside (c++/11987).  */
18715   if (typedef_variant_p (type))
18716     return type;
18717   /* If SCOPE isn't the template itself, it will not have a valid
18718      TYPE_FIELDS list.  */
18719   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
18720     /* scope is either the template itself or a compatible instantiation
18721        like X<T>, so look up the name in the original template.  */
18722     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
18723   else
18724     /* scope is a partial instantiation, so we can't do the lookup or we
18725        will lose the template arguments.  */
18726     return type;
18727   /* Enter the SCOPE so that name lookup will be resolved as if we
18728      were in the class definition.  In particular, SCOPE will no
18729      longer be considered a dependent type.  */
18730   pushed_scope = push_scope (scope);
18731   /* Look up the declaration.  */
18732   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
18733
18734   result = NULL_TREE;
18735   
18736   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
18737      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
18738   if (!decl)
18739     /*nop*/;
18740   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
18741            && TREE_CODE (decl) == TYPE_DECL)
18742     {
18743       result = TREE_TYPE (decl);
18744       if (result == error_mark_node)
18745         result = NULL_TREE;
18746     }
18747   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
18748            && DECL_CLASS_TEMPLATE_P (decl))
18749     {
18750       tree tmpl;
18751       tree args;
18752       /* Obtain the template and the arguments.  */
18753       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
18754       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
18755       /* Instantiate the template.  */
18756       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
18757                                       /*entering_scope=*/0,
18758                                       tf_error | tf_user);
18759       if (result == error_mark_node)
18760         result = NULL_TREE;
18761     }
18762   
18763   /* Leave the SCOPE.  */
18764   if (pushed_scope)
18765     pop_scope (pushed_scope);
18766
18767   /* If we failed to resolve it, return the original typename.  */
18768   if (!result)
18769     return type;
18770   
18771   /* If lookup found a typename type, resolve that too.  */
18772   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
18773     {
18774       /* Ill-formed programs can cause infinite recursion here, so we
18775          must catch that.  */
18776       TYPENAME_IS_RESOLVING_P (type) = 1;
18777       result = resolve_typename_type (result, only_current_p);
18778       TYPENAME_IS_RESOLVING_P (type) = 0;
18779     }
18780   
18781   /* Qualify the resulting type.  */
18782   quals = cp_type_quals (type);
18783   if (quals)
18784     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
18785
18786   return result;
18787 }
18788
18789 /* EXPR is an expression which is not type-dependent.  Return a proxy
18790    for EXPR that can be used to compute the types of larger
18791    expressions containing EXPR.  */
18792
18793 tree
18794 build_non_dependent_expr (tree expr)
18795 {
18796   tree inner_expr;
18797
18798   /* Preserve null pointer constants so that the type of things like
18799      "p == 0" where "p" is a pointer can be determined.  */
18800   if (null_ptr_cst_p (expr))
18801     return expr;
18802   /* Preserve OVERLOADs; the functions must be available to resolve
18803      types.  */
18804   inner_expr = expr;
18805   if (TREE_CODE (inner_expr) == STMT_EXPR)
18806     inner_expr = stmt_expr_value_expr (inner_expr);
18807   if (TREE_CODE (inner_expr) == ADDR_EXPR)
18808     inner_expr = TREE_OPERAND (inner_expr, 0);
18809   if (TREE_CODE (inner_expr) == COMPONENT_REF)
18810     inner_expr = TREE_OPERAND (inner_expr, 1);
18811   if (is_overloaded_fn (inner_expr)
18812       || TREE_CODE (inner_expr) == OFFSET_REF)
18813     return expr;
18814   /* There is no need to return a proxy for a variable.  */
18815   if (TREE_CODE (expr) == VAR_DECL)
18816     return expr;
18817   /* Preserve string constants; conversions from string constants to
18818      "char *" are allowed, even though normally a "const char *"
18819      cannot be used to initialize a "char *".  */
18820   if (TREE_CODE (expr) == STRING_CST)
18821     return expr;
18822   /* Preserve arithmetic constants, as an optimization -- there is no
18823      reason to create a new node.  */
18824   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
18825     return expr;
18826   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
18827      There is at least one place where we want to know that a
18828      particular expression is a throw-expression: when checking a ?:
18829      expression, there are special rules if the second or third
18830      argument is a throw-expression.  */
18831   if (TREE_CODE (expr) == THROW_EXPR)
18832     return expr;
18833
18834   if (TREE_CODE (expr) == COND_EXPR)
18835     return build3 (COND_EXPR,
18836                    TREE_TYPE (expr),
18837                    TREE_OPERAND (expr, 0),
18838                    (TREE_OPERAND (expr, 1)
18839                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
18840                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
18841                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
18842   if (TREE_CODE (expr) == COMPOUND_EXPR
18843       && !COMPOUND_EXPR_OVERLOADED (expr))
18844     return build2 (COMPOUND_EXPR,
18845                    TREE_TYPE (expr),
18846                    TREE_OPERAND (expr, 0),
18847                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
18848
18849   /* If the type is unknown, it can't really be non-dependent */
18850   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
18851
18852   /* Otherwise, build a NON_DEPENDENT_EXPR.
18853
18854      REFERENCE_TYPEs are not stripped for expressions in templates
18855      because doing so would play havoc with mangling.  Consider, for
18856      example:
18857
18858        template <typename T> void f<T& g>() { g(); }
18859
18860      In the body of "f", the expression for "g" will have
18861      REFERENCE_TYPE, even though the standard says that it should
18862      not.  The reason is that we must preserve the syntactic form of
18863      the expression so that mangling (say) "f<g>" inside the body of
18864      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
18865      stripped here.  */
18866   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
18867 }
18868
18869 /* ARGS is a vector of expressions as arguments to a function call.
18870    Replace the arguments with equivalent non-dependent expressions.
18871    This modifies ARGS in place.  */
18872
18873 void
18874 make_args_non_dependent (VEC(tree,gc) *args)
18875 {
18876   unsigned int ix;
18877   tree arg;
18878
18879   FOR_EACH_VEC_ELT (tree, args, ix, arg)
18880     {
18881       tree newarg = build_non_dependent_expr (arg);
18882       if (newarg != arg)
18883         VEC_replace (tree, args, ix, newarg);
18884     }
18885 }
18886
18887 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
18888    with a level one deeper than the actual template parms.  */
18889
18890 tree
18891 make_auto (void)
18892 {
18893   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
18894   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
18895                                TYPE_DECL, get_identifier ("auto"), au);
18896   TYPE_STUB_DECL (au) = TYPE_NAME (au);
18897   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
18898     (0, processing_template_decl + 1, processing_template_decl + 1,
18899      0, TYPE_NAME (au), NULL_TREE);
18900   TYPE_CANONICAL (au) = canonical_type_parameter (au);
18901   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
18902   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
18903
18904   return au;
18905 }
18906
18907 /* Given type ARG, return std::initializer_list<ARG>.  */
18908
18909 static tree
18910 listify (tree arg)
18911 {
18912   tree std_init_list = namespace_binding
18913     (get_identifier ("initializer_list"), std_node);
18914   tree argvec;
18915   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
18916     {    
18917       error ("deducing from brace-enclosed initializer list requires "
18918              "#include <initializer_list>");
18919       return error_mark_node;
18920     }
18921   argvec = make_tree_vec (1);
18922   TREE_VEC_ELT (argvec, 0) = arg;
18923   return lookup_template_class (std_init_list, argvec, NULL_TREE,
18924                                 NULL_TREE, 0, tf_warning_or_error);
18925 }
18926
18927 /* Replace auto in TYPE with std::initializer_list<auto>.  */
18928
18929 static tree
18930 listify_autos (tree type, tree auto_node)
18931 {
18932   tree init_auto = listify (auto_node);
18933   tree argvec = make_tree_vec (1);
18934   TREE_VEC_ELT (argvec, 0) = init_auto;
18935   if (processing_template_decl)
18936     argvec = add_to_template_args (current_template_args (), argvec);
18937   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18938 }
18939
18940 /* walk_tree helper for do_auto_deduction.  */
18941
18942 static tree
18943 contains_auto_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
18944                  void *type)
18945 {
18946   /* Is this a variable with the type we're looking for?  */
18947   if (DECL_P (*tp)
18948       && TREE_TYPE (*tp) == type)
18949     return *tp;
18950   else
18951     return NULL_TREE;
18952 }
18953
18954 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
18955    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
18956
18957 tree
18958 do_auto_deduction (tree type, tree init, tree auto_node)
18959 {
18960   tree parms, tparms, targs;
18961   tree args[1];
18962   tree decl;
18963   int val;
18964
18965   /* The name of the object being declared shall not appear in the
18966      initializer expression.  */
18967   decl = cp_walk_tree_without_duplicates (&init, contains_auto_r, type);
18968   if (decl)
18969     {
18970       error ("variable %q#D with %<auto%> type used in its own "
18971              "initializer", decl);
18972       return error_mark_node;
18973     }
18974
18975   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
18976      with either a new invented type template parameter U or, if the
18977      initializer is a braced-init-list (8.5.4), with
18978      std::initializer_list<U>.  */
18979   if (BRACE_ENCLOSED_INITIALIZER_P (init))
18980     type = listify_autos (type, auto_node);
18981
18982   init = resolve_nondeduced_context (init);
18983
18984   parms = build_tree_list (NULL_TREE, type);
18985   args[0] = init;
18986   tparms = make_tree_vec (1);
18987   targs = make_tree_vec (1);
18988   TREE_VEC_ELT (tparms, 0)
18989     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
18990   val = type_unification_real (tparms, targs, parms, args, 1, 0,
18991                                DEDUCE_CALL, LOOKUP_NORMAL);
18992   if (val > 0)
18993     {
18994       if (type && type != error_mark_node)
18995         /* If type is error_mark_node a diagnostic must have been
18996            emitted by now.  Also, having a mention to '<type error>'
18997            in the diagnostic is not really useful to the user.  */
18998         error ("unable to deduce %qT from %qE", type, init);
18999       return error_mark_node;
19000     }
19001
19002   /* If the list of declarators contains more than one declarator, the type
19003      of each declared variable is determined as described above. If the
19004      type deduced for the template parameter U is not the same in each
19005      deduction, the program is ill-formed.  */
19006   if (TREE_TYPE (auto_node)
19007       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
19008     {
19009       error ("inconsistent deduction for %qT: %qT and then %qT",
19010              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
19011       return error_mark_node;
19012     }
19013   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
19014
19015   if (processing_template_decl)
19016     targs = add_to_template_args (current_template_args (), targs);
19017   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
19018 }
19019
19020 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
19021    result.  */
19022
19023 tree
19024 splice_late_return_type (tree type, tree late_return_type)
19025 {
19026   tree argvec;
19027
19028   if (late_return_type == NULL_TREE)
19029     return type;
19030   argvec = make_tree_vec (1);
19031   TREE_VEC_ELT (argvec, 0) = late_return_type;
19032   if (processing_template_decl)
19033     argvec = add_to_template_args (current_template_args (), argvec);
19034   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
19035 }
19036
19037 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
19038
19039 bool
19040 is_auto (const_tree type)
19041 {
19042   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
19043       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
19044     return true;
19045   else
19046     return false;
19047 }
19048
19049 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
19050    appear as a type-specifier for the declaration in question, we don't
19051    have to look through the whole type.  */
19052
19053 tree
19054 type_uses_auto (tree type)
19055 {
19056   enum tree_code code;
19057   if (is_auto (type))
19058     return type;
19059
19060   code = TREE_CODE (type);
19061
19062   if (code == POINTER_TYPE || code == REFERENCE_TYPE
19063       || code == OFFSET_TYPE || code == FUNCTION_TYPE
19064       || code == METHOD_TYPE || code == ARRAY_TYPE)
19065     return type_uses_auto (TREE_TYPE (type));
19066
19067   if (TYPE_PTRMEMFUNC_P (type))
19068     return type_uses_auto (TREE_TYPE (TREE_TYPE
19069                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
19070
19071   return NULL_TREE;
19072 }
19073
19074 /* For a given template T, return the vector of typedefs referenced
19075    in T for which access check is needed at T instantiation time.
19076    T is either  a FUNCTION_DECL or a RECORD_TYPE.
19077    Those typedefs were added to T by the function
19078    append_type_to_template_for_access_check.  */
19079
19080 VEC(qualified_typedef_usage_t,gc)*
19081 get_types_needing_access_check (tree t)
19082 {
19083   tree ti;
19084   VEC(qualified_typedef_usage_t,gc) *result = NULL;
19085
19086   if (!t || t == error_mark_node)
19087     return NULL;
19088
19089   if (!(ti = get_template_info (t)))
19090     return NULL;
19091
19092   if (CLASS_TYPE_P (t)
19093       || TREE_CODE (t) == FUNCTION_DECL)
19094     {
19095       if (!TI_TEMPLATE (ti))
19096         return NULL;
19097
19098       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
19099     }
19100
19101   return result;
19102 }
19103
19104 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
19105    tied to T. That list of typedefs will be access checked at
19106    T instantiation time.
19107    T is either a FUNCTION_DECL or a RECORD_TYPE.
19108    TYPE_DECL is a TYPE_DECL node representing a typedef.
19109    SCOPE is the scope through which TYPE_DECL is accessed.
19110    LOCATION is the location of the usage point of TYPE_DECL.
19111
19112    This function is a subroutine of
19113    append_type_to_template_for_access_check.  */
19114
19115 static void
19116 append_type_to_template_for_access_check_1 (tree t,
19117                                             tree type_decl,
19118                                             tree scope,
19119                                             location_t location)
19120 {
19121   qualified_typedef_usage_t typedef_usage;
19122   tree ti;
19123
19124   if (!t || t == error_mark_node)
19125     return;
19126
19127   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
19128                || CLASS_TYPE_P (t))
19129               && type_decl
19130               && TREE_CODE (type_decl) == TYPE_DECL
19131               && scope);
19132
19133   if (!(ti = get_template_info (t)))
19134     return;
19135
19136   gcc_assert (TI_TEMPLATE (ti));
19137
19138   typedef_usage.typedef_decl = type_decl;
19139   typedef_usage.context = scope;
19140   typedef_usage.locus = location;
19141
19142   VEC_safe_push (qualified_typedef_usage_t, gc,
19143                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
19144                  &typedef_usage);
19145 }
19146
19147 /* Append TYPE_DECL to the template TEMPL.
19148    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
19149    At TEMPL instanciation time, TYPE_DECL will be checked to see
19150    if it can be accessed through SCOPE.
19151    LOCATION is the location of the usage point of TYPE_DECL.
19152
19153    e.g. consider the following code snippet:
19154
19155      class C
19156      {
19157        typedef int myint;
19158      };
19159
19160      template<class U> struct S
19161      {
19162        C::myint mi; // <-- usage point of the typedef C::myint
19163      };
19164
19165      S<char> s;
19166
19167    At S<char> instantiation time, we need to check the access of C::myint
19168    In other words, we need to check the access of the myint typedef through
19169    the C scope. For that purpose, this function will add the myint typedef
19170    and the scope C through which its being accessed to a list of typedefs
19171    tied to the template S. That list will be walked at template instantiation
19172    time and access check performed on each typedefs it contains.
19173    Note that this particular code snippet should yield an error because
19174    myint is private to C.  */
19175
19176 void
19177 append_type_to_template_for_access_check (tree templ,
19178                                           tree type_decl,
19179                                           tree scope,
19180                                           location_t location)
19181 {
19182   qualified_typedef_usage_t *iter;
19183   int i;
19184
19185   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
19186
19187   /* Make sure we don't append the type to the template twice.  */
19188   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
19189                     get_types_needing_access_check (templ),
19190                     i, iter)
19191     if (iter->typedef_decl == type_decl && scope == iter->context)
19192       return;
19193
19194   append_type_to_template_for_access_check_1 (templ, type_decl,
19195                                               scope, location);
19196 }
19197
19198 /* Set up the hash tables for template instantiations.  */
19199
19200 void
19201 init_template_processing (void)
19202 {
19203   decl_specializations = htab_create_ggc (37,
19204                                           hash_specialization,
19205                                           eq_specializations,
19206                                           ggc_free);
19207   type_specializations = htab_create_ggc (37,
19208                                           hash_specialization,
19209                                           eq_specializations,
19210                                           ggc_free);
19211 }
19212
19213 /* Print stats about the template hash tables for -fstats.  */
19214
19215 void
19216 print_template_statistics (void)
19217 {
19218   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
19219            "%f collisions\n", (long) htab_size (decl_specializations),
19220            (long) htab_elements (decl_specializations),
19221            htab_collisions (decl_specializations));
19222   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
19223            "%f collisions\n", (long) htab_size (type_specializations),
19224            (long) htab_elements (type_specializations),
19225            htab_collisions (type_specializations));
19226 }
19227
19228 #include "gt-cp-pt.h"