OSDN Git Service

PR c++/47956
[pf3gnuchains/gcc-fork.git] / gcc / cp / pt.c
1 /* Handle parameterized types (templates) for GNU C++.
2    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3    2001, 2002, 2003, 2004, 2005, 2007, 2008, 2009, 2010, 2011
4    Free Software Foundation, Inc.
5    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
6    Rewritten by Jason Merrill (jason@cygnus.com).
7
8 This file is part of GCC.
9
10 GCC is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3, or (at your option)
13 any later version.
14
15 GCC is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 GNU General Public License for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3.  If not see
22 <http://www.gnu.org/licenses/>.  */
23
24 /* Known bugs or deficiencies include:
25
26      all methods must be provided in header files; can't use a source
27      file that contains only the method templates and "just win".  */
28
29 #include "config.h"
30 #include "system.h"
31 #include "coretypes.h"
32 #include "tm.h"
33 #include "tree.h"
34 #include "intl.h"
35 #include "pointer-set.h"
36 #include "flags.h"
37 #include "cp-tree.h"
38 #include "c-family/c-common.h"
39 #include "c-family/c-objc.h"
40 #include "cp-objcp-common.h"
41 #include "tree-inline.h"
42 #include "decl.h"
43 #include "output.h"
44 #include "toplev.h"
45 #include "timevar.h"
46 #include "tree-iterator.h"
47 #include "vecprim.h"
48
49 /* The type of functions taking a tree, and some additional data, and
50    returning an int.  */
51 typedef int (*tree_fn_t) (tree, void*);
52
53 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
54    instantiations have been deferred, either because their definitions
55    were not yet available, or because we were putting off doing the work.  */
56 struct GTY ((chain_next ("%h.next"))) pending_template {
57   struct pending_template *next;
58   struct tinst_level *tinst;
59 };
60
61 static GTY(()) struct pending_template *pending_templates;
62 static GTY(()) struct pending_template *last_pending_template;
63
64 int processing_template_parmlist;
65 static int template_header_count;
66
67 static GTY(()) tree saved_trees;
68 static VEC(int,heap) *inline_parm_levels;
69
70 static GTY(()) struct tinst_level *current_tinst_level;
71
72 static GTY(()) tree saved_access_scope;
73
74 /* Live only within one (recursive) call to tsubst_expr.  We use
75    this to pass the statement expression node from the STMT_EXPR
76    to the EXPR_STMT that is its result.  */
77 static tree cur_stmt_expr;
78
79 /* A map from local variable declarations in the body of the template
80    presently being instantiated to the corresponding instantiated
81    local variables.  */
82 static htab_t local_specializations;
83
84 typedef struct GTY(()) spec_entry
85 {
86   tree tmpl;
87   tree args;
88   tree spec;
89 } spec_entry;
90
91 static GTY ((param_is (spec_entry)))
92   htab_t decl_specializations;
93
94 static GTY ((param_is (spec_entry)))
95   htab_t type_specializations;
96
97 /* Contains canonical template parameter types. The vector is indexed by
98    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
99    TREE_LIST, whose TREE_VALUEs contain the canonical template
100    parameters of various types and levels.  */
101 static GTY(()) VEC(tree,gc) *canonical_template_parms;
102
103 #define UNIFY_ALLOW_NONE 0
104 #define UNIFY_ALLOW_MORE_CV_QUAL 1
105 #define UNIFY_ALLOW_LESS_CV_QUAL 2
106 #define UNIFY_ALLOW_DERIVED 4
107 #define UNIFY_ALLOW_INTEGER 8
108 #define UNIFY_ALLOW_OUTER_LEVEL 16
109 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
110 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
111
112 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     pushclass (NULL_TREE);
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     popclass ();
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_NEXT (arg))
1520         val = iterative_hash_template_arg (OVL_CURRENT (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 LAMBDA_EXPR:
1573       /* A lambda can't appear in a template arg, but don't crash on
1574          erroneous input.  */
1575       gcc_assert (seen_error ());
1576       return val;
1577
1578     case CAST_EXPR:
1579     case STATIC_CAST_EXPR:
1580     case REINTERPRET_CAST_EXPR:
1581     case CONST_CAST_EXPR:
1582     case DYNAMIC_CAST_EXPR:
1583     case NEW_EXPR:
1584       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1585       /* Now hash operands as usual.  */
1586       break;
1587
1588     default:
1589       break;
1590     }
1591
1592   switch (tclass)
1593     {
1594     case tcc_type:
1595       if (TYPE_CANONICAL (arg))
1596         return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1597                                       val);
1598       else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1599         return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1600       /* Otherwise just compare the types during lookup.  */
1601       return val;
1602
1603     case tcc_declaration:
1604     case tcc_constant:
1605       return iterative_hash_expr (arg, val);
1606
1607     default:
1608       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1609       {
1610         unsigned n = TREE_OPERAND_LENGTH (arg);
1611         for (i = 0; i < n; ++i)
1612           val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1613         return val;
1614       }
1615     }
1616   gcc_unreachable ();
1617   return 0;
1618 }
1619
1620 /* Unregister the specialization SPEC as a specialization of TMPL.
1621    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1622    if the SPEC was listed as a specialization of TMPL.
1623
1624    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1625
1626 bool
1627 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1628 {
1629   spec_entry **slot;
1630   spec_entry elt;
1631
1632   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1633   elt.args = TI_ARGS (tinfo);
1634   elt.spec = NULL_TREE;
1635
1636   slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1637   if (*slot)
1638     {
1639       gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1640       gcc_assert (new_spec != NULL_TREE);
1641       (*slot)->spec = new_spec;
1642       return 1;
1643     }
1644
1645   return 0;
1646 }
1647
1648 /* Compare an entry in the local specializations hash table P1 (which
1649    is really a pointer to a TREE_LIST) with P2 (which is really a
1650    DECL).  */
1651
1652 static int
1653 eq_local_specializations (const void *p1, const void *p2)
1654 {
1655   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1656 }
1657
1658 /* Hash P1, an entry in the local specializations table.  */
1659
1660 static hashval_t
1661 hash_local_specialization (const void* p1)
1662 {
1663   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1664 }
1665
1666 /* Like register_specialization, but for local declarations.  We are
1667    registering SPEC, an instantiation of TMPL.  */
1668
1669 static void
1670 register_local_specialization (tree spec, tree tmpl)
1671 {
1672   void **slot;
1673
1674   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1675                                    htab_hash_pointer (tmpl), INSERT);
1676   *slot = build_tree_list (spec, tmpl);
1677 }
1678
1679 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1680    specialized class.  */
1681
1682 bool
1683 explicit_class_specialization_p (tree type)
1684 {
1685   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1686     return false;
1687   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1688 }
1689
1690 /* Print the list of functions at FNS, going through all the overloads
1691    for each element of the list.  Alternatively, FNS can not be a
1692    TREE_LIST, in which case it will be printed together with all the
1693    overloads.
1694
1695    MORE and *STR should respectively be FALSE and NULL when the function
1696    is called from the outside.  They are used internally on recursive
1697    calls.  print_candidates manages the two parameters and leaves NULL
1698    in *STR when it ends.  */
1699
1700 static void
1701 print_candidates_1 (tree fns, bool more, const char **str)
1702 {
1703   tree fn, fn2;
1704   char *spaces = NULL;
1705
1706   for (fn = fns; fn; fn = OVL_NEXT (fn))
1707     if (TREE_CODE (fn) == TREE_LIST)
1708       {
1709         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1710           print_candidates_1 (TREE_VALUE (fn2),
1711                               TREE_CHAIN (fn2) || more, str);
1712       }
1713     else
1714       {
1715         if (!*str)
1716           {
1717             /* Pick the prefix string.  */
1718             if (!more && !OVL_NEXT (fns))
1719               {
1720                 error ("candidate is: %+#D", OVL_CURRENT (fn));
1721                 continue;
1722               }
1723
1724             *str = _("candidates are:");
1725             spaces = get_spaces (*str);
1726           }
1727         error ("%s %+#D", *str, OVL_CURRENT (fn));
1728         *str = spaces ? spaces : *str;
1729       }
1730
1731   if (!more)
1732     {
1733       free (spaces);
1734       *str = NULL;
1735     }
1736 }
1737
1738 /* Print the list of candidate FNS in an error message.  FNS can also
1739    be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
1740
1741 void
1742 print_candidates (tree fns)
1743 {
1744   const char *str = NULL;
1745   print_candidates_1 (fns, false, &str);
1746   gcc_assert (str == NULL);
1747 }
1748
1749 /* Returns the template (one of the functions given by TEMPLATE_ID)
1750    which can be specialized to match the indicated DECL with the
1751    explicit template args given in TEMPLATE_ID.  The DECL may be
1752    NULL_TREE if none is available.  In that case, the functions in
1753    TEMPLATE_ID are non-members.
1754
1755    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1756    specialization of a member template.
1757
1758    The TEMPLATE_COUNT is the number of references to qualifying
1759    template classes that appeared in the name of the function. See
1760    check_explicit_specialization for a more accurate description.
1761
1762    TSK indicates what kind of template declaration (if any) is being
1763    declared.  TSK_TEMPLATE indicates that the declaration given by
1764    DECL, though a FUNCTION_DECL, has template parameters, and is
1765    therefore a template function.
1766
1767    The template args (those explicitly specified and those deduced)
1768    are output in a newly created vector *TARGS_OUT.
1769
1770    If it is impossible to determine the result, an error message is
1771    issued.  The error_mark_node is returned to indicate failure.  */
1772
1773 static tree
1774 determine_specialization (tree template_id,
1775                           tree decl,
1776                           tree* targs_out,
1777                           int need_member_template,
1778                           int template_count,
1779                           tmpl_spec_kind tsk)
1780 {
1781   tree fns;
1782   tree targs;
1783   tree explicit_targs;
1784   tree candidates = NULL_TREE;
1785   /* A TREE_LIST of templates of which DECL may be a specialization.
1786      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1787      corresponding TREE_PURPOSE is the set of template arguments that,
1788      when used to instantiate the template, would produce a function
1789      with the signature of DECL.  */
1790   tree templates = NULL_TREE;
1791   int header_count;
1792   struct cp_binding_level *b;
1793
1794   *targs_out = NULL_TREE;
1795
1796   if (template_id == error_mark_node || decl == error_mark_node)
1797     return error_mark_node;
1798
1799   fns = TREE_OPERAND (template_id, 0);
1800   explicit_targs = TREE_OPERAND (template_id, 1);
1801
1802   if (fns == error_mark_node)
1803     return error_mark_node;
1804
1805   /* Check for baselinks.  */
1806   if (BASELINK_P (fns))
1807     fns = BASELINK_FUNCTIONS (fns);
1808
1809   if (!is_overloaded_fn (fns))
1810     {
1811       error ("%qD is not a function template", fns);
1812       return error_mark_node;
1813     }
1814
1815   /* Count the number of template headers specified for this
1816      specialization.  */
1817   header_count = 0;
1818   for (b = current_binding_level;
1819        b->kind == sk_template_parms;
1820        b = b->level_chain)
1821     ++header_count;
1822
1823   for (; fns; fns = OVL_NEXT (fns))
1824     {
1825       tree fn = OVL_CURRENT (fns);
1826
1827       if (TREE_CODE (fn) == TEMPLATE_DECL)
1828         {
1829           tree decl_arg_types;
1830           tree fn_arg_types;
1831
1832           /* In case of explicit specialization, we need to check if
1833              the number of template headers appearing in the specialization
1834              is correct. This is usually done in check_explicit_specialization,
1835              but the check done there cannot be exhaustive when specializing
1836              member functions. Consider the following code:
1837
1838              template <> void A<int>::f(int);
1839              template <> template <> void A<int>::f(int);
1840
1841              Assuming that A<int> is not itself an explicit specialization
1842              already, the first line specializes "f" which is a non-template
1843              member function, whilst the second line specializes "f" which
1844              is a template member function. So both lines are syntactically
1845              correct, and check_explicit_specialization does not reject
1846              them.
1847
1848              Here, we can do better, as we are matching the specialization
1849              against the declarations. We count the number of template
1850              headers, and we check if they match TEMPLATE_COUNT + 1
1851              (TEMPLATE_COUNT is the number of qualifying template classes,
1852              plus there must be another header for the member template
1853              itself).
1854
1855              Notice that if header_count is zero, this is not a
1856              specialization but rather a template instantiation, so there
1857              is no check we can perform here.  */
1858           if (header_count && header_count != template_count + 1)
1859             continue;
1860
1861           /* Check that the number of template arguments at the
1862              innermost level for DECL is the same as for FN.  */
1863           if (current_binding_level->kind == sk_template_parms
1864               && !current_binding_level->explicit_spec_p
1865               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1866                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1867                                       (current_template_parms))))
1868             continue;
1869
1870           /* DECL might be a specialization of FN.  */
1871           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1872           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1873
1874           /* For a non-static member function, we need to make sure
1875              that the const qualification is the same.  Since
1876              get_bindings does not try to merge the "this" parameter,
1877              we must do the comparison explicitly.  */
1878           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1879               && !same_type_p (TREE_VALUE (fn_arg_types),
1880                                TREE_VALUE (decl_arg_types)))
1881             continue;
1882
1883           /* Skip the "this" parameter and, for constructors of
1884              classes with virtual bases, the VTT parameter.  A
1885              full specialization of a constructor will have a VTT
1886              parameter, but a template never will.  */ 
1887           decl_arg_types 
1888             = skip_artificial_parms_for (decl, decl_arg_types);
1889           fn_arg_types 
1890             = skip_artificial_parms_for (fn, fn_arg_types);
1891
1892           /* Check that the number of function parameters matches.
1893              For example,
1894                template <class T> void f(int i = 0);
1895                template <> void f<int>();
1896              The specialization f<int> is invalid but is not caught
1897              by get_bindings below.  */
1898           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1899             continue;
1900
1901           /* Function templates cannot be specializations; there are
1902              no partial specializations of functions.  Therefore, if
1903              the type of DECL does not match FN, there is no
1904              match.  */
1905           if (tsk == tsk_template)
1906             {
1907               if (compparms (fn_arg_types, decl_arg_types))
1908                 candidates = tree_cons (NULL_TREE, fn, candidates);
1909               continue;
1910             }
1911
1912           /* See whether this function might be a specialization of this
1913              template.  */
1914           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1915
1916           if (!targs)
1917             /* We cannot deduce template arguments that when used to
1918                specialize TMPL will produce DECL.  */
1919             continue;
1920
1921           /* Save this template, and the arguments deduced.  */
1922           templates = tree_cons (targs, fn, templates);
1923         }
1924       else if (need_member_template)
1925         /* FN is an ordinary member function, and we need a
1926            specialization of a member template.  */
1927         ;
1928       else if (TREE_CODE (fn) != FUNCTION_DECL)
1929         /* We can get IDENTIFIER_NODEs here in certain erroneous
1930            cases.  */
1931         ;
1932       else if (!DECL_FUNCTION_MEMBER_P (fn))
1933         /* This is just an ordinary non-member function.  Nothing can
1934            be a specialization of that.  */
1935         ;
1936       else if (DECL_ARTIFICIAL (fn))
1937         /* Cannot specialize functions that are created implicitly.  */
1938         ;
1939       else
1940         {
1941           tree decl_arg_types;
1942
1943           /* This is an ordinary member function.  However, since
1944              we're here, we can assume it's enclosing class is a
1945              template class.  For example,
1946
1947                template <typename T> struct S { void f(); };
1948                template <> void S<int>::f() {}
1949
1950              Here, S<int>::f is a non-template, but S<int> is a
1951              template class.  If FN has the same type as DECL, we
1952              might be in business.  */
1953
1954           if (!DECL_TEMPLATE_INFO (fn))
1955             /* Its enclosing class is an explicit specialization
1956                of a template class.  This is not a candidate.  */
1957             continue;
1958
1959           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1960                             TREE_TYPE (TREE_TYPE (fn))))
1961             /* The return types differ.  */
1962             continue;
1963
1964           /* Adjust the type of DECL in case FN is a static member.  */
1965           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1966           if (DECL_STATIC_FUNCTION_P (fn)
1967               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1968             decl_arg_types = TREE_CHAIN (decl_arg_types);
1969
1970           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1971                          decl_arg_types))
1972             /* They match!  */
1973             candidates = tree_cons (NULL_TREE, fn, candidates);
1974         }
1975     }
1976
1977   if (templates && TREE_CHAIN (templates))
1978     {
1979       /* We have:
1980
1981            [temp.expl.spec]
1982
1983            It is possible for a specialization with a given function
1984            signature to be instantiated from more than one function
1985            template.  In such cases, explicit specification of the
1986            template arguments must be used to uniquely identify the
1987            function template specialization being specialized.
1988
1989          Note that here, there's no suggestion that we're supposed to
1990          determine which of the candidate templates is most
1991          specialized.  However, we, also have:
1992
1993            [temp.func.order]
1994
1995            Partial ordering of overloaded function template
1996            declarations is used in the following contexts to select
1997            the function template to which a function template
1998            specialization refers:
1999
2000            -- when an explicit specialization refers to a function
2001               template.
2002
2003          So, we do use the partial ordering rules, at least for now.
2004          This extension can only serve to make invalid programs valid,
2005          so it's safe.  And, there is strong anecdotal evidence that
2006          the committee intended the partial ordering rules to apply;
2007          the EDG front end has that behavior, and John Spicer claims
2008          that the committee simply forgot to delete the wording in
2009          [temp.expl.spec].  */
2010       tree tmpl = most_specialized_instantiation (templates);
2011       if (tmpl != error_mark_node)
2012         {
2013           templates = tmpl;
2014           TREE_CHAIN (templates) = NULL_TREE;
2015         }
2016     }
2017
2018   if (templates == NULL_TREE && candidates == NULL_TREE)
2019     {
2020       error ("template-id %qD for %q+D does not match any template "
2021              "declaration", template_id, decl);
2022       if (header_count && header_count != template_count + 1)
2023         inform (input_location, "saw %d %<template<>%>, need %d for "
2024                 "specializing a member function template",
2025                 header_count, template_count + 1);
2026       return error_mark_node;
2027     }
2028   else if ((templates && TREE_CHAIN (templates))
2029            || (candidates && TREE_CHAIN (candidates))
2030            || (templates && candidates))
2031     {
2032       error ("ambiguous template specialization %qD for %q+D",
2033              template_id, decl);
2034       candidates = chainon (candidates, templates);
2035       print_candidates (candidates);
2036       return error_mark_node;
2037     }
2038
2039   /* We have one, and exactly one, match.  */
2040   if (candidates)
2041     {
2042       tree fn = TREE_VALUE (candidates);
2043       *targs_out = copy_node (DECL_TI_ARGS (fn));
2044       /* DECL is a re-declaration or partial instantiation of a template
2045          function.  */
2046       if (TREE_CODE (fn) == TEMPLATE_DECL)
2047         return fn;
2048       /* It was a specialization of an ordinary member function in a
2049          template class.  */
2050       return DECL_TI_TEMPLATE (fn);
2051     }
2052
2053   /* It was a specialization of a template.  */
2054   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2055   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2056     {
2057       *targs_out = copy_node (targs);
2058       SET_TMPL_ARGS_LEVEL (*targs_out,
2059                            TMPL_ARGS_DEPTH (*targs_out),
2060                            TREE_PURPOSE (templates));
2061     }
2062   else
2063     *targs_out = TREE_PURPOSE (templates);
2064   return TREE_VALUE (templates);
2065 }
2066
2067 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2068    but with the default argument values filled in from those in the
2069    TMPL_TYPES.  */
2070
2071 static tree
2072 copy_default_args_to_explicit_spec_1 (tree spec_types,
2073                                       tree tmpl_types)
2074 {
2075   tree new_spec_types;
2076
2077   if (!spec_types)
2078     return NULL_TREE;
2079
2080   if (spec_types == void_list_node)
2081     return void_list_node;
2082
2083   /* Substitute into the rest of the list.  */
2084   new_spec_types =
2085     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2086                                           TREE_CHAIN (tmpl_types));
2087
2088   /* Add the default argument for this parameter.  */
2089   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2090                          TREE_VALUE (spec_types),
2091                          new_spec_types);
2092 }
2093
2094 /* DECL is an explicit specialization.  Replicate default arguments
2095    from the template it specializes.  (That way, code like:
2096
2097      template <class T> void f(T = 3);
2098      template <> void f(double);
2099      void g () { f (); }
2100
2101    works, as required.)  An alternative approach would be to look up
2102    the correct default arguments at the call-site, but this approach
2103    is consistent with how implicit instantiations are handled.  */
2104
2105 static void
2106 copy_default_args_to_explicit_spec (tree decl)
2107 {
2108   tree tmpl;
2109   tree spec_types;
2110   tree tmpl_types;
2111   tree new_spec_types;
2112   tree old_type;
2113   tree new_type;
2114   tree t;
2115   tree object_type = NULL_TREE;
2116   tree in_charge = NULL_TREE;
2117   tree vtt = NULL_TREE;
2118
2119   /* See if there's anything we need to do.  */
2120   tmpl = DECL_TI_TEMPLATE (decl);
2121   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2122   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2123     if (TREE_PURPOSE (t))
2124       break;
2125   if (!t)
2126     return;
2127
2128   old_type = TREE_TYPE (decl);
2129   spec_types = TYPE_ARG_TYPES (old_type);
2130
2131   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2132     {
2133       /* Remove the this pointer, but remember the object's type for
2134          CV quals.  */
2135       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2136       spec_types = TREE_CHAIN (spec_types);
2137       tmpl_types = TREE_CHAIN (tmpl_types);
2138
2139       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2140         {
2141           /* DECL may contain more parameters than TMPL due to the extra
2142              in-charge parameter in constructors and destructors.  */
2143           in_charge = spec_types;
2144           spec_types = TREE_CHAIN (spec_types);
2145         }
2146       if (DECL_HAS_VTT_PARM_P (decl))
2147         {
2148           vtt = spec_types;
2149           spec_types = TREE_CHAIN (spec_types);
2150         }
2151     }
2152
2153   /* Compute the merged default arguments.  */
2154   new_spec_types =
2155     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2156
2157   /* Compute the new FUNCTION_TYPE.  */
2158   if (object_type)
2159     {
2160       if (vtt)
2161         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2162                                          TREE_VALUE (vtt),
2163                                          new_spec_types);
2164
2165       if (in_charge)
2166         /* Put the in-charge parameter back.  */
2167         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2168                                          TREE_VALUE (in_charge),
2169                                          new_spec_types);
2170
2171       new_type = build_method_type_directly (object_type,
2172                                              TREE_TYPE (old_type),
2173                                              new_spec_types);
2174     }
2175   else
2176     new_type = build_function_type (TREE_TYPE (old_type),
2177                                     new_spec_types);
2178   new_type = cp_build_type_attribute_variant (new_type,
2179                                               TYPE_ATTRIBUTES (old_type));
2180   new_type = build_exception_variant (new_type,
2181                                       TYPE_RAISES_EXCEPTIONS (old_type));
2182   TREE_TYPE (decl) = new_type;
2183 }
2184
2185 /* Check to see if the function just declared, as indicated in
2186    DECLARATOR, and in DECL, is a specialization of a function
2187    template.  We may also discover that the declaration is an explicit
2188    instantiation at this point.
2189
2190    Returns DECL, or an equivalent declaration that should be used
2191    instead if all goes well.  Issues an error message if something is
2192    amiss.  Returns error_mark_node if the error is not easily
2193    recoverable.
2194
2195    FLAGS is a bitmask consisting of the following flags:
2196
2197    2: The function has a definition.
2198    4: The function is a friend.
2199
2200    The TEMPLATE_COUNT is the number of references to qualifying
2201    template classes that appeared in the name of the function.  For
2202    example, in
2203
2204      template <class T> struct S { void f(); };
2205      void S<int>::f();
2206
2207    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2208    classes are not counted in the TEMPLATE_COUNT, so that in
2209
2210      template <class T> struct S {};
2211      template <> struct S<int> { void f(); }
2212      template <> void S<int>::f();
2213
2214    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2215    invalid; there should be no template <>.)
2216
2217    If the function is a specialization, it is marked as such via
2218    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2219    is set up correctly, and it is added to the list of specializations
2220    for that template.  */
2221
2222 tree
2223 check_explicit_specialization (tree declarator,
2224                                tree decl,
2225                                int template_count,
2226                                int flags)
2227 {
2228   int have_def = flags & 2;
2229   int is_friend = flags & 4;
2230   int specialization = 0;
2231   int explicit_instantiation = 0;
2232   int member_specialization = 0;
2233   tree ctype = DECL_CLASS_CONTEXT (decl);
2234   tree dname = DECL_NAME (decl);
2235   tmpl_spec_kind tsk;
2236
2237   if (is_friend)
2238     {
2239       if (!processing_specialization)
2240         tsk = tsk_none;
2241       else
2242         tsk = tsk_excessive_parms;
2243     }
2244   else
2245     tsk = current_tmpl_spec_kind (template_count);
2246
2247   switch (tsk)
2248     {
2249     case tsk_none:
2250       if (processing_specialization)
2251         {
2252           specialization = 1;
2253           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2254         }
2255       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2256         {
2257           if (is_friend)
2258             /* This could be something like:
2259
2260                template <class T> void f(T);
2261                class S { friend void f<>(int); }  */
2262             specialization = 1;
2263           else
2264             {
2265               /* This case handles bogus declarations like template <>
2266                  template <class T> void f<int>(); */
2267
2268               error ("template-id %qD in declaration of primary template",
2269                      declarator);
2270               return decl;
2271             }
2272         }
2273       break;
2274
2275     case tsk_invalid_member_spec:
2276       /* The error has already been reported in
2277          check_specialization_scope.  */
2278       return error_mark_node;
2279
2280     case tsk_invalid_expl_inst:
2281       error ("template parameter list used in explicit instantiation");
2282
2283       /* Fall through.  */
2284
2285     case tsk_expl_inst:
2286       if (have_def)
2287         error ("definition provided for explicit instantiation");
2288
2289       explicit_instantiation = 1;
2290       break;
2291
2292     case tsk_excessive_parms:
2293     case tsk_insufficient_parms:
2294       if (tsk == tsk_excessive_parms)
2295         error ("too many template parameter lists in declaration of %qD",
2296                decl);
2297       else if (template_header_count)
2298         error("too few template parameter lists in declaration of %qD", decl);
2299       else
2300         error("explicit specialization of %qD must be introduced by "
2301               "%<template <>%>", decl);
2302
2303       /* Fall through.  */
2304     case tsk_expl_spec:
2305       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2306       if (ctype)
2307         member_specialization = 1;
2308       else
2309         specialization = 1;
2310       break;
2311
2312     case tsk_template:
2313       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2314         {
2315           /* This case handles bogus declarations like template <>
2316              template <class T> void f<int>(); */
2317
2318           if (uses_template_parms (declarator))
2319             error ("function template partial specialization %qD "
2320                    "is not allowed", declarator);
2321           else
2322             error ("template-id %qD in declaration of primary template",
2323                    declarator);
2324           return decl;
2325         }
2326
2327       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2328         /* This is a specialization of a member template, without
2329            specialization the containing class.  Something like:
2330
2331              template <class T> struct S {
2332                template <class U> void f (U);
2333              };
2334              template <> template <class U> void S<int>::f(U) {}
2335
2336            That's a specialization -- but of the entire template.  */
2337         specialization = 1;
2338       break;
2339
2340     default:
2341       gcc_unreachable ();
2342     }
2343
2344   if (specialization || member_specialization)
2345     {
2346       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2347       for (; t; t = TREE_CHAIN (t))
2348         if (TREE_PURPOSE (t))
2349           {
2350             permerror (input_location, 
2351                        "default argument specified in explicit specialization");
2352             break;
2353           }
2354     }
2355
2356   if (specialization || member_specialization || explicit_instantiation)
2357     {
2358       tree tmpl = NULL_TREE;
2359       tree targs = NULL_TREE;
2360
2361       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2362       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2363         {
2364           tree fns;
2365
2366           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2367           if (ctype)
2368             fns = dname;
2369           else
2370             {
2371               /* If there is no class context, the explicit instantiation
2372                  must be at namespace scope.  */
2373               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2374
2375               /* Find the namespace binding, using the declaration
2376                  context.  */
2377               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2378                                            false, true);
2379               if (fns == error_mark_node || !is_overloaded_fn (fns))
2380                 {
2381                   error ("%qD is not a template function", dname);
2382                   fns = error_mark_node;
2383                 }
2384               else
2385                 {
2386                   tree fn = OVL_CURRENT (fns);
2387                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2388                                                 CP_DECL_CONTEXT (fn)))
2389                     error ("%qD is not declared in %qD",
2390                            decl, current_namespace);
2391                 }
2392             }
2393
2394           declarator = lookup_template_function (fns, NULL_TREE);
2395         }
2396
2397       if (declarator == error_mark_node)
2398         return error_mark_node;
2399
2400       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2401         {
2402           if (!explicit_instantiation)
2403             /* A specialization in class scope.  This is invalid,
2404                but the error will already have been flagged by
2405                check_specialization_scope.  */
2406             return error_mark_node;
2407           else
2408             {
2409               /* It's not valid to write an explicit instantiation in
2410                  class scope, e.g.:
2411
2412                    class C { template void f(); }
2413
2414                    This case is caught by the parser.  However, on
2415                    something like:
2416
2417                    template class C { void f(); };
2418
2419                    (which is invalid) we can get here.  The error will be
2420                    issued later.  */
2421               ;
2422             }
2423
2424           return decl;
2425         }
2426       else if (ctype != NULL_TREE
2427                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2428                    IDENTIFIER_NODE))
2429         {
2430           /* Find the list of functions in ctype that have the same
2431              name as the declared function.  */
2432           tree name = TREE_OPERAND (declarator, 0);
2433           tree fns = NULL_TREE;
2434           int idx;
2435
2436           if (constructor_name_p (name, ctype))
2437             {
2438               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2439
2440               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2441                   : !CLASSTYPE_DESTRUCTORS (ctype))
2442                 {
2443                   /* From [temp.expl.spec]:
2444
2445                      If such an explicit specialization for the member
2446                      of a class template names an implicitly-declared
2447                      special member function (clause _special_), the
2448                      program is ill-formed.
2449
2450                      Similar language is found in [temp.explicit].  */
2451                   error ("specialization of implicitly-declared special member function");
2452                   return error_mark_node;
2453                 }
2454
2455               name = is_constructor ? ctor_identifier : dtor_identifier;
2456             }
2457
2458           if (!DECL_CONV_FN_P (decl))
2459             {
2460               idx = lookup_fnfields_1 (ctype, name);
2461               if (idx >= 0)
2462                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2463             }
2464           else
2465             {
2466               VEC(tree,gc) *methods;
2467               tree ovl;
2468
2469               /* For a type-conversion operator, we cannot do a
2470                  name-based lookup.  We might be looking for `operator
2471                  int' which will be a specialization of `operator T'.
2472                  So, we find *all* the conversion operators, and then
2473                  select from them.  */
2474               fns = NULL_TREE;
2475
2476               methods = CLASSTYPE_METHOD_VEC (ctype);
2477               if (methods)
2478                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2479                      VEC_iterate (tree, methods, idx, ovl);
2480                      ++idx)
2481                   {
2482                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2483                       /* There are no more conversion functions.  */
2484                       break;
2485
2486                     /* Glue all these conversion functions together
2487                        with those we already have.  */
2488                     for (; ovl; ovl = OVL_NEXT (ovl))
2489                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2490                   }
2491             }
2492
2493           if (fns == NULL_TREE)
2494             {
2495               error ("no member function %qD declared in %qT", name, ctype);
2496               return error_mark_node;
2497             }
2498           else
2499             TREE_OPERAND (declarator, 0) = fns;
2500         }
2501
2502       /* Figure out what exactly is being specialized at this point.
2503          Note that for an explicit instantiation, even one for a
2504          member function, we cannot tell apriori whether the
2505          instantiation is for a member template, or just a member
2506          function of a template class.  Even if a member template is
2507          being instantiated, the member template arguments may be
2508          elided if they can be deduced from the rest of the
2509          declaration.  */
2510       tmpl = determine_specialization (declarator, decl,
2511                                        &targs,
2512                                        member_specialization,
2513                                        template_count,
2514                                        tsk);
2515
2516       if (!tmpl || tmpl == error_mark_node)
2517         /* We couldn't figure out what this declaration was
2518            specializing.  */
2519         return error_mark_node;
2520       else
2521         {
2522           tree gen_tmpl = most_general_template (tmpl);
2523
2524           if (explicit_instantiation)
2525             {
2526               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2527                  is done by do_decl_instantiation later.  */
2528
2529               int arg_depth = TMPL_ARGS_DEPTH (targs);
2530               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2531
2532               if (arg_depth > parm_depth)
2533                 {
2534                   /* If TMPL is not the most general template (for
2535                      example, if TMPL is a friend template that is
2536                      injected into namespace scope), then there will
2537                      be too many levels of TARGS.  Remove some of them
2538                      here.  */
2539                   int i;
2540                   tree new_targs;
2541
2542                   new_targs = make_tree_vec (parm_depth);
2543                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2544                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2545                       = TREE_VEC_ELT (targs, i);
2546                   targs = new_targs;
2547                 }
2548
2549               return instantiate_template (tmpl, targs, tf_error);
2550             }
2551
2552           /* If we thought that the DECL was a member function, but it
2553              turns out to be specializing a static member function,
2554              make DECL a static member function as well.  */
2555           if (DECL_STATIC_FUNCTION_P (tmpl)
2556               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2557             revert_static_member_fn (decl);
2558
2559           /* If this is a specialization of a member template of a
2560              template class, we want to return the TEMPLATE_DECL, not
2561              the specialization of it.  */
2562           if (tsk == tsk_template)
2563             {
2564               tree result = DECL_TEMPLATE_RESULT (tmpl);
2565               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2566               DECL_INITIAL (result) = NULL_TREE;
2567               if (have_def)
2568                 {
2569                   tree parm;
2570                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2571                   DECL_SOURCE_LOCATION (result)
2572                     = DECL_SOURCE_LOCATION (decl);
2573                   /* We want to use the argument list specified in the
2574                      definition, not in the original declaration.  */
2575                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2576                   for (parm = DECL_ARGUMENTS (result); parm;
2577                        parm = DECL_CHAIN (parm))
2578                     DECL_CONTEXT (parm) = result;
2579                 }
2580               return register_specialization (tmpl, gen_tmpl, targs,
2581                                               is_friend, 0);
2582             }
2583
2584           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2585           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2586
2587           /* Inherit default function arguments from the template
2588              DECL is specializing.  */
2589           copy_default_args_to_explicit_spec (decl);
2590
2591           /* This specialization has the same protection as the
2592              template it specializes.  */
2593           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2594           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2595
2596           /* 7.1.1-1 [dcl.stc]
2597
2598              A storage-class-specifier shall not be specified in an
2599              explicit specialization...
2600
2601              The parser rejects these, so unless action is taken here,
2602              explicit function specializations will always appear with
2603              global linkage.
2604
2605              The action recommended by the C++ CWG in response to C++
2606              defect report 605 is to make the storage class and linkage
2607              of the explicit specialization match the templated function:
2608
2609              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2610            */
2611           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2612             {
2613               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2614               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2615
2616               /* This specialization has the same linkage and visibility as
2617                  the function template it specializes.  */
2618               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2619               if (! TREE_PUBLIC (decl))
2620                 {
2621                   DECL_INTERFACE_KNOWN (decl) = 1;
2622                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2623                 }
2624               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2625               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2626                 {
2627                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2628                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2629                 }
2630             }
2631
2632           /* If DECL is a friend declaration, declared using an
2633              unqualified name, the namespace associated with DECL may
2634              have been set incorrectly.  For example, in:
2635
2636                template <typename T> void f(T);
2637                namespace N {
2638                  struct S { friend void f<int>(int); }
2639                }
2640
2641              we will have set the DECL_CONTEXT for the friend
2642              declaration to N, rather than to the global namespace.  */
2643           if (DECL_NAMESPACE_SCOPE_P (decl))
2644             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2645
2646           if (is_friend && !have_def)
2647             /* This is not really a declaration of a specialization.
2648                It's just the name of an instantiation.  But, it's not
2649                a request for an instantiation, either.  */
2650             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2651           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2652             /* This is indeed a specialization.  In case of constructors
2653                and destructors, we need in-charge and not-in-charge
2654                versions in V3 ABI.  */
2655             clone_function_decl (decl, /*update_method_vec_p=*/0);
2656
2657           /* Register this specialization so that we can find it
2658              again.  */
2659           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2660         }
2661     }
2662
2663   return decl;
2664 }
2665
2666 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2667    parameters.  These are represented in the same format used for
2668    DECL_TEMPLATE_PARMS.  */
2669
2670 int
2671 comp_template_parms (const_tree parms1, const_tree parms2)
2672 {
2673   const_tree p1;
2674   const_tree p2;
2675
2676   if (parms1 == parms2)
2677     return 1;
2678
2679   for (p1 = parms1, p2 = parms2;
2680        p1 != NULL_TREE && p2 != NULL_TREE;
2681        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2682     {
2683       tree t1 = TREE_VALUE (p1);
2684       tree t2 = TREE_VALUE (p2);
2685       int i;
2686
2687       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2688       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2689
2690       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2691         return 0;
2692
2693       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2694         {
2695           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2696           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2697
2698           /* If either of the template parameters are invalid, assume
2699              they match for the sake of error recovery. */
2700           if (parm1 == error_mark_node || parm2 == error_mark_node)
2701             return 1;
2702
2703           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2704             return 0;
2705
2706           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2707               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2708                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2709             continue;
2710           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2711             return 0;
2712         }
2713     }
2714
2715   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2716     /* One set of parameters has more parameters lists than the
2717        other.  */
2718     return 0;
2719
2720   return 1;
2721 }
2722
2723 /* Determine whether PARM is a parameter pack.  */
2724
2725 bool 
2726 template_parameter_pack_p (const_tree parm)
2727 {
2728   /* Determine if we have a non-type template parameter pack.  */
2729   if (TREE_CODE (parm) == PARM_DECL)
2730     return (DECL_TEMPLATE_PARM_P (parm) 
2731             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2732
2733   /* If this is a list of template parameters, we could get a
2734      TYPE_DECL or a TEMPLATE_DECL.  */ 
2735   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2736     parm = TREE_TYPE (parm);
2737
2738   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2739            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2740           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2741 }
2742
2743 /* Determine if T is a function parameter pack.  */
2744
2745 bool
2746 function_parameter_pack_p (const_tree t)
2747 {
2748   if (t && TREE_CODE (t) == PARM_DECL)
2749     return FUNCTION_PARAMETER_PACK_P (t);
2750   return false;
2751 }
2752
2753 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2754    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2755
2756 tree
2757 get_function_template_decl (const_tree primary_func_tmpl_inst)
2758 {
2759   if (! primary_func_tmpl_inst
2760       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2761       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2762     return NULL;
2763
2764   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2765 }
2766
2767 /* Return true iff the function parameter PARAM_DECL was expanded
2768    from the function parameter pack PACK.  */
2769
2770 bool
2771 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2772 {
2773   if (DECL_ARTIFICIAL (param_decl)
2774       || !function_parameter_pack_p (pack))
2775     return false;
2776
2777   /* The parameter pack and its pack arguments have the same
2778      DECL_PARM_INDEX.  */
2779   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2780 }
2781
2782 /* Determine whether ARGS describes a variadic template args list,
2783    i.e., one that is terminated by a template argument pack.  */
2784
2785 static bool 
2786 template_args_variadic_p (tree args)
2787 {
2788   int nargs;
2789   tree last_parm;
2790
2791   if (args == NULL_TREE)
2792     return false;
2793
2794   args = INNERMOST_TEMPLATE_ARGS (args);
2795   nargs = TREE_VEC_LENGTH (args);
2796
2797   if (nargs == 0)
2798     return false;
2799
2800   last_parm = TREE_VEC_ELT (args, nargs - 1);
2801
2802   return ARGUMENT_PACK_P (last_parm);
2803 }
2804
2805 /* Generate a new name for the parameter pack name NAME (an
2806    IDENTIFIER_NODE) that incorporates its */
2807
2808 static tree
2809 make_ith_pack_parameter_name (tree name, int i)
2810 {
2811   /* Munge the name to include the parameter index.  */
2812 #define NUMBUF_LEN 128
2813   char numbuf[NUMBUF_LEN];
2814   char* newname;
2815   int newname_len;
2816
2817   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2818   newname_len = IDENTIFIER_LENGTH (name)
2819                 + strlen (numbuf) + 2;
2820   newname = (char*)alloca (newname_len);
2821   snprintf (newname, newname_len,
2822             "%s#%i", IDENTIFIER_POINTER (name), i);
2823   return get_identifier (newname);
2824 }
2825
2826 /* Return true if T is a primary function
2827    or class template instantiation.  */
2828
2829 bool
2830 primary_template_instantiation_p (const_tree t)
2831 {
2832   if (!t)
2833     return false;
2834
2835   if (TREE_CODE (t) == FUNCTION_DECL)
2836     return DECL_LANG_SPECIFIC (t)
2837            && DECL_TEMPLATE_INSTANTIATION (t)
2838            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2839   else if (CLASS_TYPE_P (t))
2840     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2841            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2842   return false;
2843 }
2844
2845 /* Return true if PARM is a template template parameter.  */
2846
2847 bool
2848 template_template_parameter_p (const_tree parm)
2849 {
2850   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2851 }
2852
2853 /* Return the template parameters of T if T is a
2854    primary template instantiation, NULL otherwise.  */
2855
2856 tree
2857 get_primary_template_innermost_parameters (const_tree t)
2858 {
2859   tree parms = NULL, template_info = NULL;
2860
2861   if ((template_info = get_template_info (t))
2862       && primary_template_instantiation_p (t))
2863     parms = INNERMOST_TEMPLATE_PARMS
2864         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2865
2866   return parms;
2867 }
2868
2869 /* Return the template parameters of the LEVELth level from the full list
2870    of template parameters PARMS.  */
2871
2872 tree
2873 get_template_parms_at_level (tree parms, int level)
2874 {
2875   tree p;
2876   if (!parms
2877       || TREE_CODE (parms) != TREE_LIST
2878       || level > TMPL_PARMS_DEPTH (parms))
2879     return NULL_TREE;
2880
2881   for (p = parms; p; p = TREE_CHAIN (p))
2882     if (TMPL_PARMS_DEPTH (p) == level)
2883       return p;
2884
2885   return NULL_TREE;
2886 }
2887
2888 /* Returns the template arguments of T if T is a template instantiation,
2889    NULL otherwise.  */
2890
2891 tree
2892 get_template_innermost_arguments (const_tree t)
2893 {
2894   tree args = NULL, template_info = NULL;
2895
2896   if ((template_info = get_template_info (t))
2897       && TI_ARGS (template_info))
2898     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2899
2900   return args;
2901 }
2902
2903 /* Return the argument pack elements of T if T is a template argument pack,
2904    NULL otherwise.  */
2905
2906 tree
2907 get_template_argument_pack_elems (const_tree t)
2908 {
2909   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2910       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2911     return NULL;
2912
2913   return ARGUMENT_PACK_ARGS (t);
2914 }
2915
2916 /* Structure used to track the progress of find_parameter_packs_r.  */
2917 struct find_parameter_pack_data 
2918 {
2919   /* TREE_LIST that will contain all of the parameter packs found by
2920      the traversal.  */
2921   tree* parameter_packs;
2922
2923   /* Set of AST nodes that have been visited by the traversal.  */
2924   struct pointer_set_t *visited;
2925 };
2926
2927 /* Identifies all of the argument packs that occur in a template
2928    argument and appends them to the TREE_LIST inside DATA, which is a
2929    find_parameter_pack_data structure. This is a subroutine of
2930    make_pack_expansion and uses_parameter_packs.  */
2931 static tree
2932 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2933 {
2934   tree t = *tp;
2935   struct find_parameter_pack_data* ppd = 
2936     (struct find_parameter_pack_data*)data;
2937   bool parameter_pack_p = false;
2938
2939   /* Identify whether this is a parameter pack or not.  */
2940   switch (TREE_CODE (t))
2941     {
2942     case TEMPLATE_PARM_INDEX:
2943       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2944         parameter_pack_p = true;
2945       break;
2946
2947     case TEMPLATE_TYPE_PARM:
2948     case TEMPLATE_TEMPLATE_PARM:
2949       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2950         parameter_pack_p = true;
2951       break;
2952
2953     case PARM_DECL:
2954       if (FUNCTION_PARAMETER_PACK_P (t))
2955         {
2956           /* We don't want to walk into the type of a PARM_DECL,
2957              because we don't want to see the type parameter pack.  */
2958           *walk_subtrees = 0;
2959           parameter_pack_p = true;
2960         }
2961       break;
2962
2963     default:
2964       /* Not a parameter pack.  */
2965       break;
2966     }
2967
2968   if (parameter_pack_p)
2969     {
2970       /* Add this parameter pack to the list.  */
2971       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2972     }
2973
2974   if (TYPE_P (t))
2975     cp_walk_tree (&TYPE_CONTEXT (t), 
2976                   &find_parameter_packs_r, ppd, ppd->visited);
2977
2978   /* This switch statement will return immediately if we don't find a
2979      parameter pack.  */
2980   switch (TREE_CODE (t)) 
2981     {
2982     case TEMPLATE_PARM_INDEX:
2983       return NULL_TREE;
2984
2985     case BOUND_TEMPLATE_TEMPLATE_PARM:
2986       /* Check the template itself.  */
2987       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2988                     &find_parameter_packs_r, ppd, ppd->visited);
2989       /* Check the template arguments.  */
2990       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2991                     ppd->visited);
2992       *walk_subtrees = 0;
2993       return NULL_TREE;
2994
2995     case TEMPLATE_TYPE_PARM:
2996     case TEMPLATE_TEMPLATE_PARM:
2997       return NULL_TREE;
2998
2999     case PARM_DECL:
3000       return NULL_TREE;
3001
3002     case RECORD_TYPE:
3003       if (TYPE_PTRMEMFUNC_P (t))
3004         return NULL_TREE;
3005       /* Fall through.  */
3006
3007     case UNION_TYPE:
3008     case ENUMERAL_TYPE:
3009       if (TYPE_TEMPLATE_INFO (t))
3010         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
3011                       &find_parameter_packs_r, ppd, ppd->visited);
3012
3013       *walk_subtrees = 0;
3014       return NULL_TREE;
3015
3016     case TEMPLATE_DECL:
3017       cp_walk_tree (&TREE_TYPE (t),
3018                     &find_parameter_packs_r, ppd, ppd->visited);
3019       return NULL_TREE;
3020  
3021     case TYPENAME_TYPE:
3022       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3023                    ppd, ppd->visited);
3024       *walk_subtrees = 0;
3025       return NULL_TREE;
3026       
3027     case TYPE_PACK_EXPANSION:
3028     case EXPR_PACK_EXPANSION:
3029       *walk_subtrees = 0;
3030       return NULL_TREE;
3031
3032     case INTEGER_TYPE:
3033       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
3034                     ppd, ppd->visited);
3035       *walk_subtrees = 0;
3036       return NULL_TREE;
3037
3038     case IDENTIFIER_NODE:
3039       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
3040                     ppd->visited);
3041       *walk_subtrees = 0;
3042       return NULL_TREE;
3043
3044     default:
3045       return NULL_TREE;
3046     }
3047
3048   return NULL_TREE;
3049 }
3050
3051 /* Determines if the expression or type T uses any parameter packs.  */
3052 bool
3053 uses_parameter_packs (tree t)
3054 {
3055   tree parameter_packs = NULL_TREE;
3056   struct find_parameter_pack_data ppd;
3057   ppd.parameter_packs = &parameter_packs;
3058   ppd.visited = pointer_set_create ();
3059   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3060   pointer_set_destroy (ppd.visited);
3061   return parameter_packs != NULL_TREE;
3062 }
3063
3064 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3065    representation a base-class initializer into a parameter pack
3066    expansion. If all goes well, the resulting node will be an
3067    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3068    respectively.  */
3069 tree 
3070 make_pack_expansion (tree arg)
3071 {
3072   tree result;
3073   tree parameter_packs = NULL_TREE;
3074   bool for_types = false;
3075   struct find_parameter_pack_data ppd;
3076
3077   if (!arg || arg == error_mark_node)
3078     return arg;
3079
3080   if (TREE_CODE (arg) == TREE_LIST)
3081     {
3082       /* The only time we will see a TREE_LIST here is for a base
3083          class initializer.  In this case, the TREE_PURPOSE will be a
3084          _TYPE node (representing the base class expansion we're
3085          initializing) and the TREE_VALUE will be a TREE_LIST
3086          containing the initialization arguments. 
3087
3088          The resulting expansion looks somewhat different from most
3089          expansions. Rather than returning just one _EXPANSION, we
3090          return a TREE_LIST whose TREE_PURPOSE is a
3091          TYPE_PACK_EXPANSION containing the bases that will be
3092          initialized.  The TREE_VALUE will be identical to the
3093          original TREE_VALUE, which is a list of arguments that will
3094          be passed to each base.  We do not introduce any new pack
3095          expansion nodes into the TREE_VALUE (although it is possible
3096          that some already exist), because the TREE_PURPOSE and
3097          TREE_VALUE all need to be expanded together with the same
3098          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3099          resulting TREE_PURPOSE will mention the parameter packs in
3100          both the bases and the arguments to the bases.  */
3101       tree purpose;
3102       tree value;
3103       tree parameter_packs = NULL_TREE;
3104
3105       /* Determine which parameter packs will be used by the base
3106          class expansion.  */
3107       ppd.visited = pointer_set_create ();
3108       ppd.parameter_packs = &parameter_packs;
3109       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3110                     &ppd, ppd.visited);
3111
3112       if (parameter_packs == NULL_TREE)
3113         {
3114           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3115           pointer_set_destroy (ppd.visited);
3116           return error_mark_node;
3117         }
3118
3119       if (TREE_VALUE (arg) != void_type_node)
3120         {
3121           /* Collect the sets of parameter packs used in each of the
3122              initialization arguments.  */
3123           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3124             {
3125               /* Determine which parameter packs will be expanded in this
3126                  argument.  */
3127               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3128                             &ppd, ppd.visited);
3129             }
3130         }
3131
3132       pointer_set_destroy (ppd.visited);
3133
3134       /* Create the pack expansion type for the base type.  */
3135       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3136       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3137       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3138
3139       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3140          they will rarely be compared to anything.  */
3141       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3142
3143       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3144     }
3145
3146   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3147     for_types = true;
3148
3149   /* Build the PACK_EXPANSION_* node.  */
3150   result = for_types
3151      ? cxx_make_type (TYPE_PACK_EXPANSION)
3152      : make_node (EXPR_PACK_EXPANSION);
3153   SET_PACK_EXPANSION_PATTERN (result, arg);
3154   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3155     {
3156       /* Propagate type and const-expression information.  */
3157       TREE_TYPE (result) = TREE_TYPE (arg);
3158       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3159     }
3160   else
3161     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3162        they will rarely be compared to anything.  */
3163     SET_TYPE_STRUCTURAL_EQUALITY (result);
3164
3165   /* Determine which parameter packs will be expanded.  */
3166   ppd.parameter_packs = &parameter_packs;
3167   ppd.visited = pointer_set_create ();
3168   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3169   pointer_set_destroy (ppd.visited);
3170
3171   /* Make sure we found some parameter packs.  */
3172   if (parameter_packs == NULL_TREE)
3173     {
3174       if (TYPE_P (arg))
3175         error ("expansion pattern %<%T%> contains no argument packs", arg);
3176       else
3177         error ("expansion pattern %<%E%> contains no argument packs", arg);
3178       return error_mark_node;
3179     }
3180   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3181
3182   return result;
3183 }
3184
3185 /* Checks T for any "bare" parameter packs, which have not yet been
3186    expanded, and issues an error if any are found. This operation can
3187    only be done on full expressions or types (e.g., an expression
3188    statement, "if" condition, etc.), because we could have expressions like:
3189
3190      foo(f(g(h(args)))...)
3191
3192    where "args" is a parameter pack. check_for_bare_parameter_packs
3193    should not be called for the subexpressions args, h(args),
3194    g(h(args)), or f(g(h(args))), because we would produce erroneous
3195    error messages. 
3196
3197    Returns TRUE and emits an error if there were bare parameter packs,
3198    returns FALSE otherwise.  */
3199 bool 
3200 check_for_bare_parameter_packs (tree t)
3201 {
3202   tree parameter_packs = NULL_TREE;
3203   struct find_parameter_pack_data ppd;
3204
3205   if (!processing_template_decl || !t || t == error_mark_node)
3206     return false;
3207
3208   if (TREE_CODE (t) == TYPE_DECL)
3209     t = TREE_TYPE (t);
3210
3211   ppd.parameter_packs = &parameter_packs;
3212   ppd.visited = pointer_set_create ();
3213   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3214   pointer_set_destroy (ppd.visited);
3215
3216   if (parameter_packs) 
3217     {
3218       error ("parameter packs not expanded with %<...%>:");
3219       while (parameter_packs)
3220         {
3221           tree pack = TREE_VALUE (parameter_packs);
3222           tree name = NULL_TREE;
3223
3224           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3225               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3226             name = TYPE_NAME (pack);
3227           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3228             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3229           else
3230             name = DECL_NAME (pack);
3231
3232           if (name)
3233             inform (input_location, "        %qD", name);
3234           else
3235             inform (input_location, "        <anonymous>");
3236
3237           parameter_packs = TREE_CHAIN (parameter_packs);
3238         }
3239
3240       return true;
3241     }
3242
3243   return false;
3244 }
3245
3246 /* Expand any parameter packs that occur in the template arguments in
3247    ARGS.  */
3248 tree
3249 expand_template_argument_pack (tree args)
3250 {
3251   tree result_args = NULL_TREE;
3252   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3253   int num_result_args = -1;
3254   int non_default_args_count = -1;
3255
3256   /* First, determine if we need to expand anything, and the number of
3257      slots we'll need.  */
3258   for (in_arg = 0; in_arg < nargs; ++in_arg)
3259     {
3260       tree arg = TREE_VEC_ELT (args, in_arg);
3261       if (arg == NULL_TREE)
3262         return args;
3263       if (ARGUMENT_PACK_P (arg))
3264         {
3265           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3266           if (num_result_args < 0)
3267             num_result_args = in_arg + num_packed;
3268           else
3269             num_result_args += num_packed;
3270         }
3271       else
3272         {
3273           if (num_result_args >= 0)
3274             num_result_args++;
3275         }
3276     }
3277
3278   /* If no expansion is necessary, we're done.  */
3279   if (num_result_args < 0)
3280     return args;
3281
3282   /* Expand arguments.  */
3283   result_args = make_tree_vec (num_result_args);
3284   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3285     non_default_args_count =
3286       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3287   for (in_arg = 0; in_arg < nargs; ++in_arg)
3288     {
3289       tree arg = TREE_VEC_ELT (args, in_arg);
3290       if (ARGUMENT_PACK_P (arg))
3291         {
3292           tree packed = ARGUMENT_PACK_ARGS (arg);
3293           int i, num_packed = TREE_VEC_LENGTH (packed);
3294           for (i = 0; i < num_packed; ++i, ++out_arg)
3295             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3296           if (non_default_args_count > 0)
3297             non_default_args_count += num_packed;
3298         }
3299       else
3300         {
3301           TREE_VEC_ELT (result_args, out_arg) = arg;
3302           ++out_arg;
3303         }
3304     }
3305   if (non_default_args_count >= 0)
3306     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3307   return result_args;
3308 }
3309
3310 /* Checks if DECL shadows a template parameter.
3311
3312    [temp.local]: A template-parameter shall not be redeclared within its
3313    scope (including nested scopes).
3314
3315    Emits an error and returns TRUE if the DECL shadows a parameter,
3316    returns FALSE otherwise.  */
3317
3318 bool
3319 check_template_shadow (tree decl)
3320 {
3321   tree olddecl;
3322
3323   /* If we're not in a template, we can't possibly shadow a template
3324      parameter.  */
3325   if (!current_template_parms)
3326     return true;
3327
3328   /* Figure out what we're shadowing.  */
3329   if (TREE_CODE (decl) == OVERLOAD)
3330     decl = OVL_CURRENT (decl);
3331   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3332
3333   /* If there's no previous binding for this name, we're not shadowing
3334      anything, let alone a template parameter.  */
3335   if (!olddecl)
3336     return true;
3337
3338   /* If we're not shadowing a template parameter, we're done.  Note
3339      that OLDDECL might be an OVERLOAD (or perhaps even an
3340      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3341      node.  */
3342   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3343     return true;
3344
3345   /* We check for decl != olddecl to avoid bogus errors for using a
3346      name inside a class.  We check TPFI to avoid duplicate errors for
3347      inline member templates.  */
3348   if (decl == olddecl
3349       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3350     return true;
3351
3352   error ("declaration of %q+#D", decl);
3353   error (" shadows template parm %q+#D", olddecl);
3354   return false;
3355 }
3356
3357 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3358    ORIG_LEVEL, DECL, and TYPE.  NUM_SIBLINGS is the total number of
3359    template parameters.  */
3360
3361 static tree
3362 build_template_parm_index (int index,
3363                            int level,
3364                            int orig_level,
3365                            int num_siblings,
3366                            tree decl,
3367                            tree type)
3368 {
3369   tree t = make_node (TEMPLATE_PARM_INDEX);
3370   TEMPLATE_PARM_IDX (t) = index;
3371   TEMPLATE_PARM_LEVEL (t) = level;
3372   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3373   TEMPLATE_PARM_NUM_SIBLINGS (t) = num_siblings;
3374   TEMPLATE_PARM_DECL (t) = decl;
3375   TREE_TYPE (t) = type;
3376   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3377   TREE_READONLY (t) = TREE_READONLY (decl);
3378
3379   return t;
3380 }
3381
3382 /* Find the canonical type parameter for the given template type
3383    parameter.  Returns the canonical type parameter, which may be TYPE
3384    if no such parameter existed.  */
3385
3386 static tree
3387 canonical_type_parameter (tree type)
3388 {
3389   tree list;
3390   int idx = TEMPLATE_TYPE_IDX (type);
3391   if (!canonical_template_parms)
3392     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3393
3394   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3395     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3396
3397   list = VEC_index (tree, canonical_template_parms, idx);
3398   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3399     list = TREE_CHAIN (list);
3400
3401   if (list)
3402     return TREE_VALUE (list);
3403   else
3404     {
3405       VEC_replace(tree, canonical_template_parms, idx,
3406                   tree_cons (NULL_TREE, type, 
3407                              VEC_index (tree, canonical_template_parms, idx)));
3408       return type;
3409     }
3410 }
3411
3412 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3413    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3414    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3415    new one is created.  */
3416
3417 static tree
3418 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3419                             tsubst_flags_t complain)
3420 {
3421   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3422       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3423           != TEMPLATE_PARM_LEVEL (index) - levels)
3424       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3425     {
3426       tree orig_decl = TEMPLATE_PARM_DECL (index);
3427       tree decl, t;
3428
3429       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3430                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3431       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3432       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3433       DECL_ARTIFICIAL (decl) = 1;
3434       SET_DECL_TEMPLATE_PARM_P (decl);
3435
3436       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3437                                      TEMPLATE_PARM_LEVEL (index) - levels,
3438                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3439                                      TEMPLATE_PARM_NUM_SIBLINGS (index),
3440                                      decl, type);
3441       TEMPLATE_PARM_DESCENDANTS (index) = t;
3442       TEMPLATE_PARM_PARAMETER_PACK (t) 
3443         = TEMPLATE_PARM_PARAMETER_PACK (index);
3444
3445         /* Template template parameters need this.  */
3446       if (TREE_CODE (decl) == TEMPLATE_DECL)
3447         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3448           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3449            args, complain);
3450     }
3451
3452   return TEMPLATE_PARM_DESCENDANTS (index);
3453 }
3454
3455 /* Process information from new template parameter PARM and append it
3456    to the LIST being built.  This new parameter is a non-type
3457    parameter iff IS_NON_TYPE is true. This new parameter is a
3458    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
3459    is in PARM_LOC. NUM_TEMPLATE_PARMS is the size of the template
3460    parameter list PARM belongs to. This is used used to create a
3461    proper canonical type for the type of PARM that is to be created,
3462    iff PARM is a type.  If the size is not known, this parameter shall
3463    be set to 0.  */
3464
3465 tree
3466 process_template_parm (tree list, location_t parm_loc, tree parm,
3467                        bool is_non_type, bool is_parameter_pack,
3468                        unsigned num_template_parms)
3469 {
3470   tree decl = 0;
3471   tree defval;
3472   tree err_parm_list;
3473   int idx = 0;
3474
3475   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3476   defval = TREE_PURPOSE (parm);
3477
3478   if (list)
3479     {
3480       tree p = tree_last (list);
3481
3482       if (p && TREE_VALUE (p) != error_mark_node)
3483         {
3484           p = TREE_VALUE (p);
3485           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3486             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3487           else
3488             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3489         }
3490
3491       ++idx;
3492     }
3493   else
3494     idx = 0;
3495
3496   if (is_non_type)
3497     {
3498       parm = TREE_VALUE (parm);
3499
3500       SET_DECL_TEMPLATE_PARM_P (parm);
3501
3502       if (TREE_TYPE (parm) == error_mark_node)
3503         {
3504           err_parm_list = build_tree_list (defval, parm);
3505           TREE_VALUE (err_parm_list) = error_mark_node;
3506            return chainon (list, err_parm_list);
3507         }
3508       else
3509       {
3510         /* [temp.param]
3511
3512            The top-level cv-qualifiers on the template-parameter are
3513            ignored when determining its type.  */
3514         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3515         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3516           {
3517             err_parm_list = build_tree_list (defval, parm);
3518             TREE_VALUE (err_parm_list) = error_mark_node;
3519              return chainon (list, err_parm_list);
3520           }
3521
3522         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3523           {
3524             /* This template parameter is not a parameter pack, but it
3525                should be. Complain about "bare" parameter packs.  */
3526             check_for_bare_parameter_packs (TREE_TYPE (parm));
3527             
3528             /* Recover by calling this a parameter pack.  */
3529             is_parameter_pack = true;
3530           }
3531       }
3532
3533       /* A template parameter is not modifiable.  */
3534       TREE_CONSTANT (parm) = 1;
3535       TREE_READONLY (parm) = 1;
3536       decl = build_decl (parm_loc,
3537                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3538       TREE_CONSTANT (decl) = 1;
3539       TREE_READONLY (decl) = 1;
3540       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3541         = build_template_parm_index (idx, processing_template_decl,
3542                                      processing_template_decl,
3543                                      num_template_parms,
3544                                      decl, TREE_TYPE (parm));
3545
3546       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3547         = is_parameter_pack;
3548     }
3549   else
3550     {
3551       tree t;
3552       parm = TREE_VALUE (TREE_VALUE (parm));
3553
3554       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3555         {
3556           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3557           /* This is for distinguishing between real templates and template
3558              template parameters */
3559           TREE_TYPE (parm) = t;
3560           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3561           decl = parm;
3562         }
3563       else
3564         {
3565           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3566           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3567           decl = build_decl (parm_loc,
3568                              TYPE_DECL, parm, t);
3569         }
3570
3571       TYPE_NAME (t) = decl;
3572       TYPE_STUB_DECL (t) = decl;
3573       parm = decl;
3574       TEMPLATE_TYPE_PARM_INDEX (t)
3575         = build_template_parm_index (idx, processing_template_decl,
3576                                      processing_template_decl,
3577                                      num_template_parms,
3578                                      decl, TREE_TYPE (parm));
3579       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3580       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3581     }
3582   DECL_ARTIFICIAL (decl) = 1;
3583   SET_DECL_TEMPLATE_PARM_P (decl);
3584   pushdecl (decl);
3585   parm = build_tree_list (defval, parm);
3586   return chainon (list, parm);
3587 }
3588
3589 /* The end of a template parameter list has been reached.  Process the
3590    tree list into a parameter vector, converting each parameter into a more
3591    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3592    as PARM_DECLs.  */
3593
3594 tree
3595 end_template_parm_list (tree parms)
3596 {
3597   int nparms;
3598   tree parm, next;
3599   tree saved_parmlist = make_tree_vec (list_length (parms));
3600
3601   current_template_parms
3602     = tree_cons (size_int (processing_template_decl),
3603                  saved_parmlist, current_template_parms);
3604
3605   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3606     {
3607       next = TREE_CHAIN (parm);
3608       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3609       TREE_CHAIN (parm) = NULL_TREE;
3610     }
3611
3612   --processing_template_parmlist;
3613
3614   return saved_parmlist;
3615 }
3616
3617 /* Create a new type almost identical to TYPE but which has the
3618    following differences:
3619
3620      1/ T has a new TEMPLATE_PARM_INDEX that carries the new number of
3621      template sibling parameters of T.
3622
3623      2/ T has a new canonical type that matches the new number
3624      of sibling parms.
3625
3626      3/ From now on, T is going to be what lookups referring to the
3627      name of TYPE will return. No lookup should return TYPE anymore.
3628
3629    NUM_PARMS is the new number of sibling parms TYPE belongs to.
3630
3631    This is a subroutine of fixup_template_parms.  */
3632
3633 static tree
3634 fixup_template_type_parm_type (tree type, int num_parms)
3635 {
3636   tree orig_idx = TEMPLATE_TYPE_PARM_INDEX (type), idx;
3637   tree t;
3638   /* This is the decl which name is inserted into the symbol table for
3639      the template parm type. So whenever we lookup the type name, this
3640      is the DECL we get.  */
3641   tree decl;
3642
3643   /* Do not fix up the type twice.  */
3644   if (orig_idx && TEMPLATE_PARM_NUM_SIBLINGS (orig_idx) != 0)
3645     return type;
3646
3647   t = copy_type (type);
3648   decl = TYPE_NAME (t);
3649
3650   TYPE_MAIN_VARIANT (t) = t;
3651   TYPE_NEXT_VARIANT (t)= NULL_TREE;
3652   TYPE_POINTER_TO (t) = 0;
3653   TYPE_REFERENCE_TO (t) = 0;
3654
3655   idx = build_template_parm_index (TEMPLATE_PARM_IDX (orig_idx),
3656                                    TEMPLATE_PARM_LEVEL (orig_idx),
3657                                    TEMPLATE_PARM_ORIG_LEVEL (orig_idx),
3658                                    num_parms,
3659                                    decl, t);
3660   TEMPLATE_PARM_DESCENDANTS (idx) = TEMPLATE_PARM_DESCENDANTS (orig_idx);
3661   TEMPLATE_PARM_PARAMETER_PACK (idx) = TEMPLATE_PARM_PARAMETER_PACK (orig_idx);
3662   TEMPLATE_TYPE_PARM_INDEX (t) = idx;
3663
3664   TYPE_STUB_DECL (t) = decl;
3665   TEMPLATE_TYPE_DECL (t) = decl;
3666   if (TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
3667     TREE_TYPE (DECL_TEMPLATE_RESULT  (decl)) = t;
3668
3669   /* Update the type associated to the type name stored in the symbol
3670      table. Now, whenever the type name is looked up, the resulting
3671      type is properly fixed up.  */
3672   TREE_TYPE (decl) = t;
3673
3674   TYPE_CANONICAL (t) = canonical_type_parameter (t);
3675
3676   return t;
3677 }
3678
3679 /* Create and return a new TEMPLATE_PARM_INDEX that is almost
3680    identical to I, but that is fixed up as to:
3681
3682    1/ carry the number of sibling parms (NUM_PARMS) of the template
3683    parm represented by I.
3684
3685    2/ replace all references to template parm types declared before I
3686    (in the same template parm list as I) by references to template
3687    parm types contained in ARGS. ARGS should contain the list of
3688    template parms that have been fixed up so far, in a form suitable
3689    to be passed to tsubst.
3690
3691    This is a subroutine of fixup_template_parms.  */
3692
3693 static tree
3694 fixup_template_parm_index (tree i, tree args, int num_parms)
3695 {
3696   tree index, decl, type;
3697
3698   if (i == NULL_TREE
3699       || TREE_CODE (i) != TEMPLATE_PARM_INDEX
3700       /* Do not fix up the index twice.  */
3701       || (TEMPLATE_PARM_NUM_SIBLINGS (i) != 0))
3702     return i;
3703
3704   decl = TEMPLATE_PARM_DECL (i);
3705   type = TREE_TYPE (decl);
3706
3707   index = build_template_parm_index (TEMPLATE_PARM_IDX (i),
3708                                      TEMPLATE_PARM_LEVEL (i),
3709                                      TEMPLATE_PARM_ORIG_LEVEL (i),
3710                                      num_parms,
3711                                      decl, type);
3712
3713   TEMPLATE_PARM_DESCENDANTS (index) = TEMPLATE_PARM_DESCENDANTS (i);
3714   TEMPLATE_PARM_PARAMETER_PACK (index) = TEMPLATE_PARM_PARAMETER_PACK (i);
3715
3716   type = tsubst (type, args, tf_none, NULL_TREE);
3717   
3718   TREE_TYPE (decl) = type;
3719   TREE_TYPE (index) = type;
3720
3721   return index;
3722 }
3723
3724 /* 
3725    This is a subroutine of fixup_template_parms.
3726
3727    It computes the canonical type of the type of the template
3728    parameter PARM_DESC and update all references to that type so that
3729    they use the newly computed canonical type. No access check is
3730    performed during the fixup. PARM_DESC is a TREE_LIST which
3731    TREE_VALUE is the template parameter and its TREE_PURPOSE is the
3732    default argument of the template parm if any. IDX is the index of
3733    the template parameter, starting at 0. NUM_PARMS is the number of
3734    template parameters in the set PARM_DESC belongs to. ARGLIST is a
3735    TREE_VEC containing the full set of template parameters in a form
3736    suitable to be passed to substs functions as their ARGS
3737    argument. This is what current_template_args returns for a given
3738    template. The innermost vector of args in ARGLIST is the set of
3739    template parms that have been fixed up so far. This function adds
3740    the fixed up parameter into that vector.  */
3741
3742 static void
3743 fixup_template_parm (tree parm_desc,
3744                      int idx,
3745                      int num_parms,
3746                      tree arglist)
3747 {
3748   tree parm = TREE_VALUE (parm_desc);
3749   tree fixedup_args = INNERMOST_TEMPLATE_ARGS (arglist);
3750
3751   push_deferring_access_checks (dk_no_check);
3752
3753   if (TREE_CODE (parm) == TYPE_DECL)
3754     {
3755       /* PARM is a template type parameter. Fix up its type, add
3756          the fixed-up template parm to the vector of fixed-up
3757          template parms so far, and substitute the fixed-up
3758          template parms into the default argument of this
3759          parameter.  */
3760       tree t =
3761         fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
3762       TREE_TYPE (parm) = t;
3763
3764       TREE_VEC_ELT (fixedup_args, idx) = template_parm_to_arg (parm_desc);
3765     }
3766   else if (TREE_CODE (parm) == TEMPLATE_DECL)
3767     {
3768       /* PARM is a template template parameter. This is going to
3769          be interesting.  */
3770       tree tparms, targs, innermost_args, t;
3771       int j;
3772
3773       /* First, fix up the parms of the template template parm
3774          because the parms are involved in defining the new canonical
3775          type of the template template parm.  */
3776
3777       /* So we need to substitute the template parm types that have
3778          been fixed up so far into the template parms of this template
3779          template parm. E.g, consider this:
3780
3781          template<class T, template<T u> class TT> class S;
3782
3783          In this case we want to substitute T into the
3784          template parameters of TT.
3785
3786          So let's walk the template parms of PARM here, and
3787          tsubst ARGLIST into into each of the template
3788          parms.   */
3789
3790       /* For this substitution we need to build the full set of
3791          template parameters and use that as arguments for the
3792          tsubsting function.  */
3793       tparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
3794
3795       /* This will contain the innermost parms of PARM into which
3796          we have substituted so far.  */
3797       innermost_args = make_tree_vec (TREE_VEC_LENGTH (tparms));
3798       targs = add_to_template_args (arglist, innermost_args);
3799       for (j = 0; j < TREE_VEC_LENGTH (tparms); ++j)
3800         {
3801           tree parameter;
3802
3803           parameter = TREE_VEC_ELT (tparms, j);
3804
3805           /* INNERMOST_ARGS needs to have at least the same number
3806              of elements as the index PARAMETER, ortherwise
3807              tsubsting into PARAMETER will result in partially
3808              instantiating it, reducing its tempate parm
3809              level. Let's tactically fill INNERMOST_ARGS for that
3810              purpose.  */
3811           TREE_VEC_ELT (innermost_args, j) =
3812             template_parm_to_arg (parameter);
3813
3814           fixup_template_parm (parameter, j,
3815                                TREE_VEC_LENGTH (tparms),
3816                                targs);
3817         }
3818
3819       /* Now fix up the type of the template template parm.  */
3820
3821       t = fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
3822       TREE_TYPE (parm) = t;
3823
3824       TREE_VEC_ELT (fixedup_args, idx) =
3825         template_parm_to_arg (parm_desc);
3826     }
3827   else if (TREE_CODE (parm) == PARM_DECL)
3828     {
3829       /* PARM is a non-type template parameter. We need to:
3830
3831        * Fix up its TEMPLATE_PARM_INDEX to make it carry the
3832        proper number of sibling parameters.
3833
3834        * Make lookups of the template parameter return a reference
3835        to the fixed-up index. No lookup should return references
3836        to the former index anymore.
3837
3838        * Substitute the template parms that got fixed up so far
3839
3840        * into the type of PARM.  */
3841
3842       tree index = DECL_INITIAL (parm);
3843
3844       /* PUSHED_DECL is the decl added to the symbol table with
3845          the name of the parameter. E,g:
3846              
3847          template<class T, T u> //#0
3848          auto my_function(T t) -> decltype(u); //#1
3849
3850          Here, when looking up u at //#1, we get the decl of u
3851          resulting from the declaration in #0. This is what
3852          PUSHED_DECL is. We need to replace the reference to the
3853          old TEMPLATE_PARM_INDEX carried by PUSHED_DECL by the
3854          fixed-up TEMPLATE_PARM_INDEX.  */
3855       tree pushed_decl = TEMPLATE_PARM_DECL (index);
3856
3857       /* Let's fix up the TEMPLATE_PARM_INDEX then. Note that we must
3858          fixup the type of PUSHED_DECL as well and luckily
3859          fixup_template_parm_index does it for us too.  */
3860       tree fixed_up_index =
3861         fixup_template_parm_index (index, arglist, num_parms);
3862
3863       DECL_INITIAL (pushed_decl) = DECL_INITIAL (parm) = fixed_up_index;
3864
3865       /* Add this fixed up PARM to the template parms we've fixed
3866          up so far and use that to substitute the fixed-up
3867          template parms into the type of PARM.  */
3868       TREE_VEC_ELT (fixedup_args, idx) =
3869         template_parm_to_arg (parm_desc);
3870       TREE_TYPE (parm) = tsubst (TREE_TYPE (parm), arglist,
3871                                  tf_none, NULL_TREE);
3872     }
3873
3874   TREE_PURPOSE (parm_desc) =
3875     tsubst_template_arg (TREE_PURPOSE (parm_desc),
3876                          arglist, tf_none, parm);
3877
3878   pop_deferring_access_checks ();
3879 }
3880
3881 /* Walk the current template parms and properly compute the canonical
3882    types of the dependent types created during
3883    cp_parser_template_parameter_list.  */
3884
3885 void
3886 fixup_template_parms (void)
3887 {
3888   tree arglist;
3889   tree parameter_vec;
3890   tree fixedup_args;
3891   int i, num_parms;
3892
3893   parameter_vec = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3894   if (parameter_vec == NULL_TREE)
3895     return;
3896
3897   num_parms = TREE_VEC_LENGTH (parameter_vec);
3898
3899   /* This vector contains the current innermost template parms that
3900      have been fixed up so far.  The form of FIXEDUP_ARGS is suitable
3901      to be passed to tsubst* functions as their ARGS argument.  */
3902   fixedup_args = make_tree_vec (num_parms);
3903
3904   /* This vector contains the full set of template parms in a form
3905      suitable to be passed to substs functions as their ARGS
3906      argument.  */
3907   arglist = current_template_args ();
3908   arglist = add_outermost_template_args (arglist, fixedup_args);
3909
3910   /* Let's do the proper fixup now.  */
3911   for (i = 0; i < num_parms; ++i)
3912     fixup_template_parm (TREE_VEC_ELT (parameter_vec, i),
3913                          i, num_parms, arglist);
3914 }
3915
3916 /* end_template_decl is called after a template declaration is seen.  */
3917
3918 void
3919 end_template_decl (void)
3920 {
3921   reset_specialization ();
3922
3923   if (! processing_template_decl)
3924     return;
3925
3926   /* This matches the pushlevel in begin_template_parm_list.  */
3927   finish_scope ();
3928
3929   --processing_template_decl;
3930   current_template_parms = TREE_CHAIN (current_template_parms);
3931 }
3932
3933 /* Takes a TREE_LIST representing a template parameter and convert it
3934    into an argument suitable to be passed to the type substitution
3935    functions.  Note that If the TREE_LIST contains an error_mark
3936    node, the returned argument is error_mark_node.  */
3937
3938 static tree
3939 template_parm_to_arg (tree t)
3940 {
3941
3942   if (t == NULL_TREE
3943       || TREE_CODE (t) != TREE_LIST)
3944     return t;
3945
3946   if (error_operand_p (TREE_VALUE (t)))
3947     return error_mark_node;
3948
3949   t = TREE_VALUE (t);
3950
3951   if (TREE_CODE (t) == TYPE_DECL
3952       || TREE_CODE (t) == TEMPLATE_DECL)
3953     {
3954       t = TREE_TYPE (t);
3955
3956       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3957         {
3958           /* Turn this argument into a TYPE_ARGUMENT_PACK
3959              with a single element, which expands T.  */
3960           tree vec = make_tree_vec (1);
3961 #ifdef ENABLE_CHECKING
3962           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3963             (vec, TREE_VEC_LENGTH (vec));
3964 #endif
3965           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3966
3967           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3968           SET_ARGUMENT_PACK_ARGS (t, vec);
3969         }
3970     }
3971   else
3972     {
3973       t = DECL_INITIAL (t);
3974
3975       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3976         {
3977           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3978              with a single element, which expands T.  */
3979           tree vec = make_tree_vec (1);
3980           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3981 #ifdef ENABLE_CHECKING
3982           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3983             (vec, TREE_VEC_LENGTH (vec));
3984 #endif
3985           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3986
3987           t  = make_node (NONTYPE_ARGUMENT_PACK);
3988           SET_ARGUMENT_PACK_ARGS (t, vec);
3989           TREE_TYPE (t) = type;
3990         }
3991     }
3992   return t;
3993 }
3994
3995 /* Within the declaration of a template, return all levels of template
3996    parameters that apply.  The template parameters are represented as
3997    a TREE_VEC, in the form documented in cp-tree.h for template
3998    arguments.  */
3999
4000 static tree
4001 current_template_args (void)
4002 {
4003   tree header;
4004   tree args = NULL_TREE;
4005   int length = TMPL_PARMS_DEPTH (current_template_parms);
4006   int l = length;
4007
4008   /* If there is only one level of template parameters, we do not
4009      create a TREE_VEC of TREE_VECs.  Instead, we return a single
4010      TREE_VEC containing the arguments.  */
4011   if (length > 1)
4012     args = make_tree_vec (length);
4013
4014   for (header = current_template_parms; header; header = TREE_CHAIN (header))
4015     {
4016       tree a = copy_node (TREE_VALUE (header));
4017       int i;
4018
4019       TREE_TYPE (a) = NULL_TREE;
4020       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4021         TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4022
4023 #ifdef ENABLE_CHECKING
4024       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4025 #endif
4026
4027       if (length > 1)
4028         TREE_VEC_ELT (args, --l) = a;
4029       else
4030         args = a;
4031     }
4032
4033     if (length > 1 && TREE_VEC_ELT (args, 0) == NULL_TREE)
4034       /* This can happen for template parms of a template template
4035          parameter, e.g:
4036
4037          template<template<class T, class U> class TT> struct S;
4038
4039          Consider the level of the parms of TT; T and U both have
4040          level 2; TT has no template parm of level 1. So in this case
4041          the first element of full_template_args is NULL_TREE. If we
4042          leave it like this TMPL_ARG_DEPTH on args returns 1 instead
4043          of 2. This will make tsubst wrongly consider that T and U
4044          have level 1. Instead, let's create a dummy vector as the
4045          first element of full_template_args so that TMPL_ARG_DEPTH
4046          returns the correct depth for args.  */
4047       TREE_VEC_ELT (args, 0) = make_tree_vec (1);
4048   return args;
4049 }
4050
4051 /* Update the declared TYPE by doing any lookups which were thought to be
4052    dependent, but are not now that we know the SCOPE of the declarator.  */
4053
4054 tree
4055 maybe_update_decl_type (tree orig_type, tree scope)
4056 {
4057   tree type = orig_type;
4058
4059   if (type == NULL_TREE)
4060     return type;
4061
4062   if (TREE_CODE (orig_type) == TYPE_DECL)
4063     type = TREE_TYPE (type);
4064
4065   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4066       && dependent_type_p (type)
4067       /* Don't bother building up the args in this case.  */
4068       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4069     {
4070       /* tsubst in the args corresponding to the template parameters,
4071          including auto if present.  Most things will be unchanged, but
4072          make_typename_type and tsubst_qualified_id will resolve
4073          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4074       tree args = current_template_args ();
4075       tree auto_node = type_uses_auto (type);
4076       tree pushed;
4077       if (auto_node)
4078         {
4079           tree auto_vec = make_tree_vec (1);
4080           TREE_VEC_ELT (auto_vec, 0) = auto_node;
4081           args = add_to_template_args (args, auto_vec);
4082         }
4083       pushed = push_scope (scope);
4084       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4085       if (pushed)
4086         pop_scope (scope);
4087     }
4088
4089   if (type == error_mark_node)
4090     return orig_type;
4091
4092   if (TREE_CODE (orig_type) == TYPE_DECL)
4093     {
4094       if (same_type_p (type, TREE_TYPE (orig_type)))
4095         type = orig_type;
4096       else
4097         type = TYPE_NAME (type);
4098     }
4099   return type;
4100 }
4101
4102 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4103    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
4104    a member template.  Used by push_template_decl below.  */
4105
4106 static tree
4107 build_template_decl (tree decl, tree parms, bool member_template_p)
4108 {
4109   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4110   DECL_TEMPLATE_PARMS (tmpl) = parms;
4111   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4112   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4113
4114   return tmpl;
4115 }
4116
4117 struct template_parm_data
4118 {
4119   /* The level of the template parameters we are currently
4120      processing.  */
4121   int level;
4122
4123   /* The index of the specialization argument we are currently
4124      processing.  */
4125   int current_arg;
4126
4127   /* An array whose size is the number of template parameters.  The
4128      elements are nonzero if the parameter has been used in any one
4129      of the arguments processed so far.  */
4130   int* parms;
4131
4132   /* An array whose size is the number of template arguments.  The
4133      elements are nonzero if the argument makes use of template
4134      parameters of this level.  */
4135   int* arg_uses_template_parms;
4136 };
4137
4138 /* Subroutine of push_template_decl used to see if each template
4139    parameter in a partial specialization is used in the explicit
4140    argument list.  If T is of the LEVEL given in DATA (which is
4141    treated as a template_parm_data*), then DATA->PARMS is marked
4142    appropriately.  */
4143
4144 static int
4145 mark_template_parm (tree t, void* data)
4146 {
4147   int level;
4148   int idx;
4149   struct template_parm_data* tpd = (struct template_parm_data*) data;
4150
4151   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4152     {
4153       level = TEMPLATE_PARM_LEVEL (t);
4154       idx = TEMPLATE_PARM_IDX (t);
4155     }
4156   else
4157     {
4158       level = TEMPLATE_TYPE_LEVEL (t);
4159       idx = TEMPLATE_TYPE_IDX (t);
4160     }
4161
4162   if (level == tpd->level)
4163     {
4164       tpd->parms[idx] = 1;
4165       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4166     }
4167
4168   /* Return zero so that for_each_template_parm will continue the
4169      traversal of the tree; we want to mark *every* template parm.  */
4170   return 0;
4171 }
4172
4173 /* Process the partial specialization DECL.  */
4174
4175 static tree
4176 process_partial_specialization (tree decl)
4177 {
4178   tree type = TREE_TYPE (decl);
4179   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
4180   tree specargs = CLASSTYPE_TI_ARGS (type);
4181   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4182   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4183   tree inner_parms;
4184   tree inst;
4185   int nargs = TREE_VEC_LENGTH (inner_args);
4186   int ntparms;
4187   int  i;
4188   bool did_error_intro = false;
4189   struct template_parm_data tpd;
4190   struct template_parm_data tpd2;
4191
4192   gcc_assert (current_template_parms);
4193
4194   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4195   ntparms = TREE_VEC_LENGTH (inner_parms);
4196
4197   /* We check that each of the template parameters given in the
4198      partial specialization is used in the argument list to the
4199      specialization.  For example:
4200
4201        template <class T> struct S;
4202        template <class T> struct S<T*>;
4203
4204      The second declaration is OK because `T*' uses the template
4205      parameter T, whereas
4206
4207        template <class T> struct S<int>;
4208
4209      is no good.  Even trickier is:
4210
4211        template <class T>
4212        struct S1
4213        {
4214           template <class U>
4215           struct S2;
4216           template <class U>
4217           struct S2<T>;
4218        };
4219
4220      The S2<T> declaration is actually invalid; it is a
4221      full-specialization.  Of course,
4222
4223           template <class U>
4224           struct S2<T (*)(U)>;
4225
4226      or some such would have been OK.  */
4227   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4228   tpd.parms = XALLOCAVEC (int, ntparms);
4229   memset (tpd.parms, 0, sizeof (int) * ntparms);
4230
4231   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4232   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4233   for (i = 0; i < nargs; ++i)
4234     {
4235       tpd.current_arg = i;
4236       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4237                               &mark_template_parm,
4238                               &tpd,
4239                               NULL,
4240                               /*include_nondeduced_p=*/false);
4241     }
4242   for (i = 0; i < ntparms; ++i)
4243     if (tpd.parms[i] == 0)
4244       {
4245         /* One of the template parms was not used in the
4246            specialization.  */
4247         if (!did_error_intro)
4248           {
4249             error ("template parameters not used in partial specialization:");
4250             did_error_intro = true;
4251           }
4252
4253         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
4254       }
4255
4256   if (did_error_intro)
4257     return error_mark_node;
4258
4259   /* [temp.class.spec]
4260
4261      The argument list of the specialization shall not be identical to
4262      the implicit argument list of the primary template.  */
4263   if (comp_template_args
4264       (inner_args,
4265        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
4266                                                    (maintmpl)))))
4267     error ("partial specialization %qT does not specialize any template arguments", type);
4268
4269   /* [temp.class.spec]
4270
4271      A partially specialized non-type argument expression shall not
4272      involve template parameters of the partial specialization except
4273      when the argument expression is a simple identifier.
4274
4275      The type of a template parameter corresponding to a specialized
4276      non-type argument shall not be dependent on a parameter of the
4277      specialization. 
4278
4279      Also, we verify that pack expansions only occur at the
4280      end of the argument list.  */
4281   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
4282   tpd2.parms = 0;
4283   for (i = 0; i < nargs; ++i)
4284     {
4285       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
4286       tree arg = TREE_VEC_ELT (inner_args, i);
4287       tree packed_args = NULL_TREE;
4288       int j, len = 1;
4289
4290       if (ARGUMENT_PACK_P (arg))
4291         {
4292           /* Extract the arguments from the argument pack. We'll be
4293              iterating over these in the following loop.  */
4294           packed_args = ARGUMENT_PACK_ARGS (arg);
4295           len = TREE_VEC_LENGTH (packed_args);
4296         }
4297
4298       for (j = 0; j < len; j++)
4299         {
4300           if (packed_args)
4301             /* Get the Jth argument in the parameter pack.  */
4302             arg = TREE_VEC_ELT (packed_args, j);
4303
4304           if (PACK_EXPANSION_P (arg))
4305             {
4306               /* Pack expansions must come at the end of the
4307                  argument list.  */
4308               if ((packed_args && j < len - 1)
4309                   || (!packed_args && i < nargs - 1))
4310                 {
4311                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4312                     error ("parameter pack argument %qE must be at the "
4313                            "end of the template argument list", arg);
4314                   else
4315                     error ("parameter pack argument %qT must be at the "
4316                            "end of the template argument list", arg);
4317                 }
4318             }
4319
4320           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4321             /* We only care about the pattern.  */
4322             arg = PACK_EXPANSION_PATTERN (arg);
4323
4324           if (/* These first two lines are the `non-type' bit.  */
4325               !TYPE_P (arg)
4326               && TREE_CODE (arg) != TEMPLATE_DECL
4327               /* This next line is the `argument expression is not just a
4328                  simple identifier' condition and also the `specialized
4329                  non-type argument' bit.  */
4330               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
4331             {
4332               if ((!packed_args && tpd.arg_uses_template_parms[i])
4333                   || (packed_args && uses_template_parms (arg)))
4334                 error ("template argument %qE involves template parameter(s)",
4335                        arg);
4336               else 
4337                 {
4338                   /* Look at the corresponding template parameter,
4339                      marking which template parameters its type depends
4340                      upon.  */
4341                   tree type = TREE_TYPE (parm);
4342
4343                   if (!tpd2.parms)
4344                     {
4345                       /* We haven't yet initialized TPD2.  Do so now.  */
4346                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4347                       /* The number of parameters here is the number in the
4348                          main template, which, as checked in the assertion
4349                          above, is NARGS.  */
4350                       tpd2.parms = XALLOCAVEC (int, nargs);
4351                       tpd2.level = 
4352                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4353                     }
4354
4355                   /* Mark the template parameters.  But this time, we're
4356                      looking for the template parameters of the main
4357                      template, not in the specialization.  */
4358                   tpd2.current_arg = i;
4359                   tpd2.arg_uses_template_parms[i] = 0;
4360                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4361                   for_each_template_parm (type,
4362                                           &mark_template_parm,
4363                                           &tpd2,
4364                                           NULL,
4365                                           /*include_nondeduced_p=*/false);
4366
4367                   if (tpd2.arg_uses_template_parms [i])
4368                     {
4369                       /* The type depended on some template parameters.
4370                          If they are fully specialized in the
4371                          specialization, that's OK.  */
4372                       int j;
4373                       int count = 0;
4374                       for (j = 0; j < nargs; ++j)
4375                         if (tpd2.parms[j] != 0
4376                             && tpd.arg_uses_template_parms [j])
4377                           ++count;
4378                       if (count != 0)
4379                         error_n (input_location, count,
4380                                  "type %qT of template argument %qE depends "
4381                                  "on a template parameter",
4382                                  "type %qT of template argument %qE depends "
4383                                  "on template parameters",
4384                                  type,
4385                                  arg);
4386                     }
4387                 }
4388             }
4389         }
4390     }
4391
4392   /* We should only get here once.  */
4393   gcc_assert (!COMPLETE_TYPE_P (type));
4394
4395   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4396     = tree_cons (specargs, inner_parms,
4397                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4398   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4399
4400   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
4401        inst = TREE_CHAIN (inst))
4402     {
4403       tree inst_type = TREE_VALUE (inst);
4404       if (COMPLETE_TYPE_P (inst_type)
4405           && CLASSTYPE_IMPLICIT_INSTANTIATION (inst_type))
4406         {
4407           tree spec = most_specialized_class (inst_type, maintmpl, tf_none);
4408           if (spec && TREE_TYPE (spec) == type)
4409             permerror (input_location,
4410                        "partial specialization of %qT after instantiation "
4411                        "of %qT", type, inst_type);
4412         }
4413     }
4414
4415   return decl;
4416 }
4417
4418 /* Check that a template declaration's use of default arguments and
4419    parameter packs is not invalid.  Here, PARMS are the template
4420    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
4421    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
4422    specialization.
4423    
4424
4425    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4426    declaration (but not a definition); 1 indicates a declaration, 2
4427    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4428    emitted for extraneous default arguments.
4429
4430    Returns TRUE if there were no errors found, FALSE otherwise. */
4431
4432 bool
4433 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
4434                          int is_partial, int is_friend_decl)
4435 {
4436   const char *msg;
4437   int last_level_to_check;
4438   tree parm_level;
4439   bool no_errors = true;
4440
4441   /* [temp.param]
4442
4443      A default template-argument shall not be specified in a
4444      function template declaration or a function template definition, nor
4445      in the template-parameter-list of the definition of a member of a
4446      class template.  */
4447
4448   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
4449     /* You can't have a function template declaration in a local
4450        scope, nor you can you define a member of a class template in a
4451        local scope.  */
4452     return true;
4453
4454   if (current_class_type
4455       && !TYPE_BEING_DEFINED (current_class_type)
4456       && DECL_LANG_SPECIFIC (decl)
4457       && DECL_DECLARES_FUNCTION_P (decl)
4458       /* If this is either a friend defined in the scope of the class
4459          or a member function.  */
4460       && (DECL_FUNCTION_MEMBER_P (decl)
4461           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4462           : DECL_FRIEND_CONTEXT (decl)
4463           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4464           : false)
4465       /* And, if it was a member function, it really was defined in
4466          the scope of the class.  */
4467       && (!DECL_FUNCTION_MEMBER_P (decl)
4468           || DECL_INITIALIZED_IN_CLASS_P (decl)))
4469     /* We already checked these parameters when the template was
4470        declared, so there's no need to do it again now.  This function
4471        was defined in class scope, but we're processing it's body now
4472        that the class is complete.  */
4473     return true;
4474
4475   /* Core issue 226 (C++0x only): the following only applies to class
4476      templates.  */
4477   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
4478     {
4479       /* [temp.param]
4480
4481          If a template-parameter has a default template-argument, all
4482          subsequent template-parameters shall have a default
4483          template-argument supplied.  */
4484       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4485         {
4486           tree inner_parms = TREE_VALUE (parm_level);
4487           int ntparms = TREE_VEC_LENGTH (inner_parms);
4488           int seen_def_arg_p = 0;
4489           int i;
4490
4491           for (i = 0; i < ntparms; ++i)
4492             {
4493               tree parm = TREE_VEC_ELT (inner_parms, i);
4494
4495               if (parm == error_mark_node)
4496                 continue;
4497
4498               if (TREE_PURPOSE (parm))
4499                 seen_def_arg_p = 1;
4500               else if (seen_def_arg_p
4501                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4502                 {
4503                   error ("no default argument for %qD", TREE_VALUE (parm));
4504                   /* For better subsequent error-recovery, we indicate that
4505                      there should have been a default argument.  */
4506                   TREE_PURPOSE (parm) = error_mark_node;
4507                   no_errors = false;
4508                 }
4509               else if (is_primary
4510                        && !is_partial
4511                        && !is_friend_decl
4512                        /* Don't complain about an enclosing partial
4513                           specialization.  */
4514                        && parm_level == parms
4515                        && TREE_CODE (decl) == TYPE_DECL
4516                        && i < ntparms - 1
4517                        && template_parameter_pack_p (TREE_VALUE (parm)))
4518                 {
4519                   /* A primary class template can only have one
4520                      parameter pack, at the end of the template
4521                      parameter list.  */
4522
4523                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4524                     error ("parameter pack %qE must be at the end of the"
4525                            " template parameter list", TREE_VALUE (parm));
4526                   else
4527                     error ("parameter pack %qT must be at the end of the"
4528                            " template parameter list", 
4529                            TREE_TYPE (TREE_VALUE (parm)));
4530
4531                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4532                     = error_mark_node;
4533                   no_errors = false;
4534                 }
4535             }
4536         }
4537     }
4538
4539   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4540       || is_partial 
4541       || !is_primary
4542       || is_friend_decl)
4543     /* For an ordinary class template, default template arguments are
4544        allowed at the innermost level, e.g.:
4545          template <class T = int>
4546          struct S {};
4547        but, in a partial specialization, they're not allowed even
4548        there, as we have in [temp.class.spec]:
4549
4550          The template parameter list of a specialization shall not
4551          contain default template argument values.
4552
4553        So, for a partial specialization, or for a function template
4554        (in C++98/C++03), we look at all of them.  */
4555     ;
4556   else
4557     /* But, for a primary class template that is not a partial
4558        specialization we look at all template parameters except the
4559        innermost ones.  */
4560     parms = TREE_CHAIN (parms);
4561
4562   /* Figure out what error message to issue.  */
4563   if (is_friend_decl == 2)
4564     msg = G_("default template arguments may not be used in function template "
4565              "friend re-declaration");
4566   else if (is_friend_decl)
4567     msg = G_("default template arguments may not be used in function template "
4568              "friend declarations");
4569   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4570     msg = G_("default template arguments may not be used in function templates "
4571              "without -std=c++0x or -std=gnu++0x");
4572   else if (is_partial)
4573     msg = G_("default template arguments may not be used in "
4574              "partial specializations");
4575   else
4576     msg = G_("default argument for template parameter for class enclosing %qD");
4577
4578   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4579     /* If we're inside a class definition, there's no need to
4580        examine the parameters to the class itself.  On the one
4581        hand, they will be checked when the class is defined, and,
4582        on the other, default arguments are valid in things like:
4583          template <class T = double>
4584          struct S { template <class U> void f(U); };
4585        Here the default argument for `S' has no bearing on the
4586        declaration of `f'.  */
4587     last_level_to_check = template_class_depth (current_class_type) + 1;
4588   else
4589     /* Check everything.  */
4590     last_level_to_check = 0;
4591
4592   for (parm_level = parms;
4593        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4594        parm_level = TREE_CHAIN (parm_level))
4595     {
4596       tree inner_parms = TREE_VALUE (parm_level);
4597       int i;
4598       int ntparms;
4599
4600       ntparms = TREE_VEC_LENGTH (inner_parms);
4601       for (i = 0; i < ntparms; ++i)
4602         {
4603           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4604             continue;
4605
4606           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4607             {
4608               if (msg)
4609                 {
4610                   no_errors = false;
4611                   if (is_friend_decl == 2)
4612                     return no_errors;
4613
4614                   error (msg, decl);
4615                   msg = 0;
4616                 }
4617
4618               /* Clear out the default argument so that we are not
4619                  confused later.  */
4620               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4621             }
4622         }
4623
4624       /* At this point, if we're still interested in issuing messages,
4625          they must apply to classes surrounding the object declared.  */
4626       if (msg)
4627         msg = G_("default argument for template parameter for class "
4628                  "enclosing %qD");
4629     }
4630
4631   return no_errors;
4632 }
4633
4634 /* Worker for push_template_decl_real, called via
4635    for_each_template_parm.  DATA is really an int, indicating the
4636    level of the parameters we are interested in.  If T is a template
4637    parameter of that level, return nonzero.  */
4638
4639 static int
4640 template_parm_this_level_p (tree t, void* data)
4641 {
4642   int this_level = *(int *)data;
4643   int level;
4644
4645   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4646     level = TEMPLATE_PARM_LEVEL (t);
4647   else
4648     level = TEMPLATE_TYPE_LEVEL (t);
4649   return level == this_level;
4650 }
4651
4652 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4653    parameters given by current_template_args, or reuses a
4654    previously existing one, if appropriate.  Returns the DECL, or an
4655    equivalent one, if it is replaced via a call to duplicate_decls.
4656
4657    If IS_FRIEND is true, DECL is a friend declaration.  */
4658
4659 tree
4660 push_template_decl_real (tree decl, bool is_friend)
4661 {
4662   tree tmpl;
4663   tree args;
4664   tree info;
4665   tree ctx;
4666   int primary;
4667   int is_partial;
4668   int new_template_p = 0;
4669   /* True if the template is a member template, in the sense of
4670      [temp.mem].  */
4671   bool member_template_p = false;
4672
4673   if (decl == error_mark_node || !current_template_parms)
4674     return error_mark_node;
4675
4676   /* See if this is a partial specialization.  */
4677   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4678                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4679                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4680
4681   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4682     is_friend = true;
4683
4684   if (is_friend)
4685     /* For a friend, we want the context of the friend function, not
4686        the type of which it is a friend.  */
4687     ctx = CP_DECL_CONTEXT (decl);
4688   else if (CP_DECL_CONTEXT (decl)
4689            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4690     /* In the case of a virtual function, we want the class in which
4691        it is defined.  */
4692     ctx = CP_DECL_CONTEXT (decl);
4693   else
4694     /* Otherwise, if we're currently defining some class, the DECL
4695        is assumed to be a member of the class.  */
4696     ctx = current_scope ();
4697
4698   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4699     ctx = NULL_TREE;
4700
4701   if (!DECL_CONTEXT (decl))
4702     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4703
4704   /* See if this is a primary template.  */
4705   if (is_friend && ctx)
4706     /* A friend template that specifies a class context, i.e.
4707          template <typename T> friend void A<T>::f();
4708        is not primary.  */
4709     primary = 0;
4710   else
4711     primary = template_parm_scope_p ();
4712
4713   if (primary)
4714     {
4715       if (DECL_CLASS_SCOPE_P (decl))
4716         member_template_p = true;
4717       if (TREE_CODE (decl) == TYPE_DECL
4718           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4719         {
4720           error ("template class without a name");
4721           return error_mark_node;
4722         }
4723       else if (TREE_CODE (decl) == FUNCTION_DECL)
4724         {
4725           if (DECL_DESTRUCTOR_P (decl))
4726             {
4727               /* [temp.mem]
4728
4729                  A destructor shall not be a member template.  */
4730               error ("destructor %qD declared as member template", decl);
4731               return error_mark_node;
4732             }
4733           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4734               && (!prototype_p (TREE_TYPE (decl))
4735                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4736                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4737                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4738                       == void_list_node)))
4739             {
4740               /* [basic.stc.dynamic.allocation]
4741
4742                  An allocation function can be a function
4743                  template. ... Template allocation functions shall
4744                  have two or more parameters.  */
4745               error ("invalid template declaration of %qD", decl);
4746               return error_mark_node;
4747             }
4748         }
4749       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4750                && CLASS_TYPE_P (TREE_TYPE (decl)))
4751         /* OK */;
4752       else
4753         {
4754           error ("template declaration of %q#D", decl);
4755           return error_mark_node;
4756         }
4757     }
4758
4759   /* Check to see that the rules regarding the use of default
4760      arguments are not being violated.  */
4761   check_default_tmpl_args (decl, current_template_parms,
4762                            primary, is_partial, /*is_friend_decl=*/0);
4763
4764   /* Ensure that there are no parameter packs in the type of this
4765      declaration that have not been expanded.  */
4766   if (TREE_CODE (decl) == FUNCTION_DECL)
4767     {
4768       /* Check each of the arguments individually to see if there are
4769          any bare parameter packs.  */
4770       tree type = TREE_TYPE (decl);
4771       tree arg = DECL_ARGUMENTS (decl);
4772       tree argtype = TYPE_ARG_TYPES (type);
4773
4774       while (arg && argtype)
4775         {
4776           if (!FUNCTION_PARAMETER_PACK_P (arg)
4777               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4778             {
4779             /* This is a PARM_DECL that contains unexpanded parameter
4780                packs. We have already complained about this in the
4781                check_for_bare_parameter_packs call, so just replace
4782                these types with ERROR_MARK_NODE.  */
4783               TREE_TYPE (arg) = error_mark_node;
4784               TREE_VALUE (argtype) = error_mark_node;
4785             }
4786
4787           arg = DECL_CHAIN (arg);
4788           argtype = TREE_CHAIN (argtype);
4789         }
4790
4791       /* Check for bare parameter packs in the return type and the
4792          exception specifiers.  */
4793       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4794         /* Errors were already issued, set return type to int
4795            as the frontend doesn't expect error_mark_node as
4796            the return type.  */
4797         TREE_TYPE (type) = integer_type_node;
4798       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4799         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4800     }
4801   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4802     {
4803       TREE_TYPE (decl) = error_mark_node;
4804       return error_mark_node;
4805     }
4806
4807   if (is_partial)
4808     return process_partial_specialization (decl);
4809
4810   args = current_template_args ();
4811
4812   if (!ctx
4813       || TREE_CODE (ctx) == FUNCTION_DECL
4814       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4815       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4816     {
4817       if (DECL_LANG_SPECIFIC (decl)
4818           && DECL_TEMPLATE_INFO (decl)
4819           && DECL_TI_TEMPLATE (decl))
4820         tmpl = DECL_TI_TEMPLATE (decl);
4821       /* If DECL is a TYPE_DECL for a class-template, then there won't
4822          be DECL_LANG_SPECIFIC.  The information equivalent to
4823          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4824       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4825                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4826                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4827         {
4828           /* Since a template declaration already existed for this
4829              class-type, we must be redeclaring it here.  Make sure
4830              that the redeclaration is valid.  */
4831           redeclare_class_template (TREE_TYPE (decl),
4832                                     current_template_parms);
4833           /* We don't need to create a new TEMPLATE_DECL; just use the
4834              one we already had.  */
4835           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4836         }
4837       else
4838         {
4839           tmpl = build_template_decl (decl, current_template_parms,
4840                                       member_template_p);
4841           new_template_p = 1;
4842
4843           if (DECL_LANG_SPECIFIC (decl)
4844               && DECL_TEMPLATE_SPECIALIZATION (decl))
4845             {
4846               /* A specialization of a member template of a template
4847                  class.  */
4848               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4849               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4850               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4851             }
4852         }
4853     }
4854   else
4855     {
4856       tree a, t, current, parms;
4857       int i;
4858       tree tinfo = get_template_info (decl);
4859
4860       if (!tinfo)
4861         {
4862           error ("template definition of non-template %q#D", decl);
4863           return error_mark_node;
4864         }
4865
4866       tmpl = TI_TEMPLATE (tinfo);
4867
4868       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4869           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4870           && DECL_TEMPLATE_SPECIALIZATION (decl)
4871           && DECL_MEMBER_TEMPLATE_P (tmpl))
4872         {
4873           tree new_tmpl;
4874
4875           /* The declaration is a specialization of a member
4876              template, declared outside the class.  Therefore, the
4877              innermost template arguments will be NULL, so we
4878              replace them with the arguments determined by the
4879              earlier call to check_explicit_specialization.  */
4880           args = DECL_TI_ARGS (decl);
4881
4882           new_tmpl
4883             = build_template_decl (decl, current_template_parms,
4884                                    member_template_p);
4885           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4886           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4887           DECL_TI_TEMPLATE (decl) = new_tmpl;
4888           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4889           DECL_TEMPLATE_INFO (new_tmpl)
4890             = build_template_info (tmpl, args);
4891
4892           register_specialization (new_tmpl,
4893                                    most_general_template (tmpl),
4894                                    args,
4895                                    is_friend, 0);
4896           return decl;
4897         }
4898
4899       /* Make sure the template headers we got make sense.  */
4900
4901       parms = DECL_TEMPLATE_PARMS (tmpl);
4902       i = TMPL_PARMS_DEPTH (parms);
4903       if (TMPL_ARGS_DEPTH (args) != i)
4904         {
4905           error ("expected %d levels of template parms for %q#D, got %d",
4906                  i, decl, TMPL_ARGS_DEPTH (args));
4907         }
4908       else
4909         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4910           {
4911             a = TMPL_ARGS_LEVEL (args, i);
4912             t = INNERMOST_TEMPLATE_PARMS (parms);
4913
4914             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4915               {
4916                 if (current == decl)
4917                   error ("got %d template parameters for %q#D",
4918                          TREE_VEC_LENGTH (a), decl);
4919                 else
4920                   error ("got %d template parameters for %q#T",
4921                          TREE_VEC_LENGTH (a), current);
4922                 error ("  but %d required", TREE_VEC_LENGTH (t));
4923                 return error_mark_node;
4924               }
4925
4926             if (current == decl)
4927               current = ctx;
4928             else if (current == NULL_TREE)
4929               /* Can happen in erroneous input.  */
4930               break;
4931             else
4932               current = (TYPE_P (current)
4933                          ? TYPE_CONTEXT (current)
4934                          : DECL_CONTEXT (current));
4935           }
4936
4937       /* Check that the parms are used in the appropriate qualifying scopes
4938          in the declarator.  */
4939       if (!comp_template_args
4940           (TI_ARGS (tinfo),
4941            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4942         {
4943           error ("\
4944 template arguments to %qD do not match original template %qD",
4945                  decl, DECL_TEMPLATE_RESULT (tmpl));
4946           if (!uses_template_parms (TI_ARGS (tinfo)))
4947             inform (input_location, "use template<> for an explicit specialization");
4948           /* Avoid crash in import_export_decl.  */
4949           DECL_INTERFACE_KNOWN (decl) = 1;
4950           return error_mark_node;
4951         }
4952     }
4953
4954   DECL_TEMPLATE_RESULT (tmpl) = decl;
4955   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4956
4957   /* Push template declarations for global functions and types.  Note
4958      that we do not try to push a global template friend declared in a
4959      template class; such a thing may well depend on the template
4960      parameters of the class.  */
4961   if (new_template_p && !ctx
4962       && !(is_friend && template_class_depth (current_class_type) > 0))
4963     {
4964       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4965       if (tmpl == error_mark_node)
4966         return error_mark_node;
4967
4968       /* Hide template friend classes that haven't been declared yet.  */
4969       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4970         {
4971           DECL_ANTICIPATED (tmpl) = 1;
4972           DECL_FRIEND_P (tmpl) = 1;
4973         }
4974     }
4975
4976   if (primary)
4977     {
4978       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4979       int i;
4980
4981       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4982       if (DECL_CONV_FN_P (tmpl))
4983         {
4984           int depth = TMPL_PARMS_DEPTH (parms);
4985
4986           /* It is a conversion operator. See if the type converted to
4987              depends on innermost template operands.  */
4988
4989           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4990                                          depth))
4991             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4992         }
4993
4994       /* Give template template parms a DECL_CONTEXT of the template
4995          for which they are a parameter.  */
4996       parms = INNERMOST_TEMPLATE_PARMS (parms);
4997       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4998         {
4999           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5000           if (TREE_CODE (parm) == TEMPLATE_DECL)
5001             DECL_CONTEXT (parm) = tmpl;
5002         }
5003     }
5004
5005   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
5006      back to its most general template.  If TMPL is a specialization,
5007      ARGS may only have the innermost set of arguments.  Add the missing
5008      argument levels if necessary.  */
5009   if (DECL_TEMPLATE_INFO (tmpl))
5010     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
5011
5012   info = build_template_info (tmpl, args);
5013
5014   if (DECL_IMPLICIT_TYPEDEF_P (decl))
5015     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
5016   else if (DECL_LANG_SPECIFIC (decl))
5017     DECL_TEMPLATE_INFO (decl) = info;
5018
5019   return DECL_TEMPLATE_RESULT (tmpl);
5020 }
5021
5022 tree
5023 push_template_decl (tree decl)
5024 {
5025   return push_template_decl_real (decl, false);
5026 }
5027
5028 /* Called when a class template TYPE is redeclared with the indicated
5029    template PARMS, e.g.:
5030
5031      template <class T> struct S;
5032      template <class T> struct S {};  */
5033
5034 bool
5035 redeclare_class_template (tree type, tree parms)
5036 {
5037   tree tmpl;
5038   tree tmpl_parms;
5039   int i;
5040
5041   if (!TYPE_TEMPLATE_INFO (type))
5042     {
5043       error ("%qT is not a template type", type);
5044       return false;
5045     }
5046
5047   tmpl = TYPE_TI_TEMPLATE (type);
5048   if (!PRIMARY_TEMPLATE_P (tmpl))
5049     /* The type is nested in some template class.  Nothing to worry
5050        about here; there are no new template parameters for the nested
5051        type.  */
5052     return true;
5053
5054   if (!parms)
5055     {
5056       error ("template specifiers not specified in declaration of %qD",
5057              tmpl);
5058       return false;
5059     }
5060
5061   parms = INNERMOST_TEMPLATE_PARMS (parms);
5062   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
5063
5064   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
5065     {
5066       error_n (input_location, TREE_VEC_LENGTH (parms),
5067                "redeclared with %d template parameter",
5068                "redeclared with %d template parameters",
5069                TREE_VEC_LENGTH (parms));
5070       inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
5071                 "previous declaration %q+D used %d template parameter",
5072                 "previous declaration %q+D used %d template parameters",
5073                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
5074       return false;
5075     }
5076
5077   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
5078     {
5079       tree tmpl_parm;
5080       tree parm;
5081       tree tmpl_default;
5082       tree parm_default;
5083
5084       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
5085           || TREE_VEC_ELT (parms, i) == error_mark_node)
5086         continue;
5087
5088       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
5089       if (tmpl_parm == error_mark_node)
5090         return false;
5091
5092       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5093       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
5094       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
5095
5096       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
5097          TEMPLATE_DECL.  */
5098       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
5099           || (TREE_CODE (tmpl_parm) != TYPE_DECL
5100               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
5101           || (TREE_CODE (tmpl_parm) != PARM_DECL
5102               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
5103                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
5104           || (TREE_CODE (tmpl_parm) == PARM_DECL
5105               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
5106                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
5107         {
5108           error ("template parameter %q+#D", tmpl_parm);
5109           error ("redeclared here as %q#D", parm);
5110           return false;
5111         }
5112
5113       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
5114         {
5115           /* We have in [temp.param]:
5116
5117              A template-parameter may not be given default arguments
5118              by two different declarations in the same scope.  */
5119           error_at (input_location, "redefinition of default argument for %q#D", parm);
5120           inform (DECL_SOURCE_LOCATION (tmpl_parm),
5121                   "original definition appeared here");
5122           return false;
5123         }
5124
5125       if (parm_default != NULL_TREE)
5126         /* Update the previous template parameters (which are the ones
5127            that will really count) with the new default value.  */
5128         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
5129       else if (tmpl_default != NULL_TREE)
5130         /* Update the new parameters, too; they'll be used as the
5131            parameters for any members.  */
5132         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
5133     }
5134
5135     return true;
5136 }
5137
5138 /* Simplify EXPR if it is a non-dependent expression.  Returns the
5139    (possibly simplified) expression.  */
5140
5141 static tree
5142 fold_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
5143 {
5144   if (expr == NULL_TREE)
5145     return NULL_TREE;
5146
5147   /* If we're in a template, but EXPR isn't value dependent, simplify
5148      it.  We're supposed to treat:
5149
5150        template <typename T> void f(T[1 + 1]);
5151        template <typename T> void f(T[2]);
5152
5153      as two declarations of the same function, for example.  */
5154   if (processing_template_decl
5155       && !type_dependent_expression_p (expr)
5156       && potential_constant_expression (expr)
5157       && !value_dependent_expression_p (expr))
5158     {
5159       HOST_WIDE_INT saved_processing_template_decl;
5160
5161       saved_processing_template_decl = processing_template_decl;
5162       processing_template_decl = 0;
5163       expr = tsubst_copy_and_build (expr,
5164                                     /*args=*/NULL_TREE,
5165                                     complain,
5166                                     /*in_decl=*/NULL_TREE,
5167                                     /*function_p=*/false,
5168                                     /*integral_constant_expression_p=*/true);
5169       processing_template_decl = saved_processing_template_decl;
5170     }
5171   return expr;
5172 }
5173
5174 tree
5175 fold_non_dependent_expr (tree expr)
5176 {
5177   return fold_non_dependent_expr_sfinae (expr, tf_error);
5178 }
5179
5180 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
5181    must be a function or a pointer-to-function type, as specified
5182    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
5183    and check that the resulting function has external linkage.  */
5184
5185 static tree
5186 convert_nontype_argument_function (tree type, tree expr)
5187 {
5188   tree fns = expr;
5189   tree fn, fn_no_ptr;
5190
5191   fn = instantiate_type (type, fns, tf_none);
5192   if (fn == error_mark_node)
5193     return error_mark_node;
5194
5195   fn_no_ptr = fn;
5196   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
5197     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
5198   if (TREE_CODE (fn_no_ptr) == BASELINK)
5199     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
5200  
5201   /* [temp.arg.nontype]/1
5202
5203      A template-argument for a non-type, non-template template-parameter
5204      shall be one of:
5205      [...]
5206      -- the address of an object or function with external linkage.  */
5207   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
5208     {
5209       error ("%qE is not a valid template argument for type %qT "
5210              "because function %qD has not external linkage",
5211              expr, type, fn_no_ptr);
5212       return NULL_TREE;
5213     }
5214
5215   return fn;
5216 }
5217
5218 /* Subroutine of convert_nontype_argument.
5219    Check if EXPR of type TYPE is a valid pointer-to-member constant.
5220    Emit an error otherwise.  */
5221
5222 static bool
5223 check_valid_ptrmem_cst_expr (tree type, tree expr,
5224                              tsubst_flags_t complain)
5225 {
5226   STRIP_NOPS (expr);
5227   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
5228     return true;
5229   if (complain & tf_error)
5230     {
5231       error ("%qE is not a valid template argument for type %qT",
5232              expr, type);
5233       error ("it must be a pointer-to-member of the form %<&X::Y%>");
5234     }
5235   return false;
5236 }
5237
5238 /* Returns TRUE iff the address of OP is value-dependent.
5239
5240    14.6.2.4 [temp.dep.temp]:
5241    A non-integral non-type template-argument is dependent if its type is
5242    dependent or it has either of the following forms
5243      qualified-id
5244      & qualified-id
5245    and contains a nested-name-specifier which specifies a class-name that
5246    names a dependent type.
5247
5248    We generalize this to just say that the address of a member of a
5249    dependent class is value-dependent; the above doesn't cover the
5250    address of a static data member named with an unqualified-id.  */
5251
5252 static bool
5253 has_value_dependent_address (tree op)
5254 {
5255   /* We could use get_inner_reference here, but there's no need;
5256      this is only relevant for template non-type arguments, which
5257      can only be expressed as &id-expression.  */
5258   if (DECL_P (op))
5259     {
5260       tree ctx = CP_DECL_CONTEXT (op);
5261       if (TYPE_P (ctx) && dependent_type_p (ctx))
5262         return true;
5263     }
5264
5265   return false;
5266 }
5267
5268 /* Attempt to convert the non-type template parameter EXPR to the
5269    indicated TYPE.  If the conversion is successful, return the
5270    converted value.  If the conversion is unsuccessful, return
5271    NULL_TREE if we issued an error message, or error_mark_node if we
5272    did not.  We issue error messages for out-and-out bad template
5273    parameters, but not simply because the conversion failed, since we
5274    might be just trying to do argument deduction.  Both TYPE and EXPR
5275    must be non-dependent.
5276
5277    The conversion follows the special rules described in
5278    [temp.arg.nontype], and it is much more strict than an implicit
5279    conversion.
5280
5281    This function is called twice for each template argument (see
5282    lookup_template_class for a more accurate description of this
5283    problem). This means that we need to handle expressions which
5284    are not valid in a C++ source, but can be created from the
5285    first call (for instance, casts to perform conversions). These
5286    hacks can go away after we fix the double coercion problem.  */
5287
5288 static tree
5289 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
5290 {
5291   tree expr_type;
5292
5293   /* Detect immediately string literals as invalid non-type argument.
5294      This special-case is not needed for correctness (we would easily
5295      catch this later), but only to provide better diagnostic for this
5296      common user mistake. As suggested by DR 100, we do not mention
5297      linkage issues in the diagnostic as this is not the point.  */
5298   /* FIXME we're making this OK.  */
5299   if (TREE_CODE (expr) == STRING_CST)
5300     {
5301       if (complain & tf_error)
5302         error ("%qE is not a valid template argument for type %qT "
5303                "because string literals can never be used in this context",
5304                expr, type);
5305       return NULL_TREE;
5306     }
5307
5308   /* Add the ADDR_EXPR now for the benefit of
5309      value_dependent_expression_p.  */
5310   if (TYPE_PTROBV_P (type)
5311       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
5312     expr = decay_conversion (expr);
5313
5314   /* If we are in a template, EXPR may be non-dependent, but still
5315      have a syntactic, rather than semantic, form.  For example, EXPR
5316      might be a SCOPE_REF, rather than the VAR_DECL to which the
5317      SCOPE_REF refers.  Preserving the qualifying scope is necessary
5318      so that access checking can be performed when the template is
5319      instantiated -- but here we need the resolved form so that we can
5320      convert the argument.  */
5321   if (TYPE_REF_OBJ_P (type)
5322       && has_value_dependent_address (expr))
5323     /* If we want the address and it's value-dependent, don't fold.  */;
5324   else if (!type_unknown_p (expr))
5325     expr = fold_non_dependent_expr_sfinae (expr, complain);
5326   if (error_operand_p (expr))
5327     return error_mark_node;
5328   expr_type = TREE_TYPE (expr);
5329   if (TREE_CODE (type) == REFERENCE_TYPE)
5330     expr = mark_lvalue_use (expr);
5331   else
5332     expr = mark_rvalue_use (expr);
5333
5334   /* HACK: Due to double coercion, we can get a
5335      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
5336      which is the tree that we built on the first call (see
5337      below when coercing to reference to object or to reference to
5338      function). We just strip everything and get to the arg.
5339      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
5340      for examples.  */
5341   if (TREE_CODE (expr) == NOP_EXPR)
5342     {
5343       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
5344         {
5345           /* ??? Maybe we could use convert_from_reference here, but we
5346              would need to relax its constraints because the NOP_EXPR
5347              could actually change the type to something more cv-qualified,
5348              and this is not folded by convert_from_reference.  */
5349           tree addr = TREE_OPERAND (expr, 0);
5350           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
5351           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
5352           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
5353           gcc_assert (same_type_ignoring_top_level_qualifiers_p
5354                       (TREE_TYPE (expr_type),
5355                        TREE_TYPE (TREE_TYPE (addr))));
5356
5357           expr = TREE_OPERAND (addr, 0);
5358           expr_type = TREE_TYPE (expr);
5359         }
5360
5361       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
5362          parameter is a pointer to object, through decay and
5363          qualification conversion. Let's strip everything.  */
5364       else if (TYPE_PTROBV_P (type))
5365         {
5366           STRIP_NOPS (expr);
5367           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
5368           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
5369           /* Skip the ADDR_EXPR only if it is part of the decay for
5370              an array. Otherwise, it is part of the original argument
5371              in the source code.  */
5372           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
5373             expr = TREE_OPERAND (expr, 0);
5374           expr_type = TREE_TYPE (expr);
5375         }
5376     }
5377
5378   /* [temp.arg.nontype]/5, bullet 1
5379
5380      For a non-type template-parameter of integral or enumeration type,
5381      integral promotions (_conv.prom_) and integral conversions
5382      (_conv.integral_) are applied.  */
5383   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5384     {
5385       tree t = build_integral_nontype_arg_conv (type, expr, complain);
5386       t = maybe_constant_value (t);
5387       if (t != error_mark_node)
5388         expr = t;
5389
5390       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
5391         return error_mark_node;
5392
5393       /* Notice that there are constant expressions like '4 % 0' which
5394          do not fold into integer constants.  */
5395       if (TREE_CODE (expr) != INTEGER_CST)
5396         {
5397           if (complain & tf_error)
5398             {
5399               int errs = errorcount, warns = warningcount;
5400               expr = cxx_constant_value (expr);
5401               if (errorcount > errs || warningcount > warns)
5402                 inform (EXPR_LOC_OR_HERE (expr),
5403                         "in template argument for type %qT ", type);
5404               if (expr == error_mark_node)
5405                 return NULL_TREE;
5406               /* else cxx_constant_value complained but gave us
5407                  a real constant, so go ahead.  */
5408               gcc_assert (TREE_CODE (expr) == INTEGER_CST);
5409             }
5410           else
5411             return NULL_TREE;
5412         }
5413     }
5414   /* [temp.arg.nontype]/5, bullet 2
5415
5416      For a non-type template-parameter of type pointer to object,
5417      qualification conversions (_conv.qual_) and the array-to-pointer
5418      conversion (_conv.array_) are applied.  */
5419   else if (TYPE_PTROBV_P (type))
5420     {
5421       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
5422
5423          A template-argument for a non-type, non-template template-parameter
5424          shall be one of: [...]
5425
5426          -- the name of a non-type template-parameter;
5427          -- the address of an object or function with external linkage, [...]
5428             expressed as "& id-expression" where the & is optional if the name
5429             refers to a function or array, or if the corresponding
5430             template-parameter is a reference.
5431
5432         Here, we do not care about functions, as they are invalid anyway
5433         for a parameter of type pointer-to-object.  */
5434
5435       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
5436         /* Non-type template parameters are OK.  */
5437         ;
5438       else if (TREE_CODE (expr) != ADDR_EXPR
5439                && TREE_CODE (expr_type) != ARRAY_TYPE)
5440         {
5441           if (TREE_CODE (expr) == VAR_DECL)
5442             {
5443               error ("%qD is not a valid template argument "
5444                      "because %qD is a variable, not the address of "
5445                      "a variable",
5446                      expr, expr);
5447               return NULL_TREE;
5448             }
5449           /* Other values, like integer constants, might be valid
5450              non-type arguments of some other type.  */
5451           return error_mark_node;
5452         }
5453       else
5454         {
5455           tree decl;
5456
5457           decl = ((TREE_CODE (expr) == ADDR_EXPR)
5458                   ? TREE_OPERAND (expr, 0) : expr);
5459           if (TREE_CODE (decl) != VAR_DECL)
5460             {
5461               error ("%qE is not a valid template argument of type %qT "
5462                      "because %qE is not a variable",
5463                      expr, type, decl);
5464               return NULL_TREE;
5465             }
5466           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
5467             {
5468               error ("%qE is not a valid template argument of type %qT "
5469                      "because %qD does not have external linkage",
5470                      expr, type, decl);
5471               return NULL_TREE;
5472             }
5473         }
5474
5475       expr = decay_conversion (expr);
5476       if (expr == error_mark_node)
5477         return error_mark_node;
5478
5479       expr = perform_qualification_conversions (type, expr);
5480       if (expr == error_mark_node)
5481         return error_mark_node;
5482     }
5483   /* [temp.arg.nontype]/5, bullet 3
5484
5485      For a non-type template-parameter of type reference to object, no
5486      conversions apply. The type referred to by the reference may be more
5487      cv-qualified than the (otherwise identical) type of the
5488      template-argument. The template-parameter is bound directly to the
5489      template-argument, which must be an lvalue.  */
5490   else if (TYPE_REF_OBJ_P (type))
5491     {
5492       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5493                                                       expr_type))
5494         return error_mark_node;
5495
5496       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5497         {
5498           error ("%qE is not a valid template argument for type %qT "
5499                  "because of conflicts in cv-qualification", expr, type);
5500           return NULL_TREE;
5501         }
5502
5503       if (!real_lvalue_p (expr))
5504         {
5505           error ("%qE is not a valid template argument for type %qT "
5506                  "because it is not an lvalue", expr, type);
5507           return NULL_TREE;
5508         }
5509
5510       /* [temp.arg.nontype]/1
5511
5512          A template-argument for a non-type, non-template template-parameter
5513          shall be one of: [...]
5514
5515          -- the address of an object or function with external linkage.  */
5516       if (TREE_CODE (expr) == INDIRECT_REF
5517           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5518         {
5519           expr = TREE_OPERAND (expr, 0);
5520           if (DECL_P (expr))
5521             {
5522               error ("%q#D is not a valid template argument for type %qT "
5523                      "because a reference variable does not have a constant "
5524                      "address", expr, type);
5525               return NULL_TREE;
5526             }
5527         }
5528
5529       if (!DECL_P (expr))
5530         {
5531           error ("%qE is not a valid template argument for type %qT "
5532                  "because it is not an object with external linkage",
5533                  expr, type);
5534           return NULL_TREE;
5535         }
5536
5537       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5538         {
5539           error ("%qE is not a valid template argument for type %qT "
5540                  "because object %qD has not external linkage",
5541                  expr, type, expr);
5542           return NULL_TREE;
5543         }
5544
5545       expr = build_nop (type, build_address (expr));
5546     }
5547   /* [temp.arg.nontype]/5, bullet 4
5548
5549      For a non-type template-parameter of type pointer to function, only
5550      the function-to-pointer conversion (_conv.func_) is applied. If the
5551      template-argument represents a set of overloaded functions (or a
5552      pointer to such), the matching function is selected from the set
5553      (_over.over_).  */
5554   else if (TYPE_PTRFN_P (type))
5555     {
5556       /* If the argument is a template-id, we might not have enough
5557          context information to decay the pointer.  */
5558       if (!type_unknown_p (expr_type))
5559         {
5560           expr = decay_conversion (expr);
5561           if (expr == error_mark_node)
5562             return error_mark_node;
5563         }
5564
5565       expr = convert_nontype_argument_function (type, expr);
5566       if (!expr || expr == error_mark_node)
5567         return expr;
5568
5569       if (TREE_CODE (expr) != ADDR_EXPR)
5570         {
5571           error ("%qE is not a valid template argument for type %qT", expr, type);
5572           error ("it must be the address of a function with external linkage");
5573           return NULL_TREE;
5574         }
5575     }
5576   /* [temp.arg.nontype]/5, bullet 5
5577
5578      For a non-type template-parameter of type reference to function, no
5579      conversions apply. If the template-argument represents a set of
5580      overloaded functions, the matching function is selected from the set
5581      (_over.over_).  */
5582   else if (TYPE_REFFN_P (type))
5583     {
5584       if (TREE_CODE (expr) == ADDR_EXPR)
5585         {
5586           error ("%qE is not a valid template argument for type %qT "
5587                  "because it is a pointer", expr, type);
5588           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5589           return NULL_TREE;
5590         }
5591
5592       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5593       if (!expr || expr == error_mark_node)
5594         return expr;
5595
5596       expr = build_nop (type, build_address (expr));
5597     }
5598   /* [temp.arg.nontype]/5, bullet 6
5599
5600      For a non-type template-parameter of type pointer to member function,
5601      no conversions apply. If the template-argument represents a set of
5602      overloaded member functions, the matching member function is selected
5603      from the set (_over.over_).  */
5604   else if (TYPE_PTRMEMFUNC_P (type))
5605     {
5606       expr = instantiate_type (type, expr, tf_none);
5607       if (expr == error_mark_node)
5608         return error_mark_node;
5609
5610       /* [temp.arg.nontype] bullet 1 says the pointer to member
5611          expression must be a pointer-to-member constant.  */
5612       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5613         return error_mark_node;
5614
5615       /* There is no way to disable standard conversions in
5616          resolve_address_of_overloaded_function (called by
5617          instantiate_type). It is possible that the call succeeded by
5618          converting &B::I to &D::I (where B is a base of D), so we need
5619          to reject this conversion here.
5620
5621          Actually, even if there was a way to disable standard conversions,
5622          it would still be better to reject them here so that we can
5623          provide a superior diagnostic.  */
5624       if (!same_type_p (TREE_TYPE (expr), type))
5625         {
5626           error ("%qE is not a valid template argument for type %qT "
5627                  "because it is of type %qT", expr, type,
5628                  TREE_TYPE (expr));
5629           /* If we are just one standard conversion off, explain.  */
5630           if (can_convert (type, TREE_TYPE (expr)))
5631             inform (input_location,
5632                     "standard conversions are not allowed in this context");
5633           return NULL_TREE;
5634         }
5635     }
5636   /* [temp.arg.nontype]/5, bullet 7
5637
5638      For a non-type template-parameter of type pointer to data member,
5639      qualification conversions (_conv.qual_) are applied.  */
5640   else if (TYPE_PTRMEM_P (type))
5641     {
5642       /* [temp.arg.nontype] bullet 1 says the pointer to member
5643          expression must be a pointer-to-member constant.  */
5644       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5645         return error_mark_node;
5646
5647       expr = perform_qualification_conversions (type, expr);
5648       if (expr == error_mark_node)
5649         return expr;
5650     }
5651   /* A template non-type parameter must be one of the above.  */
5652   else
5653     gcc_unreachable ();
5654
5655   /* Sanity check: did we actually convert the argument to the
5656      right type?  */
5657   gcc_assert (same_type_ignoring_top_level_qualifiers_p
5658               (type, TREE_TYPE (expr)));
5659   return expr;
5660 }
5661
5662 /* Subroutine of coerce_template_template_parms, which returns 1 if
5663    PARM_PARM and ARG_PARM match using the rule for the template
5664    parameters of template template parameters. Both PARM and ARG are
5665    template parameters; the rest of the arguments are the same as for
5666    coerce_template_template_parms.
5667  */
5668 static int
5669 coerce_template_template_parm (tree parm,
5670                               tree arg,
5671                               tsubst_flags_t complain,
5672                               tree in_decl,
5673                               tree outer_args)
5674 {
5675   if (arg == NULL_TREE || arg == error_mark_node
5676       || parm == NULL_TREE || parm == error_mark_node)
5677     return 0;
5678   
5679   if (TREE_CODE (arg) != TREE_CODE (parm))
5680     return 0;
5681   
5682   switch (TREE_CODE (parm))
5683     {
5684     case TEMPLATE_DECL:
5685       /* We encounter instantiations of templates like
5686          template <template <template <class> class> class TT>
5687          class C;  */
5688       {
5689         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5690         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5691         
5692         if (!coerce_template_template_parms
5693             (parmparm, argparm, complain, in_decl, outer_args))
5694           return 0;
5695       }
5696       /* Fall through.  */
5697       
5698     case TYPE_DECL:
5699       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5700           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5701         /* Argument is a parameter pack but parameter is not.  */
5702         return 0;
5703       break;
5704       
5705     case PARM_DECL:
5706       /* The tsubst call is used to handle cases such as
5707          
5708            template <int> class C {};
5709            template <class T, template <T> class TT> class D {};
5710            D<int, C> d;
5711
5712          i.e. the parameter list of TT depends on earlier parameters.  */
5713       if (!uses_template_parms (TREE_TYPE (arg))
5714           && !same_type_p
5715                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5716                  TREE_TYPE (arg)))
5717         return 0;
5718       
5719       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5720           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5721         /* Argument is a parameter pack but parameter is not.  */
5722         return 0;
5723       
5724       break;
5725
5726     default:
5727       gcc_unreachable ();
5728     }
5729
5730   return 1;
5731 }
5732
5733
5734 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5735    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5736    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5737    or PARM_DECL.
5738
5739    Consider the example:
5740      template <class T> class A;
5741      template<template <class U> class TT> class B;
5742
5743    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5744    the parameters to A, and OUTER_ARGS contains A.  */
5745
5746 static int
5747 coerce_template_template_parms (tree parm_parms,
5748                                 tree arg_parms,
5749                                 tsubst_flags_t complain,
5750                                 tree in_decl,
5751                                 tree outer_args)
5752 {
5753   int nparms, nargs, i;
5754   tree parm, arg;
5755   int variadic_p = 0;
5756
5757   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5758   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5759
5760   nparms = TREE_VEC_LENGTH (parm_parms);
5761   nargs = TREE_VEC_LENGTH (arg_parms);
5762
5763   /* Determine whether we have a parameter pack at the end of the
5764      template template parameter's template parameter list.  */
5765   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5766     {
5767       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5768       
5769       if (parm == error_mark_node)
5770         return 0;
5771
5772       switch (TREE_CODE (parm))
5773         {
5774         case TEMPLATE_DECL:
5775         case TYPE_DECL:
5776           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5777             variadic_p = 1;
5778           break;
5779           
5780         case PARM_DECL:
5781           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5782             variadic_p = 1;
5783           break;
5784           
5785         default:
5786           gcc_unreachable ();
5787         }
5788     }
5789  
5790   if (nargs != nparms
5791       && !(variadic_p && nargs >= nparms - 1))
5792     return 0;
5793
5794   /* Check all of the template parameters except the parameter pack at
5795      the end (if any).  */
5796   for (i = 0; i < nparms - variadic_p; ++i)
5797     {
5798       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5799           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5800         continue;
5801
5802       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5803       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5804
5805       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5806                                           outer_args))
5807         return 0;
5808
5809     }
5810
5811   if (variadic_p)
5812     {
5813       /* Check each of the template parameters in the template
5814          argument against the template parameter pack at the end of
5815          the template template parameter.  */
5816       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5817         return 0;
5818
5819       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5820
5821       for (; i < nargs; ++i)
5822         {
5823           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5824             continue;
5825  
5826           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5827  
5828           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5829                                               outer_args))
5830             return 0;
5831         }
5832     }
5833
5834   return 1;
5835 }
5836
5837 /* Verifies that the deduced template arguments (in TARGS) for the
5838    template template parameters (in TPARMS) represent valid bindings,
5839    by comparing the template parameter list of each template argument
5840    to the template parameter list of its corresponding template
5841    template parameter, in accordance with DR150. This
5842    routine can only be called after all template arguments have been
5843    deduced. It will return TRUE if all of the template template
5844    parameter bindings are okay, FALSE otherwise.  */
5845 bool 
5846 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5847 {
5848   int i, ntparms = TREE_VEC_LENGTH (tparms);
5849   bool ret = true;
5850
5851   /* We're dealing with template parms in this process.  */
5852   ++processing_template_decl;
5853
5854   targs = INNERMOST_TEMPLATE_ARGS (targs);
5855
5856   for (i = 0; i < ntparms; ++i)
5857     {
5858       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5859       tree targ = TREE_VEC_ELT (targs, i);
5860
5861       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5862         {
5863           tree packed_args = NULL_TREE;
5864           int idx, len = 1;
5865
5866           if (ARGUMENT_PACK_P (targ))
5867             {
5868               /* Look inside the argument pack.  */
5869               packed_args = ARGUMENT_PACK_ARGS (targ);
5870               len = TREE_VEC_LENGTH (packed_args);
5871             }
5872
5873           for (idx = 0; idx < len; ++idx)
5874             {
5875               tree targ_parms = NULL_TREE;
5876
5877               if (packed_args)
5878                 /* Extract the next argument from the argument
5879                    pack.  */
5880                 targ = TREE_VEC_ELT (packed_args, idx);
5881
5882               if (PACK_EXPANSION_P (targ))
5883                 /* Look at the pattern of the pack expansion.  */
5884                 targ = PACK_EXPANSION_PATTERN (targ);
5885
5886               /* Extract the template parameters from the template
5887                  argument.  */
5888               if (TREE_CODE (targ) == TEMPLATE_DECL)
5889                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5890               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5891                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5892
5893               /* Verify that we can coerce the template template
5894                  parameters from the template argument to the template
5895                  parameter.  This requires an exact match.  */
5896               if (targ_parms
5897                   && !coerce_template_template_parms
5898                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5899                         targ_parms,
5900                         tf_none,
5901                         tparm,
5902                         targs))
5903                 {
5904                   ret = false;
5905                   goto out;
5906                 }
5907             }
5908         }
5909     }
5910
5911  out:
5912
5913   --processing_template_decl;
5914   return ret;
5915 }
5916
5917 /* Convert the indicated template ARG as necessary to match the
5918    indicated template PARM.  Returns the converted ARG, or
5919    error_mark_node if the conversion was unsuccessful.  Error and
5920    warning messages are issued under control of COMPLAIN.  This
5921    conversion is for the Ith parameter in the parameter list.  ARGS is
5922    the full set of template arguments deduced so far.  */
5923
5924 static tree
5925 convert_template_argument (tree parm,
5926                            tree arg,
5927                            tree args,
5928                            tsubst_flags_t complain,
5929                            int i,
5930                            tree in_decl)
5931 {
5932   tree orig_arg;
5933   tree val;
5934   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5935
5936   if (TREE_CODE (arg) == TREE_LIST
5937       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5938     {
5939       /* The template argument was the name of some
5940          member function.  That's usually
5941          invalid, but static members are OK.  In any
5942          case, grab the underlying fields/functions
5943          and issue an error later if required.  */
5944       orig_arg = TREE_VALUE (arg);
5945       TREE_TYPE (arg) = unknown_type_node;
5946     }
5947
5948   orig_arg = arg;
5949
5950   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5951   requires_type = (TREE_CODE (parm) == TYPE_DECL
5952                    || requires_tmpl_type);
5953
5954   /* When determining whether an argument pack expansion is a template,
5955      look at the pattern.  */
5956   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5957     arg = PACK_EXPANSION_PATTERN (arg);
5958
5959   /* Deal with an injected-class-name used as a template template arg.  */
5960   if (requires_tmpl_type && CLASS_TYPE_P (arg))
5961     {
5962       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
5963       if (TREE_CODE (t) == TEMPLATE_DECL)
5964         {
5965           if (complain & tf_warning_or_error)
5966             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
5967                      " used as template template argument", TYPE_NAME (arg));
5968           else if (flag_pedantic_errors)
5969             t = arg;
5970
5971           arg = t;
5972         }
5973     }
5974
5975   is_tmpl_type = 
5976     ((TREE_CODE (arg) == TEMPLATE_DECL
5977       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5978      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5979      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5980
5981   if (is_tmpl_type
5982       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5983           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5984     arg = TYPE_STUB_DECL (arg);
5985
5986   is_type = TYPE_P (arg) || is_tmpl_type;
5987
5988   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
5989       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
5990     {
5991       permerror (input_location, "to refer to a type member of a template parameter, "
5992                  "use %<typename %E%>", orig_arg);
5993
5994       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
5995                                      TREE_OPERAND (arg, 1),
5996                                      typename_type,
5997                                      complain & tf_error);
5998       arg = orig_arg;
5999       is_type = 1;
6000     }
6001   if (is_type != requires_type)
6002     {
6003       if (in_decl)
6004         {
6005           if (complain & tf_error)
6006             {
6007               error ("type/value mismatch at argument %d in template "
6008                      "parameter list for %qD",
6009                      i + 1, in_decl);
6010               if (is_type)
6011                 error ("  expected a constant of type %qT, got %qT",
6012                        TREE_TYPE (parm),
6013                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
6014               else if (requires_tmpl_type)
6015                 error ("  expected a class template, got %qE", orig_arg);
6016               else
6017                 error ("  expected a type, got %qE", orig_arg);
6018             }
6019         }
6020       return error_mark_node;
6021     }
6022   if (is_tmpl_type ^ requires_tmpl_type)
6023     {
6024       if (in_decl && (complain & tf_error))
6025         {
6026           error ("type/value mismatch at argument %d in template "
6027                  "parameter list for %qD",
6028                  i + 1, in_decl);
6029           if (is_tmpl_type)
6030             error ("  expected a type, got %qT", DECL_NAME (arg));
6031           else
6032             error ("  expected a class template, got %qT", orig_arg);
6033         }
6034       return error_mark_node;
6035     }
6036
6037   if (is_type)
6038     {
6039       if (requires_tmpl_type)
6040         {
6041           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
6042             /* The number of argument required is not known yet.
6043                Just accept it for now.  */
6044             val = TREE_TYPE (arg);
6045           else
6046             {
6047               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
6048               tree argparm;
6049
6050               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
6051
6052               if (coerce_template_template_parms (parmparm, argparm,
6053                                                   complain, in_decl,
6054                                                   args))
6055                 {
6056                   val = arg;
6057
6058                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
6059                      TEMPLATE_DECL.  */
6060                   if (val != error_mark_node)
6061                     {
6062                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
6063                         val = TREE_TYPE (val);
6064                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
6065                         val = make_pack_expansion (val);
6066                     }
6067                 }
6068               else
6069                 {
6070                   if (in_decl && (complain & tf_error))
6071                     {
6072                       error ("type/value mismatch at argument %d in "
6073                              "template parameter list for %qD",
6074                              i + 1, in_decl);
6075                       error ("  expected a template of type %qD, got %qT",
6076                              parm, orig_arg);
6077                     }
6078
6079                   val = error_mark_node;
6080                 }
6081             }
6082         }
6083       else
6084         val = orig_arg;
6085       /* We only form one instance of each template specialization.
6086          Therefore, if we use a non-canonical variant (i.e., a
6087          typedef), any future messages referring to the type will use
6088          the typedef, which is confusing if those future uses do not
6089          themselves also use the typedef.  */
6090       if (TYPE_P (val))
6091         val = strip_typedefs (val);
6092     }
6093   else
6094     {
6095       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
6096
6097       if (invalid_nontype_parm_type_p (t, complain))
6098         return error_mark_node;
6099
6100       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
6101         {
6102           if (same_type_p (t, TREE_TYPE (orig_arg)))
6103             val = orig_arg;
6104           else
6105             {
6106               /* Not sure if this is reachable, but it doesn't hurt
6107                  to be robust.  */
6108               error ("type mismatch in nontype parameter pack");
6109               val = error_mark_node;
6110             }
6111         }
6112       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
6113         /* We used to call digest_init here.  However, digest_init
6114            will report errors, which we don't want when complain
6115            is zero.  More importantly, digest_init will try too
6116            hard to convert things: for example, `0' should not be
6117            converted to pointer type at this point according to
6118            the standard.  Accepting this is not merely an
6119            extension, since deciding whether or not these
6120            conversions can occur is part of determining which
6121            function template to call, or whether a given explicit
6122            argument specification is valid.  */
6123         val = convert_nontype_argument (t, orig_arg, complain);
6124       else
6125         val = orig_arg;
6126
6127       if (val == NULL_TREE)
6128         val = error_mark_node;
6129       else if (val == error_mark_node && (complain & tf_error))
6130         error ("could not convert template argument %qE to %qT",  orig_arg, t);
6131
6132       if (TREE_CODE (val) == SCOPE_REF)
6133         {
6134           /* Strip typedefs from the SCOPE_REF.  */
6135           tree type = strip_typedefs (TREE_TYPE (val));
6136           tree scope = strip_typedefs (TREE_OPERAND (val, 0));
6137           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
6138                                       QUALIFIED_NAME_IS_TEMPLATE (val));
6139         }
6140     }
6141
6142   return val;
6143 }
6144
6145 /* Coerces the remaining template arguments in INNER_ARGS (from
6146    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
6147    Returns the coerced argument pack. PARM_IDX is the position of this
6148    parameter in the template parameter list. ARGS is the original
6149    template argument list.  */
6150 static tree
6151 coerce_template_parameter_pack (tree parms,
6152                                 int parm_idx,
6153                                 tree args,
6154                                 tree inner_args,
6155                                 int arg_idx,
6156                                 tree new_args,
6157                                 int* lost,
6158                                 tree in_decl,
6159                                 tsubst_flags_t complain)
6160 {
6161   tree parm = TREE_VEC_ELT (parms, parm_idx);
6162   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6163   tree packed_args;
6164   tree argument_pack;
6165   tree packed_types = NULL_TREE;
6166
6167   if (arg_idx > nargs)
6168     arg_idx = nargs;
6169
6170   packed_args = make_tree_vec (nargs - arg_idx);
6171
6172   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
6173       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
6174     {
6175       /* When the template parameter is a non-type template
6176          parameter pack whose type uses parameter packs, we need
6177          to look at each of the template arguments
6178          separately. Build a vector of the types for these
6179          non-type template parameters in PACKED_TYPES.  */
6180       tree expansion 
6181         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
6182       packed_types = tsubst_pack_expansion (expansion, args,
6183                                             complain, in_decl);
6184
6185       if (packed_types == error_mark_node)
6186         return error_mark_node;
6187
6188       /* Check that we have the right number of arguments.  */
6189       if (arg_idx < nargs
6190           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
6191           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
6192         {
6193           int needed_parms 
6194             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
6195           error ("wrong number of template arguments (%d, should be %d)",
6196                  nargs, needed_parms);
6197           return error_mark_node;
6198         }
6199
6200       /* If we aren't able to check the actual arguments now
6201          (because they haven't been expanded yet), we can at least
6202          verify that all of the types used for the non-type
6203          template parameter pack are, in fact, valid for non-type
6204          template parameters.  */
6205       if (arg_idx < nargs 
6206           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
6207         {
6208           int j, len = TREE_VEC_LENGTH (packed_types);
6209           for (j = 0; j < len; ++j)
6210             {
6211               tree t = TREE_VEC_ELT (packed_types, j);
6212               if (invalid_nontype_parm_type_p (t, complain))
6213                 return error_mark_node;
6214             }
6215         }
6216     }
6217
6218   /* Convert the remaining arguments, which will be a part of the
6219      parameter pack "parm".  */
6220   for (; arg_idx < nargs; ++arg_idx)
6221     {
6222       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
6223       tree actual_parm = TREE_VALUE (parm);
6224
6225       if (packed_types && !PACK_EXPANSION_P (arg))
6226         {
6227           /* When we have a vector of types (corresponding to the
6228              non-type template parameter pack that uses parameter
6229              packs in its type, as mention above), and the
6230              argument is not an expansion (which expands to a
6231              currently unknown number of arguments), clone the
6232              parm and give it the next type in PACKED_TYPES.  */
6233           actual_parm = copy_node (actual_parm);
6234           TREE_TYPE (actual_parm) = 
6235             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
6236         }
6237
6238       if (arg != error_mark_node)
6239         arg = convert_template_argument (actual_parm, 
6240                                          arg, new_args, complain, parm_idx,
6241                                          in_decl);
6242       if (arg == error_mark_node)
6243         (*lost)++;
6244       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
6245     }
6246
6247   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
6248       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
6249     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
6250   else
6251     {
6252       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
6253       TREE_TYPE (argument_pack) 
6254         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
6255       TREE_CONSTANT (argument_pack) = 1;
6256     }
6257
6258   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
6259 #ifdef ENABLE_CHECKING
6260   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
6261                                        TREE_VEC_LENGTH (packed_args));
6262 #endif
6263   return argument_pack;
6264 }
6265
6266 /* Convert all template arguments to their appropriate types, and
6267    return a vector containing the innermost resulting template
6268    arguments.  If any error occurs, return error_mark_node. Error and
6269    warning messages are issued under control of COMPLAIN.
6270
6271    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
6272    for arguments not specified in ARGS.  Otherwise, if
6273    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
6274    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
6275    USE_DEFAULT_ARGS is false, then all arguments must be specified in
6276    ARGS.  */
6277
6278 static tree
6279 coerce_template_parms (tree parms,
6280                        tree args,
6281                        tree in_decl,
6282                        tsubst_flags_t complain,
6283                        bool require_all_args,
6284                        bool use_default_args)
6285 {
6286   int nparms, nargs, parm_idx, arg_idx, lost = 0;
6287   tree inner_args;
6288   tree new_args;
6289   tree new_inner_args;
6290   int saved_unevaluated_operand;
6291   int saved_inhibit_evaluation_warnings;
6292
6293   /* When used as a boolean value, indicates whether this is a
6294      variadic template parameter list. Since it's an int, we can also
6295      subtract it from nparms to get the number of non-variadic
6296      parameters.  */
6297   int variadic_p = 0;
6298
6299   if (args == error_mark_node)
6300     return error_mark_node;
6301
6302   nparms = TREE_VEC_LENGTH (parms);
6303
6304   /* Determine if there are any parameter packs.  */
6305   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
6306     {
6307       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
6308       if (template_parameter_pack_p (tparm))
6309         ++variadic_p;
6310     }
6311
6312   inner_args = INNERMOST_TEMPLATE_ARGS (args);
6313   /* If there are 0 or 1 parameter packs, we need to expand any argument
6314      packs so that we can deduce a parameter pack from some non-packed args
6315      followed by an argument pack, as in variadic85.C.  If there are more
6316      than that, we need to leave argument packs intact so the arguments are
6317      assigned to the right parameter packs.  This should only happen when
6318      dealing with a nested class inside a partial specialization of a class
6319      template, as in variadic92.C.  */
6320   if (variadic_p <= 1)
6321     inner_args = expand_template_argument_pack (inner_args);
6322
6323   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6324   if ((nargs > nparms && !variadic_p)
6325       || (nargs < nparms - variadic_p
6326           && require_all_args
6327           && (!use_default_args
6328               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
6329                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
6330     {
6331       if (complain & tf_error)
6332         {
6333           if (variadic_p)
6334             {
6335               --nparms;
6336               error ("wrong number of template arguments "
6337                      "(%d, should be %d or more)", nargs, nparms);
6338             }
6339           else
6340              error ("wrong number of template arguments "
6341                     "(%d, should be %d)", nargs, nparms);
6342
6343           if (in_decl)
6344             error ("provided for %q+D", in_decl);
6345         }
6346
6347       return error_mark_node;
6348     }
6349
6350   /* We need to evaluate the template arguments, even though this
6351      template-id may be nested within a "sizeof".  */
6352   saved_unevaluated_operand = cp_unevaluated_operand;
6353   cp_unevaluated_operand = 0;
6354   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
6355   c_inhibit_evaluation_warnings = 0;
6356   new_inner_args = make_tree_vec (nparms);
6357   new_args = add_outermost_template_args (args, new_inner_args);
6358   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
6359     {
6360       tree arg;
6361       tree parm;
6362
6363       /* Get the Ith template parameter.  */
6364       parm = TREE_VEC_ELT (parms, parm_idx);
6365  
6366       if (parm == error_mark_node)
6367       {
6368         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
6369         continue;
6370       }
6371
6372       /* Calculate the next argument.  */
6373       if (arg_idx < nargs)
6374         arg = TREE_VEC_ELT (inner_args, arg_idx);
6375       else
6376         arg = NULL_TREE;
6377
6378       if (template_parameter_pack_p (TREE_VALUE (parm))
6379           && !(arg && ARGUMENT_PACK_P (arg)))
6380         {
6381           /* All remaining arguments will be placed in the
6382              template parameter pack PARM.  */
6383           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
6384                                                 inner_args, arg_idx,
6385                                                 new_args, &lost,
6386                                                 in_decl, complain);
6387
6388           /* Store this argument.  */
6389           if (arg == error_mark_node)
6390             lost++;
6391           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
6392
6393           /* We are done with all of the arguments.  */
6394           arg_idx = nargs;
6395           
6396           continue;
6397         }
6398       else if (arg)
6399         {
6400           if (PACK_EXPANSION_P (arg))
6401             {
6402               if (complain & tf_error)
6403                 {
6404                   /* FIXME this restriction was removed by N2555; see
6405                      bug 35722.  */
6406                   /* If ARG is a pack expansion, but PARM is not a
6407                      template parameter pack (if it were, we would have
6408                      handled it above), we're trying to expand into a
6409                      fixed-length argument list.  */
6410                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
6411                     sorry ("cannot expand %<%E%> into a fixed-length "
6412                            "argument list", arg);
6413                   else
6414                     sorry ("cannot expand %<%T%> into a fixed-length "
6415                            "argument list", arg);
6416                 }
6417               ++lost;
6418             }
6419         }
6420       else if (require_all_args)
6421         {
6422           /* There must be a default arg in this case.  */
6423           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
6424                                      complain, in_decl);
6425           /* The position of the first default template argument,
6426              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
6427              Record that.  */
6428           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6429             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
6430         }
6431       else
6432         break;
6433
6434       if (arg == error_mark_node)
6435         {
6436           if (complain & tf_error)
6437             error ("template argument %d is invalid", arg_idx + 1);
6438         }
6439       else if (!arg)
6440         /* This only occurs if there was an error in the template
6441            parameter list itself (which we would already have
6442            reported) that we are trying to recover from, e.g., a class
6443            template with a parameter list such as
6444            template<typename..., typename>.  */
6445         ++lost;
6446       else
6447         arg = convert_template_argument (TREE_VALUE (parm),
6448                                          arg, new_args, complain, 
6449                                          parm_idx, in_decl);
6450
6451       if (arg == error_mark_node)
6452         lost++;
6453       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6454     }
6455   cp_unevaluated_operand = saved_unevaluated_operand;
6456   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6457
6458   if (lost)
6459     return error_mark_node;
6460
6461 #ifdef ENABLE_CHECKING
6462   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6463     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6464                                          TREE_VEC_LENGTH (new_inner_args));
6465 #endif
6466
6467   return new_inner_args;
6468 }
6469
6470 /* Returns 1 if template args OT and NT are equivalent.  */
6471
6472 static int
6473 template_args_equal (tree ot, tree nt)
6474 {
6475   if (nt == ot)
6476     return 1;
6477
6478   if (TREE_CODE (nt) == TREE_VEC)
6479     /* For member templates */
6480     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6481   else if (PACK_EXPANSION_P (ot))
6482     return PACK_EXPANSION_P (nt) 
6483       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6484                               PACK_EXPANSION_PATTERN (nt));
6485   else if (ARGUMENT_PACK_P (ot))
6486     {
6487       int i, len;
6488       tree opack, npack;
6489
6490       if (!ARGUMENT_PACK_P (nt))
6491         return 0;
6492
6493       opack = ARGUMENT_PACK_ARGS (ot);
6494       npack = ARGUMENT_PACK_ARGS (nt);
6495       len = TREE_VEC_LENGTH (opack);
6496       if (TREE_VEC_LENGTH (npack) != len)
6497         return 0;
6498       for (i = 0; i < len; ++i)
6499         if (!template_args_equal (TREE_VEC_ELT (opack, i),
6500                                   TREE_VEC_ELT (npack, i)))
6501           return 0;
6502       return 1;
6503     }
6504   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6505     {
6506       /* We get here probably because we are in the middle of substituting
6507          into the pattern of a pack expansion. In that case the
6508          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6509          interested in. So we want to use the initial pack argument for
6510          the comparison.  */
6511       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6512       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6513         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6514       return template_args_equal (ot, nt);
6515     }
6516   else if (TYPE_P (nt))
6517     return TYPE_P (ot) && same_type_p (ot, nt);
6518   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6519     return 0;
6520   else
6521     return cp_tree_equal (ot, nt);
6522 }
6523
6524 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6525    of template arguments.  Returns 0 otherwise.  */
6526
6527 int
6528 comp_template_args (tree oldargs, tree newargs)
6529 {
6530   int i;
6531
6532   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6533     return 0;
6534
6535   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6536     {
6537       tree nt = TREE_VEC_ELT (newargs, i);
6538       tree ot = TREE_VEC_ELT (oldargs, i);
6539
6540       if (! template_args_equal (ot, nt))
6541         return 0;
6542     }
6543   return 1;
6544 }
6545
6546 static void
6547 add_pending_template (tree d)
6548 {
6549   tree ti = (TYPE_P (d)
6550              ? CLASSTYPE_TEMPLATE_INFO (d)
6551              : DECL_TEMPLATE_INFO (d));
6552   struct pending_template *pt;
6553   int level;
6554
6555   if (TI_PENDING_TEMPLATE_FLAG (ti))
6556     return;
6557
6558   /* We are called both from instantiate_decl, where we've already had a
6559      tinst_level pushed, and instantiate_template, where we haven't.
6560      Compensate.  */
6561   level = !current_tinst_level || current_tinst_level->decl != d;
6562
6563   if (level)
6564     push_tinst_level (d);
6565
6566   pt = ggc_alloc_pending_template ();
6567   pt->next = NULL;
6568   pt->tinst = current_tinst_level;
6569   if (last_pending_template)
6570     last_pending_template->next = pt;
6571   else
6572     pending_templates = pt;
6573
6574   last_pending_template = pt;
6575
6576   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6577
6578   if (level)
6579     pop_tinst_level ();
6580 }
6581
6582
6583 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6584    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6585    documentation for TEMPLATE_ID_EXPR.  */
6586
6587 tree
6588 lookup_template_function (tree fns, tree arglist)
6589 {
6590   tree type;
6591
6592   if (fns == error_mark_node || arglist == error_mark_node)
6593     return error_mark_node;
6594
6595   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6596   gcc_assert (fns && (is_overloaded_fn (fns)
6597                       || TREE_CODE (fns) == IDENTIFIER_NODE));
6598
6599   if (BASELINK_P (fns))
6600     {
6601       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6602                                          unknown_type_node,
6603                                          BASELINK_FUNCTIONS (fns),
6604                                          arglist);
6605       return fns;
6606     }
6607
6608   type = TREE_TYPE (fns);
6609   if (TREE_CODE (fns) == OVERLOAD || !type)
6610     type = unknown_type_node;
6611
6612   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6613 }
6614
6615 /* Within the scope of a template class S<T>, the name S gets bound
6616    (in build_self_reference) to a TYPE_DECL for the class, not a
6617    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6618    or one of its enclosing classes, and that type is a template,
6619    return the associated TEMPLATE_DECL.  Otherwise, the original
6620    DECL is returned.
6621
6622    Also handle the case when DECL is a TREE_LIST of ambiguous
6623    injected-class-names from different bases.  */
6624
6625 tree
6626 maybe_get_template_decl_from_type_decl (tree decl)
6627 {
6628   if (decl == NULL_TREE)
6629     return decl;
6630
6631   /* DR 176: A lookup that finds an injected-class-name (10.2
6632      [class.member.lookup]) can result in an ambiguity in certain cases
6633      (for example, if it is found in more than one base class). If all of
6634      the injected-class-names that are found refer to specializations of
6635      the same class template, and if the name is followed by a
6636      template-argument-list, the reference refers to the class template
6637      itself and not a specialization thereof, and is not ambiguous.  */
6638   if (TREE_CODE (decl) == TREE_LIST)
6639     {
6640       tree t, tmpl = NULL_TREE;
6641       for (t = decl; t; t = TREE_CHAIN (t))
6642         {
6643           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6644           if (!tmpl)
6645             tmpl = elt;
6646           else if (tmpl != elt)
6647             break;
6648         }
6649       if (tmpl && t == NULL_TREE)
6650         return tmpl;
6651       else
6652         return decl;
6653     }
6654
6655   return (decl != NULL_TREE
6656           && DECL_SELF_REFERENCE_P (decl)
6657           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
6658     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
6659 }
6660
6661 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
6662    parameters, find the desired type.
6663
6664    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
6665
6666    IN_DECL, if non-NULL, is the template declaration we are trying to
6667    instantiate.
6668
6669    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
6670    the class we are looking up.
6671
6672    Issue error and warning messages under control of COMPLAIN.
6673
6674    If the template class is really a local class in a template
6675    function, then the FUNCTION_CONTEXT is the function in which it is
6676    being instantiated.
6677
6678    ??? Note that this function is currently called *twice* for each
6679    template-id: the first time from the parser, while creating the
6680    incomplete type (finish_template_type), and the second type during the
6681    real instantiation (instantiate_template_class). This is surely something
6682    that we want to avoid. It also causes some problems with argument
6683    coercion (see convert_nontype_argument for more information on this).  */
6684
6685 static tree
6686 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
6687                          int entering_scope, tsubst_flags_t complain)
6688 {
6689   tree templ = NULL_TREE, parmlist;
6690   tree t;
6691   spec_entry **slot;
6692   spec_entry *entry;
6693   spec_entry elt;
6694   hashval_t hash;
6695
6696   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6697     {
6698       tree value = innermost_non_namespace_value (d1);
6699       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6700         templ = value;
6701       else
6702         {
6703           if (context)
6704             push_decl_namespace (context);
6705           templ = lookup_name (d1);
6706           templ = maybe_get_template_decl_from_type_decl (templ);
6707           if (context)
6708             pop_decl_namespace ();
6709         }
6710       if (templ)
6711         context = DECL_CONTEXT (templ);
6712     }
6713   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6714     {
6715       tree type = TREE_TYPE (d1);
6716
6717       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6718          an implicit typename for the second A.  Deal with it.  */
6719       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6720         type = TREE_TYPE (type);
6721
6722       if (CLASSTYPE_TEMPLATE_INFO (type))
6723         {
6724           templ = CLASSTYPE_TI_TEMPLATE (type);
6725           d1 = DECL_NAME (templ);
6726         }
6727     }
6728   else if (TREE_CODE (d1) == ENUMERAL_TYPE
6729            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6730     {
6731       templ = TYPE_TI_TEMPLATE (d1);
6732       d1 = DECL_NAME (templ);
6733     }
6734   else if (TREE_CODE (d1) == TEMPLATE_DECL
6735            && DECL_TEMPLATE_RESULT (d1)
6736            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6737     {
6738       templ = d1;
6739       d1 = DECL_NAME (templ);
6740       context = DECL_CONTEXT (templ);
6741     }
6742
6743   /* Issue an error message if we didn't find a template.  */
6744   if (! templ)
6745     {
6746       if (complain & tf_error)
6747         error ("%qT is not a template", d1);
6748       return error_mark_node;
6749     }
6750
6751   if (TREE_CODE (templ) != TEMPLATE_DECL
6752          /* Make sure it's a user visible template, if it was named by
6753             the user.  */
6754       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6755           && !PRIMARY_TEMPLATE_P (templ)))
6756     {
6757       if (complain & tf_error)
6758         {
6759           error ("non-template type %qT used as a template", d1);
6760           if (in_decl)
6761             error ("for template declaration %q+D", in_decl);
6762         }
6763       return error_mark_node;
6764     }
6765
6766   complain &= ~tf_user;
6767
6768   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6769     {
6770       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6771          template arguments */
6772
6773       tree parm;
6774       tree arglist2;
6775       tree outer;
6776
6777       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6778
6779       /* Consider an example where a template template parameter declared as
6780
6781            template <class T, class U = std::allocator<T> > class TT
6782
6783          The template parameter level of T and U are one level larger than
6784          of TT.  To proper process the default argument of U, say when an
6785          instantiation `TT<int>' is seen, we need to build the full
6786          arguments containing {int} as the innermost level.  Outer levels,
6787          available when not appearing as default template argument, can be
6788          obtained from the arguments of the enclosing template.
6789
6790          Suppose that TT is later substituted with std::vector.  The above
6791          instantiation is `TT<int, std::allocator<T> >' with TT at
6792          level 1, and T at level 2, while the template arguments at level 1
6793          becomes {std::vector} and the inner level 2 is {int}.  */
6794
6795       outer = DECL_CONTEXT (templ);
6796       if (outer)
6797         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
6798       else if (current_template_parms)
6799         /* This is an argument of the current template, so we haven't set
6800            DECL_CONTEXT yet.  */
6801         outer = current_template_args ();
6802
6803       if (outer)
6804         arglist = add_to_template_args (outer, arglist);
6805
6806       arglist2 = coerce_template_parms (parmlist, arglist, templ,
6807                                         complain,
6808                                         /*require_all_args=*/true,
6809                                         /*use_default_args=*/true);
6810       if (arglist2 == error_mark_node
6811           || (!uses_template_parms (arglist2)
6812               && check_instantiated_args (templ, arglist2, complain)))
6813         return error_mark_node;
6814
6815       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
6816       return parm;
6817     }
6818   else
6819     {
6820       tree template_type = TREE_TYPE (templ);
6821       tree gen_tmpl;
6822       tree type_decl;
6823       tree found = NULL_TREE;
6824       int arg_depth;
6825       int parm_depth;
6826       int is_dependent_type;
6827       int use_partial_inst_tmpl = false;
6828
6829       gen_tmpl = most_general_template (templ);
6830       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
6831       parm_depth = TMPL_PARMS_DEPTH (parmlist);
6832       arg_depth = TMPL_ARGS_DEPTH (arglist);
6833
6834       if (arg_depth == 1 && parm_depth > 1)
6835         {
6836           /* We've been given an incomplete set of template arguments.
6837              For example, given:
6838
6839                template <class T> struct S1 {
6840                  template <class U> struct S2 {};
6841                  template <class U> struct S2<U*> {};
6842                 };
6843
6844              we will be called with an ARGLIST of `U*', but the
6845              TEMPLATE will be `template <class T> template
6846              <class U> struct S1<T>::S2'.  We must fill in the missing
6847              arguments.  */
6848           arglist
6849             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
6850                                            arglist);
6851           arg_depth = TMPL_ARGS_DEPTH (arglist);
6852         }
6853
6854       /* Now we should have enough arguments.  */
6855       gcc_assert (parm_depth == arg_depth);
6856
6857       /* From here on, we're only interested in the most general
6858          template.  */
6859
6860       /* Calculate the BOUND_ARGS.  These will be the args that are
6861          actually tsubst'd into the definition to create the
6862          instantiation.  */
6863       if (parm_depth > 1)
6864         {
6865           /* We have multiple levels of arguments to coerce, at once.  */
6866           int i;
6867           int saved_depth = TMPL_ARGS_DEPTH (arglist);
6868
6869           tree bound_args = make_tree_vec (parm_depth);
6870
6871           for (i = saved_depth,
6872                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
6873                i > 0 && t != NULL_TREE;
6874                --i, t = TREE_CHAIN (t))
6875             {
6876               tree a;
6877               if (i == saved_depth)
6878                 a = coerce_template_parms (TREE_VALUE (t),
6879                                            arglist, gen_tmpl,
6880                                            complain,
6881                                            /*require_all_args=*/true,
6882                                            /*use_default_args=*/true);
6883               else
6884                 /* Outer levels should have already been coerced.  */
6885                 a = TMPL_ARGS_LEVEL (arglist, i);
6886
6887               /* Don't process further if one of the levels fails.  */
6888               if (a == error_mark_node)
6889                 {
6890                   /* Restore the ARGLIST to its full size.  */
6891                   TREE_VEC_LENGTH (arglist) = saved_depth;
6892                   return error_mark_node;
6893                 }
6894
6895               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6896
6897               /* We temporarily reduce the length of the ARGLIST so
6898                  that coerce_template_parms will see only the arguments
6899                  corresponding to the template parameters it is
6900                  examining.  */
6901               TREE_VEC_LENGTH (arglist)--;
6902             }
6903
6904           /* Restore the ARGLIST to its full size.  */
6905           TREE_VEC_LENGTH (arglist) = saved_depth;
6906
6907           arglist = bound_args;
6908         }
6909       else
6910         arglist
6911           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6912                                    INNERMOST_TEMPLATE_ARGS (arglist),
6913                                    gen_tmpl,
6914                                    complain,
6915                                    /*require_all_args=*/true,
6916                                    /*use_default_args=*/true);
6917
6918       if (arglist == error_mark_node)
6919         /* We were unable to bind the arguments.  */
6920         return error_mark_node;
6921
6922       /* In the scope of a template class, explicit references to the
6923          template class refer to the type of the template, not any
6924          instantiation of it.  For example, in:
6925
6926            template <class T> class C { void f(C<T>); }
6927
6928          the `C<T>' is just the same as `C'.  Outside of the
6929          class, however, such a reference is an instantiation.  */
6930       if ((entering_scope
6931            || !PRIMARY_TEMPLATE_P (gen_tmpl)
6932            || currently_open_class (template_type))
6933           /* comp_template_args is expensive, check it last.  */
6934           && comp_template_args (TYPE_TI_ARGS (template_type),
6935                                  arglist))
6936         return template_type;
6937
6938       /* If we already have this specialization, return it.  */
6939       elt.tmpl = gen_tmpl;
6940       elt.args = arglist;
6941       hash = hash_specialization (&elt);
6942       entry = (spec_entry *) htab_find_with_hash (type_specializations,
6943                                                   &elt, hash);
6944
6945       if (entry)
6946         return entry->spec;
6947
6948       is_dependent_type = uses_template_parms (arglist);
6949
6950       /* If the deduced arguments are invalid, then the binding
6951          failed.  */
6952       if (!is_dependent_type
6953           && check_instantiated_args (gen_tmpl,
6954                                       INNERMOST_TEMPLATE_ARGS (arglist),
6955                                       complain))
6956         return error_mark_node;
6957
6958       if (!is_dependent_type
6959           && !PRIMARY_TEMPLATE_P (gen_tmpl)
6960           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
6961           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6962         {
6963           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6964                                       DECL_NAME (gen_tmpl),
6965                                       /*tag_scope=*/ts_global);
6966           return found;
6967         }
6968
6969       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
6970                         complain, in_decl);
6971       if (!context)
6972         context = global_namespace;
6973
6974       /* Create the type.  */
6975       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
6976         {
6977           if (!is_dependent_type)
6978             {
6979               set_current_access_from_decl (TYPE_NAME (template_type));
6980               t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
6981                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
6982                                       arglist, complain, in_decl),
6983                               SCOPED_ENUM_P (template_type), NULL);
6984             }
6985           else
6986             {
6987               /* We don't want to call start_enum for this type, since
6988                  the values for the enumeration constants may involve
6989                  template parameters.  And, no one should be interested
6990                  in the enumeration constants for such a type.  */
6991               t = cxx_make_type (ENUMERAL_TYPE);
6992               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
6993             }
6994           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
6995           ENUM_FIXED_UNDERLYING_TYPE_P (t)
6996             = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
6997         }
6998       else
6999         {
7000           t = make_class_type (TREE_CODE (template_type));
7001           CLASSTYPE_DECLARED_CLASS (t)
7002             = CLASSTYPE_DECLARED_CLASS (template_type);
7003           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
7004           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
7005
7006           /* A local class.  Make sure the decl gets registered properly.  */
7007           if (context == current_function_decl)
7008             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
7009
7010           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
7011             /* This instantiation is another name for the primary
7012                template type. Set the TYPE_CANONICAL field
7013                appropriately. */
7014             TYPE_CANONICAL (t) = template_type;
7015           else if (any_template_arguments_need_structural_equality_p (arglist))
7016             /* Some of the template arguments require structural
7017                equality testing, so this template class requires
7018                structural equality testing. */
7019             SET_TYPE_STRUCTURAL_EQUALITY (t);
7020         }
7021
7022       /* If we called start_enum or pushtag above, this information
7023          will already be set up.  */
7024       if (!TYPE_NAME (t))
7025         {
7026           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
7027
7028           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
7029           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
7030           DECL_SOURCE_LOCATION (type_decl)
7031             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
7032         }
7033       else
7034         type_decl = TYPE_NAME (t);
7035
7036       TREE_PRIVATE (type_decl)
7037         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
7038       TREE_PROTECTED (type_decl)
7039         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
7040       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
7041         {
7042           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
7043           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
7044         }
7045
7046       /* Let's consider the explicit specialization of a member
7047          of a class template specialization that is implicitely instantiated,
7048          e.g.:
7049              template<class T>
7050              struct S
7051              {
7052                template<class U> struct M {}; //#0
7053              };
7054
7055              template<>
7056              template<>
7057              struct S<int>::M<char> //#1
7058              {
7059                int i;
7060              };
7061         [temp.expl.spec]/4 says this is valid.
7062
7063         In this case, when we write:
7064         S<int>::M<char> m;
7065
7066         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
7067         the one of #0.
7068
7069         When we encounter #1, we want to store the partial instantiation
7070         of M (template<class T> S<int>::M<T>) in it's CLASSTYPE_TI_TEMPLATE.
7071
7072         For all cases other than this "explicit specialization of member of a
7073         class template", we just want to store the most general template into
7074         the CLASSTYPE_TI_TEMPLATE of M.
7075
7076         This case of "explicit specialization of member of a class template"
7077         only happens when:
7078         1/ the enclosing class is an instantiation of, and therefore not
7079         the same as, the context of the most general template, and
7080         2/ we aren't looking at the partial instantiation itself, i.e.
7081         the innermost arguments are not the same as the innermost parms of
7082         the most general template.
7083
7084         So it's only when 1/ and 2/ happens that we want to use the partial
7085         instantiation of the member template in lieu of its most general
7086         template.  */
7087
7088       if (PRIMARY_TEMPLATE_P (gen_tmpl)
7089           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
7090           /* the enclosing class must be an instantiation...  */
7091           && CLASS_TYPE_P (context)
7092           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
7093         {
7094           tree partial_inst_args;
7095           TREE_VEC_LENGTH (arglist)--;
7096           ++processing_template_decl;
7097           partial_inst_args =
7098             tsubst (INNERMOST_TEMPLATE_ARGS
7099                         (CLASSTYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
7100                     arglist, complain, NULL_TREE);
7101           --processing_template_decl;
7102           TREE_VEC_LENGTH (arglist)++;
7103           use_partial_inst_tmpl =
7104             /*...and we must not be looking at the partial instantiation
7105              itself. */
7106             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
7107                                  partial_inst_args);
7108         }
7109
7110       if (!use_partial_inst_tmpl)
7111         /* This case is easy; there are no member templates involved.  */
7112         found = gen_tmpl;
7113       else
7114         {
7115           /* This is a full instantiation of a member template.  Find
7116              the partial instantiation of which this is an instance.  */
7117
7118           /* Temporarily reduce by one the number of levels in the ARGLIST
7119              so as to avoid comparing the last set of arguments.  */
7120           TREE_VEC_LENGTH (arglist)--;
7121           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
7122           TREE_VEC_LENGTH (arglist)++;
7123           found = CLASSTYPE_TI_TEMPLATE (found);
7124         }
7125
7126       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
7127
7128       elt.spec = t;
7129       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
7130                                                        &elt, hash, INSERT);
7131       *slot = ggc_alloc_spec_entry ();
7132       **slot = elt;
7133
7134       /* Note this use of the partial instantiation so we can check it
7135          later in maybe_process_partial_specialization.  */
7136       DECL_TEMPLATE_INSTANTIATIONS (templ)
7137         = tree_cons (arglist, t,
7138                      DECL_TEMPLATE_INSTANTIATIONS (templ));
7139
7140       if (TREE_CODE (t) == ENUMERAL_TYPE && !is_dependent_type)
7141         /* Now that the type has been registered on the instantiations
7142            list, we set up the enumerators.  Because the enumeration
7143            constants may involve the enumeration type itself, we make
7144            sure to register the type first, and then create the
7145            constants.  That way, doing tsubst_expr for the enumeration
7146            constants won't result in recursive calls here; we'll find
7147            the instantiation and exit above.  */
7148         tsubst_enum (template_type, t, arglist);
7149
7150       if (is_dependent_type)
7151         /* If the type makes use of template parameters, the
7152            code that generates debugging information will crash.  */
7153         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
7154
7155       /* Possibly limit visibility based on template args.  */
7156       TREE_PUBLIC (type_decl) = 1;
7157       determine_visibility (type_decl);
7158
7159       return t;
7160     }
7161 }
7162
7163 /* Wrapper for lookup_template_class_1.  */
7164
7165 tree
7166 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
7167                        int entering_scope, tsubst_flags_t complain)
7168 {
7169   tree ret;
7170   timevar_push (TV_TEMPLATE_INST);
7171   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
7172                                  entering_scope, complain);
7173   timevar_pop (TV_TEMPLATE_INST);
7174   return ret;
7175 }
7176 \f
7177 struct pair_fn_data
7178 {
7179   tree_fn_t fn;
7180   void *data;
7181   /* True when we should also visit template parameters that occur in
7182      non-deduced contexts.  */
7183   bool include_nondeduced_p;
7184   struct pointer_set_t *visited;
7185 };
7186
7187 /* Called from for_each_template_parm via walk_tree.  */
7188
7189 static tree
7190 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
7191 {
7192   tree t = *tp;
7193   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
7194   tree_fn_t fn = pfd->fn;
7195   void *data = pfd->data;
7196
7197   if (TYPE_P (t)
7198       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
7199       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
7200                                  pfd->include_nondeduced_p))
7201     return error_mark_node;
7202
7203   switch (TREE_CODE (t))
7204     {
7205     case RECORD_TYPE:
7206       if (TYPE_PTRMEMFUNC_P (t))
7207         break;
7208       /* Fall through.  */
7209
7210     case UNION_TYPE:
7211     case ENUMERAL_TYPE:
7212       if (!TYPE_TEMPLATE_INFO (t))
7213         *walk_subtrees = 0;
7214       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
7215                                        fn, data, pfd->visited, 
7216                                        pfd->include_nondeduced_p))
7217         return error_mark_node;
7218       break;
7219
7220     case INTEGER_TYPE:
7221       if (for_each_template_parm (TYPE_MIN_VALUE (t),
7222                                   fn, data, pfd->visited, 
7223                                   pfd->include_nondeduced_p)
7224           || for_each_template_parm (TYPE_MAX_VALUE (t),
7225                                      fn, data, pfd->visited,
7226                                      pfd->include_nondeduced_p))
7227         return error_mark_node;
7228       break;
7229
7230     case METHOD_TYPE:
7231       /* Since we're not going to walk subtrees, we have to do this
7232          explicitly here.  */
7233       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
7234                                   pfd->visited, pfd->include_nondeduced_p))
7235         return error_mark_node;
7236       /* Fall through.  */
7237
7238     case FUNCTION_TYPE:
7239       /* Check the return type.  */
7240       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7241                                   pfd->include_nondeduced_p))
7242         return error_mark_node;
7243
7244       /* Check the parameter types.  Since default arguments are not
7245          instantiated until they are needed, the TYPE_ARG_TYPES may
7246          contain expressions that involve template parameters.  But,
7247          no-one should be looking at them yet.  And, once they're
7248          instantiated, they don't contain template parameters, so
7249          there's no point in looking at them then, either.  */
7250       {
7251         tree parm;
7252
7253         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
7254           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
7255                                       pfd->visited, pfd->include_nondeduced_p))
7256             return error_mark_node;
7257
7258         /* Since we've already handled the TYPE_ARG_TYPES, we don't
7259            want walk_tree walking into them itself.  */
7260         *walk_subtrees = 0;
7261       }
7262       break;
7263
7264     case TYPEOF_TYPE:
7265     case UNDERLYING_TYPE:
7266       if (pfd->include_nondeduced_p
7267           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
7268                                      pfd->visited, 
7269                                      pfd->include_nondeduced_p))
7270         return error_mark_node;
7271       break;
7272
7273     case FUNCTION_DECL:
7274     case VAR_DECL:
7275       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
7276           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
7277                                      pfd->visited, pfd->include_nondeduced_p))
7278         return error_mark_node;
7279       /* Fall through.  */
7280
7281     case PARM_DECL:
7282     case CONST_DECL:
7283       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
7284           && for_each_template_parm (DECL_INITIAL (t), fn, data,
7285                                      pfd->visited, pfd->include_nondeduced_p))
7286         return error_mark_node;
7287       if (DECL_CONTEXT (t)
7288           && pfd->include_nondeduced_p
7289           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
7290                                      pfd->visited, pfd->include_nondeduced_p))
7291         return error_mark_node;
7292       break;
7293
7294     case BOUND_TEMPLATE_TEMPLATE_PARM:
7295       /* Record template parameters such as `T' inside `TT<T>'.  */
7296       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
7297                                   pfd->include_nondeduced_p))
7298         return error_mark_node;
7299       /* Fall through.  */
7300
7301     case TEMPLATE_TEMPLATE_PARM:
7302     case TEMPLATE_TYPE_PARM:
7303     case TEMPLATE_PARM_INDEX:
7304       if (fn && (*fn)(t, data))
7305         return error_mark_node;
7306       else if (!fn)
7307         return error_mark_node;
7308       break;
7309
7310     case TEMPLATE_DECL:
7311       /* A template template parameter is encountered.  */
7312       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
7313           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7314                                      pfd->include_nondeduced_p))
7315         return error_mark_node;
7316
7317       /* Already substituted template template parameter */
7318       *walk_subtrees = 0;
7319       break;
7320
7321     case TYPENAME_TYPE:
7322       if (!fn
7323           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
7324                                      data, pfd->visited, 
7325                                      pfd->include_nondeduced_p))
7326         return error_mark_node;
7327       break;
7328
7329     case CONSTRUCTOR:
7330       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
7331           && pfd->include_nondeduced_p
7332           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
7333                                      (TREE_TYPE (t)), fn, data,
7334                                      pfd->visited, pfd->include_nondeduced_p))
7335         return error_mark_node;
7336       break;
7337
7338     case INDIRECT_REF:
7339     case COMPONENT_REF:
7340       /* If there's no type, then this thing must be some expression
7341          involving template parameters.  */
7342       if (!fn && !TREE_TYPE (t))
7343         return error_mark_node;
7344       break;
7345
7346     case MODOP_EXPR:
7347     case CAST_EXPR:
7348     case REINTERPRET_CAST_EXPR:
7349     case CONST_CAST_EXPR:
7350     case STATIC_CAST_EXPR:
7351     case DYNAMIC_CAST_EXPR:
7352     case ARROW_EXPR:
7353     case DOTSTAR_EXPR:
7354     case TYPEID_EXPR:
7355     case PSEUDO_DTOR_EXPR:
7356       if (!fn)
7357         return error_mark_node;
7358       break;
7359
7360     default:
7361       break;
7362     }
7363
7364   /* We didn't find any template parameters we liked.  */
7365   return NULL_TREE;
7366 }
7367
7368 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
7369    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
7370    call FN with the parameter and the DATA.
7371    If FN returns nonzero, the iteration is terminated, and
7372    for_each_template_parm returns 1.  Otherwise, the iteration
7373    continues.  If FN never returns a nonzero value, the value
7374    returned by for_each_template_parm is 0.  If FN is NULL, it is
7375    considered to be the function which always returns 1.
7376
7377    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
7378    parameters that occur in non-deduced contexts.  When false, only
7379    visits those template parameters that can be deduced.  */
7380
7381 static int
7382 for_each_template_parm (tree t, tree_fn_t fn, void* data,
7383                         struct pointer_set_t *visited,
7384                         bool include_nondeduced_p)
7385 {
7386   struct pair_fn_data pfd;
7387   int result;
7388
7389   /* Set up.  */
7390   pfd.fn = fn;
7391   pfd.data = data;
7392   pfd.include_nondeduced_p = include_nondeduced_p;
7393
7394   /* Walk the tree.  (Conceptually, we would like to walk without
7395      duplicates, but for_each_template_parm_r recursively calls
7396      for_each_template_parm, so we would need to reorganize a fair
7397      bit to use walk_tree_without_duplicates, so we keep our own
7398      visited list.)  */
7399   if (visited)
7400     pfd.visited = visited;
7401   else
7402     pfd.visited = pointer_set_create ();
7403   result = cp_walk_tree (&t,
7404                          for_each_template_parm_r,
7405                          &pfd,
7406                          pfd.visited) != NULL_TREE;
7407
7408   /* Clean up.  */
7409   if (!visited)
7410     {
7411       pointer_set_destroy (pfd.visited);
7412       pfd.visited = 0;
7413     }
7414
7415   return result;
7416 }
7417
7418 /* Returns true if T depends on any template parameter.  */
7419
7420 int
7421 uses_template_parms (tree t)
7422 {
7423   bool dependent_p;
7424   int saved_processing_template_decl;
7425
7426   saved_processing_template_decl = processing_template_decl;
7427   if (!saved_processing_template_decl)
7428     processing_template_decl = 1;
7429   if (TYPE_P (t))
7430     dependent_p = dependent_type_p (t);
7431   else if (TREE_CODE (t) == TREE_VEC)
7432     dependent_p = any_dependent_template_arguments_p (t);
7433   else if (TREE_CODE (t) == TREE_LIST)
7434     dependent_p = (uses_template_parms (TREE_VALUE (t))
7435                    || uses_template_parms (TREE_CHAIN (t)));
7436   else if (TREE_CODE (t) == TYPE_DECL)
7437     dependent_p = dependent_type_p (TREE_TYPE (t));
7438   else if (DECL_P (t)
7439            || EXPR_P (t)
7440            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
7441            || TREE_CODE (t) == OVERLOAD
7442            || TREE_CODE (t) == BASELINK
7443            || TREE_CODE (t) == IDENTIFIER_NODE
7444            || TREE_CODE (t) == TRAIT_EXPR
7445            || TREE_CODE (t) == CONSTRUCTOR
7446            || CONSTANT_CLASS_P (t))
7447     dependent_p = (type_dependent_expression_p (t)
7448                    || value_dependent_expression_p (t));
7449   else
7450     {
7451       gcc_assert (t == error_mark_node);
7452       dependent_p = false;
7453     }
7454
7455   processing_template_decl = saved_processing_template_decl;
7456
7457   return dependent_p;
7458 }
7459
7460 /* Returns true if T depends on any template parameter with level LEVEL.  */
7461
7462 int
7463 uses_template_parms_level (tree t, int level)
7464 {
7465   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
7466                                  /*include_nondeduced_p=*/true);
7467 }
7468
7469 static int tinst_depth;
7470 extern int max_tinst_depth;
7471 #ifdef GATHER_STATISTICS
7472 int depth_reached;
7473 #endif
7474 static int tinst_level_tick;
7475 static int last_template_error_tick;
7476
7477 /* We're starting to instantiate D; record the template instantiation context
7478    for diagnostics and to restore it later.  */
7479
7480 int
7481 push_tinst_level (tree d)
7482 {
7483   struct tinst_level *new_level;
7484
7485   if (tinst_depth >= max_tinst_depth)
7486     {
7487       /* If the instantiation in question still has unbound template parms,
7488          we don't really care if we can't instantiate it, so just return.
7489          This happens with base instantiation for implicit `typename'.  */
7490       if (uses_template_parms (d))
7491         return 0;
7492
7493       last_template_error_tick = tinst_level_tick;
7494       error ("template instantiation depth exceeds maximum of %d (use "
7495              "-ftemplate-depth= to increase the maximum) instantiating %qD",
7496              max_tinst_depth, d);
7497
7498       print_instantiation_context ();
7499
7500       return 0;
7501     }
7502
7503   new_level = ggc_alloc_tinst_level ();
7504   new_level->decl = d;
7505   new_level->locus = input_location;
7506   new_level->in_system_header_p = in_system_header;
7507   new_level->next = current_tinst_level;
7508   current_tinst_level = new_level;
7509
7510   ++tinst_depth;
7511 #ifdef GATHER_STATISTICS
7512   if (tinst_depth > depth_reached)
7513     depth_reached = tinst_depth;
7514 #endif
7515
7516   ++tinst_level_tick;
7517   return 1;
7518 }
7519
7520 /* We're done instantiating this template; return to the instantiation
7521    context.  */
7522
7523 void
7524 pop_tinst_level (void)
7525 {
7526   /* Restore the filename and line number stashed away when we started
7527      this instantiation.  */
7528   input_location = current_tinst_level->locus;
7529   current_tinst_level = current_tinst_level->next;
7530   --tinst_depth;
7531   ++tinst_level_tick;
7532 }
7533
7534 /* We're instantiating a deferred template; restore the template
7535    instantiation context in which the instantiation was requested, which
7536    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
7537
7538 static tree
7539 reopen_tinst_level (struct tinst_level *level)
7540 {
7541   struct tinst_level *t;
7542
7543   tinst_depth = 0;
7544   for (t = level; t; t = t->next)
7545     ++tinst_depth;
7546
7547   current_tinst_level = level;
7548   pop_tinst_level ();
7549   return level->decl;
7550 }
7551
7552 /* Returns the TINST_LEVEL which gives the original instantiation
7553    context.  */
7554
7555 struct tinst_level *
7556 outermost_tinst_level (void)
7557 {
7558   struct tinst_level *level = current_tinst_level;
7559   if (level)
7560     while (level->next)
7561       level = level->next;
7562   return level;
7563 }
7564
7565 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
7566
7567 bool
7568 parameter_of_template_p (tree parm, tree templ)
7569 {
7570   tree parms;
7571   int i;
7572
7573   if (!parm || !templ)
7574     return false;
7575
7576   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
7577   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7578
7579   parms = DECL_TEMPLATE_PARMS (templ);
7580   parms = INNERMOST_TEMPLATE_PARMS (parms);
7581
7582   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
7583     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
7584       return true;
7585
7586   return false;
7587 }
7588
7589 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
7590    vector of template arguments, as for tsubst.
7591
7592    Returns an appropriate tsubst'd friend declaration.  */
7593
7594 static tree
7595 tsubst_friend_function (tree decl, tree args)
7596 {
7597   tree new_friend;
7598
7599   if (TREE_CODE (decl) == FUNCTION_DECL
7600       && DECL_TEMPLATE_INSTANTIATION (decl)
7601       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
7602     /* This was a friend declared with an explicit template
7603        argument list, e.g.:
7604
7605        friend void f<>(T);
7606
7607        to indicate that f was a template instantiation, not a new
7608        function declaration.  Now, we have to figure out what
7609        instantiation of what template.  */
7610     {
7611       tree template_id, arglist, fns;
7612       tree new_args;
7613       tree tmpl;
7614       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
7615
7616       /* Friend functions are looked up in the containing namespace scope.
7617          We must enter that scope, to avoid finding member functions of the
7618          current class with same name.  */
7619       push_nested_namespace (ns);
7620       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
7621                          tf_warning_or_error, NULL_TREE,
7622                          /*integral_constant_expression_p=*/false);
7623       pop_nested_namespace (ns);
7624       arglist = tsubst (DECL_TI_ARGS (decl), args,
7625                         tf_warning_or_error, NULL_TREE);
7626       template_id = lookup_template_function (fns, arglist);
7627
7628       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7629       tmpl = determine_specialization (template_id, new_friend,
7630                                        &new_args,
7631                                        /*need_member_template=*/0,
7632                                        TREE_VEC_LENGTH (args),
7633                                        tsk_none);
7634       return instantiate_template (tmpl, new_args, tf_error);
7635     }
7636
7637   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7638
7639   /* The NEW_FRIEND will look like an instantiation, to the
7640      compiler, but is not an instantiation from the point of view of
7641      the language.  For example, we might have had:
7642
7643      template <class T> struct S {
7644        template <class U> friend void f(T, U);
7645      };
7646
7647      Then, in S<int>, template <class U> void f(int, U) is not an
7648      instantiation of anything.  */
7649   if (new_friend == error_mark_node)
7650     return error_mark_node;
7651
7652   DECL_USE_TEMPLATE (new_friend) = 0;
7653   if (TREE_CODE (decl) == TEMPLATE_DECL)
7654     {
7655       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
7656       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
7657         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
7658     }
7659
7660   /* The mangled name for the NEW_FRIEND is incorrect.  The function
7661      is not a template instantiation and should not be mangled like
7662      one.  Therefore, we forget the mangling here; we'll recompute it
7663      later if we need it.  */
7664   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
7665     {
7666       SET_DECL_RTL (new_friend, NULL);
7667       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
7668     }
7669
7670   if (DECL_NAMESPACE_SCOPE_P (new_friend))
7671     {
7672       tree old_decl;
7673       tree new_friend_template_info;
7674       tree new_friend_result_template_info;
7675       tree ns;
7676       int  new_friend_is_defn;
7677
7678       /* We must save some information from NEW_FRIEND before calling
7679          duplicate decls since that function will free NEW_FRIEND if
7680          possible.  */
7681       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
7682       new_friend_is_defn =
7683             (DECL_INITIAL (DECL_TEMPLATE_RESULT
7684                            (template_for_substitution (new_friend)))
7685              != NULL_TREE);
7686       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
7687         {
7688           /* This declaration is a `primary' template.  */
7689           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
7690
7691           new_friend_result_template_info
7692             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
7693         }
7694       else
7695         new_friend_result_template_info = NULL_TREE;
7696
7697       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
7698       if (new_friend_is_defn)
7699         DECL_INITIAL (new_friend) = error_mark_node;
7700
7701       /* Inside pushdecl_namespace_level, we will push into the
7702          current namespace. However, the friend function should go
7703          into the namespace of the template.  */
7704       ns = decl_namespace_context (new_friend);
7705       push_nested_namespace (ns);
7706       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
7707       pop_nested_namespace (ns);
7708
7709       if (old_decl == error_mark_node)
7710         return error_mark_node;
7711
7712       if (old_decl != new_friend)
7713         {
7714           /* This new friend declaration matched an existing
7715              declaration.  For example, given:
7716
7717                template <class T> void f(T);
7718                template <class U> class C {
7719                  template <class T> friend void f(T) {}
7720                };
7721
7722              the friend declaration actually provides the definition
7723              of `f', once C has been instantiated for some type.  So,
7724              old_decl will be the out-of-class template declaration,
7725              while new_friend is the in-class definition.
7726
7727              But, if `f' was called before this point, the
7728              instantiation of `f' will have DECL_TI_ARGS corresponding
7729              to `T' but not to `U', references to which might appear
7730              in the definition of `f'.  Previously, the most general
7731              template for an instantiation of `f' was the out-of-class
7732              version; now it is the in-class version.  Therefore, we
7733              run through all specialization of `f', adding to their
7734              DECL_TI_ARGS appropriately.  In particular, they need a
7735              new set of outer arguments, corresponding to the
7736              arguments for this class instantiation.
7737
7738              The same situation can arise with something like this:
7739
7740                friend void f(int);
7741                template <class T> class C {
7742                  friend void f(T) {}
7743                };
7744
7745              when `C<int>' is instantiated.  Now, `f(int)' is defined
7746              in the class.  */
7747
7748           if (!new_friend_is_defn)
7749             /* On the other hand, if the in-class declaration does
7750                *not* provide a definition, then we don't want to alter
7751                existing definitions.  We can just leave everything
7752                alone.  */
7753             ;
7754           else
7755             {
7756               tree new_template = TI_TEMPLATE (new_friend_template_info);
7757               tree new_args = TI_ARGS (new_friend_template_info);
7758
7759               /* Overwrite whatever template info was there before, if
7760                  any, with the new template information pertaining to
7761                  the declaration.  */
7762               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
7763
7764               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
7765                 {
7766                   /* We should have called reregister_specialization in
7767                      duplicate_decls.  */
7768                   gcc_assert (retrieve_specialization (new_template,
7769                                                        new_args, 0)
7770                               == old_decl);
7771
7772                   /* Instantiate it if the global has already been used.  */
7773                   if (DECL_ODR_USED (old_decl))
7774                     instantiate_decl (old_decl, /*defer_ok=*/true,
7775                                       /*expl_inst_class_mem_p=*/false);
7776                 }
7777               else
7778                 {
7779                   tree t;
7780
7781                   /* Indicate that the old function template is a partial
7782                      instantiation.  */
7783                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
7784                     = new_friend_result_template_info;
7785
7786                   gcc_assert (new_template
7787                               == most_general_template (new_template));
7788                   gcc_assert (new_template != old_decl);
7789
7790                   /* Reassign any specializations already in the hash table
7791                      to the new more general template, and add the
7792                      additional template args.  */
7793                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
7794                        t != NULL_TREE;
7795                        t = TREE_CHAIN (t))
7796                     {
7797                       tree spec = TREE_VALUE (t);
7798                       spec_entry elt;
7799
7800                       elt.tmpl = old_decl;
7801                       elt.args = DECL_TI_ARGS (spec);
7802                       elt.spec = NULL_TREE;
7803
7804                       htab_remove_elt (decl_specializations, &elt);
7805
7806                       DECL_TI_ARGS (spec)
7807                         = add_outermost_template_args (new_args,
7808                                                        DECL_TI_ARGS (spec));
7809
7810                       register_specialization
7811                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
7812
7813                     }
7814                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
7815                 }
7816             }
7817
7818           /* The information from NEW_FRIEND has been merged into OLD_DECL
7819              by duplicate_decls.  */
7820           new_friend = old_decl;
7821         }
7822     }
7823   else
7824     {
7825       tree context = DECL_CONTEXT (new_friend);
7826       bool dependent_p;
7827
7828       /* In the code
7829            template <class T> class C {
7830              template <class U> friend void C1<U>::f (); // case 1
7831              friend void C2<T>::f ();                    // case 2
7832            };
7833          we only need to make sure CONTEXT is a complete type for
7834          case 2.  To distinguish between the two cases, we note that
7835          CONTEXT of case 1 remains dependent type after tsubst while
7836          this isn't true for case 2.  */
7837       ++processing_template_decl;
7838       dependent_p = dependent_type_p (context);
7839       --processing_template_decl;
7840
7841       if (!dependent_p
7842           && !complete_type_or_else (context, NULL_TREE))
7843         return error_mark_node;
7844
7845       if (COMPLETE_TYPE_P (context))
7846         {
7847           /* Check to see that the declaration is really present, and,
7848              possibly obtain an improved declaration.  */
7849           tree fn = check_classfn (context,
7850                                    new_friend, NULL_TREE);
7851
7852           if (fn)
7853             new_friend = fn;
7854         }
7855     }
7856
7857   return new_friend;
7858 }
7859
7860 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
7861    template arguments, as for tsubst.
7862
7863    Returns an appropriate tsubst'd friend type or error_mark_node on
7864    failure.  */
7865
7866 static tree
7867 tsubst_friend_class (tree friend_tmpl, tree args)
7868 {
7869   tree friend_type;
7870   tree tmpl;
7871   tree context;
7872
7873   context = CP_DECL_CONTEXT (friend_tmpl);
7874
7875   if (context != global_namespace)
7876     {
7877       if (TREE_CODE (context) == NAMESPACE_DECL)
7878         push_nested_namespace (context);
7879       else
7880         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
7881     }
7882
7883   /* Look for a class template declaration.  We look for hidden names
7884      because two friend declarations of the same template are the
7885      same.  For example, in:
7886
7887        struct A { 
7888          template <typename> friend class F;
7889        };
7890        template <typename> struct B { 
7891          template <typename> friend class F;
7892        };
7893
7894      both F templates are the same.  */
7895   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
7896                            /*block_p=*/true, 0, 
7897                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
7898
7899   /* But, if we don't find one, it might be because we're in a
7900      situation like this:
7901
7902        template <class T>
7903        struct S {
7904          template <class U>
7905          friend struct S;
7906        };
7907
7908      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
7909      for `S<int>', not the TEMPLATE_DECL.  */
7910   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
7911     {
7912       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
7913       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
7914     }
7915
7916   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
7917     {
7918       /* The friend template has already been declared.  Just
7919          check to see that the declarations match, and install any new
7920          default parameters.  We must tsubst the default parameters,
7921          of course.  We only need the innermost template parameters
7922          because that is all that redeclare_class_template will look
7923          at.  */
7924       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
7925           > TMPL_ARGS_DEPTH (args))
7926         {
7927           tree parms;
7928           location_t saved_input_location;
7929           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
7930                                          args, tf_warning_or_error);
7931
7932           saved_input_location = input_location;
7933           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
7934           redeclare_class_template (TREE_TYPE (tmpl), parms);
7935           input_location = saved_input_location;
7936           
7937         }
7938
7939       friend_type = TREE_TYPE (tmpl);
7940     }
7941   else
7942     {
7943       /* The friend template has not already been declared.  In this
7944          case, the instantiation of the template class will cause the
7945          injection of this template into the global scope.  */
7946       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7947       if (tmpl == error_mark_node)
7948         return error_mark_node;
7949
7950       /* The new TMPL is not an instantiation of anything, so we
7951          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7952          the new type because that is supposed to be the corresponding
7953          template decl, i.e., TMPL.  */
7954       DECL_USE_TEMPLATE (tmpl) = 0;
7955       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7956       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7957       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7958         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7959
7960       /* Inject this template into the global scope.  */
7961       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7962     }
7963
7964   if (context != global_namespace)
7965     {
7966       if (TREE_CODE (context) == NAMESPACE_DECL)
7967         pop_nested_namespace (context);
7968       else
7969         pop_nested_class ();
7970     }
7971
7972   return friend_type;
7973 }
7974
7975 /* Returns zero if TYPE cannot be completed later due to circularity.
7976    Otherwise returns one.  */
7977
7978 static int
7979 can_complete_type_without_circularity (tree type)
7980 {
7981   if (type == NULL_TREE || type == error_mark_node)
7982     return 0;
7983   else if (COMPLETE_TYPE_P (type))
7984     return 1;
7985   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
7986     return can_complete_type_without_circularity (TREE_TYPE (type));
7987   else if (CLASS_TYPE_P (type)
7988            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
7989     return 0;
7990   else
7991     return 1;
7992 }
7993
7994 /* Apply any attributes which had to be deferred until instantiation
7995    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
7996    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
7997
7998 static void
7999 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
8000                                 tree args, tsubst_flags_t complain, tree in_decl)
8001 {
8002   tree last_dep = NULL_TREE;
8003   tree t;
8004   tree *p;
8005
8006   for (t = attributes; t; t = TREE_CHAIN (t))
8007     if (ATTR_IS_DEPENDENT (t))
8008       {
8009         last_dep = t;
8010         attributes = copy_list (attributes);
8011         break;
8012       }
8013
8014   if (DECL_P (*decl_p))
8015     {
8016       if (TREE_TYPE (*decl_p) == error_mark_node)
8017         return;
8018       p = &DECL_ATTRIBUTES (*decl_p);
8019     }
8020   else
8021     p = &TYPE_ATTRIBUTES (*decl_p);
8022
8023   if (last_dep)
8024     {
8025       tree late_attrs = NULL_TREE;
8026       tree *q = &late_attrs;
8027
8028       for (*p = attributes; *p; )
8029         {
8030           t = *p;
8031           if (ATTR_IS_DEPENDENT (t))
8032             {
8033               *p = TREE_CHAIN (t);
8034               TREE_CHAIN (t) = NULL_TREE;
8035               /* If the first attribute argument is an identifier, don't
8036                  pass it through tsubst.  Attributes like mode, format,
8037                  cleanup and several target specific attributes expect it
8038                  unmodified.  */
8039               if (TREE_VALUE (t)
8040                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
8041                   && TREE_VALUE (TREE_VALUE (t))
8042                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
8043                       == IDENTIFIER_NODE))
8044                 {
8045                   tree chain
8046                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
8047                                    in_decl,
8048                                    /*integral_constant_expression_p=*/false);
8049                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
8050                     TREE_VALUE (t)
8051                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
8052                                    chain);
8053                 }
8054               else
8055                 TREE_VALUE (t)
8056                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
8057                                  /*integral_constant_expression_p=*/false);
8058               *q = t;
8059               q = &TREE_CHAIN (t);
8060             }
8061           else
8062             p = &TREE_CHAIN (t);
8063         }
8064
8065       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
8066     }
8067 }
8068
8069 /* Perform (or defer) access check for typedefs that were referenced
8070    from within the template TMPL code.
8071    This is a subroutine of instantiate_template and instantiate_class_template.
8072    TMPL is the template to consider and TARGS is the list of arguments of
8073    that template.  */
8074
8075 static void
8076 perform_typedefs_access_check (tree tmpl, tree targs)
8077 {
8078   location_t saved_location;
8079   int i;
8080   qualified_typedef_usage_t *iter;
8081
8082   if (!tmpl
8083       || (!CLASS_TYPE_P (tmpl)
8084           && TREE_CODE (tmpl) != FUNCTION_DECL))
8085     return;
8086
8087   saved_location = input_location;
8088   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
8089                     get_types_needing_access_check (tmpl),
8090                     i, iter)
8091     {
8092       tree type_decl = iter->typedef_decl;
8093       tree type_scope = iter->context;
8094
8095       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
8096         continue;
8097
8098       if (uses_template_parms (type_decl))
8099         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
8100       if (uses_template_parms (type_scope))
8101         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
8102
8103       /* Make access check error messages point to the location
8104          of the use of the typedef.  */
8105       input_location = iter->locus;
8106       perform_or_defer_access_check (TYPE_BINFO (type_scope),
8107                                      type_decl, type_decl);
8108     }
8109     input_location = saved_location;
8110 }
8111
8112 static tree
8113 instantiate_class_template_1 (tree type)
8114 {
8115   tree templ, args, pattern, t, member;
8116   tree typedecl;
8117   tree pbinfo;
8118   tree base_list;
8119   unsigned int saved_maximum_field_alignment;
8120
8121   if (type == error_mark_node)
8122     return error_mark_node;
8123
8124   if (COMPLETE_OR_OPEN_TYPE_P (type)
8125       || uses_template_parms (type))
8126     return type;
8127
8128   /* Figure out which template is being instantiated.  */
8129   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
8130   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
8131
8132   /* Determine what specialization of the original template to
8133      instantiate.  */
8134   t = most_specialized_class (type, templ, tf_warning_or_error);
8135   if (t == error_mark_node)
8136     {
8137       TYPE_BEING_DEFINED (type) = 1;
8138       return error_mark_node;
8139     }
8140   else if (t)
8141     {
8142       /* This TYPE is actually an instantiation of a partial
8143          specialization.  We replace the innermost set of ARGS with
8144          the arguments appropriate for substitution.  For example,
8145          given:
8146
8147            template <class T> struct S {};
8148            template <class T> struct S<T*> {};
8149
8150          and supposing that we are instantiating S<int*>, ARGS will
8151          presently be {int*} -- but we need {int}.  */
8152       pattern = TREE_TYPE (t);
8153       args = TREE_PURPOSE (t);
8154     }
8155   else
8156     {
8157       pattern = TREE_TYPE (templ);
8158       args = CLASSTYPE_TI_ARGS (type);
8159     }
8160
8161   /* If the template we're instantiating is incomplete, then clearly
8162      there's nothing we can do.  */
8163   if (!COMPLETE_TYPE_P (pattern))
8164     return type;
8165
8166   /* If we've recursively instantiated too many templates, stop.  */
8167   if (! push_tinst_level (type))
8168     return type;
8169
8170   /* Now we're really doing the instantiation.  Mark the type as in
8171      the process of being defined.  */
8172   TYPE_BEING_DEFINED (type) = 1;
8173
8174   /* We may be in the middle of deferred access check.  Disable
8175      it now.  */
8176   push_deferring_access_checks (dk_no_deferred);
8177
8178   push_to_top_level ();
8179   /* Use #pragma pack from the template context.  */
8180   saved_maximum_field_alignment = maximum_field_alignment;
8181   maximum_field_alignment = TYPE_PRECISION (pattern);
8182
8183   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
8184
8185   /* Set the input location to the most specialized template definition.
8186      This is needed if tsubsting causes an error.  */
8187   typedecl = TYPE_MAIN_DECL (pattern);
8188   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
8189     DECL_SOURCE_LOCATION (typedecl);
8190
8191   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
8192   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
8193   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
8194   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
8195   TYPE_HAS_COPY_ASSIGN (type) = TYPE_HAS_COPY_ASSIGN (pattern);
8196   TYPE_HAS_CONST_COPY_ASSIGN (type) = TYPE_HAS_CONST_COPY_ASSIGN (pattern);
8197   TYPE_HAS_COPY_CTOR (type) = TYPE_HAS_COPY_CTOR (pattern);
8198   TYPE_HAS_CONST_COPY_CTOR (type) = TYPE_HAS_CONST_COPY_CTOR (pattern);
8199   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
8200   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
8201   TYPE_PACKED (type) = TYPE_PACKED (pattern);
8202   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
8203   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
8204   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
8205   if (ANON_AGGR_TYPE_P (pattern))
8206     SET_ANON_AGGR_TYPE_P (type);
8207   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
8208     {
8209       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
8210       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
8211     }
8212   CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
8213
8214   pbinfo = TYPE_BINFO (pattern);
8215
8216   /* We should never instantiate a nested class before its enclosing
8217      class; we need to look up the nested class by name before we can
8218      instantiate it, and that lookup should instantiate the enclosing
8219      class.  */
8220   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
8221               || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
8222
8223   base_list = NULL_TREE;
8224   if (BINFO_N_BASE_BINFOS (pbinfo))
8225     {
8226       tree pbase_binfo;
8227       tree pushed_scope;
8228       int i;
8229
8230       /* We must enter the scope containing the type, as that is where
8231          the accessibility of types named in dependent bases are
8232          looked up from.  */
8233       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
8234
8235       /* Substitute into each of the bases to determine the actual
8236          basetypes.  */
8237       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
8238         {
8239           tree base;
8240           tree access = BINFO_BASE_ACCESS (pbinfo, i);
8241           tree expanded_bases = NULL_TREE;
8242           int idx, len = 1;
8243
8244           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
8245             {
8246               expanded_bases = 
8247                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
8248                                        args, tf_error, NULL_TREE);
8249               if (expanded_bases == error_mark_node)
8250                 continue;
8251
8252               len = TREE_VEC_LENGTH (expanded_bases);
8253             }
8254
8255           for (idx = 0; idx < len; idx++)
8256             {
8257               if (expanded_bases)
8258                 /* Extract the already-expanded base class.  */
8259                 base = TREE_VEC_ELT (expanded_bases, idx);
8260               else
8261                 /* Substitute to figure out the base class.  */
8262                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
8263                                NULL_TREE);
8264
8265               if (base == error_mark_node)
8266                 continue;
8267
8268               base_list = tree_cons (access, base, base_list);
8269               if (BINFO_VIRTUAL_P (pbase_binfo))
8270                 TREE_TYPE (base_list) = integer_type_node;
8271             }
8272         }
8273
8274       /* The list is now in reverse order; correct that.  */
8275       base_list = nreverse (base_list);
8276
8277       if (pushed_scope)
8278         pop_scope (pushed_scope);
8279     }
8280   /* Now call xref_basetypes to set up all the base-class
8281      information.  */
8282   xref_basetypes (type, base_list);
8283
8284   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
8285                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
8286                                   args, tf_error, NULL_TREE);
8287   fixup_attribute_variants (type);
8288
8289   /* Now that our base classes are set up, enter the scope of the
8290      class, so that name lookups into base classes, etc. will work
8291      correctly.  This is precisely analogous to what we do in
8292      begin_class_definition when defining an ordinary non-template
8293      class, except we also need to push the enclosing classes.  */
8294   push_nested_class (type);
8295
8296   /* Now members are processed in the order of declaration.  */
8297   for (member = CLASSTYPE_DECL_LIST (pattern);
8298        member; member = TREE_CHAIN (member))
8299     {
8300       tree t = TREE_VALUE (member);
8301
8302       if (TREE_PURPOSE (member))
8303         {
8304           if (TYPE_P (t))
8305             {
8306               /* Build new CLASSTYPE_NESTED_UTDS.  */
8307
8308               tree newtag;
8309               bool class_template_p;
8310
8311               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
8312                                   && TYPE_LANG_SPECIFIC (t)
8313                                   && CLASSTYPE_IS_TEMPLATE (t));
8314               /* If the member is a class template, then -- even after
8315                  substitution -- there may be dependent types in the
8316                  template argument list for the class.  We increment
8317                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
8318                  that function will assume that no types are dependent
8319                  when outside of a template.  */
8320               if (class_template_p)
8321                 ++processing_template_decl;
8322               newtag = tsubst (t, args, tf_error, NULL_TREE);
8323               if (class_template_p)
8324                 --processing_template_decl;
8325               if (newtag == error_mark_node)
8326                 continue;
8327
8328               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
8329                 {
8330                   tree name = TYPE_IDENTIFIER (t);
8331
8332                   if (class_template_p)
8333                     /* Unfortunately, lookup_template_class sets
8334                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
8335                        instantiation (i.e., for the type of a member
8336                        template class nested within a template class.)
8337                        This behavior is required for
8338                        maybe_process_partial_specialization to work
8339                        correctly, but is not accurate in this case;
8340                        the TAG is not an instantiation of anything.
8341                        (The corresponding TEMPLATE_DECL is an
8342                        instantiation, but the TYPE is not.) */
8343                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
8344
8345                   /* Now, we call pushtag to put this NEWTAG into the scope of
8346                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
8347                      pushtag calling push_template_decl.  We don't have to do
8348                      this for enums because it will already have been done in
8349                      tsubst_enum.  */
8350                   if (name)
8351                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
8352                   pushtag (name, newtag, /*tag_scope=*/ts_current);
8353                 }
8354             }
8355           else if (TREE_CODE (t) == FUNCTION_DECL
8356                    || DECL_FUNCTION_TEMPLATE_P (t))
8357             {
8358               /* Build new TYPE_METHODS.  */
8359               tree r;
8360
8361               if (TREE_CODE (t) == TEMPLATE_DECL)
8362                 ++processing_template_decl;
8363               r = tsubst (t, args, tf_error, NULL_TREE);
8364               if (TREE_CODE (t) == TEMPLATE_DECL)
8365                 --processing_template_decl;
8366               set_current_access_from_decl (r);
8367               finish_member_declaration (r);
8368             }
8369           else
8370             {
8371               /* Build new TYPE_FIELDS.  */
8372               if (TREE_CODE (t) == STATIC_ASSERT)
8373                 {
8374                   tree condition = 
8375                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
8376                                  tf_warning_or_error, NULL_TREE,
8377                                  /*integral_constant_expression_p=*/true);
8378                   finish_static_assert (condition,
8379                                         STATIC_ASSERT_MESSAGE (t), 
8380                                         STATIC_ASSERT_SOURCE_LOCATION (t),
8381                                         /*member_p=*/true);
8382                 }
8383               else if (TREE_CODE (t) != CONST_DECL)
8384                 {
8385                   tree r;
8386
8387                   /* The file and line for this declaration, to
8388                      assist in error message reporting.  Since we
8389                      called push_tinst_level above, we don't need to
8390                      restore these.  */
8391                   input_location = DECL_SOURCE_LOCATION (t);
8392
8393                   if (TREE_CODE (t) == TEMPLATE_DECL)
8394                     ++processing_template_decl;
8395                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
8396                   if (TREE_CODE (t) == TEMPLATE_DECL)
8397                     --processing_template_decl;
8398                   if (TREE_CODE (r) == VAR_DECL)
8399                     {
8400                       /* In [temp.inst]:
8401
8402                            [t]he initialization (and any associated
8403                            side-effects) of a static data member does
8404                            not occur unless the static data member is
8405                            itself used in a way that requires the
8406                            definition of the static data member to
8407                            exist.
8408
8409                          Therefore, we do not substitute into the
8410                          initialized for the static data member here.  */
8411                       finish_static_data_member_decl
8412                         (r,
8413                          /*init=*/NULL_TREE,
8414                          /*init_const_expr_p=*/false,
8415                          /*asmspec_tree=*/NULL_TREE,
8416                          /*flags=*/0);
8417                     }
8418                   else if (TREE_CODE (r) == FIELD_DECL)
8419                     {
8420                       /* Determine whether R has a valid type and can be
8421                          completed later.  If R is invalid, then it is
8422                          replaced by error_mark_node so that it will not be
8423                          added to TYPE_FIELDS.  */
8424                       tree rtype = TREE_TYPE (r);
8425                       if (can_complete_type_without_circularity (rtype))
8426                         complete_type (rtype);
8427
8428                       if (!COMPLETE_TYPE_P (rtype))
8429                         {
8430                           cxx_incomplete_type_error (r, rtype);
8431                           r = error_mark_node;
8432                         }
8433                     }
8434
8435                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
8436                      such a thing will already have been added to the field
8437                      list by tsubst_enum in finish_member_declaration in the
8438                      CLASSTYPE_NESTED_UTDS case above.  */
8439                   if (!(TREE_CODE (r) == TYPE_DECL
8440                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
8441                         && DECL_ARTIFICIAL (r)))
8442                     {
8443                       set_current_access_from_decl (r);
8444                       finish_member_declaration (r);
8445                     }
8446                 }
8447             }
8448         }
8449       else
8450         {
8451           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
8452             {
8453               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
8454
8455               tree friend_type = t;
8456               bool adjust_processing_template_decl = false;
8457
8458               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8459                 {
8460                   /* template <class T> friend class C;  */
8461                   friend_type = tsubst_friend_class (friend_type, args);
8462                   adjust_processing_template_decl = true;
8463                 }
8464               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
8465                 {
8466                   /* template <class T> friend class C::D;  */
8467                   friend_type = tsubst (friend_type, args,
8468                                         tf_warning_or_error, NULL_TREE);
8469                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8470                     friend_type = TREE_TYPE (friend_type);
8471                   adjust_processing_template_decl = true;
8472                 }
8473               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
8474                 {
8475                   /* This could be either
8476
8477                        friend class T::C;
8478
8479                      when dependent_type_p is false or
8480
8481                        template <class U> friend class T::C;
8482
8483                      otherwise.  */
8484                   friend_type = tsubst (friend_type, args,
8485                                         tf_warning_or_error, NULL_TREE);
8486                   /* Bump processing_template_decl for correct
8487                      dependent_type_p calculation.  */
8488                   ++processing_template_decl;
8489                   if (dependent_type_p (friend_type))
8490                     adjust_processing_template_decl = true;
8491                   --processing_template_decl;
8492                 }
8493               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
8494                        && hidden_name_p (TYPE_NAME (friend_type)))
8495                 {
8496                   /* friend class C;
8497
8498                      where C hasn't been declared yet.  Let's lookup name
8499                      from namespace scope directly, bypassing any name that
8500                      come from dependent base class.  */
8501                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
8502
8503                   /* The call to xref_tag_from_type does injection for friend
8504                      classes.  */
8505                   push_nested_namespace (ns);
8506                   friend_type =
8507                     xref_tag_from_type (friend_type, NULL_TREE,
8508                                         /*tag_scope=*/ts_current);
8509                   pop_nested_namespace (ns);
8510                 }
8511               else if (uses_template_parms (friend_type))
8512                 /* friend class C<T>;  */
8513                 friend_type = tsubst (friend_type, args,
8514                                       tf_warning_or_error, NULL_TREE);
8515               /* Otherwise it's
8516
8517                    friend class C;
8518
8519                  where C is already declared or
8520
8521                    friend class C<int>;
8522
8523                  We don't have to do anything in these cases.  */
8524
8525               if (adjust_processing_template_decl)
8526                 /* Trick make_friend_class into realizing that the friend
8527                    we're adding is a template, not an ordinary class.  It's
8528                    important that we use make_friend_class since it will
8529                    perform some error-checking and output cross-reference
8530                    information.  */
8531                 ++processing_template_decl;
8532
8533               if (friend_type != error_mark_node)
8534                 make_friend_class (type, friend_type, /*complain=*/false);
8535
8536               if (adjust_processing_template_decl)
8537                 --processing_template_decl;
8538             }
8539           else
8540             {
8541               /* Build new DECL_FRIENDLIST.  */
8542               tree r;
8543
8544               /* The file and line for this declaration, to
8545                  assist in error message reporting.  Since we
8546                  called push_tinst_level above, we don't need to
8547                  restore these.  */
8548               input_location = DECL_SOURCE_LOCATION (t);
8549
8550               if (TREE_CODE (t) == TEMPLATE_DECL)
8551                 {
8552                   ++processing_template_decl;
8553                   push_deferring_access_checks (dk_no_check);
8554                 }
8555
8556               r = tsubst_friend_function (t, args);
8557               add_friend (type, r, /*complain=*/false);
8558               if (TREE_CODE (t) == TEMPLATE_DECL)
8559                 {
8560                   pop_deferring_access_checks ();
8561                   --processing_template_decl;
8562                 }
8563             }
8564         }
8565     }
8566
8567   if (CLASSTYPE_LAMBDA_EXPR (type))
8568     maybe_add_lambda_conv_op (type);
8569
8570   /* Set the file and line number information to whatever is given for
8571      the class itself.  This puts error messages involving generated
8572      implicit functions at a predictable point, and the same point
8573      that would be used for non-template classes.  */
8574   input_location = DECL_SOURCE_LOCATION (typedecl);
8575
8576   unreverse_member_declarations (type);
8577   finish_struct_1 (type);
8578   TYPE_BEING_DEFINED (type) = 0;
8579
8580   /* We don't instantiate default arguments for member functions.  14.7.1:
8581
8582      The implicit instantiation of a class template specialization causes
8583      the implicit instantiation of the declarations, but not of the
8584      definitions or default arguments, of the class member functions,
8585      member classes, static data members and member templates....  */
8586
8587   /* Some typedefs referenced from within the template code need to be access
8588      checked at template instantiation time, i.e now. These types were
8589      added to the template at parsing time. Let's get those and perform
8590      the access checks then.  */
8591   perform_typedefs_access_check (pattern, args);
8592   perform_deferred_access_checks ();
8593   pop_nested_class ();
8594   maximum_field_alignment = saved_maximum_field_alignment;
8595   pop_from_top_level ();
8596   pop_deferring_access_checks ();
8597   pop_tinst_level ();
8598
8599   /* The vtable for a template class can be emitted in any translation
8600      unit in which the class is instantiated.  When there is no key
8601      method, however, finish_struct_1 will already have added TYPE to
8602      the keyed_classes list.  */
8603   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
8604     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
8605
8606   return type;
8607 }
8608
8609 /* Wrapper for instantiate_class_template_1.  */
8610
8611 tree
8612 instantiate_class_template (tree type)
8613 {
8614   tree ret;
8615   timevar_push (TV_TEMPLATE_INST);
8616   ret = instantiate_class_template_1 (type);
8617   timevar_pop (TV_TEMPLATE_INST);
8618   return ret;
8619 }
8620
8621 static tree
8622 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8623 {
8624   tree r;
8625
8626   if (!t)
8627     r = t;
8628   else if (TYPE_P (t))
8629     r = tsubst (t, args, complain, in_decl);
8630   else
8631     {
8632       if (!(complain & tf_warning))
8633         ++c_inhibit_evaluation_warnings;
8634       r = tsubst_expr (t, args, complain, in_decl,
8635                        /*integral_constant_expression_p=*/true);
8636       if (!(complain & tf_warning))
8637         --c_inhibit_evaluation_warnings;
8638     }
8639   return r;
8640 }
8641
8642 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
8643    NONTYPE_ARGUMENT_PACK.  */
8644
8645 static tree
8646 make_fnparm_pack (tree spec_parm)
8647 {
8648   /* Collect all of the extra "packed" parameters into an
8649      argument pack.  */
8650   tree parmvec;
8651   tree parmtypevec;
8652   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
8653   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
8654   int i, len = list_length (spec_parm);
8655
8656   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
8657   parmvec = make_tree_vec (len);
8658   parmtypevec = make_tree_vec (len);
8659   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
8660     {
8661       TREE_VEC_ELT (parmvec, i) = spec_parm;
8662       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
8663     }
8664
8665   /* Build the argument packs.  */
8666   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
8667   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
8668   TREE_TYPE (argpack) = argtypepack;
8669
8670   return argpack;
8671 }        
8672
8673 /* Substitute ARGS into T, which is an pack expansion
8674    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
8675    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
8676    (if only a partial substitution could be performed) or
8677    ERROR_MARK_NODE if there was an error.  */
8678 tree
8679 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
8680                        tree in_decl)
8681 {
8682   tree pattern;
8683   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
8684   int i, len = -1;
8685   tree result;
8686   int incomplete = 0;
8687   htab_t saved_local_specializations = NULL;
8688
8689   gcc_assert (PACK_EXPANSION_P (t));
8690   pattern = PACK_EXPANSION_PATTERN (t);
8691
8692   /* Determine the argument packs that will instantiate the parameter
8693      packs used in the expansion expression. While we're at it,
8694      compute the number of arguments to be expanded and make sure it
8695      is consistent.  */
8696   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
8697        pack = TREE_CHAIN (pack))
8698     {
8699       tree parm_pack = TREE_VALUE (pack);
8700       tree arg_pack = NULL_TREE;
8701       tree orig_arg = NULL_TREE;
8702
8703       if (TREE_CODE (parm_pack) == PARM_DECL)
8704         {
8705           if (!cp_unevaluated_operand)
8706             arg_pack = retrieve_local_specialization (parm_pack);
8707           else
8708             {
8709               /* We can't rely on local_specializations for a parameter
8710                  name used later in a function declaration (such as in a
8711                  late-specified return type).  Even if it exists, it might
8712                  have the wrong value for a recursive call.  Just make a
8713                  dummy decl, since it's only used for its type.  */
8714               arg_pack = tsubst_decl (parm_pack, args, complain);
8715               if (arg_pack && FUNCTION_PARAMETER_PACK_P (arg_pack))
8716                 /* Partial instantiation of the parm_pack, we can't build
8717                    up an argument pack yet.  */
8718                 arg_pack = NULL_TREE;
8719               else
8720                 arg_pack = make_fnparm_pack (arg_pack);
8721             }
8722         }
8723       else
8724         {
8725           int level, idx, levels;
8726           template_parm_level_and_index (parm_pack, &level, &idx);
8727
8728           levels = TMPL_ARGS_DEPTH (args);
8729           if (level <= levels)
8730             arg_pack = TMPL_ARG (args, level, idx);
8731         }
8732
8733       orig_arg = arg_pack;
8734       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
8735         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
8736       
8737       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
8738         /* This can only happen if we forget to expand an argument
8739            pack somewhere else. Just return an error, silently.  */
8740         {
8741           result = make_tree_vec (1);
8742           TREE_VEC_ELT (result, 0) = error_mark_node;
8743           return result;
8744         }
8745
8746       /* For clarity in the comments below let's use the
8747          representation 'argument_pack<elements>' to denote an
8748          argument pack and its elements.
8749
8750          In the 'if' block below, we want to detect cases where
8751          ARG_PACK is argument_pack<PARM_PACK...>.  I.e, we want to
8752          check if ARG_PACK is an argument pack which sole element is
8753          the expansion of PARM_PACK.  That argument pack is typically
8754          created by template_parm_to_arg when passed a parameter
8755          pack.  */
8756       if (arg_pack
8757           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
8758           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
8759         {
8760           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
8761           tree pattern = PACK_EXPANSION_PATTERN (expansion);
8762           /* So we have an argument_pack<P...>.  We want to test if P
8763              is actually PARM_PACK.  We will not use cp_tree_equal to
8764              test P and PARM_PACK because during type fixup (by
8765              fixup_template_parm) P can be a pre-fixup version of a
8766              type and PARM_PACK be its post-fixup version.
8767              cp_tree_equal would consider them as different even
8768              though we would want to consider them compatible for our
8769              precise purpose here.
8770
8771              Thus we are going to consider that P and PARM_PACK are
8772              compatible if they have the same DECL.  */
8773           if ((/* If ARG_PACK is a type parameter pack named by the
8774                   same DECL as parm_pack ...  */
8775                (TYPE_P (pattern)
8776                 && TYPE_P (parm_pack)
8777                 && TYPE_NAME (pattern) == TYPE_NAME (parm_pack))
8778                /* ... or if ARG_PACK is a non-type parameter
8779                   named by the same DECL as parm_pack ...  */
8780                || (TREE_CODE (pattern) == TEMPLATE_PARM_INDEX
8781                    && TREE_CODE (parm_pack) == PARM_DECL
8782                    && TEMPLATE_PARM_DECL (pattern)
8783                    == TEMPLATE_PARM_DECL (DECL_INITIAL (parm_pack))))
8784               && template_parameter_pack_p (pattern))
8785             /* ... then the argument pack that the parameter maps to
8786                is just an expansion of the parameter itself, such as
8787                one would find in the implicit typedef of a class
8788                inside the class itself.  Consider this parameter
8789                "unsubstituted", so that we will maintain the outer
8790                pack expansion.  */
8791             arg_pack = NULL_TREE;
8792         }
8793           
8794       if (arg_pack)
8795         {
8796           int my_len = 
8797             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
8798
8799           /* It's all-or-nothing with incomplete argument packs.  */
8800           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8801             return error_mark_node;
8802           
8803           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8804             incomplete = 1;
8805
8806           if (len < 0)
8807             len = my_len;
8808           else if (len != my_len)
8809             {
8810               if (incomplete)
8811                 /* We got explicit args for some packs but not others;
8812                    do nothing now and try again after deduction.  */
8813                 return t;
8814               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
8815                 error ("mismatched argument pack lengths while expanding "
8816                        "%<%T%>",
8817                        pattern);
8818               else
8819                 error ("mismatched argument pack lengths while expanding "
8820                        "%<%E%>",
8821                        pattern);
8822               return error_mark_node;
8823             }
8824
8825           /* Keep track of the parameter packs and their corresponding
8826              argument packs.  */
8827           packs = tree_cons (parm_pack, arg_pack, packs);
8828           TREE_TYPE (packs) = orig_arg;
8829         }
8830       else
8831         /* We can't substitute for this parameter pack.  */
8832         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
8833                                          TREE_VALUE (pack),
8834                                          unsubstituted_packs);
8835     }
8836
8837   /* We cannot expand this expansion expression, because we don't have
8838      all of the argument packs we need. Substitute into the pattern
8839      and return a PACK_EXPANSION_*. The caller will need to deal with
8840      that.  */
8841   if (unsubstituted_packs)
8842     {
8843       tree new_pat;
8844       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8845         new_pat = tsubst_expr (pattern, args, complain, in_decl,
8846                                /*integral_constant_expression_p=*/false);
8847       else
8848         new_pat = tsubst (pattern, args, complain, in_decl);
8849       return make_pack_expansion (new_pat);
8850     }
8851
8852   /* We could not find any argument packs that work.  */
8853   if (len < 0)
8854     return error_mark_node;
8855
8856   if (cp_unevaluated_operand)
8857     {
8858       /* We're in a late-specified return type, so create our own local
8859          specializations table; the current table is either NULL or (in the
8860          case of recursive unification) might have bindings that we don't
8861          want to use or alter.  */
8862       saved_local_specializations = local_specializations;
8863       local_specializations = htab_create (37,
8864                                            hash_local_specialization,
8865                                            eq_local_specializations,
8866                                            NULL);
8867     }
8868
8869   /* For each argument in each argument pack, substitute into the
8870      pattern.  */
8871   result = make_tree_vec (len + incomplete);
8872   for (i = 0; i < len + incomplete; ++i)
8873     {
8874       /* For parameter pack, change the substitution of the parameter
8875          pack to the ith argument in its argument pack, then expand
8876          the pattern.  */
8877       for (pack = packs; pack; pack = TREE_CHAIN (pack))
8878         {
8879           tree parm = TREE_PURPOSE (pack);
8880
8881           if (TREE_CODE (parm) == PARM_DECL)
8882             {
8883               /* Select the Ith argument from the pack.  */
8884               tree arg = make_node (ARGUMENT_PACK_SELECT);
8885               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
8886               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
8887               mark_used (parm);
8888               register_local_specialization (arg, parm);
8889             }
8890           else
8891             {
8892               tree value = parm;
8893               int idx, level;
8894               template_parm_level_and_index (parm, &level, &idx);
8895               
8896               if (i < len) 
8897                 {
8898                   /* Select the Ith argument from the pack. */
8899                   value = make_node (ARGUMENT_PACK_SELECT);
8900                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
8901                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
8902                 }
8903
8904               /* Update the corresponding argument.  */
8905               TMPL_ARG (args, level, idx) = value;
8906             }
8907         }
8908
8909       /* Substitute into the PATTERN with the altered arguments.  */
8910       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8911         TREE_VEC_ELT (result, i) = 
8912           tsubst_expr (pattern, args, complain, in_decl,
8913                        /*integral_constant_expression_p=*/false);
8914       else
8915         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
8916
8917       if (i == len)
8918         /* When we have incomplete argument packs, the last "expanded"
8919            result is itself a pack expansion, which allows us
8920            to deduce more arguments.  */
8921         TREE_VEC_ELT (result, i) = 
8922           make_pack_expansion (TREE_VEC_ELT (result, i));
8923
8924       if (TREE_VEC_ELT (result, i) == error_mark_node)
8925         {
8926           result = error_mark_node;
8927           break;
8928         }
8929     }
8930
8931   /* Update ARGS to restore the substitution from parameter packs to
8932      their argument packs.  */
8933   for (pack = packs; pack; pack = TREE_CHAIN (pack))
8934     {
8935       tree parm = TREE_PURPOSE (pack);
8936
8937       if (TREE_CODE (parm) == PARM_DECL)
8938         register_local_specialization (TREE_TYPE (pack), parm);
8939       else
8940         {
8941           int idx, level;
8942           template_parm_level_and_index (parm, &level, &idx);
8943           
8944           /* Update the corresponding argument.  */
8945           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
8946             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
8947               TREE_TYPE (pack);
8948           else
8949             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
8950         }
8951     }
8952
8953   if (saved_local_specializations)
8954     {
8955       htab_delete (local_specializations);
8956       local_specializations = saved_local_specializations;
8957     }
8958   
8959   return result;
8960 }
8961
8962 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
8963    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
8964    parameter packs; all parms generated from a function parameter pack will
8965    have the same DECL_PARM_INDEX.  */
8966
8967 tree
8968 get_pattern_parm (tree parm, tree tmpl)
8969 {
8970   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
8971   tree patparm;
8972
8973   if (DECL_ARTIFICIAL (parm))
8974     {
8975       for (patparm = DECL_ARGUMENTS (pattern);
8976            patparm; patparm = DECL_CHAIN (patparm))
8977         if (DECL_ARTIFICIAL (patparm)
8978             && DECL_NAME (parm) == DECL_NAME (patparm))
8979           break;
8980     }
8981   else
8982     {
8983       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
8984       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
8985       gcc_assert (DECL_PARM_INDEX (patparm)
8986                   == DECL_PARM_INDEX (parm));
8987     }
8988
8989   return patparm;
8990 }
8991
8992 /* Substitute ARGS into the vector or list of template arguments T.  */
8993
8994 static tree
8995 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8996 {
8997   tree orig_t = t;
8998   int len, need_new = 0, i, expanded_len_adjust = 0, out;
8999   tree *elts;
9000
9001   if (t == error_mark_node)
9002     return error_mark_node;
9003
9004   len = TREE_VEC_LENGTH (t);
9005   elts = XALLOCAVEC (tree, len);
9006
9007   for (i = 0; i < len; i++)
9008     {
9009       tree orig_arg = TREE_VEC_ELT (t, i);
9010       tree new_arg;
9011
9012       if (TREE_CODE (orig_arg) == TREE_VEC)
9013         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
9014       else if (PACK_EXPANSION_P (orig_arg))
9015         {
9016           /* Substitute into an expansion expression.  */
9017           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
9018
9019           if (TREE_CODE (new_arg) == TREE_VEC)
9020             /* Add to the expanded length adjustment the number of
9021                expanded arguments. We subtract one from this
9022                measurement, because the argument pack expression
9023                itself is already counted as 1 in
9024                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
9025                the argument pack is empty.  */
9026             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
9027         }
9028       else if (ARGUMENT_PACK_P (orig_arg))
9029         {
9030           /* Substitute into each of the arguments.  */
9031           new_arg = TYPE_P (orig_arg)
9032             ? cxx_make_type (TREE_CODE (orig_arg))
9033             : make_node (TREE_CODE (orig_arg));
9034           
9035           SET_ARGUMENT_PACK_ARGS (
9036             new_arg,
9037             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
9038                                   args, complain, in_decl));
9039
9040           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
9041             new_arg = error_mark_node;
9042
9043           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
9044             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
9045                                           complain, in_decl);
9046             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
9047
9048             if (TREE_TYPE (new_arg) == error_mark_node)
9049               new_arg = error_mark_node;
9050           }
9051         }
9052       else
9053         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
9054
9055       if (new_arg == error_mark_node)
9056         return error_mark_node;
9057
9058       elts[i] = new_arg;
9059       if (new_arg != orig_arg)
9060         need_new = 1;
9061     }
9062
9063   if (!need_new)
9064     return t;
9065
9066   /* Make space for the expanded arguments coming from template
9067      argument packs.  */
9068   t = make_tree_vec (len + expanded_len_adjust);
9069   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
9070      arguments for a member template.
9071      In that case each TREE_VEC in ORIG_T represents a level of template
9072      arguments, and ORIG_T won't carry any non defaulted argument count.
9073      It will rather be the nested TREE_VECs that will carry one.
9074      In other words, ORIG_T carries a non defaulted argument count only
9075      if it doesn't contain any nested TREE_VEC.  */
9076   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
9077     {
9078       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
9079       count += expanded_len_adjust;
9080       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
9081     }
9082   for (i = 0, out = 0; i < len; i++)
9083     {
9084       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
9085            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
9086           && TREE_CODE (elts[i]) == TREE_VEC)
9087         {
9088           int idx;
9089
9090           /* Now expand the template argument pack "in place".  */
9091           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
9092             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
9093         }
9094       else
9095         {
9096           TREE_VEC_ELT (t, out) = elts[i];
9097           out++;
9098         }
9099     }
9100
9101   return t;
9102 }
9103
9104 /* Return the result of substituting ARGS into the template parameters
9105    given by PARMS.  If there are m levels of ARGS and m + n levels of
9106    PARMS, then the result will contain n levels of PARMS.  For
9107    example, if PARMS is `template <class T> template <class U>
9108    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
9109    result will be `template <int*, double, class V>'.  */
9110
9111 static tree
9112 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
9113 {
9114   tree r = NULL_TREE;
9115   tree* new_parms;
9116
9117   /* When substituting into a template, we must set
9118      PROCESSING_TEMPLATE_DECL as the template parameters may be
9119      dependent if they are based on one-another, and the dependency
9120      predicates are short-circuit outside of templates.  */
9121   ++processing_template_decl;
9122
9123   for (new_parms = &r;
9124        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
9125        new_parms = &(TREE_CHAIN (*new_parms)),
9126          parms = TREE_CHAIN (parms))
9127     {
9128       tree new_vec =
9129         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
9130       int i;
9131
9132       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
9133         {
9134           tree tuple;
9135
9136           if (parms == error_mark_node)
9137             continue;
9138
9139           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
9140
9141           if (tuple == error_mark_node)
9142             continue;
9143
9144           TREE_VEC_ELT (new_vec, i) =
9145             tsubst_template_parm (tuple, args, complain);
9146         }
9147
9148       *new_parms =
9149         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
9150                              - TMPL_ARGS_DEPTH (args)),
9151                    new_vec, NULL_TREE);
9152     }
9153
9154   --processing_template_decl;
9155
9156   return r;
9157 }
9158
9159 /* Return the result of substituting ARGS into one template parameter
9160    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
9161    parameter and which TREE_PURPOSE is the default argument of the
9162    template parameter.  */
9163
9164 static tree
9165 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
9166 {
9167   tree default_value, parm_decl;
9168
9169   if (args == NULL_TREE
9170       || t == NULL_TREE
9171       || t == error_mark_node)
9172     return t;
9173
9174   gcc_assert (TREE_CODE (t) == TREE_LIST);
9175
9176   default_value = TREE_PURPOSE (t);
9177   parm_decl = TREE_VALUE (t);
9178
9179   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
9180   if (TREE_CODE (parm_decl) == PARM_DECL
9181       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
9182     parm_decl = error_mark_node;
9183   default_value = tsubst_template_arg (default_value, args,
9184                                        complain, NULL_TREE);
9185
9186   return build_tree_list (default_value, parm_decl);
9187 }
9188
9189 /* Substitute the ARGS into the indicated aggregate (or enumeration)
9190    type T.  If T is not an aggregate or enumeration type, it is
9191    handled as if by tsubst.  IN_DECL is as for tsubst.  If
9192    ENTERING_SCOPE is nonzero, T is the context for a template which
9193    we are presently tsubst'ing.  Return the substituted value.  */
9194
9195 static tree
9196 tsubst_aggr_type (tree t,
9197                   tree args,
9198                   tsubst_flags_t complain,
9199                   tree in_decl,
9200                   int entering_scope)
9201 {
9202   if (t == NULL_TREE)
9203     return NULL_TREE;
9204
9205   switch (TREE_CODE (t))
9206     {
9207     case RECORD_TYPE:
9208       if (TYPE_PTRMEMFUNC_P (t))
9209         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
9210
9211       /* Else fall through.  */
9212     case ENUMERAL_TYPE:
9213     case UNION_TYPE:
9214       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
9215         {
9216           tree argvec;
9217           tree context;
9218           tree r;
9219           int saved_unevaluated_operand;
9220           int saved_inhibit_evaluation_warnings;
9221
9222           /* In "sizeof(X<I>)" we need to evaluate "I".  */
9223           saved_unevaluated_operand = cp_unevaluated_operand;
9224           cp_unevaluated_operand = 0;
9225           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
9226           c_inhibit_evaluation_warnings = 0;
9227
9228           /* First, determine the context for the type we are looking
9229              up.  */
9230           context = TYPE_CONTEXT (t);
9231           if (context)
9232             {
9233               context = tsubst_aggr_type (context, args, complain,
9234                                           in_decl, /*entering_scope=*/1);
9235               /* If context is a nested class inside a class template,
9236                  it may still need to be instantiated (c++/33959).  */
9237               if (TYPE_P (context))
9238                 context = complete_type (context);
9239             }
9240
9241           /* Then, figure out what arguments are appropriate for the
9242              type we are trying to find.  For example, given:
9243
9244                template <class T> struct S;
9245                template <class T, class U> void f(T, U) { S<U> su; }
9246
9247              and supposing that we are instantiating f<int, double>,
9248              then our ARGS will be {int, double}, but, when looking up
9249              S we only want {double}.  */
9250           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
9251                                          complain, in_decl);
9252           if (argvec == error_mark_node)
9253             r = error_mark_node;
9254           else
9255             {
9256               r = lookup_template_class (t, argvec, in_decl, context,
9257                                          entering_scope, complain);
9258               r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
9259             }
9260
9261           cp_unevaluated_operand = saved_unevaluated_operand;
9262           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
9263
9264           return r;
9265         }
9266       else
9267         /* This is not a template type, so there's nothing to do.  */
9268         return t;
9269
9270     default:
9271       return tsubst (t, args, complain, in_decl);
9272     }
9273 }
9274
9275 /* Substitute into the default argument ARG (a default argument for
9276    FN), which has the indicated TYPE.  */
9277
9278 tree
9279 tsubst_default_argument (tree fn, tree type, tree arg)
9280 {
9281   tree saved_class_ptr = NULL_TREE;
9282   tree saved_class_ref = NULL_TREE;
9283
9284   /* This can happen in invalid code.  */
9285   if (TREE_CODE (arg) == DEFAULT_ARG)
9286     return arg;
9287
9288   /* This default argument came from a template.  Instantiate the
9289      default argument here, not in tsubst.  In the case of
9290      something like:
9291
9292        template <class T>
9293        struct S {
9294          static T t();
9295          void f(T = t());
9296        };
9297
9298      we must be careful to do name lookup in the scope of S<T>,
9299      rather than in the current class.  */
9300   push_access_scope (fn);
9301   /* The "this" pointer is not valid in a default argument.  */
9302   if (cfun)
9303     {
9304       saved_class_ptr = current_class_ptr;
9305       cp_function_chain->x_current_class_ptr = NULL_TREE;
9306       saved_class_ref = current_class_ref;
9307       cp_function_chain->x_current_class_ref = NULL_TREE;
9308     }
9309
9310   push_deferring_access_checks(dk_no_deferred);
9311   /* The default argument expression may cause implicitly defined
9312      member functions to be synthesized, which will result in garbage
9313      collection.  We must treat this situation as if we were within
9314      the body of function so as to avoid collecting live data on the
9315      stack.  */
9316   ++function_depth;
9317   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
9318                      tf_warning_or_error, NULL_TREE,
9319                      /*integral_constant_expression_p=*/false);
9320   --function_depth;
9321   pop_deferring_access_checks();
9322
9323   /* Restore the "this" pointer.  */
9324   if (cfun)
9325     {
9326       cp_function_chain->x_current_class_ptr = saved_class_ptr;
9327       cp_function_chain->x_current_class_ref = saved_class_ref;
9328     }
9329
9330   /* Make sure the default argument is reasonable.  */
9331   arg = check_default_argument (type, arg);
9332
9333   pop_access_scope (fn);
9334
9335   return arg;
9336 }
9337
9338 /* Substitute into all the default arguments for FN.  */
9339
9340 static void
9341 tsubst_default_arguments (tree fn)
9342 {
9343   tree arg;
9344   tree tmpl_args;
9345
9346   tmpl_args = DECL_TI_ARGS (fn);
9347
9348   /* If this function is not yet instantiated, we certainly don't need
9349      its default arguments.  */
9350   if (uses_template_parms (tmpl_args))
9351     return;
9352   /* Don't do this again for clones.  */
9353   if (DECL_CLONED_FUNCTION_P (fn))
9354     return;
9355
9356   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
9357        arg;
9358        arg = TREE_CHAIN (arg))
9359     if (TREE_PURPOSE (arg))
9360       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
9361                                                     TREE_VALUE (arg),
9362                                                     TREE_PURPOSE (arg));
9363 }
9364
9365 /* Substitute the ARGS into the T, which is a _DECL.  Return the
9366    result of the substitution.  Issue error and warning messages under
9367    control of COMPLAIN.  */
9368
9369 static tree
9370 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
9371 {
9372 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
9373   location_t saved_loc;
9374   tree r = NULL_TREE;
9375   tree in_decl = t;
9376   hashval_t hash = 0;
9377
9378   /* Set the filename and linenumber to improve error-reporting.  */
9379   saved_loc = input_location;
9380   input_location = DECL_SOURCE_LOCATION (t);
9381
9382   switch (TREE_CODE (t))
9383     {
9384     case TEMPLATE_DECL:
9385       {
9386         /* We can get here when processing a member function template,
9387            member class template, or template template parameter.  */
9388         tree decl = DECL_TEMPLATE_RESULT (t);
9389         tree spec;
9390         tree tmpl_args;
9391         tree full_args;
9392
9393         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9394           {
9395             /* Template template parameter is treated here.  */
9396             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9397             if (new_type == error_mark_node)
9398               RETURN (error_mark_node);
9399
9400             r = copy_decl (t);
9401             DECL_CHAIN (r) = NULL_TREE;
9402             TREE_TYPE (r) = new_type;
9403             DECL_TEMPLATE_RESULT (r)
9404               = build_decl (DECL_SOURCE_LOCATION (decl),
9405                             TYPE_DECL, DECL_NAME (decl), new_type);
9406             DECL_TEMPLATE_PARMS (r)
9407               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9408                                        complain);
9409             TYPE_NAME (new_type) = r;
9410             break;
9411           }
9412
9413         /* We might already have an instance of this template.
9414            The ARGS are for the surrounding class type, so the
9415            full args contain the tsubst'd args for the context,
9416            plus the innermost args from the template decl.  */
9417         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
9418           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
9419           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
9420         /* Because this is a template, the arguments will still be
9421            dependent, even after substitution.  If
9422            PROCESSING_TEMPLATE_DECL is not set, the dependency
9423            predicates will short-circuit.  */
9424         ++processing_template_decl;
9425         full_args = tsubst_template_args (tmpl_args, args,
9426                                           complain, in_decl);
9427         --processing_template_decl;
9428         if (full_args == error_mark_node)
9429           RETURN (error_mark_node);
9430
9431         /* If this is a default template template argument,
9432            tsubst might not have changed anything.  */
9433         if (full_args == tmpl_args)
9434           RETURN (t);
9435
9436         hash = hash_tmpl_and_args (t, full_args);
9437         spec = retrieve_specialization (t, full_args, hash);
9438         if (spec != NULL_TREE)
9439           {
9440             r = spec;
9441             break;
9442           }
9443
9444         /* Make a new template decl.  It will be similar to the
9445            original, but will record the current template arguments.
9446            We also create a new function declaration, which is just
9447            like the old one, but points to this new template, rather
9448            than the old one.  */
9449         r = copy_decl (t);
9450         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
9451         DECL_CHAIN (r) = NULL_TREE;
9452
9453         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
9454
9455         if (TREE_CODE (decl) == TYPE_DECL)
9456           {
9457             tree new_type;
9458             ++processing_template_decl;
9459             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9460             --processing_template_decl;
9461             if (new_type == error_mark_node)
9462               RETURN (error_mark_node);
9463
9464             TREE_TYPE (r) = new_type;
9465             CLASSTYPE_TI_TEMPLATE (new_type) = r;
9466             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
9467             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
9468             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
9469           }
9470         else
9471           {
9472             tree new_decl;
9473             ++processing_template_decl;
9474             new_decl = tsubst (decl, args, complain, in_decl);
9475             --processing_template_decl;
9476             if (new_decl == error_mark_node)
9477               RETURN (error_mark_node);
9478
9479             DECL_TEMPLATE_RESULT (r) = new_decl;
9480             DECL_TI_TEMPLATE (new_decl) = r;
9481             TREE_TYPE (r) = TREE_TYPE (new_decl);
9482             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
9483             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
9484           }
9485
9486         SET_DECL_IMPLICIT_INSTANTIATION (r);
9487         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
9488         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
9489
9490         /* The template parameters for this new template are all the
9491            template parameters for the old template, except the
9492            outermost level of parameters.  */
9493         DECL_TEMPLATE_PARMS (r)
9494           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9495                                    complain);
9496
9497         if (PRIMARY_TEMPLATE_P (t))
9498           DECL_PRIMARY_TEMPLATE (r) = r;
9499
9500         if (TREE_CODE (decl) != TYPE_DECL)
9501           /* Record this non-type partial instantiation.  */
9502           register_specialization (r, t,
9503                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
9504                                    false, hash);
9505       }
9506       break;
9507
9508     case FUNCTION_DECL:
9509       {
9510         tree ctx;
9511         tree argvec = NULL_TREE;
9512         tree *friends;
9513         tree gen_tmpl;
9514         tree type;
9515         int member;
9516         int args_depth;
9517         int parms_depth;
9518
9519         /* Nobody should be tsubst'ing into non-template functions.  */
9520         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
9521
9522         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
9523           {
9524             tree spec;
9525             bool dependent_p;
9526
9527             /* If T is not dependent, just return it.  We have to
9528                increment PROCESSING_TEMPLATE_DECL because
9529                value_dependent_expression_p assumes that nothing is
9530                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
9531             ++processing_template_decl;
9532             dependent_p = value_dependent_expression_p (t);
9533             --processing_template_decl;
9534             if (!dependent_p)
9535               RETURN (t);
9536
9537             /* Calculate the most general template of which R is a
9538                specialization, and the complete set of arguments used to
9539                specialize R.  */
9540             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
9541             argvec = tsubst_template_args (DECL_TI_ARGS
9542                                           (DECL_TEMPLATE_RESULT
9543                                                  (DECL_TI_TEMPLATE (t))),
9544                                            args, complain, in_decl);
9545
9546             /* Check to see if we already have this specialization.  */
9547             hash = hash_tmpl_and_args (gen_tmpl, argvec);
9548             spec = retrieve_specialization (gen_tmpl, argvec, hash);
9549
9550             if (spec)
9551               {
9552                 r = spec;
9553                 break;
9554               }
9555
9556             /* We can see more levels of arguments than parameters if
9557                there was a specialization of a member template, like
9558                this:
9559
9560                  template <class T> struct S { template <class U> void f(); }
9561                  template <> template <class U> void S<int>::f(U);
9562
9563                Here, we'll be substituting into the specialization,
9564                because that's where we can find the code we actually
9565                want to generate, but we'll have enough arguments for
9566                the most general template.
9567
9568                We also deal with the peculiar case:
9569
9570                  template <class T> struct S {
9571                    template <class U> friend void f();
9572                  };
9573                  template <class U> void f() {}
9574                  template S<int>;
9575                  template void f<double>();
9576
9577                Here, the ARGS for the instantiation of will be {int,
9578                double}.  But, we only need as many ARGS as there are
9579                levels of template parameters in CODE_PATTERN.  We are
9580                careful not to get fooled into reducing the ARGS in
9581                situations like:
9582
9583                  template <class T> struct S { template <class U> void f(U); }
9584                  template <class T> template <> void S<T>::f(int) {}
9585
9586                which we can spot because the pattern will be a
9587                specialization in this case.  */
9588             args_depth = TMPL_ARGS_DEPTH (args);
9589             parms_depth =
9590               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
9591             if (args_depth > parms_depth
9592                 && !DECL_TEMPLATE_SPECIALIZATION (t))
9593               args = get_innermost_template_args (args, parms_depth);
9594           }
9595         else
9596           {
9597             /* This special case arises when we have something like this:
9598
9599                  template <class T> struct S {
9600                    friend void f<int>(int, double);
9601                  };
9602
9603                Here, the DECL_TI_TEMPLATE for the friend declaration
9604                will be an IDENTIFIER_NODE.  We are being called from
9605                tsubst_friend_function, and we want only to create a
9606                new decl (R) with appropriate types so that we can call
9607                determine_specialization.  */
9608             gen_tmpl = NULL_TREE;
9609           }
9610
9611         if (DECL_CLASS_SCOPE_P (t))
9612           {
9613             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
9614               member = 2;
9615             else
9616               member = 1;
9617             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
9618                                     complain, t, /*entering_scope=*/1);
9619           }
9620         else
9621           {
9622             member = 0;
9623             ctx = DECL_CONTEXT (t);
9624           }
9625         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9626         if (type == error_mark_node)
9627           RETURN (error_mark_node);
9628
9629         /* We do NOT check for matching decls pushed separately at this
9630            point, as they may not represent instantiations of this
9631            template, and in any case are considered separate under the
9632            discrete model.  */
9633         r = copy_decl (t);
9634         DECL_USE_TEMPLATE (r) = 0;
9635         TREE_TYPE (r) = type;
9636         /* Clear out the mangled name and RTL for the instantiation.  */
9637         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9638         SET_DECL_RTL (r, NULL);
9639         /* Leave DECL_INITIAL set on deleted instantiations.  */
9640         if (!DECL_DELETED_FN (r))
9641           DECL_INITIAL (r) = NULL_TREE;
9642         DECL_CONTEXT (r) = ctx;
9643
9644         if (member && DECL_CONV_FN_P (r))
9645           /* Type-conversion operator.  Reconstruct the name, in
9646              case it's the name of one of the template's parameters.  */
9647           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
9648
9649         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
9650                                      complain, t);
9651         DECL_RESULT (r) = NULL_TREE;
9652
9653         TREE_STATIC (r) = 0;
9654         TREE_PUBLIC (r) = TREE_PUBLIC (t);
9655         DECL_EXTERNAL (r) = 1;
9656         /* If this is an instantiation of a function with internal
9657            linkage, we already know what object file linkage will be
9658            assigned to the instantiation.  */
9659         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
9660         DECL_DEFER_OUTPUT (r) = 0;
9661         DECL_CHAIN (r) = NULL_TREE;
9662         DECL_PENDING_INLINE_INFO (r) = 0;
9663         DECL_PENDING_INLINE_P (r) = 0;
9664         DECL_SAVED_TREE (r) = NULL_TREE;
9665         DECL_STRUCT_FUNCTION (r) = NULL;
9666         TREE_USED (r) = 0;
9667         /* We'll re-clone as appropriate in instantiate_template.  */
9668         DECL_CLONED_FUNCTION (r) = NULL_TREE;
9669
9670         /* If we aren't complaining now, return on error before we register
9671            the specialization so that we'll complain eventually.  */
9672         if ((complain & tf_error) == 0
9673             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9674             && !grok_op_properties (r, /*complain=*/false))
9675           RETURN (error_mark_node);
9676
9677         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
9678            this in the special friend case mentioned above where
9679            GEN_TMPL is NULL.  */
9680         if (gen_tmpl)
9681           {
9682             DECL_TEMPLATE_INFO (r)
9683               = build_template_info (gen_tmpl, argvec);
9684             SET_DECL_IMPLICIT_INSTANTIATION (r);
9685             register_specialization (r, gen_tmpl, argvec, false, hash);
9686
9687             /* We're not supposed to instantiate default arguments
9688                until they are called, for a template.  But, for a
9689                declaration like:
9690
9691                  template <class T> void f ()
9692                  { extern void g(int i = T()); }
9693
9694                we should do the substitution when the template is
9695                instantiated.  We handle the member function case in
9696                instantiate_class_template since the default arguments
9697                might refer to other members of the class.  */
9698             if (!member
9699                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
9700                 && !uses_template_parms (argvec))
9701               tsubst_default_arguments (r);
9702           }
9703         else
9704           DECL_TEMPLATE_INFO (r) = NULL_TREE;
9705
9706         /* Copy the list of befriending classes.  */
9707         for (friends = &DECL_BEFRIENDING_CLASSES (r);
9708              *friends;
9709              friends = &TREE_CHAIN (*friends))
9710           {
9711             *friends = copy_node (*friends);
9712             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
9713                                             args, complain,
9714                                             in_decl);
9715           }
9716
9717         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
9718           {
9719             maybe_retrofit_in_chrg (r);
9720             if (DECL_CONSTRUCTOR_P (r))
9721               grok_ctor_properties (ctx, r);
9722             /* If this is an instantiation of a member template, clone it.
9723                If it isn't, that'll be handled by
9724                clone_constructors_and_destructors.  */
9725             if (PRIMARY_TEMPLATE_P (gen_tmpl))
9726               clone_function_decl (r, /*update_method_vec_p=*/0);
9727           }
9728         else if ((complain & tf_error) != 0
9729                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9730                  && !grok_op_properties (r, /*complain=*/true))
9731           RETURN (error_mark_node);
9732
9733         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
9734           SET_DECL_FRIEND_CONTEXT (r,
9735                                    tsubst (DECL_FRIEND_CONTEXT (t),
9736                                             args, complain, in_decl));
9737
9738         /* Possibly limit visibility based on template args.  */
9739         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9740         if (DECL_VISIBILITY_SPECIFIED (t))
9741           {
9742             DECL_VISIBILITY_SPECIFIED (r) = 0;
9743             DECL_ATTRIBUTES (r)
9744               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9745           }
9746         determine_visibility (r);
9747         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
9748             && !processing_template_decl)
9749           defaulted_late_check (r);
9750
9751         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9752                                         args, complain, in_decl);
9753       }
9754       break;
9755
9756     case PARM_DECL:
9757       {
9758         tree type = NULL_TREE;
9759         int i, len = 1;
9760         tree expanded_types = NULL_TREE;
9761         tree prev_r = NULL_TREE;
9762         tree first_r = NULL_TREE;
9763
9764         if (FUNCTION_PARAMETER_PACK_P (t))
9765           {
9766             /* If there is a local specialization that isn't a
9767                parameter pack, it means that we're doing a "simple"
9768                substitution from inside tsubst_pack_expansion. Just
9769                return the local specialization (which will be a single
9770                parm).  */
9771             tree spec = retrieve_local_specialization (t);
9772             if (spec 
9773                 && TREE_CODE (spec) == PARM_DECL
9774                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
9775               RETURN (spec);
9776
9777             /* Expand the TYPE_PACK_EXPANSION that provides the types for
9778                the parameters in this function parameter pack.  */
9779             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
9780                                                     complain, in_decl);
9781             if (TREE_CODE (expanded_types) == TREE_VEC)
9782               {
9783                 len = TREE_VEC_LENGTH (expanded_types);
9784
9785                 /* Zero-length parameter packs are boring. Just substitute
9786                    into the chain.  */
9787                 if (len == 0)
9788                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
9789                                   TREE_CHAIN (t)));
9790               }
9791             else
9792               {
9793                 /* All we did was update the type. Make a note of that.  */
9794                 type = expanded_types;
9795                 expanded_types = NULL_TREE;
9796               }
9797           }
9798
9799         /* Loop through all of the parameter's we'll build. When T is
9800            a function parameter pack, LEN is the number of expanded
9801            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
9802         r = NULL_TREE;
9803         for (i = 0; i < len; ++i)
9804           {
9805             prev_r = r;
9806             r = copy_node (t);
9807             if (DECL_TEMPLATE_PARM_P (t))
9808               SET_DECL_TEMPLATE_PARM_P (r);
9809
9810             if (expanded_types)
9811               /* We're on the Ith parameter of the function parameter
9812                  pack.  */
9813               {
9814                 /* An argument of a function parameter pack is not a parameter
9815                    pack.  */
9816                 FUNCTION_PARAMETER_PACK_P (r) = false;
9817
9818                 /* Get the Ith type.  */
9819                 type = TREE_VEC_ELT (expanded_types, i);
9820
9821                 if (DECL_NAME (r))
9822                   /* Rename the parameter to include the index.  */
9823                   DECL_NAME (r) =
9824                     make_ith_pack_parameter_name (DECL_NAME (r), i);
9825               }
9826             else if (!type)
9827               /* We're dealing with a normal parameter.  */
9828               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9829
9830             type = type_decays_to (type);
9831             TREE_TYPE (r) = type;
9832             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9833
9834             if (DECL_INITIAL (r))
9835               {
9836                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
9837                   DECL_INITIAL (r) = TREE_TYPE (r);
9838                 else
9839                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
9840                                              complain, in_decl);
9841               }
9842
9843             DECL_CONTEXT (r) = NULL_TREE;
9844
9845             if (!DECL_TEMPLATE_PARM_P (r))
9846               DECL_ARG_TYPE (r) = type_passed_as (type);
9847
9848             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9849                                             args, complain, in_decl);
9850
9851             /* Keep track of the first new parameter we
9852                generate. That's what will be returned to the
9853                caller.  */
9854             if (!first_r)
9855               first_r = r;
9856
9857             /* Build a proper chain of parameters when substituting
9858                into a function parameter pack.  */
9859             if (prev_r)
9860               DECL_CHAIN (prev_r) = r;
9861           }
9862
9863         if (DECL_CHAIN (t))
9864           DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
9865                                    complain, DECL_CHAIN (t));
9866
9867         /* FIRST_R contains the start of the chain we've built.  */
9868         r = first_r;
9869       }
9870       break;
9871
9872     case FIELD_DECL:
9873       {
9874         tree type;
9875
9876         r = copy_decl (t);
9877         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9878         if (type == error_mark_node)
9879           RETURN (error_mark_node);
9880         TREE_TYPE (r) = type;
9881         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9882
9883         /* DECL_INITIAL gives the number of bits in a bit-field.  */
9884         DECL_INITIAL (r)
9885           = tsubst_expr (DECL_INITIAL (t), args,
9886                          complain, in_decl,
9887                          /*integral_constant_expression_p=*/true);
9888         /* We don't have to set DECL_CONTEXT here; it is set by
9889            finish_member_declaration.  */
9890         DECL_CHAIN (r) = NULL_TREE;
9891         if (VOID_TYPE_P (type))
9892           error ("instantiation of %q+D as type %qT", r, type);
9893
9894         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9895                                         args, complain, in_decl);
9896       }
9897       break;
9898
9899     case USING_DECL:
9900       /* We reach here only for member using decls.  */
9901       if (DECL_DEPENDENT_P (t))
9902         {
9903           r = do_class_using_decl
9904             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
9905              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
9906           if (!r)
9907             r = error_mark_node;
9908           else
9909             {
9910               TREE_PROTECTED (r) = TREE_PROTECTED (t);
9911               TREE_PRIVATE (r) = TREE_PRIVATE (t);
9912             }
9913         }
9914       else
9915         {
9916           r = copy_node (t);
9917           DECL_CHAIN (r) = NULL_TREE;
9918         }
9919       break;
9920
9921     case TYPE_DECL:
9922     case VAR_DECL:
9923       {
9924         tree argvec = NULL_TREE;
9925         tree gen_tmpl = NULL_TREE;
9926         tree spec;
9927         tree tmpl = NULL_TREE;
9928         tree ctx;
9929         tree type = NULL_TREE;
9930         bool local_p;
9931
9932         if (TREE_CODE (t) == TYPE_DECL
9933             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
9934           {
9935             /* If this is the canonical decl, we don't have to
9936                mess with instantiations, and often we can't (for
9937                typename, template type parms and such).  Note that
9938                TYPE_NAME is not correct for the above test if
9939                we've copied the type for a typedef.  */
9940             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9941             if (type == error_mark_node)
9942               RETURN (error_mark_node);
9943             r = TYPE_NAME (type);
9944             break;
9945           }
9946
9947         /* Check to see if we already have the specialization we
9948            need.  */
9949         spec = NULL_TREE;
9950         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
9951           {
9952             /* T is a static data member or namespace-scope entity.
9953                We have to substitute into namespace-scope variables
9954                (even though such entities are never templates) because
9955                of cases like:
9956                
9957                  template <class T> void f() { extern T t; }
9958
9959                where the entity referenced is not known until
9960                instantiation time.  */
9961             local_p = false;
9962             ctx = DECL_CONTEXT (t);
9963             if (DECL_CLASS_SCOPE_P (t))
9964               {
9965                 ctx = tsubst_aggr_type (ctx, args,
9966                                         complain,
9967                                         in_decl, /*entering_scope=*/1);
9968                 /* If CTX is unchanged, then T is in fact the
9969                    specialization we want.  That situation occurs when
9970                    referencing a static data member within in its own
9971                    class.  We can use pointer equality, rather than
9972                    same_type_p, because DECL_CONTEXT is always
9973                    canonical.  */
9974                 if (ctx == DECL_CONTEXT (t))
9975                   spec = t;
9976               }
9977
9978             if (!spec)
9979               {
9980                 tmpl = DECL_TI_TEMPLATE (t);
9981                 gen_tmpl = most_general_template (tmpl);
9982                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
9983                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
9984                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
9985               }
9986           }
9987         else
9988           {
9989             /* A local variable.  */
9990             local_p = true;
9991             /* Subsequent calls to pushdecl will fill this in.  */
9992             ctx = NULL_TREE;
9993             spec = retrieve_local_specialization (t);
9994           }
9995         /* If we already have the specialization we need, there is
9996            nothing more to do.  */ 
9997         if (spec)
9998           {
9999             r = spec;
10000             break;
10001           }
10002
10003         /* Create a new node for the specialization we need.  */
10004         r = copy_decl (t);
10005         if (type == NULL_TREE)
10006           {
10007             if (is_typedef_decl (t))
10008               type = DECL_ORIGINAL_TYPE (t);
10009             else
10010               type = TREE_TYPE (t);
10011             if (TREE_CODE (t) == VAR_DECL && VAR_HAD_UNKNOWN_BOUND (t))
10012               type = strip_array_domain (type);
10013             type = tsubst (type, args, complain, in_decl);
10014           }
10015         if (TREE_CODE (r) == VAR_DECL)
10016           {
10017             /* Even if the original location is out of scope, the
10018                newly substituted one is not.  */
10019             DECL_DEAD_FOR_LOCAL (r) = 0;
10020             DECL_INITIALIZED_P (r) = 0;
10021             DECL_TEMPLATE_INSTANTIATED (r) = 0;
10022             if (type == error_mark_node)
10023               RETURN (error_mark_node);
10024             if (TREE_CODE (type) == FUNCTION_TYPE)
10025               {
10026                 /* It may seem that this case cannot occur, since:
10027
10028                      typedef void f();
10029                      void g() { f x; }
10030
10031                    declares a function, not a variable.  However:
10032       
10033                      typedef void f();
10034                      template <typename T> void g() { T t; }
10035                      template void g<f>();
10036
10037                    is an attempt to declare a variable with function
10038                    type.  */
10039                 error ("variable %qD has function type",
10040                        /* R is not yet sufficiently initialized, so we
10041                           just use its name.  */
10042                        DECL_NAME (r));
10043                 RETURN (error_mark_node);
10044               }
10045             type = complete_type (type);
10046             /* Wait until cp_finish_decl to set this again, to handle
10047                circular dependency (template/instantiate6.C). */
10048             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
10049             type = check_var_type (DECL_NAME (r), type);
10050
10051             if (DECL_HAS_VALUE_EXPR_P (t))
10052               {
10053                 tree ve = DECL_VALUE_EXPR (t);
10054                 ve = tsubst_expr (ve, args, complain, in_decl,
10055                                   /*constant_expression_p=*/false);
10056                 SET_DECL_VALUE_EXPR (r, ve);
10057               }
10058           }
10059         else if (DECL_SELF_REFERENCE_P (t))
10060           SET_DECL_SELF_REFERENCE_P (r);
10061         TREE_TYPE (r) = type;
10062         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10063         DECL_CONTEXT (r) = ctx;
10064         /* Clear out the mangled name and RTL for the instantiation.  */
10065         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
10066         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10067           SET_DECL_RTL (r, NULL);
10068         /* The initializer must not be expanded until it is required;
10069            see [temp.inst].  */
10070         DECL_INITIAL (r) = NULL_TREE;
10071         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10072           SET_DECL_RTL (r, NULL);
10073         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
10074         if (TREE_CODE (r) == VAR_DECL)
10075           {
10076             /* Possibly limit visibility based on template args.  */
10077             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10078             if (DECL_VISIBILITY_SPECIFIED (t))
10079               {
10080                 DECL_VISIBILITY_SPECIFIED (r) = 0;
10081                 DECL_ATTRIBUTES (r)
10082                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10083               }
10084             determine_visibility (r);
10085           }
10086
10087         if (!local_p)
10088           {
10089             /* A static data member declaration is always marked
10090                external when it is declared in-class, even if an
10091                initializer is present.  We mimic the non-template
10092                processing here.  */
10093             DECL_EXTERNAL (r) = 1;
10094
10095             register_specialization (r, gen_tmpl, argvec, false, hash);
10096             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
10097             SET_DECL_IMPLICIT_INSTANTIATION (r);
10098           }
10099         else if (cp_unevaluated_operand)
10100           {
10101             /* We're substituting this var in a decltype outside of its
10102                scope, such as for a lambda return type.  Don't add it to
10103                local_specializations, do perform auto deduction.  */
10104             tree auto_node = type_uses_auto (type);
10105             tree init
10106               = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
10107                              /*constant_expression_p=*/false);
10108
10109             if (auto_node && init)
10110               {
10111                 init = resolve_nondeduced_context (init);
10112                 if (describable_type (init))
10113                   {
10114                     type = do_auto_deduction (type, init, auto_node);
10115                     TREE_TYPE (r) = type;
10116                   }
10117               }
10118           }
10119         else
10120           register_local_specialization (r, t);
10121
10122         DECL_CHAIN (r) = NULL_TREE;
10123
10124         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
10125                                         /*flags=*/0,
10126                                         args, complain, in_decl);
10127
10128         /* Preserve a typedef that names a type.  */
10129         if (is_typedef_decl (r))
10130           {
10131             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
10132             set_underlying_type (r);
10133           }
10134
10135         layout_decl (r, 0);
10136       }
10137       break;
10138
10139     default:
10140       gcc_unreachable ();
10141     }
10142 #undef RETURN
10143
10144  out:
10145   /* Restore the file and line information.  */
10146   input_location = saved_loc;
10147
10148   return r;
10149 }
10150
10151 /* Substitute into the ARG_TYPES of a function type.  */
10152
10153 static tree
10154 tsubst_arg_types (tree arg_types,
10155                   tree args,
10156                   tsubst_flags_t complain,
10157                   tree in_decl)
10158 {
10159   tree remaining_arg_types;
10160   tree type = NULL_TREE;
10161   int i = 1;
10162   tree expanded_args = NULL_TREE;
10163   tree default_arg;
10164
10165   if (!arg_types || arg_types == void_list_node)
10166     return arg_types;
10167
10168   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
10169                                           args, complain, in_decl);
10170   if (remaining_arg_types == error_mark_node)
10171     return error_mark_node;
10172
10173   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
10174     {
10175       /* For a pack expansion, perform substitution on the
10176          entire expression. Later on, we'll handle the arguments
10177          one-by-one.  */
10178       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
10179                                             args, complain, in_decl);
10180
10181       if (TREE_CODE (expanded_args) == TREE_VEC)
10182         /* So that we'll spin through the parameters, one by one.  */
10183         i = TREE_VEC_LENGTH (expanded_args);
10184       else
10185         {
10186           /* We only partially substituted into the parameter
10187              pack. Our type is TYPE_PACK_EXPANSION.  */
10188           type = expanded_args;
10189           expanded_args = NULL_TREE;
10190         }
10191     }
10192
10193   while (i > 0) {
10194     --i;
10195     
10196     if (expanded_args)
10197       type = TREE_VEC_ELT (expanded_args, i);
10198     else if (!type)
10199       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
10200
10201     if (type == error_mark_node)
10202       return error_mark_node;
10203     if (VOID_TYPE_P (type))
10204       {
10205         if (complain & tf_error)
10206           {
10207             error ("invalid parameter type %qT", type);
10208             if (in_decl)
10209               error ("in declaration %q+D", in_decl);
10210           }
10211         return error_mark_node;
10212     }
10213     
10214     /* Do array-to-pointer, function-to-pointer conversion, and ignore
10215        top-level qualifiers as required.  */
10216     type = TYPE_MAIN_VARIANT (type_decays_to (type));
10217
10218     /* We do not substitute into default arguments here.  The standard
10219        mandates that they be instantiated only when needed, which is
10220        done in build_over_call.  */
10221     default_arg = TREE_PURPOSE (arg_types);
10222
10223     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
10224       {
10225         /* We've instantiated a template before its default arguments
10226            have been parsed.  This can happen for a nested template
10227            class, and is not an error unless we require the default
10228            argument in a call of this function.  */
10229         remaining_arg_types = 
10230           tree_cons (default_arg, type, remaining_arg_types);
10231         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
10232                        remaining_arg_types);
10233       }
10234     else
10235       remaining_arg_types = 
10236         hash_tree_cons (default_arg, type, remaining_arg_types);
10237   }
10238         
10239   return remaining_arg_types;
10240 }
10241
10242 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
10243    *not* handle the exception-specification for FNTYPE, because the
10244    initial substitution of explicitly provided template parameters
10245    during argument deduction forbids substitution into the
10246    exception-specification:
10247
10248      [temp.deduct]
10249
10250      All references in the function type of the function template to  the
10251      corresponding template parameters are replaced by the specified tem-
10252      plate argument values.  If a substitution in a template parameter or
10253      in  the function type of the function template results in an invalid
10254      type, type deduction fails.  [Note: The equivalent  substitution  in
10255      exception specifications is done only when the function is instanti-
10256      ated, at which point a program is  ill-formed  if  the  substitution
10257      results in an invalid type.]  */
10258
10259 static tree
10260 tsubst_function_type (tree t,
10261                       tree args,
10262                       tsubst_flags_t complain,
10263                       tree in_decl)
10264 {
10265   tree return_type;
10266   tree arg_types;
10267   tree fntype;
10268
10269   /* The TYPE_CONTEXT is not used for function/method types.  */
10270   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
10271
10272   /* Substitute the return type.  */
10273   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10274   if (return_type == error_mark_node)
10275     return error_mark_node;
10276   /* The standard does not presently indicate that creation of a
10277      function type with an invalid return type is a deduction failure.
10278      However, that is clearly analogous to creating an array of "void"
10279      or a reference to a reference.  This is core issue #486.  */
10280   if (TREE_CODE (return_type) == ARRAY_TYPE
10281       || TREE_CODE (return_type) == FUNCTION_TYPE)
10282     {
10283       if (complain & tf_error)
10284         {
10285           if (TREE_CODE (return_type) == ARRAY_TYPE)
10286             error ("function returning an array");
10287           else
10288             error ("function returning a function");
10289         }
10290       return error_mark_node;
10291     }
10292
10293   /* Substitute the argument types.  */
10294   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
10295                                 complain, in_decl);
10296   if (arg_types == error_mark_node)
10297     return error_mark_node;
10298
10299   /* Construct a new type node and return it.  */
10300   if (TREE_CODE (t) == FUNCTION_TYPE)
10301     {
10302       fntype = build_function_type (return_type, arg_types);
10303       fntype = apply_memfn_quals (fntype, type_memfn_quals (t));
10304     }
10305   else
10306     {
10307       tree r = TREE_TYPE (TREE_VALUE (arg_types));
10308       if (! MAYBE_CLASS_TYPE_P (r))
10309         {
10310           /* [temp.deduct]
10311
10312              Type deduction may fail for any of the following
10313              reasons:
10314
10315              -- Attempting to create "pointer to member of T" when T
10316              is not a class type.  */
10317           if (complain & tf_error)
10318             error ("creating pointer to member function of non-class type %qT",
10319                       r);
10320           return error_mark_node;
10321         }
10322
10323       fntype = build_method_type_directly (r, return_type,
10324                                            TREE_CHAIN (arg_types));
10325     }
10326   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
10327
10328   return fntype;
10329 }
10330
10331 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
10332    ARGS into that specification, and return the substituted
10333    specification.  If there is no specification, return NULL_TREE.  */
10334
10335 static tree
10336 tsubst_exception_specification (tree fntype,
10337                                 tree args,
10338                                 tsubst_flags_t complain,
10339                                 tree in_decl)
10340 {
10341   tree specs;
10342   tree new_specs;
10343
10344   specs = TYPE_RAISES_EXCEPTIONS (fntype);
10345   new_specs = NULL_TREE;
10346   if (specs && TREE_PURPOSE (specs))
10347     {
10348       /* A noexcept-specifier.  */
10349       new_specs = tsubst_copy_and_build
10350         (TREE_PURPOSE (specs), args, complain, in_decl, /*function_p=*/false,
10351          /*integral_constant_expression_p=*/true);
10352       new_specs = build_noexcept_spec (new_specs, complain);
10353     }
10354   else if (specs)
10355     {
10356       if (! TREE_VALUE (specs))
10357         new_specs = specs;
10358       else
10359         while (specs)
10360           {
10361             tree spec;
10362             int i, len = 1;
10363             tree expanded_specs = NULL_TREE;
10364
10365             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
10366               {
10367                 /* Expand the pack expansion type.  */
10368                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
10369                                                        args, complain,
10370                                                        in_decl);
10371
10372                 if (expanded_specs == error_mark_node)
10373                   return error_mark_node;
10374                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
10375                   len = TREE_VEC_LENGTH (expanded_specs);
10376                 else
10377                   {
10378                     /* We're substituting into a member template, so
10379                        we got a TYPE_PACK_EXPANSION back.  Add that
10380                        expansion and move on.  */
10381                     gcc_assert (TREE_CODE (expanded_specs) 
10382                                 == TYPE_PACK_EXPANSION);
10383                     new_specs = add_exception_specifier (new_specs,
10384                                                          expanded_specs,
10385                                                          complain);
10386                     specs = TREE_CHAIN (specs);
10387                     continue;
10388                   }
10389               }
10390
10391             for (i = 0; i < len; ++i)
10392               {
10393                 if (expanded_specs)
10394                   spec = TREE_VEC_ELT (expanded_specs, i);
10395                 else
10396                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
10397                 if (spec == error_mark_node)
10398                   return spec;
10399                 new_specs = add_exception_specifier (new_specs, spec, 
10400                                                      complain);
10401               }
10402
10403             specs = TREE_CHAIN (specs);
10404           }
10405     }
10406   return new_specs;
10407 }
10408
10409 /* Take the tree structure T and replace template parameters used
10410    therein with the argument vector ARGS.  IN_DECL is an associated
10411    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
10412    Issue error and warning messages under control of COMPLAIN.  Note
10413    that we must be relatively non-tolerant of extensions here, in
10414    order to preserve conformance; if we allow substitutions that
10415    should not be allowed, we may allow argument deductions that should
10416    not succeed, and therefore report ambiguous overload situations
10417    where there are none.  In theory, we could allow the substitution,
10418    but indicate that it should have failed, and allow our caller to
10419    make sure that the right thing happens, but we don't try to do this
10420    yet.
10421
10422    This function is used for dealing with types, decls and the like;
10423    for expressions, use tsubst_expr or tsubst_copy.  */
10424
10425 tree
10426 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10427 {
10428   enum tree_code code;
10429   tree type, r;
10430
10431   if (t == NULL_TREE || t == error_mark_node
10432       || t == integer_type_node
10433       || t == void_type_node
10434       || t == char_type_node
10435       || t == unknown_type_node
10436       || TREE_CODE (t) == NAMESPACE_DECL
10437       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
10438     return t;
10439
10440   if (DECL_P (t))
10441     return tsubst_decl (t, args, complain);
10442
10443   if (args == NULL_TREE)
10444     return t;
10445
10446   code = TREE_CODE (t);
10447
10448   if (code == IDENTIFIER_NODE)
10449     type = IDENTIFIER_TYPE_VALUE (t);
10450   else
10451     type = TREE_TYPE (t);
10452
10453   gcc_assert (type != unknown_type_node);
10454
10455   /* Reuse typedefs.  We need to do this to handle dependent attributes,
10456      such as attribute aligned.  */
10457   if (TYPE_P (t)
10458       && typedef_variant_p (t))
10459     {
10460       tree decl = TYPE_NAME (t);
10461       
10462       if (DECL_CLASS_SCOPE_P (decl)
10463           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
10464           && uses_template_parms (DECL_CONTEXT (decl)))
10465         {
10466           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
10467           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
10468           r = retrieve_specialization (tmpl, gen_args, 0);
10469         }
10470       else if (DECL_FUNCTION_SCOPE_P (decl)
10471                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
10472                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
10473         r = retrieve_local_specialization (decl);
10474       else
10475         /* The typedef is from a non-template context.  */
10476         return t;
10477
10478       if (r)
10479         {
10480           r = TREE_TYPE (r);
10481           r = cp_build_qualified_type_real
10482             (r, cp_type_quals (t) | cp_type_quals (r),
10483              complain | tf_ignore_bad_quals);
10484           return r;
10485         }
10486       /* Else we must be instantiating the typedef, so fall through.  */
10487     }
10488
10489   if (type
10490       && code != TYPENAME_TYPE
10491       && code != TEMPLATE_TYPE_PARM
10492       && code != IDENTIFIER_NODE
10493       && code != FUNCTION_TYPE
10494       && code != METHOD_TYPE)
10495     type = tsubst (type, args, complain, in_decl);
10496   if (type == error_mark_node)
10497     return error_mark_node;
10498
10499   switch (code)
10500     {
10501     case RECORD_TYPE:
10502     case UNION_TYPE:
10503     case ENUMERAL_TYPE:
10504       return tsubst_aggr_type (t, args, complain, in_decl,
10505                                /*entering_scope=*/0);
10506
10507     case ERROR_MARK:
10508     case IDENTIFIER_NODE:
10509     case VOID_TYPE:
10510     case REAL_TYPE:
10511     case COMPLEX_TYPE:
10512     case VECTOR_TYPE:
10513     case BOOLEAN_TYPE:
10514     case NULLPTR_TYPE:
10515     case LANG_TYPE:
10516       return t;
10517
10518     case INTEGER_TYPE:
10519       if (t == integer_type_node)
10520         return t;
10521
10522       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
10523           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
10524         return t;
10525
10526       {
10527         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
10528
10529         max = tsubst_expr (omax, args, complain, in_decl,
10530                            /*integral_constant_expression_p=*/false);
10531
10532         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
10533            needed.  */
10534         if (TREE_CODE (max) == NOP_EXPR
10535             && TREE_SIDE_EFFECTS (omax)
10536             && !TREE_TYPE (max))
10537           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
10538
10539         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
10540            with TREE_SIDE_EFFECTS that indicates this is not an integral
10541            constant expression.  */
10542         if (processing_template_decl
10543             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
10544           {
10545             gcc_assert (TREE_CODE (max) == NOP_EXPR);
10546             TREE_SIDE_EFFECTS (max) = 1;
10547           }
10548
10549         return compute_array_index_type (NULL_TREE, max, complain);
10550       }
10551
10552     case TEMPLATE_TYPE_PARM:
10553     case TEMPLATE_TEMPLATE_PARM:
10554     case BOUND_TEMPLATE_TEMPLATE_PARM:
10555     case TEMPLATE_PARM_INDEX:
10556       {
10557         int idx;
10558         int level;
10559         int levels;
10560         tree arg = NULL_TREE;
10561
10562         r = NULL_TREE;
10563
10564         gcc_assert (TREE_VEC_LENGTH (args) > 0);
10565         template_parm_level_and_index (t, &level, &idx); 
10566
10567         levels = TMPL_ARGS_DEPTH (args);
10568         if (level <= levels)
10569           {
10570             arg = TMPL_ARG (args, level, idx);
10571
10572             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
10573               /* See through ARGUMENT_PACK_SELECT arguments. */
10574               arg = ARGUMENT_PACK_SELECT_ARG (arg);
10575           }
10576
10577         if (arg == error_mark_node)
10578           return error_mark_node;
10579         else if (arg != NULL_TREE)
10580           {
10581             if (ARGUMENT_PACK_P (arg))
10582               /* If ARG is an argument pack, we don't actually want to
10583                  perform a substitution here, because substitutions
10584                  for argument packs are only done
10585                  element-by-element. We can get to this point when
10586                  substituting the type of a non-type template
10587                  parameter pack, when that type actually contains
10588                  template parameter packs from an outer template, e.g.,
10589
10590                  template<typename... Types> struct A {
10591                    template<Types... Values> struct B { };
10592                  };  */
10593               return t;
10594
10595             if (code == TEMPLATE_TYPE_PARM)
10596               {
10597                 int quals;
10598                 gcc_assert (TYPE_P (arg));
10599
10600                 quals = cp_type_quals (arg) | cp_type_quals (t);
10601                   
10602                 return cp_build_qualified_type_real
10603                   (arg, quals, complain | tf_ignore_bad_quals);
10604               }
10605             else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
10606               {
10607                 /* We are processing a type constructed from a
10608                    template template parameter.  */
10609                 tree argvec = tsubst (TYPE_TI_ARGS (t),
10610                                       args, complain, in_decl);
10611                 if (argvec == error_mark_node)
10612                   return error_mark_node;
10613
10614                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
10615                    are resolving nested-types in the signature of a
10616                    member function templates.  Otherwise ARG is a
10617                    TEMPLATE_DECL and is the real template to be
10618                    instantiated.  */
10619                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
10620                   arg = TYPE_NAME (arg);
10621
10622                 r = lookup_template_class (arg,
10623                                            argvec, in_decl,
10624                                            DECL_CONTEXT (arg),
10625                                             /*entering_scope=*/0,
10626                                            complain);
10627                 return cp_build_qualified_type_real
10628                   (r, cp_type_quals (t), complain);
10629               }
10630             else
10631               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
10632               return unshare_expr (arg);
10633           }
10634
10635         if (level == 1)
10636           /* This can happen during the attempted tsubst'ing in
10637              unify.  This means that we don't yet have any information
10638              about the template parameter in question.  */
10639           return t;
10640
10641         /* If we get here, we must have been looking at a parm for a
10642            more deeply nested template.  Make a new version of this
10643            template parameter, but with a lower level.  */
10644         switch (code)
10645           {
10646           case TEMPLATE_TYPE_PARM:
10647           case TEMPLATE_TEMPLATE_PARM:
10648           case BOUND_TEMPLATE_TEMPLATE_PARM:
10649             if (cp_type_quals (t))
10650               {
10651                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
10652                 r = cp_build_qualified_type_real
10653                   (r, cp_type_quals (t),
10654                    complain | (code == TEMPLATE_TYPE_PARM
10655                                ? tf_ignore_bad_quals : 0));
10656               }
10657             else
10658               {
10659                 r = copy_type (t);
10660                 TEMPLATE_TYPE_PARM_INDEX (r)
10661                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
10662                                                 r, levels, args, complain);
10663                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
10664                 TYPE_MAIN_VARIANT (r) = r;
10665                 TYPE_POINTER_TO (r) = NULL_TREE;
10666                 TYPE_REFERENCE_TO (r) = NULL_TREE;
10667
10668                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
10669                   /* We have reduced the level of the template
10670                      template parameter, but not the levels of its
10671                      template parameters, so canonical_type_parameter
10672                      will not be able to find the canonical template
10673                      template parameter for this level. Thus, we
10674                      require structural equality checking to compare
10675                      TEMPLATE_TEMPLATE_PARMs. */
10676                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10677                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
10678                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10679                 else
10680                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
10681
10682                 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
10683                   {
10684                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
10685                                           complain, in_decl);
10686                     if (argvec == error_mark_node)
10687                       return error_mark_node;
10688
10689                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
10690                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
10691                   }
10692               }
10693             break;
10694
10695           case TEMPLATE_PARM_INDEX:
10696             r = reduce_template_parm_level (t, type, levels, args, complain);
10697             break;
10698
10699           default:
10700             gcc_unreachable ();
10701           }
10702
10703         return r;
10704       }
10705
10706     case TREE_LIST:
10707       {
10708         tree purpose, value, chain;
10709
10710         if (t == void_list_node)
10711           return t;
10712
10713         purpose = TREE_PURPOSE (t);
10714         if (purpose)
10715           {
10716             purpose = tsubst (purpose, args, complain, in_decl);
10717             if (purpose == error_mark_node)
10718               return error_mark_node;
10719           }
10720         value = TREE_VALUE (t);
10721         if (value)
10722           {
10723             value = tsubst (value, args, complain, in_decl);
10724             if (value == error_mark_node)
10725               return error_mark_node;
10726           }
10727         chain = TREE_CHAIN (t);
10728         if (chain && chain != void_type_node)
10729           {
10730             chain = tsubst (chain, args, complain, in_decl);
10731             if (chain == error_mark_node)
10732               return error_mark_node;
10733           }
10734         if (purpose == TREE_PURPOSE (t)
10735             && value == TREE_VALUE (t)
10736             && chain == TREE_CHAIN (t))
10737           return t;
10738         return hash_tree_cons (purpose, value, chain);
10739       }
10740
10741     case TREE_BINFO:
10742       /* We should never be tsubsting a binfo.  */
10743       gcc_unreachable ();
10744
10745     case TREE_VEC:
10746       /* A vector of template arguments.  */
10747       gcc_assert (!type);
10748       return tsubst_template_args (t, args, complain, in_decl);
10749
10750     case POINTER_TYPE:
10751     case REFERENCE_TYPE:
10752       {
10753         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
10754           return t;
10755
10756         /* [temp.deduct]
10757
10758            Type deduction may fail for any of the following
10759            reasons:
10760
10761            -- Attempting to create a pointer to reference type.
10762            -- Attempting to create a reference to a reference type or
10763               a reference to void.
10764
10765           Core issue 106 says that creating a reference to a reference
10766           during instantiation is no longer a cause for failure. We
10767           only enforce this check in strict C++98 mode.  */
10768         if ((TREE_CODE (type) == REFERENCE_TYPE
10769              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
10770             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
10771           {
10772             static location_t last_loc;
10773
10774             /* We keep track of the last time we issued this error
10775                message to avoid spewing a ton of messages during a
10776                single bad template instantiation.  */
10777             if (complain & tf_error
10778                 && last_loc != input_location)
10779               {
10780                 if (TREE_CODE (type) == VOID_TYPE)
10781                   error ("forming reference to void");
10782                else if (code == POINTER_TYPE)
10783                  error ("forming pointer to reference type %qT", type);
10784                else
10785                   error ("forming reference to reference type %qT", type);
10786                 last_loc = input_location;
10787               }
10788
10789             return error_mark_node;
10790           }
10791         else if (code == POINTER_TYPE)
10792           {
10793             r = build_pointer_type (type);
10794             if (TREE_CODE (type) == METHOD_TYPE)
10795               r = build_ptrmemfunc_type (r);
10796           }
10797         else if (TREE_CODE (type) == REFERENCE_TYPE)
10798           /* In C++0x, during template argument substitution, when there is an
10799              attempt to create a reference to a reference type, reference
10800              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
10801
10802              "If a template-argument for a template-parameter T names a type
10803              that is a reference to a type A, an attempt to create the type
10804              'lvalue reference to cv T' creates the type 'lvalue reference to
10805              A,' while an attempt to create the type type rvalue reference to
10806              cv T' creates the type T"
10807           */
10808           r = cp_build_reference_type
10809               (TREE_TYPE (type),
10810                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
10811         else
10812           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
10813         r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
10814
10815         if (r != error_mark_node)
10816           /* Will this ever be needed for TYPE_..._TO values?  */
10817           layout_type (r);
10818
10819         return r;
10820       }
10821     case OFFSET_TYPE:
10822       {
10823         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
10824         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
10825           {
10826             /* [temp.deduct]
10827
10828                Type deduction may fail for any of the following
10829                reasons:
10830
10831                -- Attempting to create "pointer to member of T" when T
10832                   is not a class type.  */
10833             if (complain & tf_error)
10834               error ("creating pointer to member of non-class type %qT", r);
10835             return error_mark_node;
10836           }
10837         if (TREE_CODE (type) == REFERENCE_TYPE)
10838           {
10839             if (complain & tf_error)
10840               error ("creating pointer to member reference type %qT", type);
10841             return error_mark_node;
10842           }
10843         if (TREE_CODE (type) == VOID_TYPE)
10844           {
10845             if (complain & tf_error)
10846               error ("creating pointer to member of type void");
10847             return error_mark_node;
10848           }
10849         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
10850         if (TREE_CODE (type) == FUNCTION_TYPE)
10851           {
10852             /* The type of the implicit object parameter gets its
10853                cv-qualifiers from the FUNCTION_TYPE. */
10854             tree memptr;
10855             tree method_type = build_memfn_type (type, r, type_memfn_quals (type));
10856             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
10857             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
10858                                                  complain);
10859           }
10860         else
10861           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
10862                                                cp_type_quals (t),
10863                                                complain);
10864       }
10865     case FUNCTION_TYPE:
10866     case METHOD_TYPE:
10867       {
10868         tree fntype;
10869         tree specs;
10870         fntype = tsubst_function_type (t, args, complain, in_decl);
10871         if (fntype == error_mark_node)
10872           return error_mark_node;
10873
10874         /* Substitute the exception specification.  */
10875         specs = tsubst_exception_specification (t, args, complain,
10876                                                 in_decl);
10877         if (specs == error_mark_node)
10878           return error_mark_node;
10879         if (specs)
10880           fntype = build_exception_variant (fntype, specs);
10881         return fntype;
10882       }
10883     case ARRAY_TYPE:
10884       {
10885         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
10886         if (domain == error_mark_node)
10887           return error_mark_node;
10888
10889         /* As an optimization, we avoid regenerating the array type if
10890            it will obviously be the same as T.  */
10891         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
10892           return t;
10893
10894         /* These checks should match the ones in grokdeclarator.
10895
10896            [temp.deduct]
10897
10898            The deduction may fail for any of the following reasons:
10899
10900            -- Attempting to create an array with an element type that
10901               is void, a function type, or a reference type, or [DR337]
10902               an abstract class type.  */
10903         if (TREE_CODE (type) == VOID_TYPE
10904             || TREE_CODE (type) == FUNCTION_TYPE
10905             || TREE_CODE (type) == REFERENCE_TYPE)
10906           {
10907             if (complain & tf_error)
10908               error ("creating array of %qT", type);
10909             return error_mark_node;
10910           }
10911         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
10912           {
10913             if (complain & tf_error)
10914               error ("creating array of %qT, which is an abstract class type",
10915                      type);
10916             return error_mark_node;
10917           }
10918
10919         r = build_cplus_array_type (type, domain);
10920
10921         if (TYPE_USER_ALIGN (t))
10922           {
10923             TYPE_ALIGN (r) = TYPE_ALIGN (t);
10924             TYPE_USER_ALIGN (r) = 1;
10925           }
10926
10927         return r;
10928       }
10929
10930     case TYPENAME_TYPE:
10931       {
10932         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10933                                      in_decl, /*entering_scope=*/1);
10934         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
10935                               complain, in_decl);
10936
10937         if (ctx == error_mark_node || f == error_mark_node)
10938           return error_mark_node;
10939
10940         if (!MAYBE_CLASS_TYPE_P (ctx))
10941           {
10942             if (complain & tf_error)
10943               error ("%qT is not a class, struct, or union type", ctx);
10944             return error_mark_node;
10945           }
10946         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
10947           {
10948             /* Normally, make_typename_type does not require that the CTX
10949                have complete type in order to allow things like:
10950
10951                  template <class T> struct S { typename S<T>::X Y; };
10952
10953                But, such constructs have already been resolved by this
10954                point, so here CTX really should have complete type, unless
10955                it's a partial instantiation.  */
10956             ctx = complete_type (ctx);
10957             if (!COMPLETE_TYPE_P (ctx))
10958               {
10959                 if (complain & tf_error)
10960                   cxx_incomplete_type_error (NULL_TREE, ctx);
10961                 return error_mark_node;
10962               }
10963           }
10964
10965         f = make_typename_type (ctx, f, typename_type,
10966                                 (complain & tf_error) | tf_keep_type_decl);
10967         if (f == error_mark_node)
10968           return f;
10969         if (TREE_CODE (f) == TYPE_DECL)
10970           {
10971             complain |= tf_ignore_bad_quals;
10972             f = TREE_TYPE (f);
10973           }
10974
10975         if (TREE_CODE (f) != TYPENAME_TYPE)
10976           {
10977             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
10978               {
10979                 if (complain & tf_error)
10980                   error ("%qT resolves to %qT, which is not an enumeration type",
10981                          t, f);
10982                 else
10983                   return error_mark_node;
10984               }
10985             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
10986               {
10987                 if (complain & tf_error)
10988                   error ("%qT resolves to %qT, which is is not a class type",
10989                          t, f);
10990                 else
10991                   return error_mark_node;
10992               }
10993           }
10994
10995         return cp_build_qualified_type_real
10996           (f, cp_type_quals (f) | cp_type_quals (t), complain);
10997       }
10998
10999     case UNBOUND_CLASS_TEMPLATE:
11000       {
11001         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
11002                                      in_decl, /*entering_scope=*/1);
11003         tree name = TYPE_IDENTIFIER (t);
11004         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
11005
11006         if (ctx == error_mark_node || name == error_mark_node)
11007           return error_mark_node;
11008
11009         if (parm_list)
11010           parm_list = tsubst_template_parms (parm_list, args, complain);
11011         return make_unbound_class_template (ctx, name, parm_list, complain);
11012       }
11013
11014     case TYPEOF_TYPE:
11015       {
11016         tree type;
11017
11018         ++cp_unevaluated_operand;
11019         ++c_inhibit_evaluation_warnings;
11020
11021         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
11022                             complain, in_decl,
11023                             /*integral_constant_expression_p=*/false);
11024
11025         --cp_unevaluated_operand;
11026         --c_inhibit_evaluation_warnings;
11027
11028         type = finish_typeof (type);
11029         return cp_build_qualified_type_real (type,
11030                                              cp_type_quals (t)
11031                                              | cp_type_quals (type),
11032                                              complain);
11033       }
11034
11035     case DECLTYPE_TYPE:
11036       {
11037         tree type;
11038
11039         ++cp_unevaluated_operand;
11040         ++c_inhibit_evaluation_warnings;
11041
11042         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
11043                             complain, in_decl,
11044                             /*integral_constant_expression_p=*/false);
11045
11046         --cp_unevaluated_operand;
11047         --c_inhibit_evaluation_warnings;
11048
11049         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
11050           type = lambda_capture_field_type (type);
11051         else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
11052           type = lambda_return_type (type);
11053         else
11054           type = finish_decltype_type
11055             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t), complain);
11056         return cp_build_qualified_type_real (type,
11057                                              cp_type_quals (t)
11058                                              | cp_type_quals (type),
11059                                              complain);
11060       }
11061
11062     case UNDERLYING_TYPE:
11063       {
11064         tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
11065                             complain, in_decl);
11066         return finish_underlying_type (type);
11067       }
11068
11069     case TYPE_ARGUMENT_PACK:
11070     case NONTYPE_ARGUMENT_PACK:
11071       {
11072         tree r = TYPE_P (t) ? cxx_make_type (code) : make_node (code);
11073         tree packed_out = 
11074           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
11075                                 args,
11076                                 complain,
11077                                 in_decl);
11078         SET_ARGUMENT_PACK_ARGS (r, packed_out);
11079
11080         /* For template nontype argument packs, also substitute into
11081            the type.  */
11082         if (code == NONTYPE_ARGUMENT_PACK)
11083           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
11084
11085         return r;
11086       }
11087       break;
11088
11089     case INTEGER_CST:
11090     case REAL_CST:
11091     case STRING_CST:
11092     case PLUS_EXPR:
11093     case MINUS_EXPR:
11094     case NEGATE_EXPR:
11095     case NOP_EXPR:
11096     case INDIRECT_REF:
11097     case ADDR_EXPR:
11098     case CALL_EXPR:
11099     case ARRAY_REF:
11100     case SCOPE_REF:
11101       /* We should use one of the expression tsubsts for these codes.  */
11102       gcc_unreachable ();
11103
11104     default:
11105       sorry ("use of %qs in template", tree_code_name [(int) code]);
11106       return error_mark_node;
11107     }
11108 }
11109
11110 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
11111    type of the expression on the left-hand side of the "." or "->"
11112    operator.  */
11113
11114 static tree
11115 tsubst_baselink (tree baselink, tree object_type,
11116                  tree args, tsubst_flags_t complain, tree in_decl)
11117 {
11118     tree name;
11119     tree qualifying_scope;
11120     tree fns;
11121     tree optype;
11122     tree template_args = 0;
11123     bool template_id_p = false;
11124
11125     /* A baselink indicates a function from a base class.  Both the
11126        BASELINK_ACCESS_BINFO and the base class referenced may
11127        indicate bases of the template class, rather than the
11128        instantiated class.  In addition, lookups that were not
11129        ambiguous before may be ambiguous now.  Therefore, we perform
11130        the lookup again.  */
11131     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
11132     qualifying_scope = tsubst (qualifying_scope, args,
11133                                complain, in_decl);
11134     fns = BASELINK_FUNCTIONS (baselink);
11135     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
11136     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
11137       {
11138         template_id_p = true;
11139         template_args = TREE_OPERAND (fns, 1);
11140         fns = TREE_OPERAND (fns, 0);
11141         if (template_args)
11142           template_args = tsubst_template_args (template_args, args,
11143                                                 complain, in_decl);
11144       }
11145     name = DECL_NAME (get_first_fn (fns));
11146     if (IDENTIFIER_TYPENAME_P (name))
11147       name = mangle_conv_op_name_for_type (optype);
11148     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
11149     if (!baselink)
11150       return error_mark_node;
11151
11152     /* If lookup found a single function, mark it as used at this
11153        point.  (If it lookup found multiple functions the one selected
11154        later by overload resolution will be marked as used at that
11155        point.)  */
11156     if (BASELINK_P (baselink))
11157       fns = BASELINK_FUNCTIONS (baselink);
11158     if (!template_id_p && !really_overloaded_fn (fns))
11159       mark_used (OVL_CURRENT (fns));
11160
11161     /* Add back the template arguments, if present.  */
11162     if (BASELINK_P (baselink) && template_id_p)
11163       BASELINK_FUNCTIONS (baselink)
11164         = build_nt (TEMPLATE_ID_EXPR,
11165                     BASELINK_FUNCTIONS (baselink),
11166                     template_args);
11167     /* Update the conversion operator type.  */
11168     BASELINK_OPTYPE (baselink) = optype;
11169
11170     if (!object_type)
11171       object_type = current_class_type;
11172     return adjust_result_of_qualified_name_lookup (baselink,
11173                                                    qualifying_scope,
11174                                                    object_type);
11175 }
11176
11177 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
11178    true if the qualified-id will be a postfix-expression in-and-of
11179    itself; false if more of the postfix-expression follows the
11180    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
11181    of "&".  */
11182
11183 static tree
11184 tsubst_qualified_id (tree qualified_id, tree args,
11185                      tsubst_flags_t complain, tree in_decl,
11186                      bool done, bool address_p)
11187 {
11188   tree expr;
11189   tree scope;
11190   tree name;
11191   bool is_template;
11192   tree template_args;
11193
11194   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
11195
11196   /* Figure out what name to look up.  */
11197   name = TREE_OPERAND (qualified_id, 1);
11198   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
11199     {
11200       is_template = true;
11201       template_args = TREE_OPERAND (name, 1);
11202       if (template_args)
11203         template_args = tsubst_template_args (template_args, args,
11204                                               complain, in_decl);
11205       name = TREE_OPERAND (name, 0);
11206     }
11207   else
11208     {
11209       is_template = false;
11210       template_args = NULL_TREE;
11211     }
11212
11213   /* Substitute into the qualifying scope.  When there are no ARGS, we
11214      are just trying to simplify a non-dependent expression.  In that
11215      case the qualifying scope may be dependent, and, in any case,
11216      substituting will not help.  */
11217   scope = TREE_OPERAND (qualified_id, 0);
11218   if (args)
11219     {
11220       scope = tsubst (scope, args, complain, in_decl);
11221       expr = tsubst_copy (name, args, complain, in_decl);
11222     }
11223   else
11224     expr = name;
11225
11226   if (dependent_scope_p (scope))
11227     return build_qualified_name (NULL_TREE, scope, expr,
11228                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
11229
11230   if (!BASELINK_P (name) && !DECL_P (expr))
11231     {
11232       if (TREE_CODE (expr) == BIT_NOT_EXPR)
11233         {
11234           /* A BIT_NOT_EXPR is used to represent a destructor.  */
11235           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
11236             {
11237               error ("qualifying type %qT does not match destructor name ~%qT",
11238                      scope, TREE_OPERAND (expr, 0));
11239               expr = error_mark_node;
11240             }
11241           else
11242             expr = lookup_qualified_name (scope, complete_dtor_identifier,
11243                                           /*is_type_p=*/0, false);
11244         }
11245       else
11246         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
11247       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
11248                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
11249         {
11250           if (complain & tf_error)
11251             {
11252               error ("dependent-name %qE is parsed as a non-type, but "
11253                      "instantiation yields a type", qualified_id);
11254               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
11255             }
11256           return error_mark_node;
11257         }
11258     }
11259
11260   if (DECL_P (expr))
11261     {
11262       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
11263                                            scope);
11264       /* Remember that there was a reference to this entity.  */
11265       mark_used (expr);
11266     }
11267
11268   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
11269     {
11270       if (complain & tf_error)
11271         qualified_name_lookup_error (scope,
11272                                      TREE_OPERAND (qualified_id, 1),
11273                                      expr, input_location);
11274       return error_mark_node;
11275     }
11276
11277   if (is_template)
11278     expr = lookup_template_function (expr, template_args);
11279
11280   if (expr == error_mark_node && complain & tf_error)
11281     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
11282                                  expr, input_location);
11283   else if (TYPE_P (scope))
11284     {
11285       expr = (adjust_result_of_qualified_name_lookup
11286               (expr, scope, current_class_type));
11287       expr = (finish_qualified_id_expr
11288               (scope, expr, done, address_p,
11289                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
11290                /*template_arg_p=*/false));
11291     }
11292
11293   /* Expressions do not generally have reference type.  */
11294   if (TREE_CODE (expr) != SCOPE_REF
11295       /* However, if we're about to form a pointer-to-member, we just
11296          want the referenced member referenced.  */
11297       && TREE_CODE (expr) != OFFSET_REF)
11298     expr = convert_from_reference (expr);
11299
11300   return expr;
11301 }
11302
11303 /* Like tsubst, but deals with expressions.  This function just replaces
11304    template parms; to finish processing the resultant expression, use
11305    tsubst_expr.  */
11306
11307 static tree
11308 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11309 {
11310   enum tree_code code;
11311   tree r;
11312
11313   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
11314     return t;
11315
11316   code = TREE_CODE (t);
11317
11318   switch (code)
11319     {
11320     case PARM_DECL:
11321       r = retrieve_local_specialization (t);
11322
11323       if (r == NULL)
11324         {
11325           tree c;
11326           /* This can happen for a parameter name used later in a function
11327              declaration (such as in a late-specified return type).  Just
11328              make a dummy decl, since it's only used for its type.  */
11329           gcc_assert (cp_unevaluated_operand != 0);
11330           /* We copy T because want to tsubst the PARM_DECL only,
11331              not the following PARM_DECLs that are chained to T.  */
11332           c = copy_node (t);
11333           r = tsubst_decl (c, args, complain);
11334           /* Give it the template pattern as its context; its true context
11335              hasn't been instantiated yet and this is good enough for
11336              mangling.  */
11337           DECL_CONTEXT (r) = DECL_CONTEXT (t);
11338         }
11339       
11340       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
11341         r = ARGUMENT_PACK_SELECT_ARG (r);
11342       mark_used (r);
11343       return r;
11344
11345     case CONST_DECL:
11346       {
11347         tree enum_type;
11348         tree v;
11349
11350         if (DECL_TEMPLATE_PARM_P (t))
11351           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
11352         /* There is no need to substitute into namespace-scope
11353            enumerators.  */
11354         if (DECL_NAMESPACE_SCOPE_P (t))
11355           return t;
11356         /* If ARGS is NULL, then T is known to be non-dependent.  */
11357         if (args == NULL_TREE)
11358           return integral_constant_value (t);
11359
11360         /* Unfortunately, we cannot just call lookup_name here.
11361            Consider:
11362
11363              template <int I> int f() {
11364              enum E { a = I };
11365              struct S { void g() { E e = a; } };
11366              };
11367
11368            When we instantiate f<7>::S::g(), say, lookup_name is not
11369            clever enough to find f<7>::a.  */
11370         enum_type
11371           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
11372                               /*entering_scope=*/0);
11373
11374         for (v = TYPE_VALUES (enum_type);
11375              v != NULL_TREE;
11376              v = TREE_CHAIN (v))
11377           if (TREE_PURPOSE (v) == DECL_NAME (t))
11378             return TREE_VALUE (v);
11379
11380           /* We didn't find the name.  That should never happen; if
11381              name-lookup found it during preliminary parsing, we
11382              should find it again here during instantiation.  */
11383         gcc_unreachable ();
11384       }
11385       return t;
11386
11387     case FIELD_DECL:
11388       if (DECL_CONTEXT (t))
11389         {
11390           tree ctx;
11391
11392           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
11393                                   /*entering_scope=*/1);
11394           if (ctx != DECL_CONTEXT (t))
11395             {
11396               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
11397               if (!r)
11398                 {
11399                   if (complain & tf_error)
11400                     error ("using invalid field %qD", t);
11401                   return error_mark_node;
11402                 }
11403               return r;
11404             }
11405         }
11406
11407       return t;
11408
11409     case VAR_DECL:
11410     case FUNCTION_DECL:
11411       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
11412           || local_variable_p (t))
11413         t = tsubst (t, args, complain, in_decl);
11414       mark_used (t);
11415       return t;
11416
11417     case OVERLOAD:
11418       /* An OVERLOAD will always be a non-dependent overload set; an
11419          overload set from function scope will just be represented with an
11420          IDENTIFIER_NODE, and from class scope with a BASELINK.  */
11421       gcc_assert (!uses_template_parms (t));
11422       return t;
11423
11424     case BASELINK:
11425       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
11426
11427     case TEMPLATE_DECL:
11428       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11429         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
11430                        args, complain, in_decl);
11431       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
11432         return tsubst (t, args, complain, in_decl);
11433       else if (DECL_CLASS_SCOPE_P (t)
11434                && uses_template_parms (DECL_CONTEXT (t)))
11435         {
11436           /* Template template argument like the following example need
11437              special treatment:
11438
11439                template <template <class> class TT> struct C {};
11440                template <class T> struct D {
11441                  template <class U> struct E {};
11442                  C<E> c;                                // #1
11443                };
11444                D<int> d;                                // #2
11445
11446              We are processing the template argument `E' in #1 for
11447              the template instantiation #2.  Originally, `E' is a
11448              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
11449              have to substitute this with one having context `D<int>'.  */
11450
11451           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
11452           return lookup_field (context, DECL_NAME(t), 0, false);
11453         }
11454       else
11455         /* Ordinary template template argument.  */
11456         return t;
11457
11458     case CAST_EXPR:
11459     case REINTERPRET_CAST_EXPR:
11460     case CONST_CAST_EXPR:
11461     case STATIC_CAST_EXPR:
11462     case DYNAMIC_CAST_EXPR:
11463     case NOP_EXPR:
11464       return build1
11465         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11466          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11467
11468     case SIZEOF_EXPR:
11469       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11470         {
11471
11472           tree expanded;
11473           int len = 0;
11474
11475           ++cp_unevaluated_operand;
11476           ++c_inhibit_evaluation_warnings;
11477           /* We only want to compute the number of arguments.  */
11478           expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
11479                                             complain, in_decl);
11480           --cp_unevaluated_operand;
11481           --c_inhibit_evaluation_warnings;
11482
11483           if (TREE_CODE (expanded) == TREE_VEC)
11484             len = TREE_VEC_LENGTH (expanded);
11485
11486           if (expanded == error_mark_node)
11487             return error_mark_node;
11488           else if (PACK_EXPANSION_P (expanded)
11489                    || (TREE_CODE (expanded) == TREE_VEC
11490                        && len > 0
11491                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
11492             {
11493               if (TREE_CODE (expanded) == TREE_VEC)
11494                 expanded = TREE_VEC_ELT (expanded, len - 1);
11495
11496               if (TYPE_P (expanded))
11497                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
11498                                                    complain & tf_error);
11499               else
11500                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
11501                                                    complain & tf_error);
11502             }
11503           else
11504             return build_int_cst (size_type_node, len);
11505         }
11506       /* Fall through */
11507
11508     case INDIRECT_REF:
11509     case NEGATE_EXPR:
11510     case TRUTH_NOT_EXPR:
11511     case BIT_NOT_EXPR:
11512     case ADDR_EXPR:
11513     case UNARY_PLUS_EXPR:      /* Unary + */
11514     case ALIGNOF_EXPR:
11515     case AT_ENCODE_EXPR:
11516     case ARROW_EXPR:
11517     case THROW_EXPR:
11518     case TYPEID_EXPR:
11519     case REALPART_EXPR:
11520     case IMAGPART_EXPR:
11521       return build1
11522         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11523          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11524
11525     case COMPONENT_REF:
11526       {
11527         tree object;
11528         tree name;
11529
11530         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
11531         name = TREE_OPERAND (t, 1);
11532         if (TREE_CODE (name) == BIT_NOT_EXPR)
11533           {
11534             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11535                                 complain, in_decl);
11536             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11537           }
11538         else if (TREE_CODE (name) == SCOPE_REF
11539                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
11540           {
11541             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
11542                                      complain, in_decl);
11543             name = TREE_OPERAND (name, 1);
11544             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11545                                 complain, in_decl);
11546             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11547             name = build_qualified_name (/*type=*/NULL_TREE,
11548                                          base, name,
11549                                          /*template_p=*/false);
11550           }
11551         else if (TREE_CODE (name) == BASELINK)
11552           name = tsubst_baselink (name,
11553                                   non_reference (TREE_TYPE (object)),
11554                                   args, complain,
11555                                   in_decl);
11556         else
11557           name = tsubst_copy (name, args, complain, in_decl);
11558         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
11559       }
11560
11561     case PLUS_EXPR:
11562     case MINUS_EXPR:
11563     case MULT_EXPR:
11564     case TRUNC_DIV_EXPR:
11565     case CEIL_DIV_EXPR:
11566     case FLOOR_DIV_EXPR:
11567     case ROUND_DIV_EXPR:
11568     case EXACT_DIV_EXPR:
11569     case BIT_AND_EXPR:
11570     case BIT_IOR_EXPR:
11571     case BIT_XOR_EXPR:
11572     case TRUNC_MOD_EXPR:
11573     case FLOOR_MOD_EXPR:
11574     case TRUTH_ANDIF_EXPR:
11575     case TRUTH_ORIF_EXPR:
11576     case TRUTH_AND_EXPR:
11577     case TRUTH_OR_EXPR:
11578     case RSHIFT_EXPR:
11579     case LSHIFT_EXPR:
11580     case RROTATE_EXPR:
11581     case LROTATE_EXPR:
11582     case EQ_EXPR:
11583     case NE_EXPR:
11584     case MAX_EXPR:
11585     case MIN_EXPR:
11586     case LE_EXPR:
11587     case GE_EXPR:
11588     case LT_EXPR:
11589     case GT_EXPR:
11590     case COMPOUND_EXPR:
11591     case DOTSTAR_EXPR:
11592     case MEMBER_REF:
11593     case PREDECREMENT_EXPR:
11594     case PREINCREMENT_EXPR:
11595     case POSTDECREMENT_EXPR:
11596     case POSTINCREMENT_EXPR:
11597       return build_nt
11598         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11599          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11600
11601     case SCOPE_REF:
11602       return build_qualified_name (/*type=*/NULL_TREE,
11603                                    tsubst_copy (TREE_OPERAND (t, 0),
11604                                                 args, complain, in_decl),
11605                                    tsubst_copy (TREE_OPERAND (t, 1),
11606                                                 args, complain, in_decl),
11607                                    QUALIFIED_NAME_IS_TEMPLATE (t));
11608
11609     case ARRAY_REF:
11610       return build_nt
11611         (ARRAY_REF,
11612          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11613          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11614          NULL_TREE, NULL_TREE);
11615
11616     case CALL_EXPR:
11617       {
11618         int n = VL_EXP_OPERAND_LENGTH (t);
11619         tree result = build_vl_exp (CALL_EXPR, n);
11620         int i;
11621         for (i = 0; i < n; i++)
11622           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
11623                                              complain, in_decl);
11624         return result;
11625       }
11626
11627     case COND_EXPR:
11628     case MODOP_EXPR:
11629     case PSEUDO_DTOR_EXPR:
11630       {
11631         r = build_nt
11632           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11633            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11634            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11635         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11636         return r;
11637       }
11638
11639     case NEW_EXPR:
11640       {
11641         r = build_nt
11642         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11643          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11644          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11645         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
11646         return r;
11647       }
11648
11649     case DELETE_EXPR:
11650       {
11651         r = build_nt
11652         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11653          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11654         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
11655         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
11656         return r;
11657       }
11658
11659     case TEMPLATE_ID_EXPR:
11660       {
11661         /* Substituted template arguments */
11662         tree fn = TREE_OPERAND (t, 0);
11663         tree targs = TREE_OPERAND (t, 1);
11664
11665         fn = tsubst_copy (fn, args, complain, in_decl);
11666         if (targs)
11667           targs = tsubst_template_args (targs, args, complain, in_decl);
11668
11669         return lookup_template_function (fn, targs);
11670       }
11671
11672     case TREE_LIST:
11673       {
11674         tree purpose, value, chain;
11675
11676         if (t == void_list_node)
11677           return t;
11678
11679         purpose = TREE_PURPOSE (t);
11680         if (purpose)
11681           purpose = tsubst_copy (purpose, args, complain, in_decl);
11682         value = TREE_VALUE (t);
11683         if (value)
11684           value = tsubst_copy (value, args, complain, in_decl);
11685         chain = TREE_CHAIN (t);
11686         if (chain && chain != void_type_node)
11687           chain = tsubst_copy (chain, args, complain, in_decl);
11688         if (purpose == TREE_PURPOSE (t)
11689             && value == TREE_VALUE (t)
11690             && chain == TREE_CHAIN (t))
11691           return t;
11692         return tree_cons (purpose, value, chain);
11693       }
11694
11695     case RECORD_TYPE:
11696     case UNION_TYPE:
11697     case ENUMERAL_TYPE:
11698     case INTEGER_TYPE:
11699     case TEMPLATE_TYPE_PARM:
11700     case TEMPLATE_TEMPLATE_PARM:
11701     case BOUND_TEMPLATE_TEMPLATE_PARM:
11702     case TEMPLATE_PARM_INDEX:
11703     case POINTER_TYPE:
11704     case REFERENCE_TYPE:
11705     case OFFSET_TYPE:
11706     case FUNCTION_TYPE:
11707     case METHOD_TYPE:
11708     case ARRAY_TYPE:
11709     case TYPENAME_TYPE:
11710     case UNBOUND_CLASS_TEMPLATE:
11711     case TYPEOF_TYPE:
11712     case DECLTYPE_TYPE:
11713     case TYPE_DECL:
11714       return tsubst (t, args, complain, in_decl);
11715
11716     case IDENTIFIER_NODE:
11717       if (IDENTIFIER_TYPENAME_P (t))
11718         {
11719           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11720           return mangle_conv_op_name_for_type (new_type);
11721         }
11722       else
11723         return t;
11724
11725     case CONSTRUCTOR:
11726       /* This is handled by tsubst_copy_and_build.  */
11727       gcc_unreachable ();
11728
11729     case VA_ARG_EXPR:
11730       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
11731                                           in_decl),
11732                              tsubst (TREE_TYPE (t), args, complain, in_decl));
11733
11734     case CLEANUP_POINT_EXPR:
11735       /* We shouldn't have built any of these during initial template
11736          generation.  Instead, they should be built during instantiation
11737          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
11738       gcc_unreachable ();
11739
11740     case OFFSET_REF:
11741       r = build2
11742         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11743          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11744          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11745       PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
11746       mark_used (TREE_OPERAND (r, 1));
11747       return r;
11748
11749     case EXPR_PACK_EXPANSION:
11750       error ("invalid use of pack expansion expression");
11751       return error_mark_node;
11752
11753     case NONTYPE_ARGUMENT_PACK:
11754       error ("use %<...%> to expand argument pack");
11755       return error_mark_node;
11756
11757     case INTEGER_CST:
11758     case REAL_CST:
11759     case STRING_CST:
11760     case COMPLEX_CST:
11761       {
11762         /* Instantiate any typedefs in the type.  */
11763         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11764         r = fold_convert (type, t);
11765         gcc_assert (TREE_CODE (r) == code);
11766         return r;
11767       }
11768
11769     case PTRMEM_CST:
11770       /* These can sometimes show up in a partial instantiation, but never
11771          involve template parms.  */
11772       gcc_assert (!uses_template_parms (t));
11773       return t;
11774
11775     default:
11776       /* We shouldn't get here, but keep going if !ENABLE_CHECKING.  */
11777       gcc_checking_assert (false);
11778       return t;
11779     }
11780 }
11781
11782 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
11783
11784 static tree
11785 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
11786                     tree in_decl)
11787 {
11788   tree new_clauses = NULL, nc, oc;
11789
11790   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
11791     {
11792       nc = copy_node (oc);
11793       OMP_CLAUSE_CHAIN (nc) = new_clauses;
11794       new_clauses = nc;
11795
11796       switch (OMP_CLAUSE_CODE (nc))
11797         {
11798         case OMP_CLAUSE_LASTPRIVATE:
11799           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
11800             {
11801               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
11802               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
11803                            in_decl, /*integral_constant_expression_p=*/false);
11804               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
11805                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
11806             }
11807           /* FALLTHRU */
11808         case OMP_CLAUSE_PRIVATE:
11809         case OMP_CLAUSE_SHARED:
11810         case OMP_CLAUSE_FIRSTPRIVATE:
11811         case OMP_CLAUSE_REDUCTION:
11812         case OMP_CLAUSE_COPYIN:
11813         case OMP_CLAUSE_COPYPRIVATE:
11814         case OMP_CLAUSE_IF:
11815         case OMP_CLAUSE_NUM_THREADS:
11816         case OMP_CLAUSE_SCHEDULE:
11817         case OMP_CLAUSE_COLLAPSE:
11818           OMP_CLAUSE_OPERAND (nc, 0)
11819             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
11820                            in_decl, /*integral_constant_expression_p=*/false);
11821           break;
11822         case OMP_CLAUSE_NOWAIT:
11823         case OMP_CLAUSE_ORDERED:
11824         case OMP_CLAUSE_DEFAULT:
11825         case OMP_CLAUSE_UNTIED:
11826           break;
11827         default:
11828           gcc_unreachable ();
11829         }
11830     }
11831
11832   return finish_omp_clauses (nreverse (new_clauses));
11833 }
11834
11835 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
11836
11837 static tree
11838 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
11839                           tree in_decl)
11840 {
11841 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
11842
11843   tree purpose, value, chain;
11844
11845   if (t == NULL)
11846     return t;
11847
11848   if (TREE_CODE (t) != TREE_LIST)
11849     return tsubst_copy_and_build (t, args, complain, in_decl,
11850                                   /*function_p=*/false,
11851                                   /*integral_constant_expression_p=*/false);
11852
11853   if (t == void_list_node)
11854     return t;
11855
11856   purpose = TREE_PURPOSE (t);
11857   if (purpose)
11858     purpose = RECUR (purpose);
11859   value = TREE_VALUE (t);
11860   if (value && TREE_CODE (value) != LABEL_DECL)
11861     value = RECUR (value);
11862   chain = TREE_CHAIN (t);
11863   if (chain && chain != void_type_node)
11864     chain = RECUR (chain);
11865   return tree_cons (purpose, value, chain);
11866 #undef RECUR
11867 }
11868
11869 /* Substitute one OMP_FOR iterator.  */
11870
11871 static void
11872 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
11873                          tree condv, tree incrv, tree *clauses,
11874                          tree args, tsubst_flags_t complain, tree in_decl,
11875                          bool integral_constant_expression_p)
11876 {
11877 #define RECUR(NODE)                             \
11878   tsubst_expr ((NODE), args, complain, in_decl, \
11879                integral_constant_expression_p)
11880   tree decl, init, cond, incr, auto_node;
11881
11882   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
11883   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
11884   decl = RECUR (TREE_OPERAND (init, 0));
11885   init = TREE_OPERAND (init, 1);
11886   auto_node = type_uses_auto (TREE_TYPE (decl));
11887   if (auto_node && init)
11888     {
11889       tree init_expr = init;
11890       if (TREE_CODE (init_expr) == DECL_EXPR)
11891         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
11892       init_expr = RECUR (init_expr);
11893       TREE_TYPE (decl)
11894         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
11895     }
11896   gcc_assert (!type_dependent_expression_p (decl));
11897
11898   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
11899     {
11900       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
11901       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11902       if (TREE_CODE (incr) == MODIFY_EXPR)
11903         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
11904                                     RECUR (TREE_OPERAND (incr, 1)),
11905                                     complain);
11906       else
11907         incr = RECUR (incr);
11908       TREE_VEC_ELT (declv, i) = decl;
11909       TREE_VEC_ELT (initv, i) = init;
11910       TREE_VEC_ELT (condv, i) = cond;
11911       TREE_VEC_ELT (incrv, i) = incr;
11912       return;
11913     }
11914
11915   if (init && TREE_CODE (init) != DECL_EXPR)
11916     {
11917       tree c;
11918       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
11919         {
11920           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
11921                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
11922               && OMP_CLAUSE_DECL (c) == decl)
11923             break;
11924           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
11925                    && OMP_CLAUSE_DECL (c) == decl)
11926             error ("iteration variable %qD should not be firstprivate", decl);
11927           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
11928                    && OMP_CLAUSE_DECL (c) == decl)
11929             error ("iteration variable %qD should not be reduction", decl);
11930         }
11931       if (c == NULL)
11932         {
11933           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
11934           OMP_CLAUSE_DECL (c) = decl;
11935           c = finish_omp_clauses (c);
11936           if (c)
11937             {
11938               OMP_CLAUSE_CHAIN (c) = *clauses;
11939               *clauses = c;
11940             }
11941         }
11942     }
11943   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
11944   if (COMPARISON_CLASS_P (cond))
11945     cond = build2 (TREE_CODE (cond), boolean_type_node,
11946                    RECUR (TREE_OPERAND (cond, 0)),
11947                    RECUR (TREE_OPERAND (cond, 1)));
11948   else
11949     cond = RECUR (cond);
11950   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11951   switch (TREE_CODE (incr))
11952     {
11953     case PREINCREMENT_EXPR:
11954     case PREDECREMENT_EXPR:
11955     case POSTINCREMENT_EXPR:
11956     case POSTDECREMENT_EXPR:
11957       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
11958                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
11959       break;
11960     case MODIFY_EXPR:
11961       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11962           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11963         {
11964           tree rhs = TREE_OPERAND (incr, 1);
11965           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11966                          RECUR (TREE_OPERAND (incr, 0)),
11967                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11968                                  RECUR (TREE_OPERAND (rhs, 0)),
11969                                  RECUR (TREE_OPERAND (rhs, 1))));
11970         }
11971       else
11972         incr = RECUR (incr);
11973       break;
11974     case MODOP_EXPR:
11975       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11976           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11977         {
11978           tree lhs = RECUR (TREE_OPERAND (incr, 0));
11979           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
11980                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
11981                                  TREE_TYPE (decl), lhs,
11982                                  RECUR (TREE_OPERAND (incr, 2))));
11983         }
11984       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
11985                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
11986                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
11987         {
11988           tree rhs = TREE_OPERAND (incr, 2);
11989           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11990                          RECUR (TREE_OPERAND (incr, 0)),
11991                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11992                                  RECUR (TREE_OPERAND (rhs, 0)),
11993                                  RECUR (TREE_OPERAND (rhs, 1))));
11994         }
11995       else
11996         incr = RECUR (incr);
11997       break;
11998     default:
11999       incr = RECUR (incr);
12000       break;
12001     }
12002
12003   TREE_VEC_ELT (declv, i) = decl;
12004   TREE_VEC_ELT (initv, i) = init;
12005   TREE_VEC_ELT (condv, i) = cond;
12006   TREE_VEC_ELT (incrv, i) = incr;
12007 #undef RECUR
12008 }
12009
12010 /* Like tsubst_copy for expressions, etc. but also does semantic
12011    processing.  */
12012
12013 static tree
12014 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
12015              bool integral_constant_expression_p)
12016 {
12017 #define RECUR(NODE)                             \
12018   tsubst_expr ((NODE), args, complain, in_decl, \
12019                integral_constant_expression_p)
12020
12021   tree stmt, tmp;
12022
12023   if (t == NULL_TREE || t == error_mark_node)
12024     return t;
12025
12026   if (EXPR_HAS_LOCATION (t))
12027     input_location = EXPR_LOCATION (t);
12028   if (STATEMENT_CODE_P (TREE_CODE (t)))
12029     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
12030
12031   switch (TREE_CODE (t))
12032     {
12033     case STATEMENT_LIST:
12034       {
12035         tree_stmt_iterator i;
12036         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
12037           RECUR (tsi_stmt (i));
12038         break;
12039       }
12040
12041     case CTOR_INITIALIZER:
12042       finish_mem_initializers (tsubst_initializer_list
12043                                (TREE_OPERAND (t, 0), args));
12044       break;
12045
12046     case RETURN_EXPR:
12047       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
12048       break;
12049
12050     case EXPR_STMT:
12051       tmp = RECUR (EXPR_STMT_EXPR (t));
12052       if (EXPR_STMT_STMT_EXPR_RESULT (t))
12053         finish_stmt_expr_expr (tmp, cur_stmt_expr);
12054       else
12055         finish_expr_stmt (tmp);
12056       break;
12057
12058     case USING_STMT:
12059       do_using_directive (USING_STMT_NAMESPACE (t));
12060       break;
12061
12062     case DECL_EXPR:
12063       {
12064         tree decl, pattern_decl;
12065         tree init;
12066
12067         pattern_decl = decl = DECL_EXPR_DECL (t);
12068         if (TREE_CODE (decl) == LABEL_DECL)
12069           finish_label_decl (DECL_NAME (decl));
12070         else if (TREE_CODE (decl) == USING_DECL)
12071           {
12072             tree scope = USING_DECL_SCOPE (decl);
12073             tree name = DECL_NAME (decl);
12074             tree decl;
12075
12076             scope = tsubst (scope, args, complain, in_decl);
12077             decl = lookup_qualified_name (scope, name,
12078                                           /*is_type_p=*/false,
12079                                           /*complain=*/false);
12080             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
12081               qualified_name_lookup_error (scope, name, decl, input_location);
12082             else
12083               do_local_using_decl (decl, scope, name);
12084           }
12085         else
12086           {
12087             init = DECL_INITIAL (decl);
12088             decl = tsubst (decl, args, complain, in_decl);
12089             if (decl != error_mark_node)
12090               {
12091                 /* By marking the declaration as instantiated, we avoid
12092                    trying to instantiate it.  Since instantiate_decl can't
12093                    handle local variables, and since we've already done
12094                    all that needs to be done, that's the right thing to
12095                    do.  */
12096                 if (TREE_CODE (decl) == VAR_DECL)
12097                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12098                 if (TREE_CODE (decl) == VAR_DECL
12099                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
12100                   /* Anonymous aggregates are a special case.  */
12101                   finish_anon_union (decl);
12102                 else
12103                   {
12104                     int const_init = false;
12105                     maybe_push_decl (decl);
12106                     if (TREE_CODE (decl) == VAR_DECL
12107                         && DECL_PRETTY_FUNCTION_P (decl))
12108                       {
12109                         /* For __PRETTY_FUNCTION__ we have to adjust the
12110                            initializer.  */
12111                         const char *const name
12112                           = cxx_printable_name (current_function_decl, 2);
12113                         init = cp_fname_init (name, &TREE_TYPE (decl));
12114                       }
12115                     else
12116                       {
12117                         tree t = RECUR (init);
12118
12119                         if (init && !t)
12120                           {
12121                             /* If we had an initializer but it
12122                                instantiated to nothing,
12123                                value-initialize the object.  This will
12124                                only occur when the initializer was a
12125                                pack expansion where the parameter packs
12126                                used in that expansion were of length
12127                                zero.  */
12128                             init = build_value_init (TREE_TYPE (decl),
12129                                                      complain);
12130                             if (TREE_CODE (init) == AGGR_INIT_EXPR)
12131                               init = get_target_expr_sfinae (init, complain);
12132                           }
12133                         else
12134                           init = t;
12135                       }
12136
12137                     if (TREE_CODE (decl) == VAR_DECL)
12138                       const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
12139                                     (pattern_decl));
12140                     cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
12141                   }
12142               }
12143           }
12144
12145         /* A DECL_EXPR can also be used as an expression, in the condition
12146            clause of an if/for/while construct.  */
12147         return decl;
12148       }
12149
12150     case FOR_STMT:
12151       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12152       RECUR (FOR_INIT_STMT (t));
12153       finish_for_init_stmt (stmt);
12154       tmp = RECUR (FOR_COND (t));
12155       finish_for_cond (tmp, stmt);
12156       tmp = RECUR (FOR_EXPR (t));
12157       finish_for_expr (tmp, stmt);
12158       RECUR (FOR_BODY (t));
12159       finish_for_stmt (stmt);
12160       break;
12161
12162     case RANGE_FOR_STMT:
12163       {
12164         tree decl, expr;
12165         stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12166         decl = RANGE_FOR_DECL (t);
12167         decl = tsubst (decl, args, complain, in_decl);
12168         maybe_push_decl (decl);
12169         expr = RECUR (RANGE_FOR_EXPR (t));
12170         stmt = cp_convert_range_for (stmt, decl, expr);
12171         RECUR (RANGE_FOR_BODY (t));
12172         finish_for_stmt (stmt);
12173       }
12174       break;
12175
12176     case WHILE_STMT:
12177       stmt = begin_while_stmt ();
12178       tmp = RECUR (WHILE_COND (t));
12179       finish_while_stmt_cond (tmp, stmt);
12180       RECUR (WHILE_BODY (t));
12181       finish_while_stmt (stmt);
12182       break;
12183
12184     case DO_STMT:
12185       stmt = begin_do_stmt ();
12186       RECUR (DO_BODY (t));
12187       finish_do_body (stmt);
12188       tmp = RECUR (DO_COND (t));
12189       finish_do_stmt (tmp, stmt);
12190       break;
12191
12192     case IF_STMT:
12193       stmt = begin_if_stmt ();
12194       tmp = RECUR (IF_COND (t));
12195       finish_if_stmt_cond (tmp, stmt);
12196       RECUR (THEN_CLAUSE (t));
12197       finish_then_clause (stmt);
12198
12199       if (ELSE_CLAUSE (t))
12200         {
12201           begin_else_clause (stmt);
12202           RECUR (ELSE_CLAUSE (t));
12203           finish_else_clause (stmt);
12204         }
12205
12206       finish_if_stmt (stmt);
12207       break;
12208
12209     case BIND_EXPR:
12210       if (BIND_EXPR_BODY_BLOCK (t))
12211         stmt = begin_function_body ();
12212       else
12213         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
12214                                     ? BCS_TRY_BLOCK : 0);
12215
12216       RECUR (BIND_EXPR_BODY (t));
12217
12218       if (BIND_EXPR_BODY_BLOCK (t))
12219         finish_function_body (stmt);
12220       else
12221         finish_compound_stmt (stmt);
12222       break;
12223
12224     case BREAK_STMT:
12225       finish_break_stmt ();
12226       break;
12227
12228     case CONTINUE_STMT:
12229       finish_continue_stmt ();
12230       break;
12231
12232     case SWITCH_STMT:
12233       stmt = begin_switch_stmt ();
12234       tmp = RECUR (SWITCH_STMT_COND (t));
12235       finish_switch_cond (tmp, stmt);
12236       RECUR (SWITCH_STMT_BODY (t));
12237       finish_switch_stmt (stmt);
12238       break;
12239
12240     case CASE_LABEL_EXPR:
12241       finish_case_label (EXPR_LOCATION (t),
12242                          RECUR (CASE_LOW (t)),
12243                          RECUR (CASE_HIGH (t)));
12244       break;
12245
12246     case LABEL_EXPR:
12247       {
12248         tree decl = LABEL_EXPR_LABEL (t);
12249         tree label;
12250
12251         label = finish_label_stmt (DECL_NAME (decl));
12252         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
12253           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
12254       }
12255       break;
12256
12257     case GOTO_EXPR:
12258       tmp = GOTO_DESTINATION (t);
12259       if (TREE_CODE (tmp) != LABEL_DECL)
12260         /* Computed goto's must be tsubst'd into.  On the other hand,
12261            non-computed gotos must not be; the identifier in question
12262            will have no binding.  */
12263         tmp = RECUR (tmp);
12264       else
12265         tmp = DECL_NAME (tmp);
12266       finish_goto_stmt (tmp);
12267       break;
12268
12269     case ASM_EXPR:
12270       tmp = finish_asm_stmt
12271         (ASM_VOLATILE_P (t),
12272          RECUR (ASM_STRING (t)),
12273          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
12274          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
12275          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
12276          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
12277       {
12278         tree asm_expr = tmp;
12279         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
12280           asm_expr = TREE_OPERAND (asm_expr, 0);
12281         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
12282       }
12283       break;
12284
12285     case TRY_BLOCK:
12286       if (CLEANUP_P (t))
12287         {
12288           stmt = begin_try_block ();
12289           RECUR (TRY_STMTS (t));
12290           finish_cleanup_try_block (stmt);
12291           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
12292         }
12293       else
12294         {
12295           tree compound_stmt = NULL_TREE;
12296
12297           if (FN_TRY_BLOCK_P (t))
12298             stmt = begin_function_try_block (&compound_stmt);
12299           else
12300             stmt = begin_try_block ();
12301
12302           RECUR (TRY_STMTS (t));
12303
12304           if (FN_TRY_BLOCK_P (t))
12305             finish_function_try_block (stmt);
12306           else
12307             finish_try_block (stmt);
12308
12309           RECUR (TRY_HANDLERS (t));
12310           if (FN_TRY_BLOCK_P (t))
12311             finish_function_handler_sequence (stmt, compound_stmt);
12312           else
12313             finish_handler_sequence (stmt);
12314         }
12315       break;
12316
12317     case HANDLER:
12318       {
12319         tree decl = HANDLER_PARMS (t);
12320
12321         if (decl)
12322           {
12323             decl = tsubst (decl, args, complain, in_decl);
12324             /* Prevent instantiate_decl from trying to instantiate
12325                this variable.  We've already done all that needs to be
12326                done.  */
12327             if (decl != error_mark_node)
12328               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12329           }
12330         stmt = begin_handler ();
12331         finish_handler_parms (decl, stmt);
12332         RECUR (HANDLER_BODY (t));
12333         finish_handler (stmt);
12334       }
12335       break;
12336
12337     case TAG_DEFN:
12338       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12339       break;
12340
12341     case STATIC_ASSERT:
12342       {
12343         tree condition = 
12344           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
12345                        args,
12346                        complain, in_decl,
12347                        /*integral_constant_expression_p=*/true);
12348         finish_static_assert (condition,
12349                               STATIC_ASSERT_MESSAGE (t),
12350                               STATIC_ASSERT_SOURCE_LOCATION (t),
12351                               /*member_p=*/false);
12352       }
12353       break;
12354
12355     case OMP_PARALLEL:
12356       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
12357                                 args, complain, in_decl);
12358       stmt = begin_omp_parallel ();
12359       RECUR (OMP_PARALLEL_BODY (t));
12360       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
12361         = OMP_PARALLEL_COMBINED (t);
12362       break;
12363
12364     case OMP_TASK:
12365       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
12366                                 args, complain, in_decl);
12367       stmt = begin_omp_task ();
12368       RECUR (OMP_TASK_BODY (t));
12369       finish_omp_task (tmp, stmt);
12370       break;
12371
12372     case OMP_FOR:
12373       {
12374         tree clauses, body, pre_body;
12375         tree declv, initv, condv, incrv;
12376         int i;
12377
12378         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
12379                                       args, complain, in_decl);
12380         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12381         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12382         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12383         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12384
12385         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
12386           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
12387                                    &clauses, args, complain, in_decl,
12388                                    integral_constant_expression_p);
12389
12390         stmt = begin_omp_structured_block ();
12391
12392         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
12393           if (TREE_VEC_ELT (initv, i) == NULL
12394               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
12395             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
12396           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
12397             {
12398               tree init = RECUR (TREE_VEC_ELT (initv, i));
12399               gcc_assert (init == TREE_VEC_ELT (declv, i));
12400               TREE_VEC_ELT (initv, i) = NULL_TREE;
12401             }
12402           else
12403             {
12404               tree decl_expr = TREE_VEC_ELT (initv, i);
12405               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
12406               gcc_assert (init != NULL);
12407               TREE_VEC_ELT (initv, i) = RECUR (init);
12408               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
12409               RECUR (decl_expr);
12410               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
12411             }
12412
12413         pre_body = push_stmt_list ();
12414         RECUR (OMP_FOR_PRE_BODY (t));
12415         pre_body = pop_stmt_list (pre_body);
12416
12417         body = push_stmt_list ();
12418         RECUR (OMP_FOR_BODY (t));
12419         body = pop_stmt_list (body);
12420
12421         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
12422                             body, pre_body, clauses);
12423
12424         add_stmt (finish_omp_structured_block (stmt));
12425       }
12426       break;
12427
12428     case OMP_SECTIONS:
12429     case OMP_SINGLE:
12430       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
12431       stmt = push_stmt_list ();
12432       RECUR (OMP_BODY (t));
12433       stmt = pop_stmt_list (stmt);
12434
12435       t = copy_node (t);
12436       OMP_BODY (t) = stmt;
12437       OMP_CLAUSES (t) = tmp;
12438       add_stmt (t);
12439       break;
12440
12441     case OMP_SECTION:
12442     case OMP_CRITICAL:
12443     case OMP_MASTER:
12444     case OMP_ORDERED:
12445       stmt = push_stmt_list ();
12446       RECUR (OMP_BODY (t));
12447       stmt = pop_stmt_list (stmt);
12448
12449       t = copy_node (t);
12450       OMP_BODY (t) = stmt;
12451       add_stmt (t);
12452       break;
12453
12454     case OMP_ATOMIC:
12455       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
12456       {
12457         tree op1 = TREE_OPERAND (t, 1);
12458         tree lhs = RECUR (TREE_OPERAND (op1, 0));
12459         tree rhs = RECUR (TREE_OPERAND (op1, 1));
12460         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
12461       }
12462       break;
12463
12464     case EXPR_PACK_EXPANSION:
12465       error ("invalid use of pack expansion expression");
12466       return error_mark_node;
12467
12468     case NONTYPE_ARGUMENT_PACK:
12469       error ("use %<...%> to expand argument pack");
12470       return error_mark_node;
12471
12472     default:
12473       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
12474
12475       return tsubst_copy_and_build (t, args, complain, in_decl,
12476                                     /*function_p=*/false,
12477                                     integral_constant_expression_p);
12478     }
12479
12480   return NULL_TREE;
12481 #undef RECUR
12482 }
12483
12484 /* T is a postfix-expression that is not being used in a function
12485    call.  Return the substituted version of T.  */
12486
12487 static tree
12488 tsubst_non_call_postfix_expression (tree t, tree args,
12489                                     tsubst_flags_t complain,
12490                                     tree in_decl)
12491 {
12492   if (TREE_CODE (t) == SCOPE_REF)
12493     t = tsubst_qualified_id (t, args, complain, in_decl,
12494                              /*done=*/false, /*address_p=*/false);
12495   else
12496     t = tsubst_copy_and_build (t, args, complain, in_decl,
12497                                /*function_p=*/false,
12498                                /*integral_constant_expression_p=*/false);
12499
12500   return t;
12501 }
12502
12503 /* Like tsubst but deals with expressions and performs semantic
12504    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
12505
12506 tree
12507 tsubst_copy_and_build (tree t,
12508                        tree args,
12509                        tsubst_flags_t complain,
12510                        tree in_decl,
12511                        bool function_p,
12512                        bool integral_constant_expression_p)
12513 {
12514 #define RECUR(NODE)                                             \
12515   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
12516                          /*function_p=*/false,                  \
12517                          integral_constant_expression_p)
12518
12519   tree op1;
12520
12521   if (t == NULL_TREE || t == error_mark_node)
12522     return t;
12523
12524   switch (TREE_CODE (t))
12525     {
12526     case USING_DECL:
12527       t = DECL_NAME (t);
12528       /* Fall through.  */
12529     case IDENTIFIER_NODE:
12530       {
12531         tree decl;
12532         cp_id_kind idk;
12533         bool non_integral_constant_expression_p;
12534         const char *error_msg;
12535
12536         if (IDENTIFIER_TYPENAME_P (t))
12537           {
12538             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12539             t = mangle_conv_op_name_for_type (new_type);
12540           }
12541
12542         /* Look up the name.  */
12543         decl = lookup_name (t);
12544
12545         /* By convention, expressions use ERROR_MARK_NODE to indicate
12546            failure, not NULL_TREE.  */
12547         if (decl == NULL_TREE)
12548           decl = error_mark_node;
12549
12550         decl = finish_id_expression (t, decl, NULL_TREE,
12551                                      &idk,
12552                                      integral_constant_expression_p,
12553                                      /*allow_non_integral_constant_expression_p=*/false,
12554                                      &non_integral_constant_expression_p,
12555                                      /*template_p=*/false,
12556                                      /*done=*/true,
12557                                      /*address_p=*/false,
12558                                      /*template_arg_p=*/false,
12559                                      &error_msg,
12560                                      input_location);
12561         if (error_msg)
12562           error (error_msg);
12563         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
12564           decl = unqualified_name_lookup_error (decl);
12565         return decl;
12566       }
12567
12568     case TEMPLATE_ID_EXPR:
12569       {
12570         tree object;
12571         tree templ = RECUR (TREE_OPERAND (t, 0));
12572         tree targs = TREE_OPERAND (t, 1);
12573
12574         if (targs)
12575           targs = tsubst_template_args (targs, args, complain, in_decl);
12576
12577         if (TREE_CODE (templ) == COMPONENT_REF)
12578           {
12579             object = TREE_OPERAND (templ, 0);
12580             templ = TREE_OPERAND (templ, 1);
12581           }
12582         else
12583           object = NULL_TREE;
12584         templ = lookup_template_function (templ, targs);
12585
12586         if (object)
12587           return build3 (COMPONENT_REF, TREE_TYPE (templ),
12588                          object, templ, NULL_TREE);
12589         else
12590           return baselink_for_fns (templ);
12591       }
12592
12593     case INDIRECT_REF:
12594       {
12595         tree r = RECUR (TREE_OPERAND (t, 0));
12596
12597         if (REFERENCE_REF_P (t))
12598           {
12599             /* A type conversion to reference type will be enclosed in
12600                such an indirect ref, but the substitution of the cast
12601                will have also added such an indirect ref.  */
12602             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
12603               r = convert_from_reference (r);
12604           }
12605         else
12606           r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
12607         return r;
12608       }
12609
12610     case NOP_EXPR:
12611       return build_nop
12612         (tsubst (TREE_TYPE (t), args, complain, in_decl),
12613          RECUR (TREE_OPERAND (t, 0)));
12614
12615     case CAST_EXPR:
12616     case REINTERPRET_CAST_EXPR:
12617     case CONST_CAST_EXPR:
12618     case DYNAMIC_CAST_EXPR:
12619     case STATIC_CAST_EXPR:
12620       {
12621         tree type;
12622         tree op;
12623
12624         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12625         if (integral_constant_expression_p
12626             && !cast_valid_in_integral_constant_expression_p (type))
12627           {
12628             if (complain & tf_error)
12629               error ("a cast to a type other than an integral or "
12630                      "enumeration type cannot appear in a constant-expression");
12631             return error_mark_node; 
12632           }
12633
12634         op = RECUR (TREE_OPERAND (t, 0));
12635
12636         switch (TREE_CODE (t))
12637           {
12638           case CAST_EXPR:
12639             return build_functional_cast (type, op, complain);
12640           case REINTERPRET_CAST_EXPR:
12641             return build_reinterpret_cast (type, op, complain);
12642           case CONST_CAST_EXPR:
12643             return build_const_cast (type, op, complain);
12644           case DYNAMIC_CAST_EXPR:
12645             return build_dynamic_cast (type, op, complain);
12646           case STATIC_CAST_EXPR:
12647             return build_static_cast (type, op, complain);
12648           default:
12649             gcc_unreachable ();
12650           }
12651       }
12652
12653     case POSTDECREMENT_EXPR:
12654     case POSTINCREMENT_EXPR:
12655       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12656                                                 args, complain, in_decl);
12657       return build_x_unary_op (TREE_CODE (t), op1, complain);
12658
12659     case PREDECREMENT_EXPR:
12660     case PREINCREMENT_EXPR:
12661     case NEGATE_EXPR:
12662     case BIT_NOT_EXPR:
12663     case ABS_EXPR:
12664     case TRUTH_NOT_EXPR:
12665     case UNARY_PLUS_EXPR:  /* Unary + */
12666     case REALPART_EXPR:
12667     case IMAGPART_EXPR:
12668       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
12669                                complain);
12670
12671     case ADDR_EXPR:
12672       op1 = TREE_OPERAND (t, 0);
12673       if (TREE_CODE (op1) == LABEL_DECL)
12674         return finish_label_address_expr (DECL_NAME (op1),
12675                                           EXPR_LOCATION (op1));
12676       if (TREE_CODE (op1) == SCOPE_REF)
12677         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
12678                                    /*done=*/true, /*address_p=*/true);
12679       else
12680         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
12681                                                   in_decl);
12682       return build_x_unary_op (ADDR_EXPR, op1, complain);
12683
12684     case PLUS_EXPR:
12685     case MINUS_EXPR:
12686     case MULT_EXPR:
12687     case TRUNC_DIV_EXPR:
12688     case CEIL_DIV_EXPR:
12689     case FLOOR_DIV_EXPR:
12690     case ROUND_DIV_EXPR:
12691     case EXACT_DIV_EXPR:
12692     case BIT_AND_EXPR:
12693     case BIT_IOR_EXPR:
12694     case BIT_XOR_EXPR:
12695     case TRUNC_MOD_EXPR:
12696     case FLOOR_MOD_EXPR:
12697     case TRUTH_ANDIF_EXPR:
12698     case TRUTH_ORIF_EXPR:
12699     case TRUTH_AND_EXPR:
12700     case TRUTH_OR_EXPR:
12701     case RSHIFT_EXPR:
12702     case LSHIFT_EXPR:
12703     case RROTATE_EXPR:
12704     case LROTATE_EXPR:
12705     case EQ_EXPR:
12706     case NE_EXPR:
12707     case MAX_EXPR:
12708     case MIN_EXPR:
12709     case LE_EXPR:
12710     case GE_EXPR:
12711     case LT_EXPR:
12712     case GT_EXPR:
12713     case MEMBER_REF:
12714     case DOTSTAR_EXPR:
12715       return build_x_binary_op
12716         (TREE_CODE (t),
12717          RECUR (TREE_OPERAND (t, 0)),
12718          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
12719           ? ERROR_MARK
12720           : TREE_CODE (TREE_OPERAND (t, 0))),
12721          RECUR (TREE_OPERAND (t, 1)),
12722          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
12723           ? ERROR_MARK
12724           : TREE_CODE (TREE_OPERAND (t, 1))),
12725          /*overloaded_p=*/NULL,
12726          complain);
12727
12728     case SCOPE_REF:
12729       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
12730                                   /*address_p=*/false);
12731     case ARRAY_REF:
12732       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12733                                                 args, complain, in_decl);
12734       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
12735
12736     case SIZEOF_EXPR:
12737       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
12738         return tsubst_copy (t, args, complain, in_decl);
12739       /* Fall through */
12740       
12741     case ALIGNOF_EXPR:
12742       op1 = TREE_OPERAND (t, 0);
12743       if (!args)
12744         {
12745           /* When there are no ARGS, we are trying to evaluate a
12746              non-dependent expression from the parser.  Trying to do
12747              the substitutions may not work.  */
12748           if (!TYPE_P (op1))
12749             op1 = TREE_TYPE (op1);
12750         }
12751       else
12752         {
12753           ++cp_unevaluated_operand;
12754           ++c_inhibit_evaluation_warnings;
12755           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12756                                        /*function_p=*/false,
12757                                        /*integral_constant_expression_p=*/false);
12758           --cp_unevaluated_operand;
12759           --c_inhibit_evaluation_warnings;
12760         }
12761       if (TYPE_P (op1))
12762         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
12763                                            complain & tf_error);
12764       else
12765         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
12766                                            complain & tf_error);
12767
12768     case AT_ENCODE_EXPR:
12769       {
12770         op1 = TREE_OPERAND (t, 0);
12771         ++cp_unevaluated_operand;
12772         ++c_inhibit_evaluation_warnings;
12773         op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12774                                      /*function_p=*/false,
12775                                      /*integral_constant_expression_p=*/false);
12776         --cp_unevaluated_operand;
12777         --c_inhibit_evaluation_warnings;
12778         return objc_build_encode_expr (op1);
12779       }
12780
12781     case NOEXCEPT_EXPR:
12782       op1 = TREE_OPERAND (t, 0);
12783       ++cp_unevaluated_operand;
12784       ++c_inhibit_evaluation_warnings;
12785       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12786                                    /*function_p=*/false,
12787                                    /*integral_constant_expression_p=*/false);
12788       --cp_unevaluated_operand;
12789       --c_inhibit_evaluation_warnings;
12790       return finish_noexcept_expr (op1, complain);
12791
12792     case MODOP_EXPR:
12793       {
12794         tree r = build_x_modify_expr
12795           (RECUR (TREE_OPERAND (t, 0)),
12796            TREE_CODE (TREE_OPERAND (t, 1)),
12797            RECUR (TREE_OPERAND (t, 2)),
12798            complain);
12799         /* TREE_NO_WARNING must be set if either the expression was
12800            parenthesized or it uses an operator such as >>= rather
12801            than plain assignment.  In the former case, it was already
12802            set and must be copied.  In the latter case,
12803            build_x_modify_expr sets it and it must not be reset
12804            here.  */
12805         if (TREE_NO_WARNING (t))
12806           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12807         return r;
12808       }
12809
12810     case ARROW_EXPR:
12811       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12812                                                 args, complain, in_decl);
12813       /* Remember that there was a reference to this entity.  */
12814       if (DECL_P (op1))
12815         mark_used (op1);
12816       return build_x_arrow (op1);
12817
12818     case NEW_EXPR:
12819       {
12820         tree placement = RECUR (TREE_OPERAND (t, 0));
12821         tree init = RECUR (TREE_OPERAND (t, 3));
12822         VEC(tree,gc) *placement_vec;
12823         VEC(tree,gc) *init_vec;
12824         tree ret;
12825
12826         if (placement == NULL_TREE)
12827           placement_vec = NULL;
12828         else
12829           {
12830             placement_vec = make_tree_vector ();
12831             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
12832               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
12833           }
12834
12835         /* If there was an initializer in the original tree, but it
12836            instantiated to an empty list, then we should pass a
12837            non-NULL empty vector to tell build_new that it was an
12838            empty initializer() rather than no initializer.  This can
12839            only happen when the initializer is a pack expansion whose
12840            parameter packs are of length zero.  */
12841         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
12842           init_vec = NULL;
12843         else
12844           {
12845             init_vec = make_tree_vector ();
12846             if (init == void_zero_node)
12847               gcc_assert (init_vec != NULL);
12848             else
12849               {
12850                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
12851                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
12852               }
12853           }
12854
12855         ret = build_new (&placement_vec,
12856                          tsubst (TREE_OPERAND (t, 1), args, complain, in_decl),
12857                          RECUR (TREE_OPERAND (t, 2)),
12858                          &init_vec,
12859                          NEW_EXPR_USE_GLOBAL (t),
12860                          complain);
12861
12862         if (placement_vec != NULL)
12863           release_tree_vector (placement_vec);
12864         if (init_vec != NULL)
12865           release_tree_vector (init_vec);
12866
12867         return ret;
12868       }
12869
12870     case DELETE_EXPR:
12871      return delete_sanity
12872        (RECUR (TREE_OPERAND (t, 0)),
12873         RECUR (TREE_OPERAND (t, 1)),
12874         DELETE_EXPR_USE_VEC (t),
12875         DELETE_EXPR_USE_GLOBAL (t),
12876         complain);
12877
12878     case COMPOUND_EXPR:
12879       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
12880                                     RECUR (TREE_OPERAND (t, 1)),
12881                                     complain);
12882
12883     case CALL_EXPR:
12884       {
12885         tree function;
12886         VEC(tree,gc) *call_args;
12887         unsigned int nargs, i;
12888         bool qualified_p;
12889         bool koenig_p;
12890         tree ret;
12891
12892         function = CALL_EXPR_FN (t);
12893         /* When we parsed the expression,  we determined whether or
12894            not Koenig lookup should be performed.  */
12895         koenig_p = KOENIG_LOOKUP_P (t);
12896         if (TREE_CODE (function) == SCOPE_REF)
12897           {
12898             qualified_p = true;
12899             function = tsubst_qualified_id (function, args, complain, in_decl,
12900                                             /*done=*/false,
12901                                             /*address_p=*/false);
12902           }
12903         else if (koenig_p && TREE_CODE (function) == IDENTIFIER_NODE)
12904           {
12905             /* Do nothing; calling tsubst_copy_and_build on an identifier
12906                would incorrectly perform unqualified lookup again.
12907
12908                Note that we can also have an IDENTIFIER_NODE if the earlier
12909                unqualified lookup found a member function; in that case
12910                koenig_p will be false and we do want to do the lookup
12911                again to find the instantiated member function.
12912
12913                FIXME but doing that causes c++/15272, so we need to stop
12914                using IDENTIFIER_NODE in that situation.  */
12915             qualified_p = false;
12916           }
12917         else
12918           {
12919             if (TREE_CODE (function) == COMPONENT_REF)
12920               {
12921                 tree op = TREE_OPERAND (function, 1);
12922
12923                 qualified_p = (TREE_CODE (op) == SCOPE_REF
12924                                || (BASELINK_P (op)
12925                                    && BASELINK_QUALIFIED_P (op)));
12926               }
12927             else
12928               qualified_p = false;
12929
12930             function = tsubst_copy_and_build (function, args, complain,
12931                                               in_decl,
12932                                               !qualified_p,
12933                                               integral_constant_expression_p);
12934
12935             if (BASELINK_P (function))
12936               qualified_p = true;
12937           }
12938
12939         nargs = call_expr_nargs (t);
12940         call_args = make_tree_vector ();
12941         for (i = 0; i < nargs; ++i)
12942           {
12943             tree arg = CALL_EXPR_ARG (t, i);
12944
12945             if (!PACK_EXPANSION_P (arg))
12946               VEC_safe_push (tree, gc, call_args,
12947                              RECUR (CALL_EXPR_ARG (t, i)));
12948             else
12949               {
12950                 /* Expand the pack expansion and push each entry onto
12951                    CALL_ARGS.  */
12952                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
12953                 if (TREE_CODE (arg) == TREE_VEC)
12954                   {
12955                     unsigned int len, j;
12956
12957                     len = TREE_VEC_LENGTH (arg);
12958                     for (j = 0; j < len; ++j)
12959                       {
12960                         tree value = TREE_VEC_ELT (arg, j);
12961                         if (value != NULL_TREE)
12962                           value = convert_from_reference (value);
12963                         VEC_safe_push (tree, gc, call_args, value);
12964                       }
12965                   }
12966                 else
12967                   {
12968                     /* A partial substitution.  Add one entry.  */
12969                     VEC_safe_push (tree, gc, call_args, arg);
12970                   }
12971               }
12972           }
12973
12974         /* We do not perform argument-dependent lookup if normal
12975            lookup finds a non-function, in accordance with the
12976            expected resolution of DR 218.  */
12977         if (koenig_p
12978             && ((is_overloaded_fn (function)
12979                  /* If lookup found a member function, the Koenig lookup is
12980                     not appropriate, even if an unqualified-name was used
12981                     to denote the function.  */
12982                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
12983                 || TREE_CODE (function) == IDENTIFIER_NODE)
12984             /* Only do this when substitution turns a dependent call
12985                into a non-dependent call.  */
12986             && type_dependent_expression_p_push (t)
12987             && !any_type_dependent_arguments_p (call_args))
12988           function = perform_koenig_lookup (function, call_args, false,
12989                                             tf_none);
12990
12991         if (TREE_CODE (function) == IDENTIFIER_NODE
12992             && !any_type_dependent_arguments_p (call_args))
12993           {
12994             if (koenig_p && (complain & tf_warning_or_error))
12995               {
12996                 /* For backwards compatibility and good diagnostics, try
12997                    the unqualified lookup again if we aren't in SFINAE
12998                    context.  */
12999                 tree unq = (tsubst_copy_and_build
13000                             (function, args, complain, in_decl, true,
13001                              integral_constant_expression_p));
13002                 if (unq != function)
13003                   {
13004                     tree fn = unq;
13005                     if (TREE_CODE (fn) == COMPONENT_REF)
13006                       fn = TREE_OPERAND (fn, 1);
13007                     if (is_overloaded_fn (fn))
13008                       fn = get_first_fn (fn);
13009                     permerror (EXPR_LOC_OR_HERE (t),
13010                                "%qD was not declared in this scope, "
13011                                "and no declarations were found by "
13012                                "argument-dependent lookup at the point "
13013                                "of instantiation", function);
13014                     if (DECL_CLASS_SCOPE_P (fn))
13015                       {
13016                         inform (EXPR_LOC_OR_HERE (t),
13017                                 "declarations in dependent base %qT are "
13018                                 "not found by unqualified lookup",
13019                                 DECL_CLASS_CONTEXT (fn));
13020                         if (current_class_ptr)
13021                           inform (EXPR_LOC_OR_HERE (t),
13022                                   "use %<this->%D%> instead", function);
13023                         else
13024                           inform (EXPR_LOC_OR_HERE (t),
13025                                   "use %<%T::%D%> instead",
13026                                   current_class_name, function);
13027                       }
13028                     else
13029                       inform (0, "%q+D declared here, later in the "
13030                                 "translation unit", fn);
13031                     function = unq;
13032                   }
13033               }
13034             if (TREE_CODE (function) == IDENTIFIER_NODE)
13035               {
13036                 unqualified_name_lookup_error (function);
13037                 release_tree_vector (call_args);
13038                 return error_mark_node;
13039               }
13040           }
13041
13042         /* Remember that there was a reference to this entity.  */
13043         if (DECL_P (function))
13044           mark_used (function);
13045
13046         if (TREE_CODE (function) == OFFSET_REF)
13047           ret = build_offset_ref_call_from_tree (function, &call_args);
13048         else if (TREE_CODE (function) == COMPONENT_REF)
13049           {
13050             tree instance = TREE_OPERAND (function, 0);
13051             tree fn = TREE_OPERAND (function, 1);
13052
13053             if (processing_template_decl
13054                 && (type_dependent_expression_p (instance)
13055                     || (!BASELINK_P (fn)
13056                         && TREE_CODE (fn) != FIELD_DECL)
13057                     || type_dependent_expression_p (fn)
13058                     || any_type_dependent_arguments_p (call_args)))
13059               ret = build_nt_call_vec (function, call_args);
13060             else if (!BASELINK_P (fn))
13061               ret = finish_call_expr (function, &call_args,
13062                                        /*disallow_virtual=*/false,
13063                                        /*koenig_p=*/false,
13064                                        complain);
13065             else
13066               ret = (build_new_method_call
13067                       (instance, fn,
13068                        &call_args, NULL_TREE,
13069                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
13070                        /*fn_p=*/NULL,
13071                        complain));
13072           }
13073         else
13074           ret = finish_call_expr (function, &call_args,
13075                                   /*disallow_virtual=*/qualified_p,
13076                                   koenig_p,
13077                                   complain);
13078
13079         release_tree_vector (call_args);
13080
13081         return ret;
13082       }
13083
13084     case COND_EXPR:
13085       return build_x_conditional_expr
13086         (RECUR (TREE_OPERAND (t, 0)),
13087          RECUR (TREE_OPERAND (t, 1)),
13088          RECUR (TREE_OPERAND (t, 2)),
13089          complain);
13090
13091     case PSEUDO_DTOR_EXPR:
13092       return finish_pseudo_destructor_expr
13093         (RECUR (TREE_OPERAND (t, 0)),
13094          RECUR (TREE_OPERAND (t, 1)),
13095          tsubst (TREE_OPERAND (t, 2), args, complain, in_decl));
13096
13097     case TREE_LIST:
13098       {
13099         tree purpose, value, chain;
13100
13101         if (t == void_list_node)
13102           return t;
13103
13104         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
13105             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
13106           {
13107             /* We have pack expansions, so expand those and
13108                create a new list out of it.  */
13109             tree purposevec = NULL_TREE;
13110             tree valuevec = NULL_TREE;
13111             tree chain;
13112             int i, len = -1;
13113
13114             /* Expand the argument expressions.  */
13115             if (TREE_PURPOSE (t))
13116               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
13117                                                  complain, in_decl);
13118             if (TREE_VALUE (t))
13119               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
13120                                                complain, in_decl);
13121
13122             /* Build the rest of the list.  */
13123             chain = TREE_CHAIN (t);
13124             if (chain && chain != void_type_node)
13125               chain = RECUR (chain);
13126
13127             /* Determine the number of arguments.  */
13128             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
13129               {
13130                 len = TREE_VEC_LENGTH (purposevec);
13131                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
13132               }
13133             else if (TREE_CODE (valuevec) == TREE_VEC)
13134               len = TREE_VEC_LENGTH (valuevec);
13135             else
13136               {
13137                 /* Since we only performed a partial substitution into
13138                    the argument pack, we only return a single list
13139                    node.  */
13140                 if (purposevec == TREE_PURPOSE (t)
13141                     && valuevec == TREE_VALUE (t)
13142                     && chain == TREE_CHAIN (t))
13143                   return t;
13144
13145                 return tree_cons (purposevec, valuevec, chain);
13146               }
13147             
13148             /* Convert the argument vectors into a TREE_LIST */
13149             i = len;
13150             while (i > 0)
13151               {
13152                 /* Grab the Ith values.  */
13153                 i--;
13154                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
13155                                      : NULL_TREE;
13156                 value 
13157                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
13158                              : NULL_TREE;
13159
13160                 /* Build the list (backwards).  */
13161                 chain = tree_cons (purpose, value, chain);
13162               }
13163
13164             return chain;
13165           }
13166
13167         purpose = TREE_PURPOSE (t);
13168         if (purpose)
13169           purpose = RECUR (purpose);
13170         value = TREE_VALUE (t);
13171         if (value)
13172           value = RECUR (value);
13173         chain = TREE_CHAIN (t);
13174         if (chain && chain != void_type_node)
13175           chain = RECUR (chain);
13176         if (purpose == TREE_PURPOSE (t)
13177             && value == TREE_VALUE (t)
13178             && chain == TREE_CHAIN (t))
13179           return t;
13180         return tree_cons (purpose, value, chain);
13181       }
13182
13183     case COMPONENT_REF:
13184       {
13185         tree object;
13186         tree object_type;
13187         tree member;
13188
13189         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13190                                                      args, complain, in_decl);
13191         /* Remember that there was a reference to this entity.  */
13192         if (DECL_P (object))
13193           mark_used (object);
13194         object_type = TREE_TYPE (object);
13195
13196         member = TREE_OPERAND (t, 1);
13197         if (BASELINK_P (member))
13198           member = tsubst_baselink (member,
13199                                     non_reference (TREE_TYPE (object)),
13200                                     args, complain, in_decl);
13201         else
13202           member = tsubst_copy (member, args, complain, in_decl);
13203         if (member == error_mark_node)
13204           return error_mark_node;
13205
13206         if (object_type && !CLASS_TYPE_P (object_type))
13207           {
13208             if (SCALAR_TYPE_P (object_type))
13209               {
13210                 tree s = NULL_TREE;
13211                 tree dtor = member;
13212
13213                 if (TREE_CODE (dtor) == SCOPE_REF)
13214                   {
13215                     s = TREE_OPERAND (dtor, 0);
13216                     dtor = TREE_OPERAND (dtor, 1);
13217                   }
13218                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
13219                   {
13220                     dtor = TREE_OPERAND (dtor, 0);
13221                     if (TYPE_P (dtor))
13222                       return finish_pseudo_destructor_expr (object, s, dtor);
13223                   }
13224               }
13225           }
13226         else if (TREE_CODE (member) == SCOPE_REF
13227                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
13228           {
13229             tree tmpl;
13230             tree args;
13231
13232             /* Lookup the template functions now that we know what the
13233                scope is.  */
13234             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
13235             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
13236             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
13237                                             /*is_type_p=*/false,
13238                                             /*complain=*/false);
13239             if (BASELINK_P (member))
13240               {
13241                 BASELINK_FUNCTIONS (member)
13242                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
13243                               args);
13244                 member = (adjust_result_of_qualified_name_lookup
13245                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
13246                            object_type));
13247               }
13248             else
13249               {
13250                 qualified_name_lookup_error (object_type, tmpl, member,
13251                                              input_location);
13252                 return error_mark_node;
13253               }
13254           }
13255         else if (TREE_CODE (member) == SCOPE_REF
13256                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
13257                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
13258           {
13259             if (complain & tf_error)
13260               {
13261                 if (TYPE_P (TREE_OPERAND (member, 0)))
13262                   error ("%qT is not a class or namespace",
13263                          TREE_OPERAND (member, 0));
13264                 else
13265                   error ("%qD is not a class or namespace",
13266                          TREE_OPERAND (member, 0));
13267               }
13268             return error_mark_node;
13269           }
13270         else if (TREE_CODE (member) == FIELD_DECL)
13271           return finish_non_static_data_member (member, object, NULL_TREE);
13272
13273         return finish_class_member_access_expr (object, member,
13274                                                 /*template_p=*/false,
13275                                                 complain);
13276       }
13277
13278     case THROW_EXPR:
13279       return build_throw
13280         (RECUR (TREE_OPERAND (t, 0)));
13281
13282     case CONSTRUCTOR:
13283       {
13284         VEC(constructor_elt,gc) *n;
13285         constructor_elt *ce;
13286         unsigned HOST_WIDE_INT idx;
13287         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13288         bool process_index_p;
13289         int newlen;
13290         bool need_copy_p = false;
13291         tree r;
13292
13293         if (type == error_mark_node)
13294           return error_mark_node;
13295
13296         /* digest_init will do the wrong thing if we let it.  */
13297         if (type && TYPE_PTRMEMFUNC_P (type))
13298           return t;
13299
13300         /* We do not want to process the index of aggregate
13301            initializers as they are identifier nodes which will be
13302            looked up by digest_init.  */
13303         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
13304
13305         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
13306         newlen = VEC_length (constructor_elt, n);
13307         FOR_EACH_VEC_ELT (constructor_elt, n, idx, ce)
13308           {
13309             if (ce->index && process_index_p)
13310               ce->index = RECUR (ce->index);
13311
13312             if (PACK_EXPANSION_P (ce->value))
13313               {
13314                 /* Substitute into the pack expansion.  */
13315                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
13316                                                   in_decl);
13317
13318                 if (ce->value == error_mark_node
13319                     || PACK_EXPANSION_P (ce->value))
13320                   ;
13321                 else if (TREE_VEC_LENGTH (ce->value) == 1)
13322                   /* Just move the argument into place.  */
13323                   ce->value = TREE_VEC_ELT (ce->value, 0);
13324                 else
13325                   {
13326                     /* Update the length of the final CONSTRUCTOR
13327                        arguments vector, and note that we will need to
13328                        copy.*/
13329                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
13330                     need_copy_p = true;
13331                   }
13332               }
13333             else
13334               ce->value = RECUR (ce->value);
13335           }
13336
13337         if (need_copy_p)
13338           {
13339             VEC(constructor_elt,gc) *old_n = n;
13340
13341             n = VEC_alloc (constructor_elt, gc, newlen);
13342             FOR_EACH_VEC_ELT (constructor_elt, old_n, idx, ce)
13343               {
13344                 if (TREE_CODE (ce->value) == TREE_VEC)
13345                   {
13346                     int i, len = TREE_VEC_LENGTH (ce->value);
13347                     for (i = 0; i < len; ++i)
13348                       CONSTRUCTOR_APPEND_ELT (n, 0,
13349                                               TREE_VEC_ELT (ce->value, i));
13350                   }
13351                 else
13352                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
13353               }
13354           }
13355
13356         r = build_constructor (init_list_type_node, n);
13357         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
13358
13359         if (TREE_HAS_CONSTRUCTOR (t))
13360           return finish_compound_literal (type, r, complain);
13361
13362         TREE_TYPE (r) = type;
13363         return r;
13364       }
13365
13366     case TYPEID_EXPR:
13367       {
13368         tree operand_0 = TREE_OPERAND (t, 0);
13369         if (TYPE_P (operand_0))
13370           {
13371             operand_0 = tsubst (operand_0, args, complain, in_decl);
13372             return get_typeid (operand_0);
13373           }
13374         else
13375           {
13376             operand_0 = RECUR (operand_0);
13377             return build_typeid (operand_0);
13378           }
13379       }
13380
13381     case VAR_DECL:
13382       if (!args)
13383         return t;
13384       /* Fall through */
13385
13386     case PARM_DECL:
13387       {
13388         tree r = tsubst_copy (t, args, complain, in_decl);
13389
13390         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
13391           /* If the original type was a reference, we'll be wrapped in
13392              the appropriate INDIRECT_REF.  */
13393           r = convert_from_reference (r);
13394         return r;
13395       }
13396
13397     case VA_ARG_EXPR:
13398       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
13399                              tsubst (TREE_TYPE (t), args, complain, in_decl));
13400
13401     case OFFSETOF_EXPR:
13402       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
13403
13404     case TRAIT_EXPR:
13405       {
13406         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
13407                                   complain, in_decl);
13408
13409         tree type2 = TRAIT_EXPR_TYPE2 (t);
13410         if (type2)
13411           type2 = tsubst_copy (type2, args, complain, in_decl);
13412         
13413         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
13414       }
13415
13416     case STMT_EXPR:
13417       {
13418         tree old_stmt_expr = cur_stmt_expr;
13419         tree stmt_expr = begin_stmt_expr ();
13420
13421         cur_stmt_expr = stmt_expr;
13422         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
13423                      integral_constant_expression_p);
13424         stmt_expr = finish_stmt_expr (stmt_expr, false);
13425         cur_stmt_expr = old_stmt_expr;
13426
13427         /* If the resulting list of expression statement is empty,
13428            fold it further into void_zero_node.  */
13429         if (empty_expr_stmt_p (stmt_expr))
13430           stmt_expr = void_zero_node;
13431
13432         return stmt_expr;
13433       }
13434
13435     case CONST_DECL:
13436       t = tsubst_copy (t, args, complain, in_decl);
13437       /* As in finish_id_expression, we resolve enumeration constants
13438          to their underlying values.  */
13439       if (TREE_CODE (t) == CONST_DECL)
13440         {
13441           used_types_insert (TREE_TYPE (t));
13442           return DECL_INITIAL (t);
13443         }
13444       return t;
13445
13446     case LAMBDA_EXPR:
13447       {
13448         tree r = build_lambda_expr ();
13449
13450         tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
13451         TREE_TYPE (r) = type;
13452         CLASSTYPE_LAMBDA_EXPR (type) = r;
13453
13454         LAMBDA_EXPR_LOCATION (r)
13455           = LAMBDA_EXPR_LOCATION (t);
13456         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
13457           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
13458         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
13459         LAMBDA_EXPR_DISCRIMINATOR (r)
13460           = (LAMBDA_EXPR_DISCRIMINATOR (t));
13461         LAMBDA_EXPR_CAPTURE_LIST (r)
13462           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
13463         LAMBDA_EXPR_THIS_CAPTURE (r)
13464           = RECUR (LAMBDA_EXPR_THIS_CAPTURE (t));
13465         LAMBDA_EXPR_EXTRA_SCOPE (r)
13466           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
13467
13468         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
13469         determine_visibility (TYPE_NAME (type));
13470         /* Now that we know visibility, instantiate the type so we have a
13471            declaration of the op() for later calls to lambda_function.  */
13472         complete_type (type);
13473
13474         type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
13475         if (type)
13476           apply_lambda_return_type (r, type);
13477
13478         return build_lambda_object (r);
13479       }
13480
13481     case TARGET_EXPR:
13482       /* We can get here for a constant initializer of non-dependent type.
13483          FIXME stop folding in cp_parser_initializer_clause.  */
13484       gcc_assert (TREE_CONSTANT (t));
13485       {
13486         tree r = get_target_expr (RECUR (TARGET_EXPR_INITIAL (t)));
13487         TREE_CONSTANT (r) = true;
13488         return r;
13489       }
13490
13491     default:
13492       /* Handle Objective-C++ constructs, if appropriate.  */
13493       {
13494         tree subst
13495           = objcp_tsubst_copy_and_build (t, args, complain,
13496                                          in_decl, /*function_p=*/false);
13497         if (subst)
13498           return subst;
13499       }
13500       return tsubst_copy (t, args, complain, in_decl);
13501     }
13502
13503 #undef RECUR
13504 }
13505
13506 /* Verify that the instantiated ARGS are valid. For type arguments,
13507    make sure that the type's linkage is ok. For non-type arguments,
13508    make sure they are constants if they are integral or enumerations.
13509    Emit an error under control of COMPLAIN, and return TRUE on error.  */
13510
13511 static bool
13512 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
13513 {
13514   if (ARGUMENT_PACK_P (t))
13515     {
13516       tree vec = ARGUMENT_PACK_ARGS (t);
13517       int len = TREE_VEC_LENGTH (vec);
13518       bool result = false;
13519       int i;
13520
13521       for (i = 0; i < len; ++i)
13522         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
13523           result = true;
13524       return result;
13525     }
13526   else if (TYPE_P (t))
13527     {
13528       /* [basic.link]: A name with no linkage (notably, the name
13529          of a class or enumeration declared in a local scope)
13530          shall not be used to declare an entity with linkage.
13531          This implies that names with no linkage cannot be used as
13532          template arguments
13533
13534          DR 757 relaxes this restriction for C++0x.  */
13535       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
13536                  : no_linkage_check (t, /*relaxed_p=*/false));
13537
13538       if (nt)
13539         {
13540           /* DR 488 makes use of a type with no linkage cause
13541              type deduction to fail.  */
13542           if (complain & tf_error)
13543             {
13544               if (TYPE_ANONYMOUS_P (nt))
13545                 error ("%qT is/uses anonymous type", t);
13546               else
13547                 error ("template argument for %qD uses local type %qT",
13548                        tmpl, t);
13549             }
13550           return true;
13551         }
13552       /* In order to avoid all sorts of complications, we do not
13553          allow variably-modified types as template arguments.  */
13554       else if (variably_modified_type_p (t, NULL_TREE))
13555         {
13556           if (complain & tf_error)
13557             error ("%qT is a variably modified type", t);
13558           return true;
13559         }
13560     }
13561   /* A non-type argument of integral or enumerated type must be a
13562      constant.  */
13563   else if (TREE_TYPE (t)
13564            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
13565            && !TREE_CONSTANT (t))
13566     {
13567       if (complain & tf_error)
13568         error ("integral expression %qE is not constant", t);
13569       return true;
13570     }
13571   return false;
13572 }
13573
13574 static bool
13575 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
13576 {
13577   int ix, len = DECL_NTPARMS (tmpl);
13578   bool result = false;
13579
13580   for (ix = 0; ix != len; ix++)
13581     {
13582       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
13583         result = true;
13584     }
13585   if (result && (complain & tf_error))
13586     error ("  trying to instantiate %qD", tmpl);
13587   return result;
13588 }
13589
13590 DEF_VEC_O (spec_entry);
13591 DEF_VEC_ALLOC_O (spec_entry,gc);
13592 static GTY(()) VEC(spec_entry,gc) *current_deduction_vec;
13593 static GTY((param_is (spec_entry))) htab_t current_deduction_htab;
13594
13595 /* In C++0x, it's possible to have a function template whose type depends
13596    on itself recursively.  This is most obvious with decltype, but can also
13597    occur with enumeration scope (c++/48969).  So we need to catch infinite
13598    recursion and reject the substitution at deduction time.
13599
13600    Use of a VEC here is O(n^2) in the depth of function template argument
13601    deduction substitution, but using a hash table creates a lot of constant
13602    overhead for the typical case of very low depth.  So to make the typical
13603    case fast we start out with a VEC and switch to a hash table only if
13604    depth gets to be significant; in one metaprogramming testcase, even at
13605    depth 80 the overhead of the VEC relative to a hash table was only about
13606    0.5% of compile time.  */
13607
13608 static tree
13609 deduction_tsubst_fntype (tree fn, tree targs)
13610 {
13611   unsigned i;
13612   spec_entry **slot;
13613   spec_entry *p;
13614   spec_entry elt;
13615   tree r;
13616   hashval_t hash;
13617
13618   tree fntype = TREE_TYPE (fn);
13619
13620   /* We don't need to worry about this in C++98.  */
13621   if (cxx_dialect < cxx0x)
13622     return tsubst (fntype, targs, tf_none, NULL_TREE);
13623
13624   /* If we're seeing a lot of recursion, switch over to a hash table.  The
13625      constant 40 is fairly arbitrary.  */
13626   if (!current_deduction_htab
13627       && VEC_length (spec_entry, current_deduction_vec) > 40)
13628     {
13629       current_deduction_htab = htab_create_ggc (40*2, hash_specialization,
13630                                                 eq_specializations, ggc_free);
13631       FOR_EACH_VEC_ELT (spec_entry, current_deduction_vec, i, p)
13632         {
13633           slot = (spec_entry **) htab_find_slot (current_deduction_htab,
13634                                                  p, INSERT);
13635           *slot = ggc_alloc_spec_entry ();
13636           **slot = *p;
13637         }
13638       VEC_free (spec_entry, gc, current_deduction_vec);
13639     }
13640
13641   /* Now check everything in the vector, if any.  */
13642   FOR_EACH_VEC_ELT (spec_entry, current_deduction_vec, i, p)
13643     if (p->tmpl == fn && comp_template_args (p->args, targs))
13644       {
13645         p->spec = error_mark_node;
13646         return error_mark_node;
13647       }
13648
13649   elt.tmpl = fn;
13650   elt.args = targs;
13651   elt.spec = NULL_TREE;
13652
13653   /* If we've created a hash table, look there.  */
13654   if (current_deduction_htab)
13655     {
13656       hash = hash_specialization (&elt);
13657       slot = (spec_entry **)
13658         htab_find_slot_with_hash (current_deduction_htab, &elt, hash, INSERT);
13659       if (*slot)
13660         {
13661           /* We already have an entry for this.  */
13662           (*slot)->spec = error_mark_node;
13663           return error_mark_node;
13664         }
13665       else
13666         {
13667           /* Create a new entry.  */
13668           *slot = ggc_alloc_spec_entry ();
13669           **slot = elt;
13670         }
13671     }
13672   else
13673     {
13674       /* No hash table, so add it to the VEC.  */
13675       hash = 0;
13676       VEC_safe_push (spec_entry, gc, current_deduction_vec, &elt);
13677     }
13678
13679   r = tsubst (fntype, targs, tf_none, NULL_TREE);
13680
13681   /* After doing the substitution, make sure we didn't hit it again.  Note
13682      that we might have switched to a hash table during tsubst.  */
13683   if (current_deduction_htab)
13684     {
13685       if (hash == 0)
13686         hash = hash_specialization (&elt);
13687       slot = (spec_entry **)
13688         htab_find_slot_with_hash (current_deduction_htab, &elt, hash,
13689                                   NO_INSERT);
13690       if ((*slot)->spec == error_mark_node)
13691         r = error_mark_node;
13692       htab_clear_slot (current_deduction_htab, (void**)slot);
13693     }
13694   else
13695     {
13696       if (VEC_last (spec_entry, current_deduction_vec)->spec
13697           == error_mark_node)
13698         r = error_mark_node;
13699       VEC_pop (spec_entry, current_deduction_vec);
13700     }
13701   return r;
13702 }
13703
13704 /* Instantiate the indicated variable or function template TMPL with
13705    the template arguments in TARG_PTR.  */
13706
13707 static tree
13708 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
13709 {
13710   tree targ_ptr = orig_args;
13711   tree fndecl;
13712   tree gen_tmpl;
13713   tree spec;
13714   HOST_WIDE_INT saved_processing_template_decl;
13715
13716   if (tmpl == error_mark_node)
13717     return error_mark_node;
13718
13719   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
13720
13721   /* If this function is a clone, handle it specially.  */
13722   if (DECL_CLONED_FUNCTION_P (tmpl))
13723     {
13724       tree spec;
13725       tree clone;
13726
13727       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
13728          DECL_CLONED_FUNCTION.  */
13729       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
13730                                    targ_ptr, complain);
13731       if (spec == error_mark_node)
13732         return error_mark_node;
13733
13734       /* Look for the clone.  */
13735       FOR_EACH_CLONE (clone, spec)
13736         if (DECL_NAME (clone) == DECL_NAME (tmpl))
13737           return clone;
13738       /* We should always have found the clone by now.  */
13739       gcc_unreachable ();
13740       return NULL_TREE;
13741     }
13742
13743   /* Check to see if we already have this specialization.  */
13744   gen_tmpl = most_general_template (tmpl);
13745   if (tmpl != gen_tmpl)
13746     /* The TMPL is a partial instantiation.  To get a full set of
13747        arguments we must add the arguments used to perform the
13748        partial instantiation.  */
13749     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
13750                                             targ_ptr);
13751
13752   /* It would be nice to avoid hashing here and then again in tsubst_decl,
13753      but it doesn't seem to be on the hot path.  */
13754   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
13755
13756   gcc_assert (tmpl == gen_tmpl
13757               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
13758                   == spec)
13759               || fndecl == NULL_TREE);
13760
13761   if (spec != NULL_TREE)
13762     return spec;
13763
13764   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
13765                                complain))
13766     return error_mark_node;
13767
13768   /* We are building a FUNCTION_DECL, during which the access of its
13769      parameters and return types have to be checked.  However this
13770      FUNCTION_DECL which is the desired context for access checking
13771      is not built yet.  We solve this chicken-and-egg problem by
13772      deferring all checks until we have the FUNCTION_DECL.  */
13773   push_deferring_access_checks (dk_deferred);
13774
13775   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
13776      (because, for example, we have encountered a non-dependent
13777      function call in the body of a template function and must now
13778      determine which of several overloaded functions will be called),
13779      within the instantiation itself we are not processing a
13780      template.  */  
13781   saved_processing_template_decl = processing_template_decl;
13782   processing_template_decl = 0;
13783   /* Substitute template parameters to obtain the specialization.  */
13784   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
13785                    targ_ptr, complain, gen_tmpl);
13786   processing_template_decl = saved_processing_template_decl;
13787   if (fndecl == error_mark_node)
13788     return error_mark_node;
13789
13790   /* Now we know the specialization, compute access previously
13791      deferred.  */
13792   push_access_scope (fndecl);
13793
13794   /* Some typedefs referenced from within the template code need to be access
13795      checked at template instantiation time, i.e now. These types were
13796      added to the template at parsing time. Let's get those and perfom
13797      the acces checks then.  */
13798   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
13799   perform_deferred_access_checks ();
13800   pop_access_scope (fndecl);
13801   pop_deferring_access_checks ();
13802
13803   /* The DECL_TI_TEMPLATE should always be the immediate parent
13804      template, not the most general template.  */
13805   DECL_TI_TEMPLATE (fndecl) = tmpl;
13806
13807   /* If we've just instantiated the main entry point for a function,
13808      instantiate all the alternate entry points as well.  We do this
13809      by cloning the instantiation of the main entry point, not by
13810      instantiating the template clones.  */
13811   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
13812     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
13813
13814   return fndecl;
13815 }
13816
13817 /* Wrapper for instantiate_template_1.  */
13818
13819 tree
13820 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
13821 {
13822   tree ret;
13823   timevar_push (TV_TEMPLATE_INST);
13824   ret = instantiate_template_1 (tmpl, orig_args,  complain);
13825   timevar_pop (TV_TEMPLATE_INST);
13826   return ret;
13827 }
13828
13829 /* We're going to do deduction substitution on the type of TMPL, a function
13830    template.  In C++11 mode, push into that access scope.  In C++03 mode,
13831    disable access checking.  */
13832
13833 static void
13834 push_deduction_access_scope (tree tmpl)
13835 {
13836   if (cxx_dialect >= cxx0x)
13837     push_access_scope (DECL_TEMPLATE_RESULT (tmpl));
13838   else
13839     push_deferring_access_checks (dk_no_check);
13840 }
13841
13842 /* And pop back out.  */
13843
13844 static void
13845 pop_deduction_access_scope (tree tmpl)
13846 {
13847   if (cxx_dialect >= cxx0x)
13848     pop_access_scope (DECL_TEMPLATE_RESULT (tmpl));
13849   else
13850     pop_deferring_access_checks ();
13851 }
13852
13853 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
13854    NARGS elements of the arguments that are being used when calling
13855    it.  TARGS is a vector into which the deduced template arguments
13856    are placed.
13857
13858    Return zero for success, 2 for an incomplete match that doesn't resolve
13859    all the types, and 1 for complete failure.  An error message will be
13860    printed only for an incomplete match.
13861
13862    If FN is a conversion operator, or we are trying to produce a specific
13863    specialization, RETURN_TYPE is the return type desired.
13864
13865    The EXPLICIT_TARGS are explicit template arguments provided via a
13866    template-id.
13867
13868    The parameter STRICT is one of:
13869
13870    DEDUCE_CALL:
13871      We are deducing arguments for a function call, as in
13872      [temp.deduct.call].
13873
13874    DEDUCE_CONV:
13875      We are deducing arguments for a conversion function, as in
13876      [temp.deduct.conv].
13877
13878    DEDUCE_EXACT:
13879      We are deducing arguments when doing an explicit instantiation
13880      as in [temp.explicit], when determining an explicit specialization
13881      as in [temp.expl.spec], or when taking the address of a function
13882      template, as in [temp.deduct.funcaddr].  */
13883
13884 int
13885 fn_type_unification (tree fn,
13886                      tree explicit_targs,
13887                      tree targs,
13888                      const tree *args,
13889                      unsigned int nargs,
13890                      tree return_type,
13891                      unification_kind_t strict,
13892                      int flags)
13893 {
13894   tree parms;
13895   tree fntype;
13896   int result;
13897   bool incomplete_argument_packs_p = false;
13898
13899   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
13900
13901   fntype = TREE_TYPE (fn);
13902   if (explicit_targs)
13903     {
13904       /* [temp.deduct]
13905
13906          The specified template arguments must match the template
13907          parameters in kind (i.e., type, nontype, template), and there
13908          must not be more arguments than there are parameters;
13909          otherwise type deduction fails.
13910
13911          Nontype arguments must match the types of the corresponding
13912          nontype template parameters, or must be convertible to the
13913          types of the corresponding nontype parameters as specified in
13914          _temp.arg.nontype_, otherwise type deduction fails.
13915
13916          All references in the function type of the function template
13917          to the corresponding template parameters are replaced by the
13918          specified template argument values.  If a substitution in a
13919          template parameter or in the function type of the function
13920          template results in an invalid type, type deduction fails.  */
13921       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
13922       int i, len = TREE_VEC_LENGTH (tparms);
13923       tree converted_args;
13924       bool incomplete = false;
13925
13926       if (explicit_targs == error_mark_node)
13927         return 1;
13928
13929       converted_args
13930         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
13931                                   /*require_all_args=*/false,
13932                                   /*use_default_args=*/false));
13933       if (converted_args == error_mark_node)
13934         return 1;
13935
13936       /* Substitute the explicit args into the function type.  This is
13937          necessary so that, for instance, explicitly declared function
13938          arguments can match null pointed constants.  If we were given
13939          an incomplete set of explicit args, we must not do semantic
13940          processing during substitution as we could create partial
13941          instantiations.  */
13942       for (i = 0; i < len; i++)
13943         {
13944           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13945           bool parameter_pack = false;
13946
13947           /* Dig out the actual parm.  */
13948           if (TREE_CODE (parm) == TYPE_DECL
13949               || TREE_CODE (parm) == TEMPLATE_DECL)
13950             {
13951               parm = TREE_TYPE (parm);
13952               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
13953             }
13954           else if (TREE_CODE (parm) == PARM_DECL)
13955             {
13956               parm = DECL_INITIAL (parm);
13957               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
13958             }
13959
13960           if (parameter_pack)
13961             {
13962               int level, idx;
13963               tree targ;
13964               template_parm_level_and_index (parm, &level, &idx);
13965
13966               /* Mark the argument pack as "incomplete". We could
13967                  still deduce more arguments during unification.
13968                  We remove this mark in type_unification_real.  */
13969               targ = TMPL_ARG (converted_args, level, idx);
13970               if (targ)
13971                 {
13972                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
13973                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
13974                     = ARGUMENT_PACK_ARGS (targ);
13975                 }
13976
13977               /* We have some incomplete argument packs.  */
13978               incomplete_argument_packs_p = true;
13979             }
13980         }
13981
13982       if (incomplete_argument_packs_p)
13983         /* Any substitution is guaranteed to be incomplete if there
13984            are incomplete argument packs, because we can still deduce
13985            more arguments.  */
13986         incomplete = 1;
13987       else
13988         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
13989
13990       processing_template_decl += incomplete;
13991       push_deduction_access_scope (fn);
13992       fntype = deduction_tsubst_fntype (fn, converted_args);
13993       pop_deduction_access_scope (fn);
13994       processing_template_decl -= incomplete;
13995
13996       if (fntype == error_mark_node)
13997         return 1;
13998
13999       /* Place the explicitly specified arguments in TARGS.  */
14000       for (i = NUM_TMPL_ARGS (converted_args); i--;)
14001         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
14002     }
14003
14004   /* Never do unification on the 'this' parameter.  */
14005   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
14006
14007   if (return_type)
14008     {
14009       tree *new_args;
14010
14011       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
14012       new_args = XALLOCAVEC (tree, nargs + 1);
14013       new_args[0] = return_type;
14014       memcpy (new_args + 1, args, nargs * sizeof (tree));
14015       args = new_args;
14016       ++nargs;
14017     }
14018
14019   /* We allow incomplete unification without an error message here
14020      because the standard doesn't seem to explicitly prohibit it.  Our
14021      callers must be ready to deal with unification failures in any
14022      event.  */
14023   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
14024                                   targs, parms, args, nargs, /*subr=*/0,
14025                                   strict, flags);
14026
14027   /* Now that we have bindings for all of the template arguments,
14028      ensure that the arguments deduced for the template template
14029      parameters have compatible template parameter lists.  We cannot
14030      check this property before we have deduced all template
14031      arguments, because the template parameter types of a template
14032      template parameter might depend on prior template parameters
14033      deduced after the template template parameter.  The following
14034      ill-formed example illustrates this issue:
14035
14036        template<typename T, template<T> class C> void f(C<5>, T);
14037
14038        template<int N> struct X {};
14039
14040        void g() {
14041          f(X<5>(), 5l); // error: template argument deduction fails
14042        }
14043
14044      The template parameter list of 'C' depends on the template type
14045      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
14046      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
14047      time that we deduce 'C'.  */
14048   if (result == 0
14049       && !template_template_parm_bindings_ok_p 
14050            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
14051     return 1;
14052
14053   if (result == 0)
14054     /* All is well so far.  Now, check:
14055
14056        [temp.deduct]
14057
14058        When all template arguments have been deduced, all uses of
14059        template parameters in nondeduced contexts are replaced with
14060        the corresponding deduced argument values.  If the
14061        substitution results in an invalid type, as described above,
14062        type deduction fails.  */
14063     {
14064       tree substed;
14065       push_deduction_access_scope (fn);
14066       substed = deduction_tsubst_fntype (fn, targs);
14067       pop_deduction_access_scope (fn);
14068       if (substed == error_mark_node)
14069         return 1;
14070
14071       /* If we're looking for an exact match, check that what we got
14072          is indeed an exact match.  It might not be if some template
14073          parameters are used in non-deduced contexts.  */
14074       if (strict == DEDUCE_EXACT)
14075         {
14076           unsigned int i;
14077
14078           tree sarg
14079             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
14080           if (return_type)
14081             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
14082           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
14083             if (!same_type_p (args[i], TREE_VALUE (sarg)))
14084               return 1;
14085         }
14086     }
14087
14088   return result;
14089 }
14090
14091 /* Adjust types before performing type deduction, as described in
14092    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
14093    sections are symmetric.  PARM is the type of a function parameter
14094    or the return type of the conversion function.  ARG is the type of
14095    the argument passed to the call, or the type of the value
14096    initialized with the result of the conversion function.
14097    ARG_EXPR is the original argument expression, which may be null.  */
14098
14099 static int
14100 maybe_adjust_types_for_deduction (unification_kind_t strict,
14101                                   tree* parm,
14102                                   tree* arg,
14103                                   tree arg_expr)
14104 {
14105   int result = 0;
14106
14107   switch (strict)
14108     {
14109     case DEDUCE_CALL:
14110       break;
14111
14112     case DEDUCE_CONV:
14113       {
14114         /* Swap PARM and ARG throughout the remainder of this
14115            function; the handling is precisely symmetric since PARM
14116            will initialize ARG rather than vice versa.  */
14117         tree* temp = parm;
14118         parm = arg;
14119         arg = temp;
14120         break;
14121       }
14122
14123     case DEDUCE_EXACT:
14124       /* Core issue #873: Do the DR606 thing (see below) for these cases,
14125          too, but here handle it by stripping the reference from PARM
14126          rather than by adding it to ARG.  */
14127       if (TREE_CODE (*parm) == REFERENCE_TYPE
14128           && TYPE_REF_IS_RVALUE (*parm)
14129           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
14130           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
14131           && TREE_CODE (*arg) == REFERENCE_TYPE
14132           && !TYPE_REF_IS_RVALUE (*arg))
14133         *parm = TREE_TYPE (*parm);
14134       /* Nothing else to do in this case.  */
14135       return 0;
14136
14137     default:
14138       gcc_unreachable ();
14139     }
14140
14141   if (TREE_CODE (*parm) != REFERENCE_TYPE)
14142     {
14143       /* [temp.deduct.call]
14144
14145          If P is not a reference type:
14146
14147          --If A is an array type, the pointer type produced by the
14148          array-to-pointer standard conversion (_conv.array_) is
14149          used in place of A for type deduction; otherwise,
14150
14151          --If A is a function type, the pointer type produced by
14152          the function-to-pointer standard conversion
14153          (_conv.func_) is used in place of A for type deduction;
14154          otherwise,
14155
14156          --If A is a cv-qualified type, the top level
14157          cv-qualifiers of A's type are ignored for type
14158          deduction.  */
14159       if (TREE_CODE (*arg) == ARRAY_TYPE)
14160         *arg = build_pointer_type (TREE_TYPE (*arg));
14161       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
14162         *arg = build_pointer_type (*arg);
14163       else
14164         *arg = TYPE_MAIN_VARIANT (*arg);
14165     }
14166
14167   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
14168      of the form T&&, where T is a template parameter, and the argument
14169      is an lvalue, T is deduced as A& */
14170   if (TREE_CODE (*parm) == REFERENCE_TYPE
14171       && TYPE_REF_IS_RVALUE (*parm)
14172       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
14173       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
14174       && (arg_expr ? real_lvalue_p (arg_expr)
14175           /* try_one_overload doesn't provide an arg_expr, but
14176              functions are always lvalues.  */
14177           : TREE_CODE (*arg) == FUNCTION_TYPE))
14178     *arg = build_reference_type (*arg);
14179
14180   /* [temp.deduct.call]
14181
14182      If P is a cv-qualified type, the top level cv-qualifiers
14183      of P's type are ignored for type deduction.  If P is a
14184      reference type, the type referred to by P is used for
14185      type deduction.  */
14186   *parm = TYPE_MAIN_VARIANT (*parm);
14187   if (TREE_CODE (*parm) == REFERENCE_TYPE)
14188     {
14189       *parm = TREE_TYPE (*parm);
14190       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14191     }
14192
14193   /* DR 322. For conversion deduction, remove a reference type on parm
14194      too (which has been swapped into ARG).  */
14195   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
14196     *arg = TREE_TYPE (*arg);
14197
14198   return result;
14199 }
14200
14201 /* Most parms like fn_type_unification.
14202
14203    If SUBR is 1, we're being called recursively (to unify the
14204    arguments of a function or method parameter of a function
14205    template). */
14206
14207 static int
14208 type_unification_real (tree tparms,
14209                        tree targs,
14210                        tree xparms,
14211                        const tree *xargs,
14212                        unsigned int xnargs,
14213                        int subr,
14214                        unification_kind_t strict,
14215                        int flags)
14216 {
14217   tree parm, arg, arg_expr;
14218   int i;
14219   int ntparms = TREE_VEC_LENGTH (tparms);
14220   int sub_strict;
14221   int saw_undeduced = 0;
14222   tree parms;
14223   const tree *args;
14224   unsigned int nargs;
14225   unsigned int ia;
14226
14227   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
14228   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
14229   gcc_assert (ntparms > 0);
14230
14231   /* Reset the number of non-defaulted template arguments contained
14232      in TARGS.  */
14233   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
14234
14235   switch (strict)
14236     {
14237     case DEDUCE_CALL:
14238       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
14239                     | UNIFY_ALLOW_DERIVED);
14240       break;
14241
14242     case DEDUCE_CONV:
14243       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14244       break;
14245
14246     case DEDUCE_EXACT:
14247       sub_strict = UNIFY_ALLOW_NONE;
14248       break;
14249
14250     default:
14251       gcc_unreachable ();
14252     }
14253
14254  again:
14255   parms = xparms;
14256   args = xargs;
14257   nargs = xnargs;
14258
14259   ia = 0;
14260   while (parms && parms != void_list_node
14261          && ia < nargs)
14262     {
14263       parm = TREE_VALUE (parms);
14264
14265       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
14266           && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
14267         /* For a function parameter pack that occurs at the end of the
14268            parameter-declaration-list, the type A of each remaining
14269            argument of the call is compared with the type P of the
14270            declarator-id of the function parameter pack.  */
14271         break;
14272
14273       parms = TREE_CHAIN (parms);
14274
14275       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
14276         /* For a function parameter pack that does not occur at the
14277            end of the parameter-declaration-list, the type of the
14278            parameter pack is a non-deduced context.  */
14279         continue;
14280
14281       arg = args[ia];
14282       ++ia;
14283       arg_expr = NULL;
14284
14285       if (arg == error_mark_node)
14286         return 1;
14287       if (arg == unknown_type_node)
14288         /* We can't deduce anything from this, but we might get all the
14289            template args from other function args.  */
14290         continue;
14291
14292       /* Conversions will be performed on a function argument that
14293          corresponds with a function parameter that contains only
14294          non-deducible template parameters and explicitly specified
14295          template parameters.  */
14296       if (!uses_template_parms (parm))
14297         {
14298           tree type;
14299
14300           if (!TYPE_P (arg))
14301             type = TREE_TYPE (arg);
14302           else
14303             type = arg;
14304
14305           if (same_type_p (parm, type))
14306             continue;
14307           if (strict != DEDUCE_EXACT
14308               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
14309                                   flags))
14310             continue;
14311
14312           return 1;
14313         }
14314
14315       if (!TYPE_P (arg))
14316         {
14317           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14318           if (type_unknown_p (arg))
14319             {
14320               /* [temp.deduct.type] 
14321
14322                  A template-argument can be deduced from a pointer to
14323                  function or pointer to member function argument if
14324                  the set of overloaded functions does not contain
14325                  function templates and at most one of a set of
14326                  overloaded functions provides a unique match.  */
14327               if (resolve_overloaded_unification
14328                   (tparms, targs, parm, arg, strict, sub_strict))
14329                 continue;
14330
14331               return 1;
14332             }
14333           arg_expr = arg;
14334           arg = unlowered_expr_type (arg);
14335           if (arg == error_mark_node)
14336             return 1;
14337         }
14338
14339       {
14340         int arg_strict = sub_strict;
14341
14342         if (!subr)
14343           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
14344                                                           arg_expr);
14345
14346         if (arg == init_list_type_node && arg_expr)
14347           arg = arg_expr;
14348         if (unify (tparms, targs, parm, arg, arg_strict))
14349           return 1;
14350       }
14351     }
14352
14353
14354   if (parms 
14355       && parms != void_list_node
14356       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
14357     {
14358       /* Unify the remaining arguments with the pack expansion type.  */
14359       tree argvec;
14360       tree parmvec = make_tree_vec (1);
14361
14362       /* Allocate a TREE_VEC and copy in all of the arguments */ 
14363       argvec = make_tree_vec (nargs - ia);
14364       for (i = 0; ia < nargs; ++ia, ++i)
14365         TREE_VEC_ELT (argvec, i) = args[ia];
14366
14367       /* Copy the parameter into parmvec.  */
14368       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
14369       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
14370                                 /*call_args_p=*/true, /*subr=*/subr))
14371         return 1;
14372
14373       /* Advance to the end of the list of parameters.  */
14374       parms = TREE_CHAIN (parms);
14375     }
14376
14377   /* Fail if we've reached the end of the parm list, and more args
14378      are present, and the parm list isn't variadic.  */
14379   if (ia < nargs && parms == void_list_node)
14380     return 1;
14381   /* Fail if parms are left and they don't have default values.  */
14382   if (parms && parms != void_list_node
14383       && TREE_PURPOSE (parms) == NULL_TREE)
14384     return 1;
14385
14386   if (!subr)
14387     {
14388       /* Check to see if we need another pass before we start clearing
14389          ARGUMENT_PACK_INCOMPLETE_P.  */
14390       for (i = 0; i < ntparms; i++)
14391         {
14392           tree targ = TREE_VEC_ELT (targs, i);
14393           tree tparm = TREE_VEC_ELT (tparms, i);
14394
14395           if (targ || tparm == error_mark_node)
14396             continue;
14397           tparm = TREE_VALUE (tparm);
14398
14399           /* If this is an undeduced nontype parameter that depends on
14400              a type parameter, try another pass; its type may have been
14401              deduced from a later argument than the one from which
14402              this parameter can be deduced.  */
14403           if (TREE_CODE (tparm) == PARM_DECL
14404               && uses_template_parms (TREE_TYPE (tparm))
14405               && !saw_undeduced++)
14406             goto again;
14407         }
14408
14409       for (i = 0; i < ntparms; i++)
14410         {
14411           tree targ = TREE_VEC_ELT (targs, i);
14412           tree tparm = TREE_VEC_ELT (tparms, i);
14413
14414           /* Clear the "incomplete" flags on all argument packs now so that
14415              substituting them into later default arguments works.  */
14416           if (targ && ARGUMENT_PACK_P (targ))
14417             {
14418               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
14419               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
14420             }
14421
14422           if (targ || tparm == error_mark_node)
14423             continue;
14424           tparm = TREE_VALUE (tparm);
14425
14426           /* Core issue #226 (C++0x) [temp.deduct]:
14427
14428              If a template argument has not been deduced, its
14429              default template argument, if any, is used. 
14430
14431              When we are in C++98 mode, TREE_PURPOSE will either
14432              be NULL_TREE or ERROR_MARK_NODE, so we do not need
14433              to explicitly check cxx_dialect here.  */
14434           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
14435             {
14436               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
14437               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
14438               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
14439               arg = convert_template_argument (parm, arg, targs, tf_none,
14440                                                i, NULL_TREE);
14441               if (arg == error_mark_node)
14442                 return 1;
14443               else
14444                 {
14445                   TREE_VEC_ELT (targs, i) = arg;
14446                   /* The position of the first default template argument,
14447                      is also the number of non-defaulted arguments in TARGS.
14448                      Record that.  */
14449                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
14450                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
14451                   continue;
14452                 }
14453             }
14454
14455           /* If the type parameter is a parameter pack, then it will
14456              be deduced to an empty parameter pack.  */
14457           if (template_parameter_pack_p (tparm))
14458             {
14459               tree arg;
14460
14461               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
14462                 {
14463                   arg = make_node (NONTYPE_ARGUMENT_PACK);
14464                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
14465                   TREE_CONSTANT (arg) = 1;
14466                 }
14467               else
14468                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
14469
14470               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
14471
14472               TREE_VEC_ELT (targs, i) = arg;
14473               continue;
14474             }
14475
14476           return 2;
14477         }
14478     }
14479 #ifdef ENABLE_CHECKING
14480   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
14481     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
14482 #endif
14483
14484   return 0;
14485 }
14486
14487 /* Subroutine of type_unification_real.  Args are like the variables
14488    at the call site.  ARG is an overloaded function (or template-id);
14489    we try deducing template args from each of the overloads, and if
14490    only one succeeds, we go with that.  Modifies TARGS and returns
14491    true on success.  */
14492
14493 static bool
14494 resolve_overloaded_unification (tree tparms,
14495                                 tree targs,
14496                                 tree parm,
14497                                 tree arg,
14498                                 unification_kind_t strict,
14499                                 int sub_strict)
14500 {
14501   tree tempargs = copy_node (targs);
14502   int good = 0;
14503   tree goodfn = NULL_TREE;
14504   bool addr_p;
14505
14506   if (TREE_CODE (arg) == ADDR_EXPR)
14507     {
14508       arg = TREE_OPERAND (arg, 0);
14509       addr_p = true;
14510     }
14511   else
14512     addr_p = false;
14513
14514   if (TREE_CODE (arg) == COMPONENT_REF)
14515     /* Handle `&x' where `x' is some static or non-static member
14516        function name.  */
14517     arg = TREE_OPERAND (arg, 1);
14518
14519   if (TREE_CODE (arg) == OFFSET_REF)
14520     arg = TREE_OPERAND (arg, 1);
14521
14522   /* Strip baselink information.  */
14523   if (BASELINK_P (arg))
14524     arg = BASELINK_FUNCTIONS (arg);
14525
14526   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
14527     {
14528       /* If we got some explicit template args, we need to plug them into
14529          the affected templates before we try to unify, in case the
14530          explicit args will completely resolve the templates in question.  */
14531
14532       tree expl_subargs = TREE_OPERAND (arg, 1);
14533       arg = TREE_OPERAND (arg, 0);
14534
14535       for (; arg; arg = OVL_NEXT (arg))
14536         {
14537           tree fn = OVL_CURRENT (arg);
14538           tree subargs, elem;
14539
14540           if (TREE_CODE (fn) != TEMPLATE_DECL)
14541             continue;
14542
14543           ++processing_template_decl;
14544           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
14545                                   expl_subargs, /*check_ret=*/false);
14546           if (subargs)
14547             {
14548               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
14549               if (try_one_overload (tparms, targs, tempargs, parm,
14550                                     elem, strict, sub_strict, addr_p)
14551                   && (!goodfn || !decls_match (goodfn, elem)))
14552                 {
14553                   goodfn = elem;
14554                   ++good;
14555                 }
14556             }
14557           --processing_template_decl;
14558         }
14559     }
14560   else if (TREE_CODE (arg) != OVERLOAD
14561            && TREE_CODE (arg) != FUNCTION_DECL)
14562     /* If ARG is, for example, "(0, &f)" then its type will be unknown
14563        -- but the deduction does not succeed because the expression is
14564        not just the function on its own.  */
14565     return false;
14566   else
14567     for (; arg; arg = OVL_NEXT (arg))
14568       if (try_one_overload (tparms, targs, tempargs, parm,
14569                             TREE_TYPE (OVL_CURRENT (arg)),
14570                             strict, sub_strict, addr_p)
14571           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
14572         {
14573           goodfn = OVL_CURRENT (arg);
14574           ++good;
14575         }
14576
14577   /* [temp.deduct.type] A template-argument can be deduced from a pointer
14578      to function or pointer to member function argument if the set of
14579      overloaded functions does not contain function templates and at most
14580      one of a set of overloaded functions provides a unique match.
14581
14582      So if we found multiple possibilities, we return success but don't
14583      deduce anything.  */
14584
14585   if (good == 1)
14586     {
14587       int i = TREE_VEC_LENGTH (targs);
14588       for (; i--; )
14589         if (TREE_VEC_ELT (tempargs, i))
14590           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
14591     }
14592   if (good)
14593     return true;
14594
14595   return false;
14596 }
14597
14598 /* Core DR 115: In contexts where deduction is done and fails, or in
14599    contexts where deduction is not done, if a template argument list is
14600    specified and it, along with any default template arguments, identifies
14601    a single function template specialization, then the template-id is an
14602    lvalue for the function template specialization.  */
14603
14604 tree
14605 resolve_nondeduced_context (tree orig_expr)
14606 {
14607   tree expr, offset, baselink;
14608   bool addr;
14609
14610   if (!type_unknown_p (orig_expr))
14611     return orig_expr;
14612
14613   expr = orig_expr;
14614   addr = false;
14615   offset = NULL_TREE;
14616   baselink = NULL_TREE;
14617
14618   if (TREE_CODE (expr) == ADDR_EXPR)
14619     {
14620       expr = TREE_OPERAND (expr, 0);
14621       addr = true;
14622     }
14623   if (TREE_CODE (expr) == OFFSET_REF)
14624     {
14625       offset = expr;
14626       expr = TREE_OPERAND (expr, 1);
14627     }
14628   if (TREE_CODE (expr) == BASELINK)
14629     {
14630       baselink = expr;
14631       expr = BASELINK_FUNCTIONS (expr);
14632     }
14633
14634   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
14635     {
14636       int good = 0;
14637       tree goodfn = NULL_TREE;
14638
14639       /* If we got some explicit template args, we need to plug them into
14640          the affected templates before we try to unify, in case the
14641          explicit args will completely resolve the templates in question.  */
14642
14643       tree expl_subargs = TREE_OPERAND (expr, 1);
14644       tree arg = TREE_OPERAND (expr, 0);
14645       tree badfn = NULL_TREE;
14646       tree badargs = NULL_TREE;
14647
14648       for (; arg; arg = OVL_NEXT (arg))
14649         {
14650           tree fn = OVL_CURRENT (arg);
14651           tree subargs, elem;
14652
14653           if (TREE_CODE (fn) != TEMPLATE_DECL)
14654             continue;
14655
14656           ++processing_template_decl;
14657           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
14658                                   expl_subargs, /*check_ret=*/false);
14659           if (subargs && !any_dependent_template_arguments_p (subargs))
14660             {
14661               elem = instantiate_template (fn, subargs, tf_none);
14662               if (elem == error_mark_node)
14663                 {
14664                   badfn = fn;
14665                   badargs = subargs;
14666                 }
14667               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
14668                 {
14669                   goodfn = elem;
14670                   ++good;
14671                 }
14672             }
14673           --processing_template_decl;
14674         }
14675       if (good == 1)
14676         {
14677           expr = goodfn;
14678           if (baselink)
14679             expr = build_baselink (BASELINK_BINFO (baselink),
14680                                    BASELINK_ACCESS_BINFO (baselink),
14681                                    expr, BASELINK_OPTYPE (baselink));
14682           if (offset)
14683             {
14684               tree base
14685                 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
14686               expr = build_offset_ref (base, expr, addr);
14687             }
14688           if (addr)
14689             expr = cp_build_addr_expr (expr, tf_warning_or_error);
14690           return expr;
14691         }
14692       else if (good == 0 && badargs)
14693         /* There were no good options and at least one bad one, so let the
14694            user know what the problem is.  */
14695         instantiate_template (badfn, badargs, tf_warning_or_error);
14696     }
14697   return orig_expr;
14698 }
14699
14700 /* Subroutine of resolve_overloaded_unification; does deduction for a single
14701    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
14702    different overloads deduce different arguments for a given parm.
14703    ADDR_P is true if the expression for which deduction is being
14704    performed was of the form "& fn" rather than simply "fn".
14705
14706    Returns 1 on success.  */
14707
14708 static int
14709 try_one_overload (tree tparms,
14710                   tree orig_targs,
14711                   tree targs,
14712                   tree parm,
14713                   tree arg,
14714                   unification_kind_t strict,
14715                   int sub_strict,
14716                   bool addr_p)
14717 {
14718   int nargs;
14719   tree tempargs;
14720   int i;
14721
14722   /* [temp.deduct.type] A template-argument can be deduced from a pointer
14723      to function or pointer to member function argument if the set of
14724      overloaded functions does not contain function templates and at most
14725      one of a set of overloaded functions provides a unique match.
14726
14727      So if this is a template, just return success.  */
14728
14729   if (uses_template_parms (arg))
14730     return 1;
14731
14732   if (TREE_CODE (arg) == METHOD_TYPE)
14733     arg = build_ptrmemfunc_type (build_pointer_type (arg));
14734   else if (addr_p)
14735     arg = build_pointer_type (arg);
14736
14737   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
14738
14739   /* We don't copy orig_targs for this because if we have already deduced
14740      some template args from previous args, unify would complain when we
14741      try to deduce a template parameter for the same argument, even though
14742      there isn't really a conflict.  */
14743   nargs = TREE_VEC_LENGTH (targs);
14744   tempargs = make_tree_vec (nargs);
14745
14746   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
14747     return 0;
14748
14749   /* First make sure we didn't deduce anything that conflicts with
14750      explicitly specified args.  */
14751   for (i = nargs; i--; )
14752     {
14753       tree elt = TREE_VEC_ELT (tempargs, i);
14754       tree oldelt = TREE_VEC_ELT (orig_targs, i);
14755
14756       if (!elt)
14757         /*NOP*/;
14758       else if (uses_template_parms (elt))
14759         /* Since we're unifying against ourselves, we will fill in
14760            template args used in the function parm list with our own
14761            template parms.  Discard them.  */
14762         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
14763       else if (oldelt && !template_args_equal (oldelt, elt))
14764         return 0;
14765     }
14766
14767   for (i = nargs; i--; )
14768     {
14769       tree elt = TREE_VEC_ELT (tempargs, i);
14770
14771       if (elt)
14772         TREE_VEC_ELT (targs, i) = elt;
14773     }
14774
14775   return 1;
14776 }
14777
14778 /* PARM is a template class (perhaps with unbound template
14779    parameters).  ARG is a fully instantiated type.  If ARG can be
14780    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
14781    TARGS are as for unify.  */
14782
14783 static tree
14784 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
14785 {
14786   tree copy_of_targs;
14787
14788   if (!CLASSTYPE_TEMPLATE_INFO (arg)
14789       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
14790           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
14791     return NULL_TREE;
14792
14793   /* We need to make a new template argument vector for the call to
14794      unify.  If we used TARGS, we'd clutter it up with the result of
14795      the attempted unification, even if this class didn't work out.
14796      We also don't want to commit ourselves to all the unifications
14797      we've already done, since unification is supposed to be done on
14798      an argument-by-argument basis.  In other words, consider the
14799      following pathological case:
14800
14801        template <int I, int J, int K>
14802        struct S {};
14803
14804        template <int I, int J>
14805        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
14806
14807        template <int I, int J, int K>
14808        void f(S<I, J, K>, S<I, I, I>);
14809
14810        void g() {
14811          S<0, 0, 0> s0;
14812          S<0, 1, 2> s2;
14813
14814          f(s0, s2);
14815        }
14816
14817      Now, by the time we consider the unification involving `s2', we
14818      already know that we must have `f<0, 0, 0>'.  But, even though
14819      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
14820      because there are two ways to unify base classes of S<0, 1, 2>
14821      with S<I, I, I>.  If we kept the already deduced knowledge, we
14822      would reject the possibility I=1.  */
14823   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
14824
14825   /* If unification failed, we're done.  */
14826   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
14827              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
14828     return NULL_TREE;
14829
14830   return arg;
14831 }
14832
14833 /* Given a template type PARM and a class type ARG, find the unique
14834    base type in ARG that is an instance of PARM.  We do not examine
14835    ARG itself; only its base-classes.  If there is not exactly one
14836    appropriate base class, return NULL_TREE.  PARM may be the type of
14837    a partial specialization, as well as a plain template type.  Used
14838    by unify.  */
14839
14840 static tree
14841 get_template_base (tree tparms, tree targs, tree parm, tree arg)
14842 {
14843   tree rval = NULL_TREE;
14844   tree binfo;
14845
14846   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
14847
14848   binfo = TYPE_BINFO (complete_type (arg));
14849   if (!binfo)
14850     /* The type could not be completed.  */
14851     return NULL_TREE;
14852
14853   /* Walk in inheritance graph order.  The search order is not
14854      important, and this avoids multiple walks of virtual bases.  */
14855   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
14856     {
14857       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
14858
14859       if (r)
14860         {
14861           /* If there is more than one satisfactory baseclass, then:
14862
14863                [temp.deduct.call]
14864
14865               If they yield more than one possible deduced A, the type
14866               deduction fails.
14867
14868              applies.  */
14869           if (rval && !same_type_p (r, rval))
14870             return NULL_TREE;
14871
14872           rval = r;
14873         }
14874     }
14875
14876   return rval;
14877 }
14878
14879 /* Returns the level of DECL, which declares a template parameter.  */
14880
14881 static int
14882 template_decl_level (tree decl)
14883 {
14884   switch (TREE_CODE (decl))
14885     {
14886     case TYPE_DECL:
14887     case TEMPLATE_DECL:
14888       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
14889
14890     case PARM_DECL:
14891       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
14892
14893     default:
14894       gcc_unreachable ();
14895     }
14896   return 0;
14897 }
14898
14899 /* Decide whether ARG can be unified with PARM, considering only the
14900    cv-qualifiers of each type, given STRICT as documented for unify.
14901    Returns nonzero iff the unification is OK on that basis.  */
14902
14903 static int
14904 check_cv_quals_for_unify (int strict, tree arg, tree parm)
14905 {
14906   int arg_quals = cp_type_quals (arg);
14907   int parm_quals = cp_type_quals (parm);
14908
14909   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14910       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14911     {
14912       /*  Although a CVR qualifier is ignored when being applied to a
14913           substituted template parameter ([8.3.2]/1 for example), that
14914           does not allow us to unify "const T" with "int&" because both
14915           types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
14916           It is ok when we're allowing additional CV qualifiers
14917           at the outer level [14.8.2.1]/3,1st bullet.  */
14918       if ((TREE_CODE (arg) == REFERENCE_TYPE
14919            || TREE_CODE (arg) == FUNCTION_TYPE
14920            || TREE_CODE (arg) == METHOD_TYPE)
14921           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
14922         return 0;
14923
14924       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
14925           && (parm_quals & TYPE_QUAL_RESTRICT))
14926         return 0;
14927     }
14928
14929   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14930       && (arg_quals & parm_quals) != parm_quals)
14931     return 0;
14932
14933   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
14934       && (parm_quals & arg_quals) != arg_quals)
14935     return 0;
14936
14937   return 1;
14938 }
14939
14940 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
14941 void 
14942 template_parm_level_and_index (tree parm, int* level, int* index)
14943 {
14944   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14945       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14946       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14947     {
14948       *index = TEMPLATE_TYPE_IDX (parm);
14949       *level = TEMPLATE_TYPE_LEVEL (parm);
14950     }
14951   else
14952     {
14953       *index = TEMPLATE_PARM_IDX (parm);
14954       *level = TEMPLATE_PARM_LEVEL (parm);
14955     }
14956 }
14957
14958 /* Unifies the remaining arguments in PACKED_ARGS with the pack
14959    expansion at the end of PACKED_PARMS. Returns 0 if the type
14960    deduction succeeds, 1 otherwise. STRICT is the same as in
14961    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
14962    call argument list. We'll need to adjust the arguments to make them
14963    types. SUBR tells us if this is from a recursive call to
14964    type_unification_real.  */
14965 int
14966 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
14967                       tree packed_args, int strict, bool call_args_p,
14968                       bool subr)
14969 {
14970   tree parm 
14971     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
14972   tree pattern = PACK_EXPANSION_PATTERN (parm);
14973   tree pack, packs = NULL_TREE;
14974   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
14975   int len = TREE_VEC_LENGTH (packed_args);
14976
14977   /* Determine the parameter packs we will be deducing from the
14978      pattern, and record their current deductions.  */
14979   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
14980        pack; pack = TREE_CHAIN (pack))
14981     {
14982       tree parm_pack = TREE_VALUE (pack);
14983       int idx, level;
14984
14985       /* Determine the index and level of this parameter pack.  */
14986       template_parm_level_and_index (parm_pack, &level, &idx);
14987
14988       /* Keep track of the parameter packs and their corresponding
14989          argument packs.  */
14990       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
14991       TREE_TYPE (packs) = make_tree_vec (len - start);
14992     }
14993   
14994   /* Loop through all of the arguments that have not yet been
14995      unified and unify each with the pattern.  */
14996   for (i = start; i < len; i++)
14997     {
14998       tree parm = pattern;
14999
15000       /* For each parameter pack, clear out the deduced value so that
15001          we can deduce it again.  */
15002       for (pack = packs; pack; pack = TREE_CHAIN (pack))
15003         {
15004           int idx, level;
15005           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15006
15007           TMPL_ARG (targs, level, idx) = NULL_TREE;
15008         }
15009
15010       /* Unify the pattern with the current argument.  */
15011       {
15012         tree arg = TREE_VEC_ELT (packed_args, i);
15013         tree arg_expr = NULL_TREE;
15014         int arg_strict = strict;
15015         bool skip_arg_p = false;
15016
15017         if (call_args_p)
15018           {
15019             int sub_strict;
15020
15021             /* This mirrors what we do in type_unification_real.  */
15022             switch (strict)
15023               {
15024               case DEDUCE_CALL:
15025                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
15026                               | UNIFY_ALLOW_MORE_CV_QUAL
15027                               | UNIFY_ALLOW_DERIVED);
15028                 break;
15029                 
15030               case DEDUCE_CONV:
15031                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
15032                 break;
15033                 
15034               case DEDUCE_EXACT:
15035                 sub_strict = UNIFY_ALLOW_NONE;
15036                 break;
15037                 
15038               default:
15039                 gcc_unreachable ();
15040               }
15041
15042             if (!TYPE_P (arg))
15043               {
15044                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
15045                 if (type_unknown_p (arg))
15046                   {
15047                     /* [temp.deduct.type] A template-argument can be
15048                        deduced from a pointer to function or pointer
15049                        to member function argument if the set of
15050                        overloaded functions does not contain function
15051                        templates and at most one of a set of
15052                        overloaded functions provides a unique
15053                        match.  */
15054
15055                     if (resolve_overloaded_unification
15056                         (tparms, targs, parm, arg,
15057                          (unification_kind_t) strict,
15058                          sub_strict)
15059                         != 0)
15060                       return 1;
15061                     skip_arg_p = true;
15062                   }
15063
15064                 if (!skip_arg_p)
15065                   {
15066                     arg_expr = arg;
15067                     arg = unlowered_expr_type (arg);
15068                     if (arg == error_mark_node)
15069                       return 1;
15070                   }
15071               }
15072       
15073             arg_strict = sub_strict;
15074
15075             if (!subr)
15076               arg_strict |= 
15077                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
15078                                                   &parm, &arg, arg_expr);
15079           }
15080
15081         if (!skip_arg_p)
15082           {
15083             /* For deduction from an init-list we need the actual list.  */
15084             if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
15085               arg = arg_expr;
15086             if (unify (tparms, targs, parm, arg, arg_strict))
15087               return 1;
15088           }
15089       }
15090
15091       /* For each parameter pack, collect the deduced value.  */
15092       for (pack = packs; pack; pack = TREE_CHAIN (pack))
15093         {
15094           int idx, level;
15095           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15096
15097           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
15098             TMPL_ARG (targs, level, idx);
15099         }
15100     }
15101
15102   /* Verify that the results of unification with the parameter packs
15103      produce results consistent with what we've seen before, and make
15104      the deduced argument packs available.  */
15105   for (pack = packs; pack; pack = TREE_CHAIN (pack))
15106     {
15107       tree old_pack = TREE_VALUE (pack);
15108       tree new_args = TREE_TYPE (pack);
15109       int i, len = TREE_VEC_LENGTH (new_args);
15110       int idx, level;
15111       bool nondeduced_p = false;
15112
15113       /* By default keep the original deduced argument pack.
15114          If necessary, more specific code is going to update the
15115          resulting deduced argument later down in this function.  */
15116       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15117       TMPL_ARG (targs, level, idx) = old_pack;
15118
15119       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
15120          actually deduce anything.  */
15121       for (i = 0; i < len && !nondeduced_p; ++i)
15122         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
15123           nondeduced_p = true;
15124       if (nondeduced_p)
15125         continue;
15126
15127       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
15128         {
15129           /* Prepend the explicit arguments onto NEW_ARGS.  */
15130           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
15131           tree old_args = new_args;
15132           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
15133           int len = explicit_len + TREE_VEC_LENGTH (old_args);
15134
15135           /* Copy the explicit arguments.  */
15136           new_args = make_tree_vec (len);
15137           for (i = 0; i < explicit_len; i++)
15138             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
15139
15140           /* Copy the deduced arguments.  */
15141           for (; i < len; i++)
15142             TREE_VEC_ELT (new_args, i) =
15143               TREE_VEC_ELT (old_args, i - explicit_len);
15144         }
15145
15146       if (!old_pack)
15147         {
15148           tree result;
15149           /* Build the deduced *_ARGUMENT_PACK.  */
15150           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
15151             {
15152               result = make_node (NONTYPE_ARGUMENT_PACK);
15153               TREE_TYPE (result) = 
15154                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
15155               TREE_CONSTANT (result) = 1;
15156             }
15157           else
15158             result = cxx_make_type (TYPE_ARGUMENT_PACK);
15159
15160           SET_ARGUMENT_PACK_ARGS (result, new_args);
15161
15162           /* Note the deduced argument packs for this parameter
15163              pack.  */
15164           TMPL_ARG (targs, level, idx) = result;
15165         }
15166       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
15167                && (ARGUMENT_PACK_ARGS (old_pack) 
15168                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
15169         {
15170           /* We only had the explicitly-provided arguments before, but
15171              now we have a complete set of arguments.  */
15172           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
15173
15174           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
15175           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
15176           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
15177         }
15178       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
15179                                     new_args))
15180         /* Inconsistent unification of this parameter pack.  */
15181         return 1;
15182     }
15183
15184   return 0;
15185 }
15186
15187 /* Deduce the value of template parameters.  TPARMS is the (innermost)
15188    set of template parameters to a template.  TARGS is the bindings
15189    for those template parameters, as determined thus far; TARGS may
15190    include template arguments for outer levels of template parameters
15191    as well.  PARM is a parameter to a template function, or a
15192    subcomponent of that parameter; ARG is the corresponding argument.
15193    This function attempts to match PARM with ARG in a manner
15194    consistent with the existing assignments in TARGS.  If more values
15195    are deduced, then TARGS is updated.
15196
15197    Returns 0 if the type deduction succeeds, 1 otherwise.  The
15198    parameter STRICT is a bitwise or of the following flags:
15199
15200      UNIFY_ALLOW_NONE:
15201        Require an exact match between PARM and ARG.
15202      UNIFY_ALLOW_MORE_CV_QUAL:
15203        Allow the deduced ARG to be more cv-qualified (by qualification
15204        conversion) than ARG.
15205      UNIFY_ALLOW_LESS_CV_QUAL:
15206        Allow the deduced ARG to be less cv-qualified than ARG.
15207      UNIFY_ALLOW_DERIVED:
15208        Allow the deduced ARG to be a template base class of ARG,
15209        or a pointer to a template base class of the type pointed to by
15210        ARG.
15211      UNIFY_ALLOW_INTEGER:
15212        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
15213        case for more information.
15214      UNIFY_ALLOW_OUTER_LEVEL:
15215        This is the outermost level of a deduction. Used to determine validity
15216        of qualification conversions. A valid qualification conversion must
15217        have const qualified pointers leading up to the inner type which
15218        requires additional CV quals, except at the outer level, where const
15219        is not required [conv.qual]. It would be normal to set this flag in
15220        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
15221      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
15222        This is the outermost level of a deduction, and PARM can be more CV
15223        qualified at this point.
15224      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
15225        This is the outermost level of a deduction, and PARM can be less CV
15226        qualified at this point.  */
15227
15228 static int
15229 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
15230 {
15231   int idx;
15232   tree targ;
15233   tree tparm;
15234   int strict_in = strict;
15235
15236   /* I don't think this will do the right thing with respect to types.
15237      But the only case I've seen it in so far has been array bounds, where
15238      signedness is the only information lost, and I think that will be
15239      okay.  */
15240   while (TREE_CODE (parm) == NOP_EXPR)
15241     parm = TREE_OPERAND (parm, 0);
15242
15243   if (arg == error_mark_node)
15244     return 1;
15245   if (arg == unknown_type_node
15246       || arg == init_list_type_node)
15247     /* We can't deduce anything from this, but we might get all the
15248        template args from other function args.  */
15249     return 0;
15250
15251   /* If PARM uses template parameters, then we can't bail out here,
15252      even if ARG == PARM, since we won't record unifications for the
15253      template parameters.  We might need them if we're trying to
15254      figure out which of two things is more specialized.  */
15255   if (arg == parm && !uses_template_parms (parm))
15256     return 0;
15257
15258   /* Handle init lists early, so the rest of the function can assume
15259      we're dealing with a type. */
15260   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
15261     {
15262       tree elt, elttype;
15263       unsigned i;
15264       tree orig_parm = parm;
15265
15266       /* Replace T with std::initializer_list<T> for deduction.  */
15267       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15268           && flag_deduce_init_list)
15269         parm = listify (parm);
15270
15271       if (!is_std_init_list (parm))
15272         /* We can only deduce from an initializer list argument if the
15273            parameter is std::initializer_list; otherwise this is a
15274            non-deduced context. */
15275         return 0;
15276
15277       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
15278
15279       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
15280         {
15281           int elt_strict = strict;
15282
15283           if (elt == error_mark_node)
15284             return 1;
15285
15286           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
15287             {
15288               tree type = TREE_TYPE (elt);
15289               /* It should only be possible to get here for a call.  */
15290               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
15291               elt_strict |= maybe_adjust_types_for_deduction
15292                 (DEDUCE_CALL, &elttype, &type, elt);
15293               elt = type;
15294             }
15295
15296           if (unify (tparms, targs, elttype, elt, elt_strict))
15297             return 1;
15298         }
15299
15300       /* If the std::initializer_list<T> deduction worked, replace the
15301          deduced A with std::initializer_list<A>.  */
15302       if (orig_parm != parm)
15303         {
15304           idx = TEMPLATE_TYPE_IDX (orig_parm);
15305           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15306           targ = listify (targ);
15307           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
15308         }
15309       return 0;
15310     }
15311
15312   /* Immediately reject some pairs that won't unify because of
15313      cv-qualification mismatches.  */
15314   if (TREE_CODE (arg) == TREE_CODE (parm)
15315       && TYPE_P (arg)
15316       /* It is the elements of the array which hold the cv quals of an array
15317          type, and the elements might be template type parms. We'll check
15318          when we recurse.  */
15319       && TREE_CODE (arg) != ARRAY_TYPE
15320       /* We check the cv-qualifiers when unifying with template type
15321          parameters below.  We want to allow ARG `const T' to unify with
15322          PARM `T' for example, when computing which of two templates
15323          is more specialized, for example.  */
15324       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
15325       && !check_cv_quals_for_unify (strict_in, arg, parm))
15326     return 1;
15327
15328   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
15329       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
15330     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
15331   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
15332   strict &= ~UNIFY_ALLOW_DERIVED;
15333   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
15334   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
15335
15336   switch (TREE_CODE (parm))
15337     {
15338     case TYPENAME_TYPE:
15339     case SCOPE_REF:
15340     case UNBOUND_CLASS_TEMPLATE:
15341       /* In a type which contains a nested-name-specifier, template
15342          argument values cannot be deduced for template parameters used
15343          within the nested-name-specifier.  */
15344       return 0;
15345
15346     case TEMPLATE_TYPE_PARM:
15347     case TEMPLATE_TEMPLATE_PARM:
15348     case BOUND_TEMPLATE_TEMPLATE_PARM:
15349       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
15350       if (tparm == error_mark_node)
15351         return 1;
15352
15353       if (TEMPLATE_TYPE_LEVEL (parm)
15354           != template_decl_level (tparm))
15355         /* The PARM is not one we're trying to unify.  Just check
15356            to see if it matches ARG.  */
15357         return (TREE_CODE (arg) == TREE_CODE (parm)
15358                 && same_type_p (parm, arg)) ? 0 : 1;
15359       idx = TEMPLATE_TYPE_IDX (parm);
15360       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15361       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
15362
15363       /* Check for mixed types and values.  */
15364       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15365            && TREE_CODE (tparm) != TYPE_DECL)
15366           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15367               && TREE_CODE (tparm) != TEMPLATE_DECL))
15368         return 1;
15369
15370       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15371         {
15372           /* ARG must be constructed from a template class or a template
15373              template parameter.  */
15374           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
15375               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
15376             return 1;
15377
15378           {
15379             tree parmvec = TYPE_TI_ARGS (parm);
15380             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
15381             tree full_argvec = add_to_template_args (targs, argvec);
15382             tree parm_parms 
15383               = DECL_INNERMOST_TEMPLATE_PARMS
15384                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
15385             int i, len;
15386             int parm_variadic_p = 0;
15387
15388             /* The resolution to DR150 makes clear that default
15389                arguments for an N-argument may not be used to bind T
15390                to a template template parameter with fewer than N
15391                parameters.  It is not safe to permit the binding of
15392                default arguments as an extension, as that may change
15393                the meaning of a conforming program.  Consider:
15394
15395                   struct Dense { static const unsigned int dim = 1; };
15396
15397                   template <template <typename> class View,
15398                             typename Block>
15399                   void operator+(float, View<Block> const&);
15400
15401                   template <typename Block,
15402                             unsigned int Dim = Block::dim>
15403                   struct Lvalue_proxy { operator float() const; };
15404
15405                   void
15406                   test_1d (void) {
15407                     Lvalue_proxy<Dense> p;
15408                     float b;
15409                     b + p;
15410                   }
15411
15412               Here, if Lvalue_proxy is permitted to bind to View, then
15413               the global operator+ will be used; if they are not, the
15414               Lvalue_proxy will be converted to float.  */
15415             if (coerce_template_parms (parm_parms,
15416                                        full_argvec,
15417                                        TYPE_TI_TEMPLATE (parm),
15418                                        tf_none,
15419                                        /*require_all_args=*/true,
15420                                        /*use_default_args=*/false)
15421                 == error_mark_node)
15422               return 1;
15423
15424             /* Deduce arguments T, i from TT<T> or TT<i>.
15425                We check each element of PARMVEC and ARGVEC individually
15426                rather than the whole TREE_VEC since they can have
15427                different number of elements.  */
15428
15429             parmvec = expand_template_argument_pack (parmvec);
15430             argvec = expand_template_argument_pack (argvec);
15431
15432             len = TREE_VEC_LENGTH (parmvec);
15433
15434             /* Check if the parameters end in a pack, making them
15435                variadic.  */
15436             if (len > 0
15437                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
15438               parm_variadic_p = 1;
15439             
15440             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
15441               return 1;
15442
15443              for (i = 0; i < len - parm_variadic_p; ++i)
15444               {
15445                 if (unify (tparms, targs,
15446                            TREE_VEC_ELT (parmvec, i),
15447                            TREE_VEC_ELT (argvec, i),
15448                            UNIFY_ALLOW_NONE))
15449                   return 1;
15450               }
15451
15452             if (parm_variadic_p
15453                 && unify_pack_expansion (tparms, targs,
15454                                          parmvec, argvec,
15455                                          UNIFY_ALLOW_NONE,
15456                                          /*call_args_p=*/false,
15457                                          /*subr=*/false))
15458               return 1;
15459           }
15460           arg = TYPE_TI_TEMPLATE (arg);
15461
15462           /* Fall through to deduce template name.  */
15463         }
15464
15465       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15466           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15467         {
15468           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
15469
15470           /* Simple cases: Value already set, does match or doesn't.  */
15471           if (targ != NULL_TREE && template_args_equal (targ, arg))
15472             return 0;
15473           else if (targ)
15474             return 1;
15475         }
15476       else
15477         {
15478           /* If PARM is `const T' and ARG is only `int', we don't have
15479              a match unless we are allowing additional qualification.
15480              If ARG is `const int' and PARM is just `T' that's OK;
15481              that binds `const int' to `T'.  */
15482           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
15483                                          arg, parm))
15484             return 1;
15485
15486           /* Consider the case where ARG is `const volatile int' and
15487              PARM is `const T'.  Then, T should be `volatile int'.  */
15488           arg = cp_build_qualified_type_real
15489             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
15490           if (arg == error_mark_node)
15491             return 1;
15492
15493           /* Simple cases: Value already set, does match or doesn't.  */
15494           if (targ != NULL_TREE && same_type_p (targ, arg))
15495             return 0;
15496           else if (targ)
15497             return 1;
15498
15499           /* Make sure that ARG is not a variable-sized array.  (Note
15500              that were talking about variable-sized arrays (like
15501              `int[n]'), rather than arrays of unknown size (like
15502              `int[]').)  We'll get very confused by such a type since
15503              the bound of the array will not be computable in an
15504              instantiation.  Besides, such types are not allowed in
15505              ISO C++, so we can do as we please here.  */
15506           if (variably_modified_type_p (arg, NULL_TREE))
15507             return 1;
15508
15509           /* Strip typedefs as in convert_template_argument.  */
15510           arg = strip_typedefs (arg);
15511         }
15512
15513       /* If ARG is a parameter pack or an expansion, we cannot unify
15514          against it unless PARM is also a parameter pack.  */
15515       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
15516           && !template_parameter_pack_p (parm))
15517         return 1;
15518
15519       /* If the argument deduction results is a METHOD_TYPE,
15520          then there is a problem.
15521          METHOD_TYPE doesn't map to any real C++ type the result of
15522          the deduction can not be of that type.  */
15523       if (TREE_CODE (arg) == METHOD_TYPE)
15524         return 1;
15525
15526       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
15527       return 0;
15528
15529     case TEMPLATE_PARM_INDEX:
15530       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
15531       if (tparm == error_mark_node)
15532         return 1;
15533
15534       if (TEMPLATE_PARM_LEVEL (parm)
15535           != template_decl_level (tparm))
15536         /* The PARM is not one we're trying to unify.  Just check
15537            to see if it matches ARG.  */
15538         return !(TREE_CODE (arg) == TREE_CODE (parm)
15539                  && cp_tree_equal (parm, arg));
15540
15541       idx = TEMPLATE_PARM_IDX (parm);
15542       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15543
15544       if (targ)
15545         return !cp_tree_equal (targ, arg);
15546
15547       /* [temp.deduct.type] If, in the declaration of a function template
15548          with a non-type template-parameter, the non-type
15549          template-parameter is used in an expression in the function
15550          parameter-list and, if the corresponding template-argument is
15551          deduced, the template-argument type shall match the type of the
15552          template-parameter exactly, except that a template-argument
15553          deduced from an array bound may be of any integral type.
15554          The non-type parameter might use already deduced type parameters.  */
15555       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
15556       if (!TREE_TYPE (arg))
15557         /* Template-parameter dependent expression.  Just accept it for now.
15558            It will later be processed in convert_template_argument.  */
15559         ;
15560       else if (same_type_p (TREE_TYPE (arg), tparm))
15561         /* OK */;
15562       else if ((strict & UNIFY_ALLOW_INTEGER)
15563                && (TREE_CODE (tparm) == INTEGER_TYPE
15564                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
15565         /* Convert the ARG to the type of PARM; the deduced non-type
15566            template argument must exactly match the types of the
15567            corresponding parameter.  */
15568         arg = fold (build_nop (tparm, arg));
15569       else if (uses_template_parms (tparm))
15570         /* We haven't deduced the type of this parameter yet.  Try again
15571            later.  */
15572         return 0;
15573       else
15574         return 1;
15575
15576       /* If ARG is a parameter pack or an expansion, we cannot unify
15577          against it unless PARM is also a parameter pack.  */
15578       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
15579           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
15580         return 1;
15581
15582       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
15583       return 0;
15584
15585     case PTRMEM_CST:
15586      {
15587         /* A pointer-to-member constant can be unified only with
15588          another constant.  */
15589       if (TREE_CODE (arg) != PTRMEM_CST)
15590         return 1;
15591
15592       /* Just unify the class member. It would be useless (and possibly
15593          wrong, depending on the strict flags) to unify also
15594          PTRMEM_CST_CLASS, because we want to be sure that both parm and
15595          arg refer to the same variable, even if through different
15596          classes. For instance:
15597
15598          struct A { int x; };
15599          struct B : A { };
15600
15601          Unification of &A::x and &B::x must succeed.  */
15602       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
15603                     PTRMEM_CST_MEMBER (arg), strict);
15604      }
15605
15606     case POINTER_TYPE:
15607       {
15608         if (TREE_CODE (arg) != POINTER_TYPE)
15609           return 1;
15610
15611         /* [temp.deduct.call]
15612
15613            A can be another pointer or pointer to member type that can
15614            be converted to the deduced A via a qualification
15615            conversion (_conv.qual_).
15616
15617            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
15618            This will allow for additional cv-qualification of the
15619            pointed-to types if appropriate.  */
15620
15621         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
15622           /* The derived-to-base conversion only persists through one
15623              level of pointers.  */
15624           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
15625
15626         return unify (tparms, targs, TREE_TYPE (parm),
15627                       TREE_TYPE (arg), strict);
15628       }
15629
15630     case REFERENCE_TYPE:
15631       if (TREE_CODE (arg) != REFERENCE_TYPE)
15632         return 1;
15633       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15634                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
15635
15636     case ARRAY_TYPE:
15637       if (TREE_CODE (arg) != ARRAY_TYPE)
15638         return 1;
15639       if ((TYPE_DOMAIN (parm) == NULL_TREE)
15640           != (TYPE_DOMAIN (arg) == NULL_TREE))
15641         return 1;
15642       if (TYPE_DOMAIN (parm) != NULL_TREE)
15643         {
15644           tree parm_max;
15645           tree arg_max;
15646           bool parm_cst;
15647           bool arg_cst;
15648
15649           /* Our representation of array types uses "N - 1" as the
15650              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
15651              not an integer constant.  We cannot unify arbitrarily
15652              complex expressions, so we eliminate the MINUS_EXPRs
15653              here.  */
15654           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
15655           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
15656           if (!parm_cst)
15657             {
15658               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
15659               parm_max = TREE_OPERAND (parm_max, 0);
15660             }
15661           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
15662           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
15663           if (!arg_cst)
15664             {
15665               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
15666                  trying to unify the type of a variable with the type
15667                  of a template parameter.  For example:
15668
15669                    template <unsigned int N>
15670                    void f (char (&) [N]);
15671                    int g(); 
15672                    void h(int i) {
15673                      char a[g(i)];
15674                      f(a); 
15675                    }
15676
15677                 Here, the type of the ARG will be "int [g(i)]", and
15678                 may be a SAVE_EXPR, etc.  */
15679               if (TREE_CODE (arg_max) != MINUS_EXPR)
15680                 return 1;
15681               arg_max = TREE_OPERAND (arg_max, 0);
15682             }
15683
15684           /* If only one of the bounds used a MINUS_EXPR, compensate
15685              by adding one to the other bound.  */
15686           if (parm_cst && !arg_cst)
15687             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
15688                                     integer_type_node,
15689                                     parm_max,
15690                                     integer_one_node);
15691           else if (arg_cst && !parm_cst)
15692             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
15693                                    integer_type_node,
15694                                    arg_max,
15695                                    integer_one_node);
15696
15697           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
15698             return 1;
15699         }
15700       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15701                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
15702
15703     case REAL_TYPE:
15704     case COMPLEX_TYPE:
15705     case VECTOR_TYPE:
15706     case INTEGER_TYPE:
15707     case BOOLEAN_TYPE:
15708     case ENUMERAL_TYPE:
15709     case VOID_TYPE:
15710       if (TREE_CODE (arg) != TREE_CODE (parm))
15711         return 1;
15712
15713       /* We have already checked cv-qualification at the top of the
15714          function.  */
15715       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
15716         return 1;
15717
15718       /* As far as unification is concerned, this wins.  Later checks
15719          will invalidate it if necessary.  */
15720       return 0;
15721
15722       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
15723       /* Type INTEGER_CST can come from ordinary constant template args.  */
15724     case INTEGER_CST:
15725       while (TREE_CODE (arg) == NOP_EXPR)
15726         arg = TREE_OPERAND (arg, 0);
15727
15728       if (TREE_CODE (arg) != INTEGER_CST)
15729         return 1;
15730       return !tree_int_cst_equal (parm, arg);
15731
15732     case TREE_VEC:
15733       {
15734         int i;
15735         if (TREE_CODE (arg) != TREE_VEC)
15736           return 1;
15737         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
15738           return 1;
15739         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
15740           if (unify (tparms, targs,
15741                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
15742                      UNIFY_ALLOW_NONE))
15743             return 1;
15744         return 0;
15745       }
15746
15747     case RECORD_TYPE:
15748     case UNION_TYPE:
15749       if (TREE_CODE (arg) != TREE_CODE (parm))
15750         return 1;
15751
15752       if (TYPE_PTRMEMFUNC_P (parm))
15753         {
15754           if (!TYPE_PTRMEMFUNC_P (arg))
15755             return 1;
15756
15757           return unify (tparms, targs,
15758                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
15759                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
15760                         strict);
15761         }
15762
15763       if (CLASSTYPE_TEMPLATE_INFO (parm))
15764         {
15765           tree t = NULL_TREE;
15766
15767           if (strict_in & UNIFY_ALLOW_DERIVED)
15768             {
15769               /* First, we try to unify the PARM and ARG directly.  */
15770               t = try_class_unification (tparms, targs,
15771                                          parm, arg);
15772
15773               if (!t)
15774                 {
15775                   /* Fallback to the special case allowed in
15776                      [temp.deduct.call]:
15777
15778                        If P is a class, and P has the form
15779                        template-id, then A can be a derived class of
15780                        the deduced A.  Likewise, if P is a pointer to
15781                        a class of the form template-id, A can be a
15782                        pointer to a derived class pointed to by the
15783                        deduced A.  */
15784                   t = get_template_base (tparms, targs, parm, arg);
15785
15786                   if (!t)
15787                     return 1;
15788                 }
15789             }
15790           else if (CLASSTYPE_TEMPLATE_INFO (arg)
15791                    && (CLASSTYPE_TI_TEMPLATE (parm)
15792                        == CLASSTYPE_TI_TEMPLATE (arg)))
15793             /* Perhaps PARM is something like S<U> and ARG is S<int>.
15794                Then, we should unify `int' and `U'.  */
15795             t = arg;
15796           else
15797             /* There's no chance of unification succeeding.  */
15798             return 1;
15799
15800           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
15801                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
15802         }
15803       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
15804         return 1;
15805       return 0;
15806
15807     case METHOD_TYPE:
15808     case FUNCTION_TYPE:
15809       {
15810         unsigned int nargs;
15811         tree *args;
15812         tree a;
15813         unsigned int i;
15814
15815         if (TREE_CODE (arg) != TREE_CODE (parm))
15816           return 1;
15817
15818         /* CV qualifications for methods can never be deduced, they must
15819            match exactly.  We need to check them explicitly here,
15820            because type_unification_real treats them as any other
15821            cv-qualified parameter.  */
15822         if (TREE_CODE (parm) == METHOD_TYPE
15823             && (!check_cv_quals_for_unify
15824                 (UNIFY_ALLOW_NONE,
15825                  class_of_this_parm (arg),
15826                  class_of_this_parm (parm))))
15827           return 1;
15828
15829         if (unify (tparms, targs, TREE_TYPE (parm),
15830                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
15831           return 1;
15832
15833         nargs = list_length (TYPE_ARG_TYPES (arg));
15834         args = XALLOCAVEC (tree, nargs);
15835         for (a = TYPE_ARG_TYPES (arg), i = 0;
15836              a != NULL_TREE && a != void_list_node;
15837              a = TREE_CHAIN (a), ++i)
15838           args[i] = TREE_VALUE (a);
15839         nargs = i;
15840
15841         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
15842                                       args, nargs, 1, DEDUCE_EXACT,
15843                                       LOOKUP_NORMAL);
15844       }
15845
15846     case OFFSET_TYPE:
15847       /* Unify a pointer to member with a pointer to member function, which
15848          deduces the type of the member as a function type. */
15849       if (TYPE_PTRMEMFUNC_P (arg))
15850         {
15851           tree method_type;
15852           tree fntype;
15853
15854           /* Check top-level cv qualifiers */
15855           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
15856             return 1;
15857
15858           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15859                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
15860             return 1;
15861
15862           /* Determine the type of the function we are unifying against. */
15863           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
15864           fntype =
15865             build_function_type (TREE_TYPE (method_type),
15866                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
15867
15868           /* Extract the cv-qualifiers of the member function from the
15869              implicit object parameter and place them on the function
15870              type to be restored later. */
15871           fntype = apply_memfn_quals (fntype, type_memfn_quals (method_type));
15872           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
15873         }
15874
15875       if (TREE_CODE (arg) != OFFSET_TYPE)
15876         return 1;
15877       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15878                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
15879         return 1;
15880       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15881                     strict);
15882
15883     case CONST_DECL:
15884       if (DECL_TEMPLATE_PARM_P (parm))
15885         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
15886       if (arg != integral_constant_value (parm))
15887         return 1;
15888       return 0;
15889
15890     case FIELD_DECL:
15891     case TEMPLATE_DECL:
15892       /* Matched cases are handled by the ARG == PARM test above.  */
15893       return 1;
15894
15895     case VAR_DECL:
15896       /* A non-type template parameter that is a variable should be a
15897          an integral constant, in which case, it whould have been
15898          folded into its (constant) value. So we should not be getting
15899          a variable here.  */
15900       gcc_unreachable ();
15901
15902     case TYPE_ARGUMENT_PACK:
15903     case NONTYPE_ARGUMENT_PACK:
15904       {
15905         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
15906         tree packed_args = ARGUMENT_PACK_ARGS (arg);
15907         int i, len = TREE_VEC_LENGTH (packed_parms);
15908         int argslen = TREE_VEC_LENGTH (packed_args);
15909         int parm_variadic_p = 0;
15910
15911         for (i = 0; i < len; ++i)
15912           {
15913             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
15914               {
15915                 if (i == len - 1)
15916                   /* We can unify against something with a trailing
15917                      parameter pack.  */
15918                   parm_variadic_p = 1;
15919                 else
15920                   /* Since there is something following the pack
15921                      expansion, we cannot unify this template argument
15922                      list.  */
15923                   return 0;
15924               }
15925           }
15926           
15927
15928         /* If we don't have enough arguments to satisfy the parameters
15929            (not counting the pack expression at the end), or we have
15930            too many arguments for a parameter list that doesn't end in
15931            a pack expression, we can't unify.  */
15932         if (argslen < (len - parm_variadic_p)
15933             || (argslen > len && !parm_variadic_p))
15934           return 1;
15935
15936         /* Unify all of the parameters that precede the (optional)
15937            pack expression.  */
15938         for (i = 0; i < len - parm_variadic_p; ++i)
15939           {
15940             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
15941                        TREE_VEC_ELT (packed_args, i), strict))
15942               return 1;
15943           }
15944
15945         if (parm_variadic_p)
15946           return unify_pack_expansion (tparms, targs, 
15947                                        packed_parms, packed_args,
15948                                        strict, /*call_args_p=*/false,
15949                                        /*subr=*/false);
15950         return 0;
15951       }
15952
15953       break;
15954
15955     case TYPEOF_TYPE:
15956     case DECLTYPE_TYPE:
15957     case UNDERLYING_TYPE:
15958       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
15959          or UNDERLYING_TYPE nodes.  */
15960       return 0;
15961
15962     case ERROR_MARK:
15963       /* Unification fails if we hit an error node.  */
15964       return 1;
15965
15966     default:
15967       /* An unresolved overload is a nondeduced context.  */
15968       if (type_unknown_p (parm))
15969         return 0;
15970       gcc_assert (EXPR_P (parm));
15971
15972       /* We must be looking at an expression.  This can happen with
15973          something like:
15974
15975            template <int I>
15976            void foo(S<I>, S<I + 2>);
15977
15978          This is a "nondeduced context":
15979
15980            [deduct.type]
15981
15982            The nondeduced contexts are:
15983
15984            --A type that is a template-id in which one or more of
15985              the template-arguments is an expression that references
15986              a template-parameter.
15987
15988          In these cases, we assume deduction succeeded, but don't
15989          actually infer any unifications.  */
15990
15991       if (!uses_template_parms (parm)
15992           && !template_args_equal (parm, arg))
15993         return 1;
15994       else
15995         return 0;
15996     }
15997 }
15998 \f
15999 /* Note that DECL can be defined in this translation unit, if
16000    required.  */
16001
16002 static void
16003 mark_definable (tree decl)
16004 {
16005   tree clone;
16006   DECL_NOT_REALLY_EXTERN (decl) = 1;
16007   FOR_EACH_CLONE (clone, decl)
16008     DECL_NOT_REALLY_EXTERN (clone) = 1;
16009 }
16010
16011 /* Called if RESULT is explicitly instantiated, or is a member of an
16012    explicitly instantiated class.  */
16013
16014 void
16015 mark_decl_instantiated (tree result, int extern_p)
16016 {
16017   SET_DECL_EXPLICIT_INSTANTIATION (result);
16018
16019   /* If this entity has already been written out, it's too late to
16020      make any modifications.  */
16021   if (TREE_ASM_WRITTEN (result))
16022     return;
16023
16024   if (TREE_CODE (result) != FUNCTION_DECL)
16025     /* The TREE_PUBLIC flag for function declarations will have been
16026        set correctly by tsubst.  */
16027     TREE_PUBLIC (result) = 1;
16028
16029   /* This might have been set by an earlier implicit instantiation.  */
16030   DECL_COMDAT (result) = 0;
16031
16032   if (extern_p)
16033     DECL_NOT_REALLY_EXTERN (result) = 0;
16034   else
16035     {
16036       mark_definable (result);
16037       /* Always make artificials weak.  */
16038       if (DECL_ARTIFICIAL (result) && flag_weak)
16039         comdat_linkage (result);
16040       /* For WIN32 we also want to put explicit instantiations in
16041          linkonce sections.  */
16042       else if (TREE_PUBLIC (result))
16043         maybe_make_one_only (result);
16044     }
16045
16046   /* If EXTERN_P, then this function will not be emitted -- unless
16047      followed by an explicit instantiation, at which point its linkage
16048      will be adjusted.  If !EXTERN_P, then this function will be
16049      emitted here.  In neither circumstance do we want
16050      import_export_decl to adjust the linkage.  */
16051   DECL_INTERFACE_KNOWN (result) = 1;
16052 }
16053
16054 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
16055    important template arguments.  If any are missing, we check whether
16056    they're important by using error_mark_node for substituting into any
16057    args that were used for partial ordering (the ones between ARGS and END)
16058    and seeing if it bubbles up.  */
16059
16060 static bool
16061 check_undeduced_parms (tree targs, tree args, tree end)
16062 {
16063   bool found = false;
16064   int i;
16065   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
16066     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
16067       {
16068         found = true;
16069         TREE_VEC_ELT (targs, i) = error_mark_node;
16070       }
16071   if (found)
16072     {
16073       for (; args != end; args = TREE_CHAIN (args))
16074         {
16075           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
16076           if (substed == error_mark_node)
16077             return true;
16078         }
16079     }
16080   return false;
16081 }
16082
16083 /* Given two function templates PAT1 and PAT2, return:
16084
16085    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
16086    -1 if PAT2 is more specialized than PAT1.
16087    0 if neither is more specialized.
16088
16089    LEN indicates the number of parameters we should consider
16090    (defaulted parameters should not be considered).
16091
16092    The 1998 std underspecified function template partial ordering, and
16093    DR214 addresses the issue.  We take pairs of arguments, one from
16094    each of the templates, and deduce them against each other.  One of
16095    the templates will be more specialized if all the *other*
16096    template's arguments deduce against its arguments and at least one
16097    of its arguments *does* *not* deduce against the other template's
16098    corresponding argument.  Deduction is done as for class templates.
16099    The arguments used in deduction have reference and top level cv
16100    qualifiers removed.  Iff both arguments were originally reference
16101    types *and* deduction succeeds in both directions, the template
16102    with the more cv-qualified argument wins for that pairing (if
16103    neither is more cv-qualified, they both are equal).  Unlike regular
16104    deduction, after all the arguments have been deduced in this way,
16105    we do *not* verify the deduced template argument values can be
16106    substituted into non-deduced contexts.
16107
16108    The logic can be a bit confusing here, because we look at deduce1 and
16109    targs1 to see if pat2 is at least as specialized, and vice versa; if we
16110    can find template arguments for pat1 to make arg1 look like arg2, that
16111    means that arg2 is at least as specialized as arg1.  */
16112
16113 int
16114 more_specialized_fn (tree pat1, tree pat2, int len)
16115 {
16116   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
16117   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
16118   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
16119   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
16120   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
16121   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
16122   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
16123   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
16124   tree origs1, origs2;
16125   bool lose1 = false;
16126   bool lose2 = false;
16127
16128   /* Remove the this parameter from non-static member functions.  If
16129      one is a non-static member function and the other is not a static
16130      member function, remove the first parameter from that function
16131      also.  This situation occurs for operator functions where we
16132      locate both a member function (with this pointer) and non-member
16133      operator (with explicit first operand).  */
16134   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
16135     {
16136       len--; /* LEN is the number of significant arguments for DECL1 */
16137       args1 = TREE_CHAIN (args1);
16138       if (!DECL_STATIC_FUNCTION_P (decl2))
16139         args2 = TREE_CHAIN (args2);
16140     }
16141   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
16142     {
16143       args2 = TREE_CHAIN (args2);
16144       if (!DECL_STATIC_FUNCTION_P (decl1))
16145         {
16146           len--;
16147           args1 = TREE_CHAIN (args1);
16148         }
16149     }
16150
16151   /* If only one is a conversion operator, they are unordered.  */
16152   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
16153     return 0;
16154
16155   /* Consider the return type for a conversion function */
16156   if (DECL_CONV_FN_P (decl1))
16157     {
16158       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
16159       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
16160       len++;
16161     }
16162
16163   processing_template_decl++;
16164
16165   origs1 = args1;
16166   origs2 = args2;
16167
16168   while (len--
16169          /* Stop when an ellipsis is seen.  */
16170          && args1 != NULL_TREE && args2 != NULL_TREE)
16171     {
16172       tree arg1 = TREE_VALUE (args1);
16173       tree arg2 = TREE_VALUE (args2);
16174       int deduce1, deduce2;
16175       int quals1 = -1;
16176       int quals2 = -1;
16177
16178       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
16179           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16180         {
16181           /* When both arguments are pack expansions, we need only
16182              unify the patterns themselves.  */
16183           arg1 = PACK_EXPANSION_PATTERN (arg1);
16184           arg2 = PACK_EXPANSION_PATTERN (arg2);
16185
16186           /* This is the last comparison we need to do.  */
16187           len = 0;
16188         }
16189
16190       if (TREE_CODE (arg1) == REFERENCE_TYPE)
16191         {
16192           arg1 = TREE_TYPE (arg1);
16193           quals1 = cp_type_quals (arg1);
16194         }
16195
16196       if (TREE_CODE (arg2) == REFERENCE_TYPE)
16197         {
16198           arg2 = TREE_TYPE (arg2);
16199           quals2 = cp_type_quals (arg2);
16200         }
16201
16202       if ((quals1 < 0) != (quals2 < 0))
16203         {
16204           /* Only of the args is a reference, see if we should apply
16205              array/function pointer decay to it.  This is not part of
16206              DR214, but is, IMHO, consistent with the deduction rules
16207              for the function call itself, and with our earlier
16208              implementation of the underspecified partial ordering
16209              rules.  (nathan).  */
16210           if (quals1 >= 0)
16211             {
16212               switch (TREE_CODE (arg1))
16213                 {
16214                 case ARRAY_TYPE:
16215                   arg1 = TREE_TYPE (arg1);
16216                   /* FALLTHROUGH. */
16217                 case FUNCTION_TYPE:
16218                   arg1 = build_pointer_type (arg1);
16219                   break;
16220
16221                 default:
16222                   break;
16223                 }
16224             }
16225           else
16226             {
16227               switch (TREE_CODE (arg2))
16228                 {
16229                 case ARRAY_TYPE:
16230                   arg2 = TREE_TYPE (arg2);
16231                   /* FALLTHROUGH. */
16232                 case FUNCTION_TYPE:
16233                   arg2 = build_pointer_type (arg2);
16234                   break;
16235
16236                 default:
16237                   break;
16238                 }
16239             }
16240         }
16241
16242       arg1 = TYPE_MAIN_VARIANT (arg1);
16243       arg2 = TYPE_MAIN_VARIANT (arg2);
16244
16245       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
16246         {
16247           int i, len2 = list_length (args2);
16248           tree parmvec = make_tree_vec (1);
16249           tree argvec = make_tree_vec (len2);
16250           tree ta = args2;
16251
16252           /* Setup the parameter vector, which contains only ARG1.  */
16253           TREE_VEC_ELT (parmvec, 0) = arg1;
16254
16255           /* Setup the argument vector, which contains the remaining
16256              arguments.  */
16257           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
16258             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
16259
16260           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
16261                                            argvec, UNIFY_ALLOW_NONE, 
16262                                            /*call_args_p=*/false, 
16263                                            /*subr=*/0);
16264
16265           /* We cannot deduce in the other direction, because ARG1 is
16266              a pack expansion but ARG2 is not.  */
16267           deduce2 = 0;
16268         }
16269       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16270         {
16271           int i, len1 = list_length (args1);
16272           tree parmvec = make_tree_vec (1);
16273           tree argvec = make_tree_vec (len1);
16274           tree ta = args1;
16275
16276           /* Setup the parameter vector, which contains only ARG1.  */
16277           TREE_VEC_ELT (parmvec, 0) = arg2;
16278
16279           /* Setup the argument vector, which contains the remaining
16280              arguments.  */
16281           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
16282             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
16283
16284           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
16285                                            argvec, UNIFY_ALLOW_NONE, 
16286                                            /*call_args_p=*/false, 
16287                                            /*subr=*/0);
16288
16289           /* We cannot deduce in the other direction, because ARG2 is
16290              a pack expansion but ARG1 is not.*/
16291           deduce1 = 0;
16292         }
16293
16294       else
16295         {
16296           /* The normal case, where neither argument is a pack
16297              expansion.  */
16298           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
16299           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
16300         }
16301
16302       /* If we couldn't deduce arguments for tparms1 to make arg1 match
16303          arg2, then arg2 is not as specialized as arg1.  */
16304       if (!deduce1)
16305         lose2 = true;
16306       if (!deduce2)
16307         lose1 = true;
16308
16309       /* "If, for a given type, deduction succeeds in both directions
16310          (i.e., the types are identical after the transformations above)
16311          and if the type from the argument template is more cv-qualified
16312          than the type from the parameter template (as described above)
16313          that type is considered to be more specialized than the other. If
16314          neither type is more cv-qualified than the other then neither type
16315          is more specialized than the other."  */
16316
16317       if (deduce1 && deduce2
16318           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
16319         {
16320           if ((quals1 & quals2) == quals2)
16321             lose2 = true;
16322           if ((quals1 & quals2) == quals1)
16323             lose1 = true;
16324         }
16325
16326       if (lose1 && lose2)
16327         /* We've failed to deduce something in either direction.
16328            These must be unordered.  */
16329         break;
16330
16331       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
16332           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16333         /* We have already processed all of the arguments in our
16334            handing of the pack expansion type.  */
16335         len = 0;
16336
16337       args1 = TREE_CHAIN (args1);
16338       args2 = TREE_CHAIN (args2);
16339     }
16340
16341   /* "In most cases, all template parameters must have values in order for
16342      deduction to succeed, but for partial ordering purposes a template
16343      parameter may remain without a value provided it is not used in the
16344      types being used for partial ordering."
16345
16346      Thus, if we are missing any of the targs1 we need to substitute into
16347      origs1, then pat2 is not as specialized as pat1.  This can happen when
16348      there is a nondeduced context.  */
16349   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
16350     lose2 = true;
16351   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
16352     lose1 = true;
16353
16354   processing_template_decl--;
16355
16356   /* All things being equal, if the next argument is a pack expansion
16357      for one function but not for the other, prefer the
16358      non-variadic function.  FIXME this is bogus; see c++/41958.  */
16359   if (lose1 == lose2
16360       && args1 && TREE_VALUE (args1)
16361       && args2 && TREE_VALUE (args2))
16362     {
16363       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
16364       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
16365     }
16366
16367   if (lose1 == lose2)
16368     return 0;
16369   else if (!lose1)
16370     return 1;
16371   else
16372     return -1;
16373 }
16374
16375 /* Determine which of two partial specializations is more specialized.
16376
16377    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
16378    to the first partial specialization.  The TREE_VALUE is the
16379    innermost set of template parameters for the partial
16380    specialization.  PAT2 is similar, but for the second template.
16381
16382    Return 1 if the first partial specialization is more specialized;
16383    -1 if the second is more specialized; 0 if neither is more
16384    specialized.
16385
16386    See [temp.class.order] for information about determining which of
16387    two templates is more specialized.  */
16388
16389 static int
16390 more_specialized_class (tree pat1, tree pat2)
16391 {
16392   tree targs;
16393   tree tmpl1, tmpl2;
16394   int winner = 0;
16395   bool any_deductions = false;
16396
16397   tmpl1 = TREE_TYPE (pat1);
16398   tmpl2 = TREE_TYPE (pat2);
16399
16400   /* Just like what happens for functions, if we are ordering between
16401      different class template specializations, we may encounter dependent
16402      types in the arguments, and we need our dependency check functions
16403      to behave correctly.  */
16404   ++processing_template_decl;
16405   targs = get_class_bindings (TREE_VALUE (pat1),
16406                               CLASSTYPE_TI_ARGS (tmpl1),
16407                               CLASSTYPE_TI_ARGS (tmpl2));
16408   if (targs)
16409     {
16410       --winner;
16411       any_deductions = true;
16412     }
16413
16414   targs = get_class_bindings (TREE_VALUE (pat2),
16415                               CLASSTYPE_TI_ARGS (tmpl2),
16416                               CLASSTYPE_TI_ARGS (tmpl1));
16417   if (targs)
16418     {
16419       ++winner;
16420       any_deductions = true;
16421     }
16422   --processing_template_decl;
16423
16424   /* In the case of a tie where at least one of the class templates
16425      has a parameter pack at the end, the template with the most
16426      non-packed parameters wins.  */
16427   if (winner == 0
16428       && any_deductions
16429       && (template_args_variadic_p (TREE_PURPOSE (pat1))
16430           || template_args_variadic_p (TREE_PURPOSE (pat2))))
16431     {
16432       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
16433       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
16434       int len1 = TREE_VEC_LENGTH (args1);
16435       int len2 = TREE_VEC_LENGTH (args2);
16436
16437       /* We don't count the pack expansion at the end.  */
16438       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
16439         --len1;
16440       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
16441         --len2;
16442
16443       if (len1 > len2)
16444         return 1;
16445       else if (len1 < len2)
16446         return -1;
16447     }
16448
16449   return winner;
16450 }
16451
16452 /* Return the template arguments that will produce the function signature
16453    DECL from the function template FN, with the explicit template
16454    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
16455    also match.  Return NULL_TREE if no satisfactory arguments could be
16456    found.  */
16457
16458 static tree
16459 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
16460 {
16461   int ntparms = DECL_NTPARMS (fn);
16462   tree targs = make_tree_vec (ntparms);
16463   tree decl_type;
16464   tree decl_arg_types;
16465   tree *args;
16466   unsigned int nargs, ix;
16467   tree arg;
16468
16469   /* Substitute the explicit template arguments into the type of DECL.
16470      The call to fn_type_unification will handle substitution into the
16471      FN.  */
16472   decl_type = TREE_TYPE (decl);
16473   if (explicit_args && uses_template_parms (decl_type))
16474     {
16475       tree tmpl;
16476       tree converted_args;
16477
16478       if (DECL_TEMPLATE_INFO (decl))
16479         tmpl = DECL_TI_TEMPLATE (decl);
16480       else
16481         /* We can get here for some invalid specializations.  */
16482         return NULL_TREE;
16483
16484       converted_args
16485         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
16486                                  explicit_args, NULL_TREE,
16487                                  tf_none,
16488                                  /*require_all_args=*/false,
16489                                  /*use_default_args=*/false);
16490       if (converted_args == error_mark_node)
16491         return NULL_TREE;
16492
16493       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
16494       if (decl_type == error_mark_node)
16495         return NULL_TREE;
16496     }
16497
16498   /* Never do unification on the 'this' parameter.  */
16499   decl_arg_types = skip_artificial_parms_for (decl, 
16500                                               TYPE_ARG_TYPES (decl_type));
16501
16502   nargs = list_length (decl_arg_types);
16503   args = XALLOCAVEC (tree, nargs);
16504   for (arg = decl_arg_types, ix = 0;
16505        arg != NULL_TREE && arg != void_list_node;
16506        arg = TREE_CHAIN (arg), ++ix)
16507     args[ix] = TREE_VALUE (arg);
16508
16509   if (fn_type_unification (fn, explicit_args, targs,
16510                            args, ix,
16511                            (check_rettype || DECL_CONV_FN_P (fn)
16512                             ? TREE_TYPE (decl_type) : NULL_TREE),
16513                            DEDUCE_EXACT, LOOKUP_NORMAL))
16514     return NULL_TREE;
16515
16516   return targs;
16517 }
16518
16519 /* Return the innermost template arguments that, when applied to a
16520    template specialization whose innermost template parameters are
16521    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
16522    ARGS.
16523
16524    For example, suppose we have:
16525
16526      template <class T, class U> struct S {};
16527      template <class T> struct S<T*, int> {};
16528
16529    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
16530    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
16531    int}.  The resulting vector will be {double}, indicating that `T'
16532    is bound to `double'.  */
16533
16534 static tree
16535 get_class_bindings (tree tparms, tree spec_args, tree args)
16536 {
16537   int i, ntparms = TREE_VEC_LENGTH (tparms);
16538   tree deduced_args;
16539   tree innermost_deduced_args;
16540
16541   innermost_deduced_args = make_tree_vec (ntparms);
16542   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
16543     {
16544       deduced_args = copy_node (args);
16545       SET_TMPL_ARGS_LEVEL (deduced_args,
16546                            TMPL_ARGS_DEPTH (deduced_args),
16547                            innermost_deduced_args);
16548     }
16549   else
16550     deduced_args = innermost_deduced_args;
16551
16552   if (unify (tparms, deduced_args,
16553              INNERMOST_TEMPLATE_ARGS (spec_args),
16554              INNERMOST_TEMPLATE_ARGS (args),
16555              UNIFY_ALLOW_NONE))
16556     return NULL_TREE;
16557
16558   for (i =  0; i < ntparms; ++i)
16559     if (! TREE_VEC_ELT (innermost_deduced_args, i))
16560       return NULL_TREE;
16561
16562   /* Verify that nondeduced template arguments agree with the type
16563      obtained from argument deduction.
16564
16565      For example:
16566
16567        struct A { typedef int X; };
16568        template <class T, class U> struct C {};
16569        template <class T> struct C<T, typename T::X> {};
16570
16571      Then with the instantiation `C<A, int>', we can deduce that
16572      `T' is `A' but unify () does not check whether `typename T::X'
16573      is `int'.  */
16574   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
16575   if (spec_args == error_mark_node
16576       /* We only need to check the innermost arguments; the other
16577          arguments will always agree.  */
16578       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
16579                               INNERMOST_TEMPLATE_ARGS (args)))
16580     return NULL_TREE;
16581
16582   /* Now that we have bindings for all of the template arguments,
16583      ensure that the arguments deduced for the template template
16584      parameters have compatible template parameter lists.  See the use
16585      of template_template_parm_bindings_ok_p in fn_type_unification
16586      for more information.  */
16587   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
16588     return NULL_TREE;
16589
16590   return deduced_args;
16591 }
16592
16593 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
16594    Return the TREE_LIST node with the most specialized template, if
16595    any.  If there is no most specialized template, the error_mark_node
16596    is returned.
16597
16598    Note that this function does not look at, or modify, the
16599    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
16600    returned is one of the elements of INSTANTIATIONS, callers may
16601    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
16602    and retrieve it from the value returned.  */
16603
16604 tree
16605 most_specialized_instantiation (tree templates)
16606 {
16607   tree fn, champ;
16608
16609   ++processing_template_decl;
16610
16611   champ = templates;
16612   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
16613     {
16614       int fate = 0;
16615
16616       if (get_bindings (TREE_VALUE (champ),
16617                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
16618                         NULL_TREE, /*check_ret=*/false))
16619         fate--;
16620
16621       if (get_bindings (TREE_VALUE (fn),
16622                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
16623                         NULL_TREE, /*check_ret=*/false))
16624         fate++;
16625
16626       if (fate == -1)
16627         champ = fn;
16628       else if (!fate)
16629         {
16630           /* Equally specialized, move to next function.  If there
16631              is no next function, nothing's most specialized.  */
16632           fn = TREE_CHAIN (fn);
16633           champ = fn;
16634           if (!fn)
16635             break;
16636         }
16637     }
16638
16639   if (champ)
16640     /* Now verify that champ is better than everything earlier in the
16641        instantiation list.  */
16642     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
16643       if (get_bindings (TREE_VALUE (champ),
16644                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
16645                         NULL_TREE, /*check_ret=*/false)
16646           || !get_bindings (TREE_VALUE (fn),
16647                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
16648                             NULL_TREE, /*check_ret=*/false))
16649         {
16650           champ = NULL_TREE;
16651           break;
16652         }
16653
16654   processing_template_decl--;
16655
16656   if (!champ)
16657     return error_mark_node;
16658
16659   return champ;
16660 }
16661
16662 /* If DECL is a specialization of some template, return the most
16663    general such template.  Otherwise, returns NULL_TREE.
16664
16665    For example, given:
16666
16667      template <class T> struct S { template <class U> void f(U); };
16668
16669    if TMPL is `template <class U> void S<int>::f(U)' this will return
16670    the full template.  This function will not trace past partial
16671    specializations, however.  For example, given in addition:
16672
16673      template <class T> struct S<T*> { template <class U> void f(U); };
16674
16675    if TMPL is `template <class U> void S<int*>::f(U)' this will return
16676    `template <class T> template <class U> S<T*>::f(U)'.  */
16677
16678 tree
16679 most_general_template (tree decl)
16680 {
16681   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
16682      an immediate specialization.  */
16683   if (TREE_CODE (decl) == FUNCTION_DECL)
16684     {
16685       if (DECL_TEMPLATE_INFO (decl)) {
16686         decl = DECL_TI_TEMPLATE (decl);
16687
16688         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
16689            template friend.  */
16690         if (TREE_CODE (decl) != TEMPLATE_DECL)
16691           return NULL_TREE;
16692       } else
16693         return NULL_TREE;
16694     }
16695
16696   /* Look for more and more general templates.  */
16697   while (DECL_TEMPLATE_INFO (decl))
16698     {
16699       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
16700          (See cp-tree.h for details.)  */
16701       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
16702         break;
16703
16704       if (CLASS_TYPE_P (TREE_TYPE (decl))
16705           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
16706         break;
16707
16708       /* Stop if we run into an explicitly specialized class template.  */
16709       if (!DECL_NAMESPACE_SCOPE_P (decl)
16710           && DECL_CONTEXT (decl)
16711           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
16712         break;
16713
16714       decl = DECL_TI_TEMPLATE (decl);
16715     }
16716
16717   return decl;
16718 }
16719
16720 /* Return the most specialized of the class template partial
16721    specializations of TMPL which can produce TYPE, a specialization of
16722    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
16723    a _TYPE node corresponding to the partial specialization, while the
16724    TREE_PURPOSE is the set of template arguments that must be
16725    substituted into the TREE_TYPE in order to generate TYPE.
16726
16727    If the choice of partial specialization is ambiguous, a diagnostic
16728    is issued, and the error_mark_node is returned.  If there are no
16729    partial specializations of TMPL matching TYPE, then NULL_TREE is
16730    returned.  */
16731
16732 static tree
16733 most_specialized_class (tree type, tree tmpl, tsubst_flags_t complain)
16734 {
16735   tree list = NULL_TREE;
16736   tree t;
16737   tree champ;
16738   int fate;
16739   bool ambiguous_p;
16740   tree args;
16741   tree outer_args = NULL_TREE;
16742
16743   tmpl = most_general_template (tmpl);
16744   args = CLASSTYPE_TI_ARGS (type);
16745
16746   /* For determining which partial specialization to use, only the
16747      innermost args are interesting.  */
16748   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
16749     {
16750       outer_args = strip_innermost_template_args (args, 1);
16751       args = INNERMOST_TEMPLATE_ARGS (args);
16752     }
16753
16754   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
16755     {
16756       tree partial_spec_args;
16757       tree spec_args;
16758       tree parms = TREE_VALUE (t);
16759
16760       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
16761
16762       ++processing_template_decl;
16763
16764       if (outer_args)
16765         {
16766           int i;
16767
16768           /* Discard the outer levels of args, and then substitute in the
16769              template args from the enclosing class.  */
16770           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
16771           partial_spec_args = tsubst_template_args
16772             (partial_spec_args, outer_args, tf_none, NULL_TREE);
16773
16774           /* PARMS already refers to just the innermost parms, but the
16775              template parms in partial_spec_args had their levels lowered
16776              by tsubst, so we need to do the same for the parm list.  We
16777              can't just tsubst the TREE_VEC itself, as tsubst wants to
16778              treat a TREE_VEC as an argument vector.  */
16779           parms = copy_node (parms);
16780           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
16781             TREE_VEC_ELT (parms, i) =
16782               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
16783
16784         }
16785
16786       partial_spec_args =
16787           coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
16788                                  add_to_template_args (outer_args,
16789                                                        partial_spec_args),
16790                                  tmpl, tf_none,
16791                                  /*require_all_args=*/true,
16792                                  /*use_default_args=*/true);
16793
16794       --processing_template_decl;
16795
16796       if (partial_spec_args == error_mark_node)
16797         return error_mark_node;
16798
16799       spec_args = get_class_bindings (parms,
16800                                       partial_spec_args,
16801                                       args);
16802       if (spec_args)
16803         {
16804           if (outer_args)
16805             spec_args = add_to_template_args (outer_args, spec_args);
16806           list = tree_cons (spec_args, TREE_VALUE (t), list);
16807           TREE_TYPE (list) = TREE_TYPE (t);
16808         }
16809     }
16810
16811   if (! list)
16812     return NULL_TREE;
16813
16814   ambiguous_p = false;
16815   t = list;
16816   champ = t;
16817   t = TREE_CHAIN (t);
16818   for (; t; t = TREE_CHAIN (t))
16819     {
16820       fate = more_specialized_class (champ, t);
16821       if (fate == 1)
16822         ;
16823       else
16824         {
16825           if (fate == 0)
16826             {
16827               t = TREE_CHAIN (t);
16828               if (! t)
16829                 {
16830                   ambiguous_p = true;
16831                   break;
16832                 }
16833             }
16834           champ = t;
16835         }
16836     }
16837
16838   if (!ambiguous_p)
16839     for (t = list; t && t != champ; t = TREE_CHAIN (t))
16840       {
16841         fate = more_specialized_class (champ, t);
16842         if (fate != 1)
16843           {
16844             ambiguous_p = true;
16845             break;
16846           }
16847       }
16848
16849   if (ambiguous_p)
16850     {
16851       const char *str;
16852       char *spaces = NULL;
16853       if (!(complain & tf_error))
16854         return error_mark_node;
16855       error ("ambiguous class template instantiation for %q#T", type);
16856       str = ngettext ("candidate is:", "candidates are:", list_length (list));
16857       for (t = list; t; t = TREE_CHAIN (t))
16858         {
16859           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
16860           spaces = spaces ? spaces : get_spaces (str);
16861         }
16862       free (spaces);
16863       return error_mark_node;
16864     }
16865
16866   return champ;
16867 }
16868
16869 /* Explicitly instantiate DECL.  */
16870
16871 void
16872 do_decl_instantiation (tree decl, tree storage)
16873 {
16874   tree result = NULL_TREE;
16875   int extern_p = 0;
16876
16877   if (!decl || decl == error_mark_node)
16878     /* An error occurred, for which grokdeclarator has already issued
16879        an appropriate message.  */
16880     return;
16881   else if (! DECL_LANG_SPECIFIC (decl))
16882     {
16883       error ("explicit instantiation of non-template %q#D", decl);
16884       return;
16885     }
16886   else if (TREE_CODE (decl) == VAR_DECL)
16887     {
16888       /* There is an asymmetry here in the way VAR_DECLs and
16889          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
16890          the latter, the DECL we get back will be marked as a
16891          template instantiation, and the appropriate
16892          DECL_TEMPLATE_INFO will be set up.  This does not happen for
16893          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
16894          should handle VAR_DECLs as it currently handles
16895          FUNCTION_DECLs.  */
16896       if (!DECL_CLASS_SCOPE_P (decl))
16897         {
16898           error ("%qD is not a static data member of a class template", decl);
16899           return;
16900         }
16901       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
16902       if (!result || TREE_CODE (result) != VAR_DECL)
16903         {
16904           error ("no matching template for %qD found", decl);
16905           return;
16906         }
16907       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
16908         {
16909           error ("type %qT for explicit instantiation %qD does not match "
16910                  "declared type %qT", TREE_TYPE (result), decl,
16911                  TREE_TYPE (decl));
16912           return;
16913         }
16914     }
16915   else if (TREE_CODE (decl) != FUNCTION_DECL)
16916     {
16917       error ("explicit instantiation of %q#D", decl);
16918       return;
16919     }
16920   else
16921     result = decl;
16922
16923   /* Check for various error cases.  Note that if the explicit
16924      instantiation is valid the RESULT will currently be marked as an
16925      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
16926      until we get here.  */
16927
16928   if (DECL_TEMPLATE_SPECIALIZATION (result))
16929     {
16930       /* DR 259 [temp.spec].
16931
16932          Both an explicit instantiation and a declaration of an explicit
16933          specialization shall not appear in a program unless the explicit
16934          instantiation follows a declaration of the explicit specialization.
16935
16936          For a given set of template parameters, if an explicit
16937          instantiation of a template appears after a declaration of an
16938          explicit specialization for that template, the explicit
16939          instantiation has no effect.  */
16940       return;
16941     }
16942   else if (DECL_EXPLICIT_INSTANTIATION (result))
16943     {
16944       /* [temp.spec]
16945
16946          No program shall explicitly instantiate any template more
16947          than once.
16948
16949          We check DECL_NOT_REALLY_EXTERN so as not to complain when
16950          the first instantiation was `extern' and the second is not,
16951          and EXTERN_P for the opposite case.  */
16952       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
16953         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
16954       /* If an "extern" explicit instantiation follows an ordinary
16955          explicit instantiation, the template is instantiated.  */
16956       if (extern_p)
16957         return;
16958     }
16959   else if (!DECL_IMPLICIT_INSTANTIATION (result))
16960     {
16961       error ("no matching template for %qD found", result);
16962       return;
16963     }
16964   else if (!DECL_TEMPLATE_INFO (result))
16965     {
16966       permerror (input_location, "explicit instantiation of non-template %q#D", result);
16967       return;
16968     }
16969
16970   if (storage == NULL_TREE)
16971     ;
16972   else if (storage == ridpointers[(int) RID_EXTERN])
16973     {
16974       if (!in_system_header && (cxx_dialect == cxx98))
16975         pedwarn (input_location, OPT_pedantic, 
16976                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
16977                  "instantiations");
16978       extern_p = 1;
16979     }
16980   else
16981     error ("storage class %qD applied to template instantiation", storage);
16982
16983   check_explicit_instantiation_namespace (result);
16984   mark_decl_instantiated (result, extern_p);
16985   if (! extern_p)
16986     instantiate_decl (result, /*defer_ok=*/1,
16987                       /*expl_inst_class_mem_p=*/false);
16988 }
16989
16990 static void
16991 mark_class_instantiated (tree t, int extern_p)
16992 {
16993   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
16994   SET_CLASSTYPE_INTERFACE_KNOWN (t);
16995   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
16996   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
16997   if (! extern_p)
16998     {
16999       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
17000       rest_of_type_compilation (t, 1);
17001     }
17002 }
17003
17004 /* Called from do_type_instantiation through binding_table_foreach to
17005    do recursive instantiation for the type bound in ENTRY.  */
17006 static void
17007 bt_instantiate_type_proc (binding_entry entry, void *data)
17008 {
17009   tree storage = *(tree *) data;
17010
17011   if (MAYBE_CLASS_TYPE_P (entry->type)
17012       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
17013     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
17014 }
17015
17016 /* Called from do_type_instantiation to instantiate a member
17017    (a member function or a static member variable) of an
17018    explicitly instantiated class template.  */
17019 static void
17020 instantiate_class_member (tree decl, int extern_p)
17021 {
17022   mark_decl_instantiated (decl, extern_p);
17023   if (! extern_p)
17024     instantiate_decl (decl, /*defer_ok=*/1,
17025                       /*expl_inst_class_mem_p=*/true);
17026 }
17027
17028 /* Perform an explicit instantiation of template class T.  STORAGE, if
17029    non-null, is the RID for extern, inline or static.  COMPLAIN is
17030    nonzero if this is called from the parser, zero if called recursively,
17031    since the standard is unclear (as detailed below).  */
17032
17033 void
17034 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
17035 {
17036   int extern_p = 0;
17037   int nomem_p = 0;
17038   int static_p = 0;
17039   int previous_instantiation_extern_p = 0;
17040
17041   if (TREE_CODE (t) == TYPE_DECL)
17042     t = TREE_TYPE (t);
17043
17044   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
17045     {
17046       error ("explicit instantiation of non-template type %qT", t);
17047       return;
17048     }
17049
17050   complete_type (t);
17051
17052   if (!COMPLETE_TYPE_P (t))
17053     {
17054       if (complain & tf_error)
17055         error ("explicit instantiation of %q#T before definition of template",
17056                t);
17057       return;
17058     }
17059
17060   if (storage != NULL_TREE)
17061     {
17062       if (!in_system_header)
17063         {
17064           if (storage == ridpointers[(int) RID_EXTERN])
17065             {
17066               if (cxx_dialect == cxx98)
17067                 pedwarn (input_location, OPT_pedantic, 
17068                          "ISO C++ 1998 forbids the use of %<extern%> on "
17069                          "explicit instantiations");
17070             }
17071           else
17072             pedwarn (input_location, OPT_pedantic, 
17073                      "ISO C++ forbids the use of %qE"
17074                      " on explicit instantiations", storage);
17075         }
17076
17077       if (storage == ridpointers[(int) RID_INLINE])
17078         nomem_p = 1;
17079       else if (storage == ridpointers[(int) RID_EXTERN])
17080         extern_p = 1;
17081       else if (storage == ridpointers[(int) RID_STATIC])
17082         static_p = 1;
17083       else
17084         {
17085           error ("storage class %qD applied to template instantiation",
17086                  storage);
17087           extern_p = 0;
17088         }
17089     }
17090
17091   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
17092     {
17093       /* DR 259 [temp.spec].
17094
17095          Both an explicit instantiation and a declaration of an explicit
17096          specialization shall not appear in a program unless the explicit
17097          instantiation follows a declaration of the explicit specialization.
17098
17099          For a given set of template parameters, if an explicit
17100          instantiation of a template appears after a declaration of an
17101          explicit specialization for that template, the explicit
17102          instantiation has no effect.  */
17103       return;
17104     }
17105   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
17106     {
17107       /* [temp.spec]
17108
17109          No program shall explicitly instantiate any template more
17110          than once.
17111
17112          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
17113          instantiation was `extern'.  If EXTERN_P then the second is.
17114          These cases are OK.  */
17115       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
17116
17117       if (!previous_instantiation_extern_p && !extern_p
17118           && (complain & tf_error))
17119         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
17120
17121       /* If we've already instantiated the template, just return now.  */
17122       if (!CLASSTYPE_INTERFACE_ONLY (t))
17123         return;
17124     }
17125
17126   check_explicit_instantiation_namespace (TYPE_NAME (t));
17127   mark_class_instantiated (t, extern_p);
17128
17129   if (nomem_p)
17130     return;
17131
17132   {
17133     tree tmp;
17134
17135     /* In contrast to implicit instantiation, where only the
17136        declarations, and not the definitions, of members are
17137        instantiated, we have here:
17138
17139          [temp.explicit]
17140
17141          The explicit instantiation of a class template specialization
17142          implies the instantiation of all of its members not
17143          previously explicitly specialized in the translation unit
17144          containing the explicit instantiation.
17145
17146        Of course, we can't instantiate member template classes, since
17147        we don't have any arguments for them.  Note that the standard
17148        is unclear on whether the instantiation of the members are
17149        *explicit* instantiations or not.  However, the most natural
17150        interpretation is that it should be an explicit instantiation.  */
17151
17152     if (! static_p)
17153       for (tmp = TYPE_METHODS (t); tmp; tmp = DECL_CHAIN (tmp))
17154         if (TREE_CODE (tmp) == FUNCTION_DECL
17155             && DECL_TEMPLATE_INSTANTIATION (tmp))
17156           instantiate_class_member (tmp, extern_p);
17157
17158     for (tmp = TYPE_FIELDS (t); tmp; tmp = DECL_CHAIN (tmp))
17159       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
17160         instantiate_class_member (tmp, extern_p);
17161
17162     if (CLASSTYPE_NESTED_UTDS (t))
17163       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
17164                              bt_instantiate_type_proc, &storage);
17165   }
17166 }
17167
17168 /* Given a function DECL, which is a specialization of TMPL, modify
17169    DECL to be a re-instantiation of TMPL with the same template
17170    arguments.  TMPL should be the template into which tsubst'ing
17171    should occur for DECL, not the most general template.
17172
17173    One reason for doing this is a scenario like this:
17174
17175      template <class T>
17176      void f(const T&, int i);
17177
17178      void g() { f(3, 7); }
17179
17180      template <class T>
17181      void f(const T& t, const int i) { }
17182
17183    Note that when the template is first instantiated, with
17184    instantiate_template, the resulting DECL will have no name for the
17185    first parameter, and the wrong type for the second.  So, when we go
17186    to instantiate the DECL, we regenerate it.  */
17187
17188 static void
17189 regenerate_decl_from_template (tree decl, tree tmpl)
17190 {
17191   /* The arguments used to instantiate DECL, from the most general
17192      template.  */
17193   tree args;
17194   tree code_pattern;
17195
17196   args = DECL_TI_ARGS (decl);
17197   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
17198
17199   /* Make sure that we can see identifiers, and compute access
17200      correctly.  */
17201   push_access_scope (decl);
17202
17203   if (TREE_CODE (decl) == FUNCTION_DECL)
17204     {
17205       tree decl_parm;
17206       tree pattern_parm;
17207       tree specs;
17208       int args_depth;
17209       int parms_depth;
17210
17211       args_depth = TMPL_ARGS_DEPTH (args);
17212       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
17213       if (args_depth > parms_depth)
17214         args = get_innermost_template_args (args, parms_depth);
17215
17216       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
17217                                               args, tf_error, NULL_TREE);
17218       if (specs)
17219         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
17220                                                     specs);
17221
17222       /* Merge parameter declarations.  */
17223       decl_parm = skip_artificial_parms_for (decl,
17224                                              DECL_ARGUMENTS (decl));
17225       pattern_parm
17226         = skip_artificial_parms_for (code_pattern,
17227                                      DECL_ARGUMENTS (code_pattern));
17228       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
17229         {
17230           tree parm_type;
17231           tree attributes;
17232           
17233           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
17234             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
17235           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
17236                               NULL_TREE);
17237           parm_type = type_decays_to (parm_type);
17238           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
17239             TREE_TYPE (decl_parm) = parm_type;
17240           attributes = DECL_ATTRIBUTES (pattern_parm);
17241           if (DECL_ATTRIBUTES (decl_parm) != attributes)
17242             {
17243               DECL_ATTRIBUTES (decl_parm) = attributes;
17244               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
17245             }
17246           decl_parm = DECL_CHAIN (decl_parm);
17247           pattern_parm = DECL_CHAIN (pattern_parm);
17248         }
17249       /* Merge any parameters that match with the function parameter
17250          pack.  */
17251       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
17252         {
17253           int i, len;
17254           tree expanded_types;
17255           /* Expand the TYPE_PACK_EXPANSION that provides the types for
17256              the parameters in this function parameter pack.  */
17257           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
17258                                                  args, tf_error, NULL_TREE);
17259           len = TREE_VEC_LENGTH (expanded_types);
17260           for (i = 0; i < len; i++)
17261             {
17262               tree parm_type;
17263               tree attributes;
17264           
17265               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
17266                 /* Rename the parameter to include the index.  */
17267                 DECL_NAME (decl_parm) = 
17268                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
17269               parm_type = TREE_VEC_ELT (expanded_types, i);
17270               parm_type = type_decays_to (parm_type);
17271               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
17272                 TREE_TYPE (decl_parm) = parm_type;
17273               attributes = DECL_ATTRIBUTES (pattern_parm);
17274               if (DECL_ATTRIBUTES (decl_parm) != attributes)
17275                 {
17276                   DECL_ATTRIBUTES (decl_parm) = attributes;
17277                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
17278                 }
17279               decl_parm = DECL_CHAIN (decl_parm);
17280             }
17281         }
17282       /* Merge additional specifiers from the CODE_PATTERN.  */
17283       if (DECL_DECLARED_INLINE_P (code_pattern)
17284           && !DECL_DECLARED_INLINE_P (decl))
17285         DECL_DECLARED_INLINE_P (decl) = 1;
17286     }
17287   else if (TREE_CODE (decl) == VAR_DECL)
17288     {
17289       DECL_INITIAL (decl) =
17290         tsubst_expr (DECL_INITIAL (code_pattern), args,
17291                      tf_error, DECL_TI_TEMPLATE (decl),
17292                      /*integral_constant_expression_p=*/false);
17293       if (VAR_HAD_UNKNOWN_BOUND (decl))
17294         TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
17295                                    tf_error, DECL_TI_TEMPLATE (decl));
17296     }
17297   else
17298     gcc_unreachable ();
17299
17300   pop_access_scope (decl);
17301 }
17302
17303 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
17304    substituted to get DECL.  */
17305
17306 tree
17307 template_for_substitution (tree decl)
17308 {
17309   tree tmpl = DECL_TI_TEMPLATE (decl);
17310
17311   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
17312      for the instantiation.  This is not always the most general
17313      template.  Consider, for example:
17314
17315         template <class T>
17316         struct S { template <class U> void f();
17317                    template <> void f<int>(); };
17318
17319      and an instantiation of S<double>::f<int>.  We want TD to be the
17320      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
17321   while (/* An instantiation cannot have a definition, so we need a
17322             more general template.  */
17323          DECL_TEMPLATE_INSTANTIATION (tmpl)
17324            /* We must also deal with friend templates.  Given:
17325
17326                 template <class T> struct S {
17327                   template <class U> friend void f() {};
17328                 };
17329
17330               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
17331               so far as the language is concerned, but that's still
17332               where we get the pattern for the instantiation from.  On
17333               other hand, if the definition comes outside the class, say:
17334
17335                 template <class T> struct S {
17336                   template <class U> friend void f();
17337                 };
17338                 template <class U> friend void f() {}
17339
17340               we don't need to look any further.  That's what the check for
17341               DECL_INITIAL is for.  */
17342           || (TREE_CODE (decl) == FUNCTION_DECL
17343               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
17344               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
17345     {
17346       /* The present template, TD, should not be a definition.  If it
17347          were a definition, we should be using it!  Note that we
17348          cannot restructure the loop to just keep going until we find
17349          a template with a definition, since that might go too far if
17350          a specialization was declared, but not defined.  */
17351       gcc_assert (TREE_CODE (decl) != VAR_DECL
17352                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
17353
17354       /* Fetch the more general template.  */
17355       tmpl = DECL_TI_TEMPLATE (tmpl);
17356     }
17357
17358   return tmpl;
17359 }
17360
17361 /* Returns true if we need to instantiate this template instance even if we
17362    know we aren't going to emit it..  */
17363
17364 bool
17365 always_instantiate_p (tree decl)
17366 {
17367   /* We always instantiate inline functions so that we can inline them.  An
17368      explicit instantiation declaration prohibits implicit instantiation of
17369      non-inline functions.  With high levels of optimization, we would
17370      normally inline non-inline functions -- but we're not allowed to do
17371      that for "extern template" functions.  Therefore, we check
17372      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
17373   return ((TREE_CODE (decl) == FUNCTION_DECL
17374            && DECL_DECLARED_INLINE_P (decl))
17375           /* And we need to instantiate static data members so that
17376              their initializers are available in integral constant
17377              expressions.  */
17378           || (TREE_CODE (decl) == VAR_DECL
17379               && decl_maybe_constant_var_p (decl)));
17380 }
17381
17382 /* Produce the definition of D, a _DECL generated from a template.  If
17383    DEFER_OK is nonzero, then we don't have to actually do the
17384    instantiation now; we just have to do it sometime.  Normally it is
17385    an error if this is an explicit instantiation but D is undefined.
17386    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
17387    explicitly instantiated class template.  */
17388
17389 tree
17390 instantiate_decl (tree d, int defer_ok,
17391                   bool expl_inst_class_mem_p)
17392 {
17393   tree tmpl = DECL_TI_TEMPLATE (d);
17394   tree gen_args;
17395   tree args;
17396   tree td;
17397   tree code_pattern;
17398   tree spec;
17399   tree gen_tmpl;
17400   bool pattern_defined;
17401   int need_push;
17402   location_t saved_loc = input_location;
17403   bool external_p;
17404
17405   /* This function should only be used to instantiate templates for
17406      functions and static member variables.  */
17407   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
17408               || TREE_CODE (d) == VAR_DECL);
17409
17410   /* Variables are never deferred; if instantiation is required, they
17411      are instantiated right away.  That allows for better code in the
17412      case that an expression refers to the value of the variable --
17413      if the variable has a constant value the referring expression can
17414      take advantage of that fact.  */
17415   if (TREE_CODE (d) == VAR_DECL
17416       || DECL_DECLARED_CONSTEXPR_P (d))
17417     defer_ok = 0;
17418
17419   /* Don't instantiate cloned functions.  Instead, instantiate the
17420      functions they cloned.  */
17421   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
17422     d = DECL_CLONED_FUNCTION (d);
17423
17424   if (DECL_TEMPLATE_INSTANTIATED (d)
17425       || DECL_TEMPLATE_SPECIALIZATION (d))
17426     /* D has already been instantiated or explicitly specialized, so
17427        there's nothing for us to do here.
17428
17429        It might seem reasonable to check whether or not D is an explicit
17430        instantiation, and, if so, stop here.  But when an explicit
17431        instantiation is deferred until the end of the compilation,
17432        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
17433        the instantiation.  */
17434     return d;
17435
17436   /* Check to see whether we know that this template will be
17437      instantiated in some other file, as with "extern template"
17438      extension.  */
17439   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
17440
17441   /* In general, we do not instantiate such templates.  */
17442   if (external_p && !always_instantiate_p (d))
17443     return d;
17444
17445   gen_tmpl = most_general_template (tmpl);
17446   gen_args = DECL_TI_ARGS (d);
17447
17448   if (tmpl != gen_tmpl)
17449     /* We should already have the extra args.  */
17450     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
17451                 == TMPL_ARGS_DEPTH (gen_args));
17452   /* And what's in the hash table should match D.  */
17453   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
17454               || spec == NULL_TREE);
17455
17456   /* This needs to happen before any tsubsting.  */
17457   if (! push_tinst_level (d))
17458     return d;
17459
17460   timevar_push (TV_TEMPLATE_INST);
17461
17462   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
17463      for the instantiation.  */
17464   td = template_for_substitution (d);
17465   code_pattern = DECL_TEMPLATE_RESULT (td);
17466
17467   /* We should never be trying to instantiate a member of a class
17468      template or partial specialization.  */
17469   gcc_assert (d != code_pattern);
17470
17471   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
17472       || DECL_TEMPLATE_SPECIALIZATION (td))
17473     /* In the case of a friend template whose definition is provided
17474        outside the class, we may have too many arguments.  Drop the
17475        ones we don't need.  The same is true for specializations.  */
17476     args = get_innermost_template_args
17477       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
17478   else
17479     args = gen_args;
17480
17481   if (TREE_CODE (d) == FUNCTION_DECL)
17482     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE
17483                        || DECL_DEFAULTED_OUTSIDE_CLASS_P (code_pattern));
17484   else
17485     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
17486
17487   /* We may be in the middle of deferred access check.  Disable it now.  */
17488   push_deferring_access_checks (dk_no_deferred);
17489
17490   /* Unless an explicit instantiation directive has already determined
17491      the linkage of D, remember that a definition is available for
17492      this entity.  */
17493   if (pattern_defined
17494       && !DECL_INTERFACE_KNOWN (d)
17495       && !DECL_NOT_REALLY_EXTERN (d))
17496     mark_definable (d);
17497
17498   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
17499   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
17500   input_location = DECL_SOURCE_LOCATION (d);
17501
17502   /* If D is a member of an explicitly instantiated class template,
17503      and no definition is available, treat it like an implicit
17504      instantiation.  */
17505   if (!pattern_defined && expl_inst_class_mem_p
17506       && DECL_EXPLICIT_INSTANTIATION (d))
17507     {
17508       /* Leave linkage flags alone on instantiations with anonymous
17509          visibility.  */
17510       if (TREE_PUBLIC (d))
17511         {
17512           DECL_NOT_REALLY_EXTERN (d) = 0;
17513           DECL_INTERFACE_KNOWN (d) = 0;
17514         }
17515       SET_DECL_IMPLICIT_INSTANTIATION (d);
17516     }
17517
17518   /* Recheck the substitutions to obtain any warning messages
17519      about ignoring cv qualifiers.  Don't do this for artificial decls,
17520      as it breaks the context-sensitive substitution for lambda op(). */
17521   if (!defer_ok && !DECL_ARTIFICIAL (d))
17522     {
17523       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
17524       tree type = TREE_TYPE (gen);
17525
17526       /* Make sure that we can see identifiers, and compute access
17527          correctly.  D is already the target FUNCTION_DECL with the
17528          right context.  */
17529       push_access_scope (d);
17530
17531       if (TREE_CODE (gen) == FUNCTION_DECL)
17532         {
17533           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
17534           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
17535                                           d);
17536           /* Don't simply tsubst the function type, as that will give
17537              duplicate warnings about poor parameter qualifications.
17538              The function arguments are the same as the decl_arguments
17539              without the top level cv qualifiers.  */
17540           type = TREE_TYPE (type);
17541         }
17542       tsubst (type, gen_args, tf_warning_or_error, d);
17543
17544       pop_access_scope (d);
17545     }
17546
17547   /* Defer all other templates, unless we have been explicitly
17548      forbidden from doing so.  */
17549   if (/* If there is no definition, we cannot instantiate the
17550          template.  */
17551       ! pattern_defined
17552       /* If it's OK to postpone instantiation, do so.  */
17553       || defer_ok
17554       /* If this is a static data member that will be defined
17555          elsewhere, we don't want to instantiate the entire data
17556          member, but we do want to instantiate the initializer so that
17557          we can substitute that elsewhere.  */
17558       || (external_p && TREE_CODE (d) == VAR_DECL))
17559     {
17560       /* The definition of the static data member is now required so
17561          we must substitute the initializer.  */
17562       if (TREE_CODE (d) == VAR_DECL
17563           && !DECL_INITIAL (d)
17564           && DECL_INITIAL (code_pattern))
17565         {
17566           tree ns;
17567           tree init;
17568           bool const_init = false;
17569
17570           ns = decl_namespace_context (d);
17571           push_nested_namespace (ns);
17572           push_nested_class (DECL_CONTEXT (d));
17573           init = tsubst_expr (DECL_INITIAL (code_pattern),
17574                               args,
17575                               tf_warning_or_error, NULL_TREE,
17576                               /*integral_constant_expression_p=*/false);
17577           /* Make sure the initializer is still constant, in case of
17578              circular dependency (template/instantiate6.C). */
17579           const_init
17580             = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
17581           cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
17582                           /*asmspec_tree=*/NULL_TREE,
17583                           LOOKUP_ONLYCONVERTING);
17584           pop_nested_class ();
17585           pop_nested_namespace (ns);
17586         }
17587
17588       /* We restore the source position here because it's used by
17589          add_pending_template.  */
17590       input_location = saved_loc;
17591
17592       if (at_eof && !pattern_defined
17593           && DECL_EXPLICIT_INSTANTIATION (d)
17594           && DECL_NOT_REALLY_EXTERN (d))
17595         /* [temp.explicit]
17596
17597            The definition of a non-exported function template, a
17598            non-exported member function template, or a non-exported
17599            member function or static data member of a class template
17600            shall be present in every translation unit in which it is
17601            explicitly instantiated.  */
17602         permerror (input_location,  "explicit instantiation of %qD "
17603                    "but no definition available", d);
17604
17605       /* If we're in unevaluated context, we just wanted to get the
17606          constant value; this isn't an odr use, so don't queue
17607          a full instantiation.  */
17608       if (cp_unevaluated_operand != 0)
17609         goto out;
17610       /* ??? Historically, we have instantiated inline functions, even
17611          when marked as "extern template".  */
17612       if (!(external_p && TREE_CODE (d) == VAR_DECL))
17613         add_pending_template (d);
17614       goto out;
17615     }
17616   /* Tell the repository that D is available in this translation unit
17617      -- and see if it is supposed to be instantiated here.  */
17618   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
17619     {
17620       /* In a PCH file, despite the fact that the repository hasn't
17621          requested instantiation in the PCH it is still possible that
17622          an instantiation will be required in a file that includes the
17623          PCH.  */
17624       if (pch_file)
17625         add_pending_template (d);
17626       /* Instantiate inline functions so that the inliner can do its
17627          job, even though we'll not be emitting a copy of this
17628          function.  */
17629       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
17630         goto out;
17631     }
17632
17633   need_push = !cfun || !global_bindings_p ();
17634   if (need_push)
17635     push_to_top_level ();
17636
17637   /* Mark D as instantiated so that recursive calls to
17638      instantiate_decl do not try to instantiate it again.  */
17639   DECL_TEMPLATE_INSTANTIATED (d) = 1;
17640
17641   /* Regenerate the declaration in case the template has been modified
17642      by a subsequent redeclaration.  */
17643   regenerate_decl_from_template (d, td);
17644
17645   /* We already set the file and line above.  Reset them now in case
17646      they changed as a result of calling regenerate_decl_from_template.  */
17647   input_location = DECL_SOURCE_LOCATION (d);
17648
17649   if (TREE_CODE (d) == VAR_DECL)
17650     {
17651       tree init;
17652       bool const_init = false;
17653
17654       /* Clear out DECL_RTL; whatever was there before may not be right
17655          since we've reset the type of the declaration.  */
17656       SET_DECL_RTL (d, NULL);
17657       DECL_IN_AGGR_P (d) = 0;
17658
17659       /* The initializer is placed in DECL_INITIAL by
17660          regenerate_decl_from_template so we don't need to
17661          push/pop_access_scope again here.  Pull it out so that
17662          cp_finish_decl can process it.  */
17663       init = DECL_INITIAL (d);
17664       DECL_INITIAL (d) = NULL_TREE;
17665       DECL_INITIALIZED_P (d) = 0;
17666
17667       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
17668          initializer.  That function will defer actual emission until
17669          we have a chance to determine linkage.  */
17670       DECL_EXTERNAL (d) = 0;
17671
17672       /* Enter the scope of D so that access-checking works correctly.  */
17673       push_nested_class (DECL_CONTEXT (d));
17674       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
17675       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
17676       pop_nested_class ();
17677     }
17678   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
17679     synthesize_method (d);
17680   else if (TREE_CODE (d) == FUNCTION_DECL)
17681     {
17682       htab_t saved_local_specializations;
17683       tree subst_decl;
17684       tree tmpl_parm;
17685       tree spec_parm;
17686
17687       /* Save away the current list, in case we are instantiating one
17688          template from within the body of another.  */
17689       saved_local_specializations = local_specializations;
17690
17691       /* Set up the list of local specializations.  */
17692       local_specializations = htab_create (37,
17693                                            hash_local_specialization,
17694                                            eq_local_specializations,
17695                                            NULL);
17696
17697       /* Set up context.  */
17698       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
17699
17700       /* Create substitution entries for the parameters.  */
17701       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
17702       tmpl_parm = DECL_ARGUMENTS (subst_decl);
17703       spec_parm = DECL_ARGUMENTS (d);
17704       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
17705         {
17706           register_local_specialization (spec_parm, tmpl_parm);
17707           spec_parm = skip_artificial_parms_for (d, spec_parm);
17708           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
17709         }
17710       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
17711         {
17712           register_local_specialization (spec_parm, tmpl_parm);
17713           tmpl_parm = DECL_CHAIN (tmpl_parm);
17714           spec_parm = DECL_CHAIN (spec_parm);
17715         }
17716       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
17717         {
17718           /* Register the (value) argument pack as a specialization of
17719              TMPL_PARM, then move on.  */
17720           tree argpack = make_fnparm_pack (spec_parm);
17721           register_local_specialization (argpack, tmpl_parm);
17722           tmpl_parm = DECL_CHAIN (tmpl_parm);
17723           spec_parm = NULL_TREE;
17724         }
17725       gcc_assert (!spec_parm);
17726
17727       /* Substitute into the body of the function.  */
17728       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
17729                    tf_warning_or_error, tmpl,
17730                    /*integral_constant_expression_p=*/false);
17731
17732       /* Set the current input_location to the end of the function
17733          so that finish_function knows where we are.  */
17734       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
17735
17736       /* We don't need the local specializations any more.  */
17737       htab_delete (local_specializations);
17738       local_specializations = saved_local_specializations;
17739
17740       /* Finish the function.  */
17741       d = finish_function (0);
17742       expand_or_defer_fn (d);
17743     }
17744
17745   /* We're not deferring instantiation any more.  */
17746   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
17747
17748   if (need_push)
17749     pop_from_top_level ();
17750
17751 out:
17752   input_location = saved_loc;
17753   pop_deferring_access_checks ();
17754   pop_tinst_level ();
17755
17756   timevar_pop (TV_TEMPLATE_INST);
17757
17758   return d;
17759 }
17760
17761 /* Run through the list of templates that we wish we could
17762    instantiate, and instantiate any we can.  RETRIES is the
17763    number of times we retry pending template instantiation.  */
17764
17765 void
17766 instantiate_pending_templates (int retries)
17767 {
17768   int reconsider;
17769   location_t saved_loc = input_location;
17770
17771   /* Instantiating templates may trigger vtable generation.  This in turn
17772      may require further template instantiations.  We place a limit here
17773      to avoid infinite loop.  */
17774   if (pending_templates && retries >= max_tinst_depth)
17775     {
17776       tree decl = pending_templates->tinst->decl;
17777
17778       error ("template instantiation depth exceeds maximum of %d"
17779              " instantiating %q+D, possibly from virtual table generation"
17780              " (use -ftemplate-depth= to increase the maximum)",
17781              max_tinst_depth, decl);
17782       if (TREE_CODE (decl) == FUNCTION_DECL)
17783         /* Pretend that we defined it.  */
17784         DECL_INITIAL (decl) = error_mark_node;
17785       return;
17786     }
17787
17788   do
17789     {
17790       struct pending_template **t = &pending_templates;
17791       struct pending_template *last = NULL;
17792       reconsider = 0;
17793       while (*t)
17794         {
17795           tree instantiation = reopen_tinst_level ((*t)->tinst);
17796           bool complete = false;
17797
17798           if (TYPE_P (instantiation))
17799             {
17800               tree fn;
17801
17802               if (!COMPLETE_TYPE_P (instantiation))
17803                 {
17804                   instantiate_class_template (instantiation);
17805                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
17806                     for (fn = TYPE_METHODS (instantiation);
17807                          fn;
17808                          fn = TREE_CHAIN (fn))
17809                       if (! DECL_ARTIFICIAL (fn))
17810                         instantiate_decl (fn,
17811                                           /*defer_ok=*/0,
17812                                           /*expl_inst_class_mem_p=*/false);
17813                   if (COMPLETE_TYPE_P (instantiation))
17814                     reconsider = 1;
17815                 }
17816
17817               complete = COMPLETE_TYPE_P (instantiation);
17818             }
17819           else
17820             {
17821               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
17822                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
17823                 {
17824                   instantiation
17825                     = instantiate_decl (instantiation,
17826                                         /*defer_ok=*/0,
17827                                         /*expl_inst_class_mem_p=*/false);
17828                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
17829                     reconsider = 1;
17830                 }
17831
17832               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
17833                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
17834             }
17835
17836           if (complete)
17837             /* If INSTANTIATION has been instantiated, then we don't
17838                need to consider it again in the future.  */
17839             *t = (*t)->next;
17840           else
17841             {
17842               last = *t;
17843               t = &(*t)->next;
17844             }
17845           tinst_depth = 0;
17846           current_tinst_level = NULL;
17847         }
17848       last_pending_template = last;
17849     }
17850   while (reconsider);
17851
17852   input_location = saved_loc;
17853 }
17854
17855 /* Substitute ARGVEC into T, which is a list of initializers for
17856    either base class or a non-static data member.  The TREE_PURPOSEs
17857    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
17858    instantiate_decl.  */
17859
17860 static tree
17861 tsubst_initializer_list (tree t, tree argvec)
17862 {
17863   tree inits = NULL_TREE;
17864
17865   for (; t; t = TREE_CHAIN (t))
17866     {
17867       tree decl;
17868       tree init;
17869       tree expanded_bases = NULL_TREE;
17870       tree expanded_arguments = NULL_TREE;
17871       int i, len = 1;
17872
17873       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
17874         {
17875           tree expr;
17876           tree arg;
17877
17878           /* Expand the base class expansion type into separate base
17879              classes.  */
17880           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
17881                                                  tf_warning_or_error,
17882                                                  NULL_TREE);
17883           if (expanded_bases == error_mark_node)
17884             continue;
17885           
17886           /* We'll be building separate TREE_LISTs of arguments for
17887              each base.  */
17888           len = TREE_VEC_LENGTH (expanded_bases);
17889           expanded_arguments = make_tree_vec (len);
17890           for (i = 0; i < len; i++)
17891             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
17892
17893           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
17894              expand each argument in the TREE_VALUE of t.  */
17895           expr = make_node (EXPR_PACK_EXPANSION);
17896           PACK_EXPANSION_PARAMETER_PACKS (expr) =
17897             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
17898
17899           if (TREE_VALUE (t) == void_type_node)
17900             /* VOID_TYPE_NODE is used to indicate
17901                value-initialization.  */
17902             {
17903               for (i = 0; i < len; i++)
17904                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
17905             }
17906           else
17907             {
17908               /* Substitute parameter packs into each argument in the
17909                  TREE_LIST.  */
17910               in_base_initializer = 1;
17911               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
17912                 {
17913                   tree expanded_exprs;
17914
17915                   /* Expand the argument.  */
17916                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
17917                   expanded_exprs 
17918                     = tsubst_pack_expansion (expr, argvec,
17919                                              tf_warning_or_error,
17920                                              NULL_TREE);
17921                   if (expanded_exprs == error_mark_node)
17922                     continue;
17923
17924                   /* Prepend each of the expanded expressions to the
17925                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
17926                   for (i = 0; i < len; i++)
17927                     {
17928                       TREE_VEC_ELT (expanded_arguments, i) = 
17929                         tree_cons (NULL_TREE, 
17930                                    TREE_VEC_ELT (expanded_exprs, i),
17931                                    TREE_VEC_ELT (expanded_arguments, i));
17932                     }
17933                 }
17934               in_base_initializer = 0;
17935
17936               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
17937                  since we built them backwards.  */
17938               for (i = 0; i < len; i++)
17939                 {
17940                   TREE_VEC_ELT (expanded_arguments, i) = 
17941                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
17942                 }
17943             }
17944         }
17945
17946       for (i = 0; i < len; ++i)
17947         {
17948           if (expanded_bases)
17949             {
17950               decl = TREE_VEC_ELT (expanded_bases, i);
17951               decl = expand_member_init (decl);
17952               init = TREE_VEC_ELT (expanded_arguments, i);
17953             }
17954           else
17955             {
17956               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
17957                                   tf_warning_or_error, NULL_TREE);
17958
17959               decl = expand_member_init (decl);
17960               if (decl && !DECL_P (decl))
17961                 in_base_initializer = 1;
17962
17963               init = TREE_VALUE (t);
17964               if (init != void_type_node)
17965                 init = tsubst_expr (init, argvec,
17966                                     tf_warning_or_error, NULL_TREE,
17967                                     /*integral_constant_expression_p=*/false);
17968               in_base_initializer = 0;
17969             }
17970
17971           if (decl)
17972             {
17973               init = build_tree_list (decl, init);
17974               TREE_CHAIN (init) = inits;
17975               inits = init;
17976             }
17977         }
17978     }
17979   return inits;
17980 }
17981
17982 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
17983
17984 static void
17985 set_current_access_from_decl (tree decl)
17986 {
17987   if (TREE_PRIVATE (decl))
17988     current_access_specifier = access_private_node;
17989   else if (TREE_PROTECTED (decl))
17990     current_access_specifier = access_protected_node;
17991   else
17992     current_access_specifier = access_public_node;
17993 }
17994
17995 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
17996    is the instantiation (which should have been created with
17997    start_enum) and ARGS are the template arguments to use.  */
17998
17999 static void
18000 tsubst_enum (tree tag, tree newtag, tree args)
18001 {
18002   tree e;
18003
18004   if (SCOPED_ENUM_P (newtag))
18005     begin_scope (sk_scoped_enum, newtag);
18006
18007   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
18008     {
18009       tree value;
18010       tree decl;
18011
18012       decl = TREE_VALUE (e);
18013       /* Note that in a template enum, the TREE_VALUE is the
18014          CONST_DECL, not the corresponding INTEGER_CST.  */
18015       value = tsubst_expr (DECL_INITIAL (decl),
18016                            args, tf_warning_or_error, NULL_TREE,
18017                            /*integral_constant_expression_p=*/true);
18018
18019       /* Give this enumeration constant the correct access.  */
18020       set_current_access_from_decl (decl);
18021
18022       /* Actually build the enumerator itself.  */
18023       build_enumerator
18024         (DECL_NAME (decl), value, newtag, DECL_SOURCE_LOCATION (decl));
18025     }
18026
18027   if (SCOPED_ENUM_P (newtag))
18028     finish_scope ();
18029
18030   finish_enum_value_list (newtag);
18031   finish_enum (newtag);
18032
18033   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
18034     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
18035 }
18036
18037 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
18038    its type -- but without substituting the innermost set of template
18039    arguments.  So, innermost set of template parameters will appear in
18040    the type.  */
18041
18042 tree
18043 get_mostly_instantiated_function_type (tree decl)
18044 {
18045   tree fn_type;
18046   tree tmpl;
18047   tree targs;
18048   tree tparms;
18049   int parm_depth;
18050
18051   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
18052   targs = DECL_TI_ARGS (decl);
18053   tparms = DECL_TEMPLATE_PARMS (tmpl);
18054   parm_depth = TMPL_PARMS_DEPTH (tparms);
18055
18056   /* There should be as many levels of arguments as there are levels
18057      of parameters.  */
18058   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
18059
18060   fn_type = TREE_TYPE (tmpl);
18061
18062   if (parm_depth == 1)
18063     /* No substitution is necessary.  */
18064     ;
18065   else
18066     {
18067       int i;
18068       tree partial_args;
18069
18070       /* Replace the innermost level of the TARGS with NULL_TREEs to
18071          let tsubst know not to substitute for those parameters.  */
18072       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
18073       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
18074         SET_TMPL_ARGS_LEVEL (partial_args, i,
18075                              TMPL_ARGS_LEVEL (targs, i));
18076       SET_TMPL_ARGS_LEVEL (partial_args,
18077                            TMPL_ARGS_DEPTH (targs),
18078                            make_tree_vec (DECL_NTPARMS (tmpl)));
18079
18080       /* Disable access control as this function is used only during
18081          name-mangling.  */
18082       push_deferring_access_checks (dk_no_check);
18083
18084       ++processing_template_decl;
18085       /* Now, do the (partial) substitution to figure out the
18086          appropriate function type.  */
18087       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
18088       --processing_template_decl;
18089
18090       /* Substitute into the template parameters to obtain the real
18091          innermost set of parameters.  This step is important if the
18092          innermost set of template parameters contains value
18093          parameters whose types depend on outer template parameters.  */
18094       TREE_VEC_LENGTH (partial_args)--;
18095       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
18096
18097       pop_deferring_access_checks ();
18098     }
18099
18100   return fn_type;
18101 }
18102
18103 /* Return truthvalue if we're processing a template different from
18104    the last one involved in diagnostics.  */
18105 int
18106 problematic_instantiation_changed (void)
18107 {
18108   return last_template_error_tick != tinst_level_tick;
18109 }
18110
18111 /* Remember current template involved in diagnostics.  */
18112 void
18113 record_last_problematic_instantiation (void)
18114 {
18115   last_template_error_tick = tinst_level_tick;
18116 }
18117
18118 struct tinst_level *
18119 current_instantiation (void)
18120 {
18121   return current_tinst_level;
18122 }
18123
18124 /* [temp.param] Check that template non-type parm TYPE is of an allowable
18125    type. Return zero for ok, nonzero for disallowed. Issue error and
18126    warning messages under control of COMPLAIN.  */
18127
18128 static int
18129 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
18130 {
18131   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
18132     return 0;
18133   else if (POINTER_TYPE_P (type))
18134     return 0;
18135   else if (TYPE_PTR_TO_MEMBER_P (type))
18136     return 0;
18137   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
18138     return 0;
18139   else if (TREE_CODE (type) == TYPENAME_TYPE)
18140     return 0;
18141   else if (TREE_CODE (type) == DECLTYPE_TYPE)
18142     return 0;
18143
18144   if (complain & tf_error)
18145     error ("%q#T is not a valid type for a template constant parameter", type);
18146   return 1;
18147 }
18148
18149 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
18150    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
18151
18152 static bool
18153 dependent_type_p_r (tree type)
18154 {
18155   tree scope;
18156
18157   /* [temp.dep.type]
18158
18159      A type is dependent if it is:
18160
18161      -- a template parameter. Template template parameters are types
18162         for us (since TYPE_P holds true for them) so we handle
18163         them here.  */
18164   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18165       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
18166     return true;
18167   /* -- a qualified-id with a nested-name-specifier which contains a
18168         class-name that names a dependent type or whose unqualified-id
18169         names a dependent type.  */
18170   if (TREE_CODE (type) == TYPENAME_TYPE)
18171     return true;
18172   /* -- a cv-qualified type where the cv-unqualified type is
18173         dependent.  */
18174   type = TYPE_MAIN_VARIANT (type);
18175   /* -- a compound type constructed from any dependent type.  */
18176   if (TYPE_PTR_TO_MEMBER_P (type))
18177     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
18178             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
18179                                            (type)));
18180   else if (TREE_CODE (type) == POINTER_TYPE
18181            || TREE_CODE (type) == REFERENCE_TYPE)
18182     return dependent_type_p (TREE_TYPE (type));
18183   else if (TREE_CODE (type) == FUNCTION_TYPE
18184            || TREE_CODE (type) == METHOD_TYPE)
18185     {
18186       tree arg_type;
18187
18188       if (dependent_type_p (TREE_TYPE (type)))
18189         return true;
18190       for (arg_type = TYPE_ARG_TYPES (type);
18191            arg_type;
18192            arg_type = TREE_CHAIN (arg_type))
18193         if (dependent_type_p (TREE_VALUE (arg_type)))
18194           return true;
18195       return false;
18196     }
18197   /* -- an array type constructed from any dependent type or whose
18198         size is specified by a constant expression that is
18199         value-dependent.
18200
18201         We checked for type- and value-dependence of the bounds in
18202         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
18203   if (TREE_CODE (type) == ARRAY_TYPE)
18204     {
18205       if (TYPE_DOMAIN (type)
18206           && dependent_type_p (TYPE_DOMAIN (type)))
18207         return true;
18208       return dependent_type_p (TREE_TYPE (type));
18209     }
18210
18211   /* -- a template-id in which either the template name is a template
18212      parameter ...  */
18213   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
18214     return true;
18215   /* ... or any of the template arguments is a dependent type or
18216         an expression that is type-dependent or value-dependent.  */
18217   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
18218            && (any_dependent_template_arguments_p
18219                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
18220     return true;
18221
18222   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
18223      dependent; if the argument of the `typeof' expression is not
18224      type-dependent, then it should already been have resolved.  */
18225   if (TREE_CODE (type) == TYPEOF_TYPE
18226       || TREE_CODE (type) == DECLTYPE_TYPE
18227       || TREE_CODE (type) == UNDERLYING_TYPE)
18228     return true;
18229
18230   /* A template argument pack is dependent if any of its packed
18231      arguments are.  */
18232   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
18233     {
18234       tree args = ARGUMENT_PACK_ARGS (type);
18235       int i, len = TREE_VEC_LENGTH (args);
18236       for (i = 0; i < len; ++i)
18237         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
18238           return true;
18239     }
18240
18241   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
18242      be template parameters.  */
18243   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
18244     return true;
18245
18246   /* The standard does not specifically mention types that are local
18247      to template functions or local classes, but they should be
18248      considered dependent too.  For example:
18249
18250        template <int I> void f() {
18251          enum E { a = I };
18252          S<sizeof (E)> s;
18253        }
18254
18255      The size of `E' cannot be known until the value of `I' has been
18256      determined.  Therefore, `E' must be considered dependent.  */
18257   scope = TYPE_CONTEXT (type);
18258   if (scope && TYPE_P (scope))
18259     return dependent_type_p (scope);
18260   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
18261     return type_dependent_expression_p (scope);
18262
18263   /* Other types are non-dependent.  */
18264   return false;
18265 }
18266
18267 /* Returns TRUE if TYPE is dependent, in the sense of
18268    [temp.dep.type].  Note that a NULL type is considered dependent.  */
18269
18270 bool
18271 dependent_type_p (tree type)
18272 {
18273   /* If there are no template parameters in scope, then there can't be
18274      any dependent types.  */
18275   if (!processing_template_decl)
18276     {
18277       /* If we are not processing a template, then nobody should be
18278          providing us with a dependent type.  */
18279       gcc_assert (type);
18280       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
18281       return false;
18282     }
18283
18284   /* If the type is NULL, we have not computed a type for the entity
18285      in question; in that case, the type is dependent.  */
18286   if (!type)
18287     return true;
18288
18289   /* Erroneous types can be considered non-dependent.  */
18290   if (type == error_mark_node)
18291     return false;
18292
18293   /* If we have not already computed the appropriate value for TYPE,
18294      do so now.  */
18295   if (!TYPE_DEPENDENT_P_VALID (type))
18296     {
18297       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
18298       TYPE_DEPENDENT_P_VALID (type) = 1;
18299     }
18300
18301   return TYPE_DEPENDENT_P (type);
18302 }
18303
18304 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
18305    lookup.  In other words, a dependent type that is not the current
18306    instantiation.  */
18307
18308 bool
18309 dependent_scope_p (tree scope)
18310 {
18311   return (scope && TYPE_P (scope) && dependent_type_p (scope)
18312           && !currently_open_class (scope));
18313 }
18314
18315 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
18316    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
18317    expression.  */
18318
18319 /* Note that this predicate is not appropriate for general expressions;
18320    only constant expressions (that satisfy potential_constant_expression)
18321    can be tested for value dependence.
18322
18323    We should really also have a predicate for "instantiation-dependent".
18324
18325    fold_non_dependent_expr: fold if constant and not type-dependent and not value-dependent.
18326      (what about instantiation-dependent constant-expressions?)
18327    is_late_template_attribute: defer if instantiation-dependent.
18328    compute_array_index_type: proceed if constant and not t- or v-dependent
18329      if instantiation-dependent, need to remember full expression
18330    uses_template_parms: FIXME - need to audit callers
18331    tsubst_decl [function_decl]: Why is this using value_dependent_expression_p?
18332    dependent_type_p [array_type]: dependent if index type is dependent
18333      (or non-constant?)
18334    static_assert - instantiation-dependent */
18335
18336 bool
18337 value_dependent_expression_p (tree expression)
18338 {
18339   if (!processing_template_decl)
18340     return false;
18341
18342   /* A name declared with a dependent type.  */
18343   if (DECL_P (expression) && type_dependent_expression_p (expression))
18344     return true;
18345
18346   switch (TREE_CODE (expression))
18347     {
18348     case IDENTIFIER_NODE:
18349       /* A name that has not been looked up -- must be dependent.  */
18350       return true;
18351
18352     case TEMPLATE_PARM_INDEX:
18353       /* A non-type template parm.  */
18354       return true;
18355
18356     case CONST_DECL:
18357       /* A non-type template parm.  */
18358       if (DECL_TEMPLATE_PARM_P (expression))
18359         return true;
18360       return value_dependent_expression_p (DECL_INITIAL (expression));
18361
18362     case VAR_DECL:
18363        /* A constant with literal type and is initialized
18364           with an expression that is value-dependent.  */
18365       if (DECL_INITIAL (expression)
18366           && decl_constant_var_p (expression)
18367           && value_dependent_expression_p (DECL_INITIAL (expression)))
18368         return true;
18369       return false;
18370
18371     case DYNAMIC_CAST_EXPR:
18372     case STATIC_CAST_EXPR:
18373     case CONST_CAST_EXPR:
18374     case REINTERPRET_CAST_EXPR:
18375     case CAST_EXPR:
18376       /* These expressions are value-dependent if the type to which
18377          the cast occurs is dependent or the expression being casted
18378          is value-dependent.  */
18379       {
18380         tree type = TREE_TYPE (expression);
18381
18382         if (dependent_type_p (type))
18383           return true;
18384
18385         /* A functional cast has a list of operands.  */
18386         expression = TREE_OPERAND (expression, 0);
18387         if (!expression)
18388           {
18389             /* If there are no operands, it must be an expression such
18390                as "int()". This should not happen for aggregate types
18391                because it would form non-constant expressions.  */
18392             gcc_assert (cxx_dialect >= cxx0x
18393                         || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
18394
18395             return false;
18396           }
18397
18398         if (TREE_CODE (expression) == TREE_LIST)
18399           return any_value_dependent_elements_p (expression);
18400
18401         return value_dependent_expression_p (expression);
18402       }
18403
18404     case SIZEOF_EXPR:
18405     case ALIGNOF_EXPR:
18406     case TYPEID_EXPR:
18407       /* A `sizeof' expression is value-dependent if the operand is
18408          type-dependent or is a pack expansion.  */
18409       expression = TREE_OPERAND (expression, 0);
18410       if (PACK_EXPANSION_P (expression))
18411         return true;
18412       else if (TYPE_P (expression))
18413         return dependent_type_p (expression);
18414       return type_dependent_expression_p (expression);
18415
18416     case AT_ENCODE_EXPR:
18417       /* An 'encode' expression is value-dependent if the operand is
18418          type-dependent.  */
18419       expression = TREE_OPERAND (expression, 0);
18420       return dependent_type_p (expression);
18421
18422     case NOEXCEPT_EXPR:
18423       expression = TREE_OPERAND (expression, 0);
18424       return type_dependent_expression_p (expression);
18425
18426     case SCOPE_REF:
18427       {
18428         tree name = TREE_OPERAND (expression, 1);
18429         return value_dependent_expression_p (name);
18430       }
18431
18432     case COMPONENT_REF:
18433       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
18434               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
18435
18436     case NONTYPE_ARGUMENT_PACK:
18437       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
18438          is value-dependent.  */
18439       {
18440         tree values = ARGUMENT_PACK_ARGS (expression);
18441         int i, len = TREE_VEC_LENGTH (values);
18442         
18443         for (i = 0; i < len; ++i)
18444           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
18445             return true;
18446         
18447         return false;
18448       }
18449
18450     case TRAIT_EXPR:
18451       {
18452         tree type2 = TRAIT_EXPR_TYPE2 (expression);
18453         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
18454                 || (type2 ? dependent_type_p (type2) : false));
18455       }
18456
18457     case MODOP_EXPR:
18458       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
18459               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
18460
18461     case ARRAY_REF:
18462       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
18463               || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
18464
18465     case ADDR_EXPR:
18466       {
18467         tree op = TREE_OPERAND (expression, 0);
18468         return (value_dependent_expression_p (op)
18469                 || has_value_dependent_address (op));
18470       }
18471
18472     case CALL_EXPR:
18473       {
18474         tree fn = get_callee_fndecl (expression);
18475         int i, nargs;
18476         if (!fn && value_dependent_expression_p (CALL_EXPR_FN (expression)))
18477           return true;
18478         nargs = call_expr_nargs (expression);
18479         for (i = 0; i < nargs; ++i)
18480           {
18481             tree op = CALL_EXPR_ARG (expression, i);
18482             /* In a call to a constexpr member function, look through the
18483                implicit ADDR_EXPR on the object argument so that it doesn't
18484                cause the call to be considered value-dependent.  We also
18485                look through it in potential_constant_expression.  */
18486             if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
18487                 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
18488                 && TREE_CODE (op) == ADDR_EXPR)
18489               op = TREE_OPERAND (op, 0);
18490             if (value_dependent_expression_p (op))
18491               return true;
18492           }
18493         return false;
18494       }
18495
18496     case TEMPLATE_ID_EXPR:
18497       /* If a TEMPLATE_ID_EXPR involves a dependent name, it will be
18498          type-dependent.  */
18499       return type_dependent_expression_p (expression);
18500
18501     case CONSTRUCTOR:
18502       {
18503         unsigned ix;
18504         tree val;
18505         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
18506           if (value_dependent_expression_p (val))
18507             return true;
18508         return false;
18509       }
18510
18511     default:
18512       /* A constant expression is value-dependent if any subexpression is
18513          value-dependent.  */
18514       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
18515         {
18516         case tcc_reference:
18517         case tcc_unary:
18518         case tcc_comparison:
18519         case tcc_binary:
18520         case tcc_expression:
18521         case tcc_vl_exp:
18522           {
18523             int i, len = cp_tree_operand_length (expression);
18524
18525             for (i = 0; i < len; i++)
18526               {
18527                 tree t = TREE_OPERAND (expression, i);
18528
18529                 /* In some cases, some of the operands may be missing.l
18530                    (For example, in the case of PREDECREMENT_EXPR, the
18531                    amount to increment by may be missing.)  That doesn't
18532                    make the expression dependent.  */
18533                 if (t && value_dependent_expression_p (t))
18534                   return true;
18535               }
18536           }
18537           break;
18538         default:
18539           break;
18540         }
18541       break;
18542     }
18543
18544   /* The expression is not value-dependent.  */
18545   return false;
18546 }
18547
18548 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
18549    [temp.dep.expr].  Note that an expression with no type is
18550    considered dependent.  Other parts of the compiler arrange for an
18551    expression with type-dependent subexpressions to have no type, so
18552    this function doesn't have to be fully recursive.  */
18553
18554 bool
18555 type_dependent_expression_p (tree expression)
18556 {
18557   if (!processing_template_decl)
18558     return false;
18559
18560   if (expression == error_mark_node)
18561     return false;
18562
18563   /* An unresolved name is always dependent.  */
18564   if (TREE_CODE (expression) == IDENTIFIER_NODE
18565       || TREE_CODE (expression) == USING_DECL)
18566     return true;
18567
18568   /* Some expression forms are never type-dependent.  */
18569   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
18570       || TREE_CODE (expression) == SIZEOF_EXPR
18571       || TREE_CODE (expression) == ALIGNOF_EXPR
18572       || TREE_CODE (expression) == AT_ENCODE_EXPR
18573       || TREE_CODE (expression) == NOEXCEPT_EXPR
18574       || TREE_CODE (expression) == TRAIT_EXPR
18575       || TREE_CODE (expression) == TYPEID_EXPR
18576       || TREE_CODE (expression) == DELETE_EXPR
18577       || TREE_CODE (expression) == VEC_DELETE_EXPR
18578       || TREE_CODE (expression) == THROW_EXPR)
18579     return false;
18580
18581   /* The types of these expressions depends only on the type to which
18582      the cast occurs.  */
18583   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
18584       || TREE_CODE (expression) == STATIC_CAST_EXPR
18585       || TREE_CODE (expression) == CONST_CAST_EXPR
18586       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
18587       || TREE_CODE (expression) == CAST_EXPR)
18588     return dependent_type_p (TREE_TYPE (expression));
18589
18590   /* The types of these expressions depends only on the type created
18591      by the expression.  */
18592   if (TREE_CODE (expression) == NEW_EXPR
18593       || TREE_CODE (expression) == VEC_NEW_EXPR)
18594     {
18595       /* For NEW_EXPR tree nodes created inside a template, either
18596          the object type itself or a TREE_LIST may appear as the
18597          operand 1.  */
18598       tree type = TREE_OPERAND (expression, 1);
18599       if (TREE_CODE (type) == TREE_LIST)
18600         /* This is an array type.  We need to check array dimensions
18601            as well.  */
18602         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
18603                || value_dependent_expression_p
18604                     (TREE_OPERAND (TREE_VALUE (type), 1));
18605       else
18606         return dependent_type_p (type);
18607     }
18608
18609   if (TREE_CODE (expression) == SCOPE_REF)
18610     {
18611       tree scope = TREE_OPERAND (expression, 0);
18612       tree name = TREE_OPERAND (expression, 1);
18613
18614       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
18615          contains an identifier associated by name lookup with one or more
18616          declarations declared with a dependent type, or...a
18617          nested-name-specifier or qualified-id that names a member of an
18618          unknown specialization.  */
18619       return (type_dependent_expression_p (name)
18620               || dependent_scope_p (scope));
18621     }
18622
18623   if (TREE_CODE (expression) == FUNCTION_DECL
18624       && DECL_LANG_SPECIFIC (expression)
18625       && DECL_TEMPLATE_INFO (expression)
18626       && (any_dependent_template_arguments_p
18627           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
18628     return true;
18629
18630   if (TREE_CODE (expression) == TEMPLATE_DECL
18631       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
18632     return false;
18633
18634   if (TREE_CODE (expression) == STMT_EXPR)
18635     expression = stmt_expr_value_expr (expression);
18636
18637   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
18638     {
18639       tree elt;
18640       unsigned i;
18641
18642       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
18643         {
18644           if (type_dependent_expression_p (elt))
18645             return true;
18646         }
18647       return false;
18648     }
18649
18650   /* A static data member of the current instantiation with incomplete
18651      array type is type-dependent, as the definition and specializations
18652      can have different bounds.  */
18653   if (TREE_CODE (expression) == VAR_DECL
18654       && DECL_CLASS_SCOPE_P (expression)
18655       && dependent_type_p (DECL_CONTEXT (expression))
18656       && VAR_HAD_UNKNOWN_BOUND (expression))
18657     return true;
18658
18659   if (TREE_TYPE (expression) == unknown_type_node)
18660     {
18661       if (TREE_CODE (expression) == ADDR_EXPR)
18662         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
18663       if (TREE_CODE (expression) == COMPONENT_REF
18664           || TREE_CODE (expression) == OFFSET_REF)
18665         {
18666           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
18667             return true;
18668           expression = TREE_OPERAND (expression, 1);
18669           if (TREE_CODE (expression) == IDENTIFIER_NODE)
18670             return false;
18671         }
18672       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
18673       if (TREE_CODE (expression) == SCOPE_REF)
18674         return false;
18675
18676       if (TREE_CODE (expression) == BASELINK)
18677         expression = BASELINK_FUNCTIONS (expression);
18678
18679       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
18680         {
18681           if (any_dependent_template_arguments_p
18682               (TREE_OPERAND (expression, 1)))
18683             return true;
18684           expression = TREE_OPERAND (expression, 0);
18685         }
18686       gcc_assert (TREE_CODE (expression) == OVERLOAD
18687                   || TREE_CODE (expression) == FUNCTION_DECL);
18688
18689       while (expression)
18690         {
18691           if (type_dependent_expression_p (OVL_CURRENT (expression)))
18692             return true;
18693           expression = OVL_NEXT (expression);
18694         }
18695       return false;
18696     }
18697
18698   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
18699
18700   return (dependent_type_p (TREE_TYPE (expression)));
18701 }
18702
18703 /* Like type_dependent_expression_p, but it also works while not processing
18704    a template definition, i.e. during substitution or mangling.  */
18705
18706 bool
18707 type_dependent_expression_p_push (tree expr)
18708 {
18709   bool b;
18710   ++processing_template_decl;
18711   b = type_dependent_expression_p (expr);
18712   --processing_template_decl;
18713   return b;
18714 }
18715
18716 /* Returns TRUE if ARGS contains a type-dependent expression.  */
18717
18718 bool
18719 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
18720 {
18721   unsigned int i;
18722   tree arg;
18723
18724   FOR_EACH_VEC_ELT (tree, args, i, arg)
18725     {
18726       if (type_dependent_expression_p (arg))
18727         return true;
18728     }
18729   return false;
18730 }
18731
18732 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
18733    expressions) contains any type-dependent expressions.  */
18734
18735 bool
18736 any_type_dependent_elements_p (const_tree list)
18737 {
18738   for (; list; list = TREE_CHAIN (list))
18739     if (value_dependent_expression_p (TREE_VALUE (list)))
18740       return true;
18741
18742   return false;
18743 }
18744
18745 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
18746    expressions) contains any value-dependent expressions.  */
18747
18748 bool
18749 any_value_dependent_elements_p (const_tree list)
18750 {
18751   for (; list; list = TREE_CHAIN (list))
18752     if (value_dependent_expression_p (TREE_VALUE (list)))
18753       return true;
18754
18755   return false;
18756 }
18757
18758 /* Returns TRUE if the ARG (a template argument) is dependent.  */
18759
18760 bool
18761 dependent_template_arg_p (tree arg)
18762 {
18763   if (!processing_template_decl)
18764     return false;
18765
18766   /* Assume a template argument that was wrongly written by the user
18767      is dependent. This is consistent with what
18768      any_dependent_template_arguments_p [that calls this function]
18769      does.  */
18770   if (arg == error_mark_node)
18771     return true;
18772
18773   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
18774     arg = ARGUMENT_PACK_SELECT_ARG (arg);
18775
18776   if (TREE_CODE (arg) == TEMPLATE_DECL
18777       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
18778     return dependent_template_p (arg);
18779   else if (ARGUMENT_PACK_P (arg))
18780     {
18781       tree args = ARGUMENT_PACK_ARGS (arg);
18782       int i, len = TREE_VEC_LENGTH (args);
18783       for (i = 0; i < len; ++i)
18784         {
18785           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
18786             return true;
18787         }
18788
18789       return false;
18790     }
18791   else if (TYPE_P (arg))
18792     return dependent_type_p (arg);
18793   else
18794     return (type_dependent_expression_p (arg)
18795             || value_dependent_expression_p (arg));
18796 }
18797
18798 /* Returns true if ARGS (a collection of template arguments) contains
18799    any types that require structural equality testing.  */
18800
18801 bool
18802 any_template_arguments_need_structural_equality_p (tree args)
18803 {
18804   int i;
18805   int j;
18806
18807   if (!args)
18808     return false;
18809   if (args == error_mark_node)
18810     return true;
18811
18812   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
18813     {
18814       tree level = TMPL_ARGS_LEVEL (args, i + 1);
18815       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
18816         {
18817           tree arg = TREE_VEC_ELT (level, j);
18818           tree packed_args = NULL_TREE;
18819           int k, len = 1;
18820
18821           if (ARGUMENT_PACK_P (arg))
18822             {
18823               /* Look inside the argument pack.  */
18824               packed_args = ARGUMENT_PACK_ARGS (arg);
18825               len = TREE_VEC_LENGTH (packed_args);
18826             }
18827
18828           for (k = 0; k < len; ++k)
18829             {
18830               if (packed_args)
18831                 arg = TREE_VEC_ELT (packed_args, k);
18832
18833               if (error_operand_p (arg))
18834                 return true;
18835               else if (TREE_CODE (arg) == TEMPLATE_DECL
18836                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
18837                 continue;
18838               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
18839                 return true;
18840               else if (!TYPE_P (arg) && TREE_TYPE (arg)
18841                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
18842                 return true;
18843             }
18844         }
18845     }
18846
18847   return false;
18848 }
18849
18850 /* Returns true if ARGS (a collection of template arguments) contains
18851    any dependent arguments.  */
18852
18853 bool
18854 any_dependent_template_arguments_p (const_tree args)
18855 {
18856   int i;
18857   int j;
18858
18859   if (!args)
18860     return false;
18861   if (args == error_mark_node)
18862     return true;
18863
18864   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
18865     {
18866       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
18867       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
18868         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
18869           return true;
18870     }
18871
18872   return false;
18873 }
18874
18875 /* Returns TRUE if the template TMPL is dependent.  */
18876
18877 bool
18878 dependent_template_p (tree tmpl)
18879 {
18880   if (TREE_CODE (tmpl) == OVERLOAD)
18881     {
18882       while (tmpl)
18883         {
18884           if (dependent_template_p (OVL_CURRENT (tmpl)))
18885             return true;
18886           tmpl = OVL_NEXT (tmpl);
18887         }
18888       return false;
18889     }
18890
18891   /* Template template parameters are dependent.  */
18892   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
18893       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
18894     return true;
18895   /* So are names that have not been looked up.  */
18896   if (TREE_CODE (tmpl) == SCOPE_REF
18897       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
18898     return true;
18899   /* So are member templates of dependent classes.  */
18900   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
18901     return dependent_type_p (DECL_CONTEXT (tmpl));
18902   return false;
18903 }
18904
18905 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
18906
18907 bool
18908 dependent_template_id_p (tree tmpl, tree args)
18909 {
18910   return (dependent_template_p (tmpl)
18911           || any_dependent_template_arguments_p (args));
18912 }
18913
18914 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
18915    is dependent.  */
18916
18917 bool
18918 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
18919 {
18920   int i;
18921
18922   if (!processing_template_decl)
18923     return false;
18924
18925   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
18926     {
18927       tree decl = TREE_VEC_ELT (declv, i);
18928       tree init = TREE_VEC_ELT (initv, i);
18929       tree cond = TREE_VEC_ELT (condv, i);
18930       tree incr = TREE_VEC_ELT (incrv, i);
18931
18932       if (type_dependent_expression_p (decl))
18933         return true;
18934
18935       if (init && type_dependent_expression_p (init))
18936         return true;
18937
18938       if (type_dependent_expression_p (cond))
18939         return true;
18940
18941       if (COMPARISON_CLASS_P (cond)
18942           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
18943               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
18944         return true;
18945
18946       if (TREE_CODE (incr) == MODOP_EXPR)
18947         {
18948           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
18949               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
18950             return true;
18951         }
18952       else if (type_dependent_expression_p (incr))
18953         return true;
18954       else if (TREE_CODE (incr) == MODIFY_EXPR)
18955         {
18956           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
18957             return true;
18958           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
18959             {
18960               tree t = TREE_OPERAND (incr, 1);
18961               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
18962                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
18963                 return true;
18964             }
18965         }
18966     }
18967
18968   return false;
18969 }
18970
18971 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
18972    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
18973    no such TYPE can be found.  Note that this function peers inside
18974    uninstantiated templates and therefore should be used only in
18975    extremely limited situations.  ONLY_CURRENT_P restricts this
18976    peering to the currently open classes hierarchy (which is required
18977    when comparing types).  */
18978
18979 tree
18980 resolve_typename_type (tree type, bool only_current_p)
18981 {
18982   tree scope;
18983   tree name;
18984   tree decl;
18985   int quals;
18986   tree pushed_scope;
18987   tree result;
18988
18989   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
18990
18991   scope = TYPE_CONTEXT (type);
18992   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
18993      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
18994      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
18995      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
18996      identifier  of the TYPENAME_TYPE anymore.
18997      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
18998      TYPENAME_TYPE instead, we avoid messing up with a possible
18999      typedef variant case.  */
19000   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
19001
19002   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
19003      it first before we can figure out what NAME refers to.  */
19004   if (TREE_CODE (scope) == TYPENAME_TYPE)
19005     scope = resolve_typename_type (scope, only_current_p);
19006   /* If we don't know what SCOPE refers to, then we cannot resolve the
19007      TYPENAME_TYPE.  */
19008   if (TREE_CODE (scope) == TYPENAME_TYPE)
19009     return type;
19010   /* If the SCOPE is a template type parameter, we have no way of
19011      resolving the name.  */
19012   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
19013     return type;
19014   /* If the SCOPE is not the current instantiation, there's no reason
19015      to look inside it.  */
19016   if (only_current_p && !currently_open_class (scope))
19017     return type;
19018   /* If this is a typedef, we don't want to look inside (c++/11987).  */
19019   if (typedef_variant_p (type))
19020     return type;
19021   /* If SCOPE isn't the template itself, it will not have a valid
19022      TYPE_FIELDS list.  */
19023   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
19024     /* scope is either the template itself or a compatible instantiation
19025        like X<T>, so look up the name in the original template.  */
19026     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
19027   else
19028     /* scope is a partial instantiation, so we can't do the lookup or we
19029        will lose the template arguments.  */
19030     return type;
19031   /* Enter the SCOPE so that name lookup will be resolved as if we
19032      were in the class definition.  In particular, SCOPE will no
19033      longer be considered a dependent type.  */
19034   pushed_scope = push_scope (scope);
19035   /* Look up the declaration.  */
19036   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
19037
19038   result = NULL_TREE;
19039   
19040   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
19041      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
19042   if (!decl)
19043     /*nop*/;
19044   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
19045            && TREE_CODE (decl) == TYPE_DECL)
19046     {
19047       result = TREE_TYPE (decl);
19048       if (result == error_mark_node)
19049         result = NULL_TREE;
19050     }
19051   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
19052            && DECL_CLASS_TEMPLATE_P (decl))
19053     {
19054       tree tmpl;
19055       tree args;
19056       /* Obtain the template and the arguments.  */
19057       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
19058       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
19059       /* Instantiate the template.  */
19060       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
19061                                       /*entering_scope=*/0,
19062                                       tf_error | tf_user);
19063       if (result == error_mark_node)
19064         result = NULL_TREE;
19065     }
19066   
19067   /* Leave the SCOPE.  */
19068   if (pushed_scope)
19069     pop_scope (pushed_scope);
19070
19071   /* If we failed to resolve it, return the original typename.  */
19072   if (!result)
19073     return type;
19074   
19075   /* If lookup found a typename type, resolve that too.  */
19076   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
19077     {
19078       /* Ill-formed programs can cause infinite recursion here, so we
19079          must catch that.  */
19080       TYPENAME_IS_RESOLVING_P (type) = 1;
19081       result = resolve_typename_type (result, only_current_p);
19082       TYPENAME_IS_RESOLVING_P (type) = 0;
19083     }
19084   
19085   /* Qualify the resulting type.  */
19086   quals = cp_type_quals (type);
19087   if (quals)
19088     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
19089
19090   return result;
19091 }
19092
19093 /* EXPR is an expression which is not type-dependent.  Return a proxy
19094    for EXPR that can be used to compute the types of larger
19095    expressions containing EXPR.  */
19096
19097 tree
19098 build_non_dependent_expr (tree expr)
19099 {
19100   tree inner_expr;
19101
19102 #ifdef ENABLE_CHECKING
19103   /* Try to get a constant value for all non-type-dependent expressions in
19104       order to expose bugs in *_dependent_expression_p and constexpr.  */
19105   if (cxx_dialect >= cxx0x)
19106     maybe_constant_value (fold_non_dependent_expr (expr));
19107 #endif
19108
19109   /* Preserve OVERLOADs; the functions must be available to resolve
19110      types.  */
19111   inner_expr = expr;
19112   if (TREE_CODE (inner_expr) == STMT_EXPR)
19113     inner_expr = stmt_expr_value_expr (inner_expr);
19114   if (TREE_CODE (inner_expr) == ADDR_EXPR)
19115     inner_expr = TREE_OPERAND (inner_expr, 0);
19116   if (TREE_CODE (inner_expr) == COMPONENT_REF)
19117     inner_expr = TREE_OPERAND (inner_expr, 1);
19118   if (is_overloaded_fn (inner_expr)
19119       || TREE_CODE (inner_expr) == OFFSET_REF)
19120     return expr;
19121   /* There is no need to return a proxy for a variable.  */
19122   if (TREE_CODE (expr) == VAR_DECL)
19123     return expr;
19124   /* Preserve string constants; conversions from string constants to
19125      "char *" are allowed, even though normally a "const char *"
19126      cannot be used to initialize a "char *".  */
19127   if (TREE_CODE (expr) == STRING_CST)
19128     return expr;
19129   /* Preserve arithmetic constants, as an optimization -- there is no
19130      reason to create a new node.  */
19131   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
19132     return expr;
19133   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
19134      There is at least one place where we want to know that a
19135      particular expression is a throw-expression: when checking a ?:
19136      expression, there are special rules if the second or third
19137      argument is a throw-expression.  */
19138   if (TREE_CODE (expr) == THROW_EXPR)
19139     return expr;
19140
19141   if (TREE_CODE (expr) == COND_EXPR)
19142     return build3 (COND_EXPR,
19143                    TREE_TYPE (expr),
19144                    TREE_OPERAND (expr, 0),
19145                    (TREE_OPERAND (expr, 1)
19146                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
19147                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
19148                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
19149   if (TREE_CODE (expr) == COMPOUND_EXPR
19150       && !COMPOUND_EXPR_OVERLOADED (expr))
19151     return build2 (COMPOUND_EXPR,
19152                    TREE_TYPE (expr),
19153                    TREE_OPERAND (expr, 0),
19154                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
19155
19156   /* Keep dereferences outside the NON_DEPENDENT_EXPR so lvalue_kind
19157      doesn't need to look inside.  */
19158   if (REFERENCE_REF_P (expr))
19159     return convert_from_reference (build_non_dependent_expr
19160                                    (TREE_OPERAND (expr, 0)));
19161
19162   /* If the type is unknown, it can't really be non-dependent */
19163   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
19164
19165   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
19166   return build1 (NON_DEPENDENT_EXPR, TREE_TYPE (expr), expr);
19167 }
19168
19169 /* ARGS is a vector of expressions as arguments to a function call.
19170    Replace the arguments with equivalent non-dependent expressions.
19171    This modifies ARGS in place.  */
19172
19173 void
19174 make_args_non_dependent (VEC(tree,gc) *args)
19175 {
19176   unsigned int ix;
19177   tree arg;
19178
19179   FOR_EACH_VEC_ELT (tree, args, ix, arg)
19180     {
19181       tree newarg = build_non_dependent_expr (arg);
19182       if (newarg != arg)
19183         VEC_replace (tree, args, ix, newarg);
19184     }
19185 }
19186
19187 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
19188    with a level one deeper than the actual template parms.  */
19189
19190 tree
19191 make_auto (void)
19192 {
19193   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
19194   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
19195                                TYPE_DECL, get_identifier ("auto"), au);
19196   TYPE_STUB_DECL (au) = TYPE_NAME (au);
19197   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
19198     (0, processing_template_decl + 1, processing_template_decl + 1,
19199      0, TYPE_NAME (au), NULL_TREE);
19200   TYPE_CANONICAL (au) = canonical_type_parameter (au);
19201   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
19202   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
19203
19204   return au;
19205 }
19206
19207 /* Given type ARG, return std::initializer_list<ARG>.  */
19208
19209 static tree
19210 listify (tree arg)
19211 {
19212   tree std_init_list = namespace_binding
19213     (get_identifier ("initializer_list"), std_node);
19214   tree argvec;
19215   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
19216     {    
19217       error ("deducing from brace-enclosed initializer list requires "
19218              "#include <initializer_list>");
19219       return error_mark_node;
19220     }
19221   argvec = make_tree_vec (1);
19222   TREE_VEC_ELT (argvec, 0) = arg;
19223   return lookup_template_class (std_init_list, argvec, NULL_TREE,
19224                                 NULL_TREE, 0, tf_warning_or_error);
19225 }
19226
19227 /* Replace auto in TYPE with std::initializer_list<auto>.  */
19228
19229 static tree
19230 listify_autos (tree type, tree auto_node)
19231 {
19232   tree init_auto = listify (auto_node);
19233   tree argvec = make_tree_vec (1);
19234   TREE_VEC_ELT (argvec, 0) = init_auto;
19235   if (processing_template_decl)
19236     argvec = add_to_template_args (current_template_args (), argvec);
19237   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
19238 }
19239
19240 /* walk_tree helper for do_auto_deduction.  */
19241
19242 static tree
19243 contains_auto_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
19244                  void *type)
19245 {
19246   /* Is this a variable with the type we're looking for?  */
19247   if (DECL_P (*tp)
19248       && TREE_TYPE (*tp) == type)
19249     return *tp;
19250   else
19251     return NULL_TREE;
19252 }
19253
19254 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
19255    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
19256
19257 tree
19258 do_auto_deduction (tree type, tree init, tree auto_node)
19259 {
19260   tree parms, tparms, targs;
19261   tree args[1];
19262   tree decl;
19263   int val;
19264
19265   /* The name of the object being declared shall not appear in the
19266      initializer expression.  */
19267   decl = cp_walk_tree_without_duplicates (&init, contains_auto_r, type);
19268   if (decl)
19269     {
19270       error ("variable %q#D with %<auto%> type used in its own "
19271              "initializer", decl);
19272       return error_mark_node;
19273     }
19274
19275   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
19276      with either a new invented type template parameter U or, if the
19277      initializer is a braced-init-list (8.5.4), with
19278      std::initializer_list<U>.  */
19279   if (BRACE_ENCLOSED_INITIALIZER_P (init))
19280     type = listify_autos (type, auto_node);
19281
19282   init = resolve_nondeduced_context (init);
19283
19284   parms = build_tree_list (NULL_TREE, type);
19285   args[0] = init;
19286   tparms = make_tree_vec (1);
19287   targs = make_tree_vec (1);
19288   TREE_VEC_ELT (tparms, 0)
19289     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
19290   val = type_unification_real (tparms, targs, parms, args, 1, 0,
19291                                DEDUCE_CALL, LOOKUP_NORMAL);
19292   if (val > 0)
19293     {
19294       if (type && type != error_mark_node)
19295         /* If type is error_mark_node a diagnostic must have been
19296            emitted by now.  Also, having a mention to '<type error>'
19297            in the diagnostic is not really useful to the user.  */
19298         error ("unable to deduce %qT from %qE", type, init);
19299       return error_mark_node;
19300     }
19301
19302   /* If the list of declarators contains more than one declarator, the type
19303      of each declared variable is determined as described above. If the
19304      type deduced for the template parameter U is not the same in each
19305      deduction, the program is ill-formed.  */
19306   if (TREE_TYPE (auto_node)
19307       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
19308     {
19309       error ("inconsistent deduction for %qT: %qT and then %qT",
19310              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
19311       return error_mark_node;
19312     }
19313   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
19314
19315   if (processing_template_decl)
19316     targs = add_to_template_args (current_template_args (), targs);
19317   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
19318 }
19319
19320 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
19321    result.  */
19322
19323 tree
19324 splice_late_return_type (tree type, tree late_return_type)
19325 {
19326   tree argvec;
19327
19328   if (late_return_type == NULL_TREE)
19329     return type;
19330   argvec = make_tree_vec (1);
19331   TREE_VEC_ELT (argvec, 0) = late_return_type;
19332   if (processing_template_parmlist)
19333     /* For a late-specified return type in a template type-parameter, we
19334        need to add a dummy argument level for its parmlist.  */
19335     argvec = add_to_template_args
19336       (make_tree_vec (processing_template_parmlist), argvec);
19337   if (current_template_parms)
19338     argvec = add_to_template_args (current_template_args (), argvec);
19339   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
19340 }
19341
19342 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
19343
19344 bool
19345 is_auto (const_tree type)
19346 {
19347   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
19348       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
19349     return true;
19350   else
19351     return false;
19352 }
19353
19354 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
19355    appear as a type-specifier for the declaration in question, we don't
19356    have to look through the whole type.  */
19357
19358 tree
19359 type_uses_auto (tree type)
19360 {
19361   enum tree_code code;
19362   if (is_auto (type))
19363     return type;
19364
19365   code = TREE_CODE (type);
19366
19367   if (code == POINTER_TYPE || code == REFERENCE_TYPE
19368       || code == OFFSET_TYPE || code == FUNCTION_TYPE
19369       || code == METHOD_TYPE || code == ARRAY_TYPE)
19370     return type_uses_auto (TREE_TYPE (type));
19371
19372   if (TYPE_PTRMEMFUNC_P (type))
19373     return type_uses_auto (TREE_TYPE (TREE_TYPE
19374                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
19375
19376   return NULL_TREE;
19377 }
19378
19379 /* For a given template T, return the vector of typedefs referenced
19380    in T for which access check is needed at T instantiation time.
19381    T is either  a FUNCTION_DECL or a RECORD_TYPE.
19382    Those typedefs were added to T by the function
19383    append_type_to_template_for_access_check.  */
19384
19385 VEC(qualified_typedef_usage_t,gc)*
19386 get_types_needing_access_check (tree t)
19387 {
19388   tree ti;
19389   VEC(qualified_typedef_usage_t,gc) *result = NULL;
19390
19391   if (!t || t == error_mark_node)
19392     return NULL;
19393
19394   if (!(ti = get_template_info (t)))
19395     return NULL;
19396
19397   if (CLASS_TYPE_P (t)
19398       || TREE_CODE (t) == FUNCTION_DECL)
19399     {
19400       if (!TI_TEMPLATE (ti))
19401         return NULL;
19402
19403       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
19404     }
19405
19406   return result;
19407 }
19408
19409 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
19410    tied to T. That list of typedefs will be access checked at
19411    T instantiation time.
19412    T is either a FUNCTION_DECL or a RECORD_TYPE.
19413    TYPE_DECL is a TYPE_DECL node representing a typedef.
19414    SCOPE is the scope through which TYPE_DECL is accessed.
19415    LOCATION is the location of the usage point of TYPE_DECL.
19416
19417    This function is a subroutine of
19418    append_type_to_template_for_access_check.  */
19419
19420 static void
19421 append_type_to_template_for_access_check_1 (tree t,
19422                                             tree type_decl,
19423                                             tree scope,
19424                                             location_t location)
19425 {
19426   qualified_typedef_usage_t typedef_usage;
19427   tree ti;
19428
19429   if (!t || t == error_mark_node)
19430     return;
19431
19432   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
19433                || CLASS_TYPE_P (t))
19434               && type_decl
19435               && TREE_CODE (type_decl) == TYPE_DECL
19436               && scope);
19437
19438   if (!(ti = get_template_info (t)))
19439     return;
19440
19441   gcc_assert (TI_TEMPLATE (ti));
19442
19443   typedef_usage.typedef_decl = type_decl;
19444   typedef_usage.context = scope;
19445   typedef_usage.locus = location;
19446
19447   VEC_safe_push (qualified_typedef_usage_t, gc,
19448                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
19449                  &typedef_usage);
19450 }
19451
19452 /* Append TYPE_DECL to the template TEMPL.
19453    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
19454    At TEMPL instanciation time, TYPE_DECL will be checked to see
19455    if it can be accessed through SCOPE.
19456    LOCATION is the location of the usage point of TYPE_DECL.
19457
19458    e.g. consider the following code snippet:
19459
19460      class C
19461      {
19462        typedef int myint;
19463      };
19464
19465      template<class U> struct S
19466      {
19467        C::myint mi; // <-- usage point of the typedef C::myint
19468      };
19469
19470      S<char> s;
19471
19472    At S<char> instantiation time, we need to check the access of C::myint
19473    In other words, we need to check the access of the myint typedef through
19474    the C scope. For that purpose, this function will add the myint typedef
19475    and the scope C through which its being accessed to a list of typedefs
19476    tied to the template S. That list will be walked at template instantiation
19477    time and access check performed on each typedefs it contains.
19478    Note that this particular code snippet should yield an error because
19479    myint is private to C.  */
19480
19481 void
19482 append_type_to_template_for_access_check (tree templ,
19483                                           tree type_decl,
19484                                           tree scope,
19485                                           location_t location)
19486 {
19487   qualified_typedef_usage_t *iter;
19488   int i;
19489
19490   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
19491
19492   /* Make sure we don't append the type to the template twice.  */
19493   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
19494                     get_types_needing_access_check (templ),
19495                     i, iter)
19496     if (iter->typedef_decl == type_decl && scope == iter->context)
19497       return;
19498
19499   append_type_to_template_for_access_check_1 (templ, type_decl,
19500                                               scope, location);
19501 }
19502
19503 /* Set up the hash tables for template instantiations.  */
19504
19505 void
19506 init_template_processing (void)
19507 {
19508   decl_specializations = htab_create_ggc (37,
19509                                           hash_specialization,
19510                                           eq_specializations,
19511                                           ggc_free);
19512   type_specializations = htab_create_ggc (37,
19513                                           hash_specialization,
19514                                           eq_specializations,
19515                                           ggc_free);
19516 }
19517
19518 /* Print stats about the template hash tables for -fstats.  */
19519
19520 void
19521 print_template_statistics (void)
19522 {
19523   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
19524            "%f collisions\n", (long) htab_size (decl_specializations),
19525            (long) htab_elements (decl_specializations),
19526            htab_collisions (decl_specializations));
19527   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
19528            "%f collisions\n", (long) htab_size (type_specializations),
19529            (long) htab_elements (type_specializations),
19530            htab_collisions (type_specializations));
19531   if (current_deduction_htab)
19532     fprintf (stderr, "current_deduction_htab: size %ld, %ld elements, "
19533              "%f collisions\n", (long) htab_size (current_deduction_htab),
19534              (long) htab_elements (current_deduction_htab),
19535              htab_collisions (current_deduction_htab));
19536 }
19537
19538 #include "gt-cp-pt.h"