OSDN Git Service

PR c++/46304
[pf3gnuchains/gcc-fork.git] / gcc / cp / pt.c
1 /* Handle parameterized types (templates) for GNU C++.
2    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3    2001, 2002, 2003, 2004, 2005, 2007, 2008, 2009, 2010
4    Free Software Foundation, Inc.
5    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
6    Rewritten by Jason Merrill (jason@cygnus.com).
7
8 This file is part of GCC.
9
10 GCC is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3, or (at your option)
13 any later version.
14
15 GCC is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 GNU General Public License for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3.  If not see
22 <http://www.gnu.org/licenses/>.  */
23
24 /* Known bugs or deficiencies include:
25
26      all methods must be provided in header files; can't use a source
27      file that contains only the method templates and "just win".  */
28
29 #include "config.h"
30 #include "system.h"
31 #include "coretypes.h"
32 #include "tm.h"
33 #include "tree.h"
34 #include "intl.h"
35 #include "pointer-set.h"
36 #include "flags.h"
37 #include "cp-tree.h"
38 #include "c-family/c-common.h"
39 #include "cp-objcp-common.h"
40 #include "tree-inline.h"
41 #include "decl.h"
42 #include "output.h"
43 #include "toplev.h"
44 #include "timevar.h"
45 #include "tree-iterator.h"
46 #include "vecprim.h"
47
48 /* The type of functions taking a tree, and some additional data, and
49    returning an int.  */
50 typedef int (*tree_fn_t) (tree, void*);
51
52 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
53    instantiations have been deferred, either because their definitions
54    were not yet available, or because we were putting off doing the work.  */
55 struct GTY (()) pending_template {
56   struct pending_template *next;
57   struct tinst_level *tinst;
58 };
59
60 static GTY(()) struct pending_template *pending_templates;
61 static GTY(()) struct pending_template *last_pending_template;
62
63 int processing_template_parmlist;
64 static int template_header_count;
65
66 static GTY(()) tree saved_trees;
67 static VEC(int,heap) *inline_parm_levels;
68
69 static GTY(()) struct tinst_level *current_tinst_level;
70
71 static GTY(()) tree saved_access_scope;
72
73 /* Live only within one (recursive) call to tsubst_expr.  We use
74    this to pass the statement expression node from the STMT_EXPR
75    to the EXPR_STMT that is its result.  */
76 static tree cur_stmt_expr;
77
78 /* A map from local variable declarations in the body of the template
79    presently being instantiated to the corresponding instantiated
80    local variables.  */
81 static htab_t local_specializations;
82
83 typedef struct GTY(()) spec_entry
84 {
85   tree tmpl;
86   tree args;
87   tree spec;
88 } spec_entry;
89
90 static GTY ((param_is (spec_entry)))
91   htab_t decl_specializations;
92
93 static GTY ((param_is (spec_entry)))
94   htab_t type_specializations;
95
96 /* Contains canonical template parameter types. The vector is indexed by
97    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
98    TREE_LIST, whose TREE_VALUEs contain the canonical template
99    parameters of various types and levels.  */
100 static GTY(()) VEC(tree,gc) *canonical_template_parms;
101
102 #define UNIFY_ALLOW_NONE 0
103 #define UNIFY_ALLOW_MORE_CV_QUAL 1
104 #define UNIFY_ALLOW_LESS_CV_QUAL 2
105 #define UNIFY_ALLOW_DERIVED 4
106 #define UNIFY_ALLOW_INTEGER 8
107 #define UNIFY_ALLOW_OUTER_LEVEL 16
108 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
109 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
110
111 static void push_access_scope (tree);
112 static void pop_access_scope (tree);
113 static bool resolve_overloaded_unification (tree, tree, tree, tree,
114                                             unification_kind_t, int);
115 static int try_one_overload (tree, tree, tree, tree, tree,
116                              unification_kind_t, int, bool);
117 static int unify (tree, tree, tree, tree, int);
118 static void add_pending_template (tree);
119 static tree reopen_tinst_level (struct tinst_level *);
120 static tree tsubst_initializer_list (tree, tree);
121 static tree get_class_bindings (tree, tree, tree);
122 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
123                                    bool, bool);
124 static void tsubst_enum (tree, tree, tree);
125 static tree add_to_template_args (tree, tree);
126 static tree add_outermost_template_args (tree, tree);
127 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
128 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
129                                              tree);
130 static int type_unification_real (tree, tree, tree, const tree *,
131                                   unsigned int, int, unification_kind_t, int);
132 static void note_template_header (int);
133 static tree convert_nontype_argument_function (tree, tree);
134 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
135 static tree convert_template_argument (tree, tree, tree,
136                                        tsubst_flags_t, int, tree);
137 static int for_each_template_parm (tree, tree_fn_t, void*,
138                                    struct pointer_set_t*, bool);
139 static tree expand_template_argument_pack (tree);
140 static tree build_template_parm_index (int, int, int, int, tree, tree);
141 static bool inline_needs_template_parms (tree);
142 static void push_inline_template_parms_recursive (tree, int);
143 static tree retrieve_local_specialization (tree);
144 static void register_local_specialization (tree, tree);
145 static hashval_t hash_specialization (const void *p);
146 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
147 static int mark_template_parm (tree, void *);
148 static int template_parm_this_level_p (tree, void *);
149 static tree tsubst_friend_function (tree, tree);
150 static tree tsubst_friend_class (tree, tree);
151 static int can_complete_type_without_circularity (tree);
152 static tree get_bindings (tree, tree, tree, bool);
153 static int template_decl_level (tree);
154 static int check_cv_quals_for_unify (int, tree, tree);
155 static void template_parm_level_and_index (tree, int*, int*);
156 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
157 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
158 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
159 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
160 static void regenerate_decl_from_template (tree, tree);
161 static tree most_specialized_class (tree, tree, tsubst_flags_t);
162 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
163 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
164 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
165 static bool check_specialization_scope (void);
166 static tree process_partial_specialization (tree);
167 static void set_current_access_from_decl (tree);
168 static tree get_template_base (tree, tree, tree, tree);
169 static tree try_class_unification (tree, tree, tree, tree);
170 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
171                                            tree, tree);
172 static bool template_template_parm_bindings_ok_p (tree, tree);
173 static int template_args_equal (tree, tree);
174 static void tsubst_default_arguments (tree);
175 static tree for_each_template_parm_r (tree *, int *, void *);
176 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
177 static void copy_default_args_to_explicit_spec (tree);
178 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
179 static int eq_local_specializations (const void *, const void *);
180 static bool dependent_template_arg_p (tree);
181 static bool any_template_arguments_need_structural_equality_p (tree);
182 static bool dependent_type_p_r (tree);
183 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
184 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
185 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
186 static tree tsubst_decl (tree, tree, tsubst_flags_t);
187 static void perform_typedefs_access_check (tree tmpl, tree targs);
188 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
189                                                         location_t);
190 static tree listify (tree);
191 static tree listify_autos (tree, tree);
192 static tree template_parm_to_arg (tree t);
193 static tree current_template_args (void);
194 static tree fixup_template_type_parm_type (tree, int);
195 static tree fixup_template_parm_index (tree, tree, int);
196 static void fixup_template_parms (void);
197 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
198
199 /* Make the current scope suitable for access checking when we are
200    processing T.  T can be FUNCTION_DECL for instantiated function
201    template, or VAR_DECL for static member variable (need by
202    instantiate_decl).  */
203
204 static void
205 push_access_scope (tree t)
206 {
207   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
208               || TREE_CODE (t) == VAR_DECL);
209
210   if (DECL_FRIEND_CONTEXT (t))
211     push_nested_class (DECL_FRIEND_CONTEXT (t));
212   else if (DECL_CLASS_SCOPE_P (t))
213     push_nested_class (DECL_CONTEXT (t));
214   else
215     push_to_top_level ();
216
217   if (TREE_CODE (t) == FUNCTION_DECL)
218     {
219       saved_access_scope = tree_cons
220         (NULL_TREE, current_function_decl, saved_access_scope);
221       current_function_decl = t;
222     }
223 }
224
225 /* Restore the scope set up by push_access_scope.  T is the node we
226    are processing.  */
227
228 static void
229 pop_access_scope (tree t)
230 {
231   if (TREE_CODE (t) == FUNCTION_DECL)
232     {
233       current_function_decl = TREE_VALUE (saved_access_scope);
234       saved_access_scope = TREE_CHAIN (saved_access_scope);
235     }
236
237   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
238     pop_nested_class ();
239   else
240     pop_from_top_level ();
241 }
242
243 /* Do any processing required when DECL (a member template
244    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
245    to DECL, unless it is a specialization, in which case the DECL
246    itself is returned.  */
247
248 tree
249 finish_member_template_decl (tree decl)
250 {
251   if (decl == error_mark_node)
252     return error_mark_node;
253
254   gcc_assert (DECL_P (decl));
255
256   if (TREE_CODE (decl) == TYPE_DECL)
257     {
258       tree type;
259
260       type = TREE_TYPE (decl);
261       if (type == error_mark_node)
262         return error_mark_node;
263       if (MAYBE_CLASS_TYPE_P (type)
264           && CLASSTYPE_TEMPLATE_INFO (type)
265           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
266         {
267           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
268           check_member_template (tmpl);
269           return tmpl;
270         }
271       return NULL_TREE;
272     }
273   else if (TREE_CODE (decl) == FIELD_DECL)
274     error ("data member %qD cannot be a member template", decl);
275   else if (DECL_TEMPLATE_INFO (decl))
276     {
277       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
278         {
279           check_member_template (DECL_TI_TEMPLATE (decl));
280           return DECL_TI_TEMPLATE (decl);
281         }
282       else
283         return decl;
284     }
285   else
286     error ("invalid member template declaration %qD", decl);
287
288   return error_mark_node;
289 }
290
291 /* Create a template info node.  */
292
293 tree
294 build_template_info (tree template_decl, tree template_args)
295 {
296   tree result = make_node (TEMPLATE_INFO);
297   TI_TEMPLATE (result) = template_decl;
298   TI_ARGS (result) = template_args;
299   return result;
300 }
301
302 /* Return the template info node corresponding to T, whatever T is.  */
303
304 tree
305 get_template_info (const_tree t)
306 {
307   tree tinfo = NULL_TREE;
308
309   if (!t || t == error_mark_node)
310     return NULL;
311
312   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
313     tinfo = DECL_TEMPLATE_INFO (t);
314
315   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
316     t = TREE_TYPE (t);
317
318   if (TAGGED_TYPE_P (t))
319     tinfo = TYPE_TEMPLATE_INFO (t);
320   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
321     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
322
323   return tinfo;
324 }
325
326 /* Returns the template nesting level of the indicated class TYPE.
327
328    For example, in:
329      template <class T>
330      struct A
331      {
332        template <class U>
333        struct B {};
334      };
335
336    A<T>::B<U> has depth two, while A<T> has depth one.
337    Both A<T>::B<int> and A<int>::B<U> have depth one, if
338    they are instantiations, not specializations.
339
340    This function is guaranteed to return 0 if passed NULL_TREE so
341    that, for example, `template_class_depth (current_class_type)' is
342    always safe.  */
343
344 int
345 template_class_depth (tree type)
346 {
347   int depth;
348
349   for (depth = 0;
350        type && TREE_CODE (type) != NAMESPACE_DECL;
351        type = (TREE_CODE (type) == FUNCTION_DECL)
352          ? CP_DECL_CONTEXT (type) : CP_TYPE_CONTEXT (type))
353     {
354       tree tinfo = get_template_info (type);
355
356       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
357           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
358         ++depth;
359     }
360
361   return depth;
362 }
363
364 /* Subroutine of maybe_begin_member_template_processing.
365    Returns true if processing DECL needs us to push template parms.  */
366
367 static bool
368 inline_needs_template_parms (tree decl)
369 {
370   if (! DECL_TEMPLATE_INFO (decl))
371     return false;
372
373   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
374           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
375 }
376
377 /* Subroutine of maybe_begin_member_template_processing.
378    Push the template parms in PARMS, starting from LEVELS steps into the
379    chain, and ending at the beginning, since template parms are listed
380    innermost first.  */
381
382 static void
383 push_inline_template_parms_recursive (tree parmlist, int levels)
384 {
385   tree parms = TREE_VALUE (parmlist);
386   int i;
387
388   if (levels > 1)
389     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
390
391   ++processing_template_decl;
392   current_template_parms
393     = tree_cons (size_int (processing_template_decl),
394                  parms, current_template_parms);
395   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
396
397   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
398                NULL);
399   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
400     {
401       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
402
403       if (parm == error_mark_node)
404         continue;
405
406       gcc_assert (DECL_P (parm));
407
408       switch (TREE_CODE (parm))
409         {
410         case TYPE_DECL:
411         case TEMPLATE_DECL:
412           pushdecl (parm);
413           break;
414
415         case PARM_DECL:
416           {
417             /* Make a CONST_DECL as is done in process_template_parm.
418                It is ugly that we recreate this here; the original
419                version built in process_template_parm is no longer
420                available.  */
421             tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
422                                     CONST_DECL, DECL_NAME (parm),
423                                     TREE_TYPE (parm));
424             DECL_ARTIFICIAL (decl) = 1;
425             TREE_CONSTANT (decl) = 1;
426             TREE_READONLY (decl) = 1;
427             DECL_INITIAL (decl) = DECL_INITIAL (parm);
428             SET_DECL_TEMPLATE_PARM_P (decl);
429             pushdecl (decl);
430           }
431           break;
432
433         default:
434           gcc_unreachable ();
435         }
436     }
437 }
438
439 /* Restore the template parameter context for a member template or
440    a friend template defined in a class definition.  */
441
442 void
443 maybe_begin_member_template_processing (tree decl)
444 {
445   tree parms;
446   int levels = 0;
447
448   if (inline_needs_template_parms (decl))
449     {
450       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
451       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
452
453       if (DECL_TEMPLATE_SPECIALIZATION (decl))
454         {
455           --levels;
456           parms = TREE_CHAIN (parms);
457         }
458
459       push_inline_template_parms_recursive (parms, levels);
460     }
461
462   /* Remember how many levels of template parameters we pushed so that
463      we can pop them later.  */
464   VEC_safe_push (int, heap, inline_parm_levels, levels);
465 }
466
467 /* Undo the effects of maybe_begin_member_template_processing.  */
468
469 void
470 maybe_end_member_template_processing (void)
471 {
472   int i;
473   int last;
474
475   if (VEC_length (int, inline_parm_levels) == 0)
476     return;
477
478   last = VEC_pop (int, inline_parm_levels);
479   for (i = 0; i < last; ++i)
480     {
481       --processing_template_decl;
482       current_template_parms = TREE_CHAIN (current_template_parms);
483       poplevel (0, 0, 0);
484     }
485 }
486
487 /* Return a new template argument vector which contains all of ARGS,
488    but has as its innermost set of arguments the EXTRA_ARGS.  */
489
490 static tree
491 add_to_template_args (tree args, tree extra_args)
492 {
493   tree new_args;
494   int extra_depth;
495   int i;
496   int j;
497
498   if (args == NULL_TREE || extra_args == error_mark_node)
499     return extra_args;
500
501   extra_depth = TMPL_ARGS_DEPTH (extra_args);
502   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
503
504   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
505     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
506
507   for (j = 1; j <= extra_depth; ++j, ++i)
508     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
509
510   return new_args;
511 }
512
513 /* Like add_to_template_args, but only the outermost ARGS are added to
514    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
515    (EXTRA_ARGS) levels are added.  This function is used to combine
516    the template arguments from a partial instantiation with the
517    template arguments used to attain the full instantiation from the
518    partial instantiation.  */
519
520 static tree
521 add_outermost_template_args (tree args, tree extra_args)
522 {
523   tree new_args;
524
525   /* If there are more levels of EXTRA_ARGS than there are ARGS,
526      something very fishy is going on.  */
527   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
528
529   /* If *all* the new arguments will be the EXTRA_ARGS, just return
530      them.  */
531   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
532     return extra_args;
533
534   /* For the moment, we make ARGS look like it contains fewer levels.  */
535   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
536
537   new_args = add_to_template_args (args, extra_args);
538
539   /* Now, we restore ARGS to its full dimensions.  */
540   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
541
542   return new_args;
543 }
544
545 /* Return the N levels of innermost template arguments from the ARGS.  */
546
547 tree
548 get_innermost_template_args (tree args, int n)
549 {
550   tree new_args;
551   int extra_levels;
552   int i;
553
554   gcc_assert (n >= 0);
555
556   /* If N is 1, just return the innermost set of template arguments.  */
557   if (n == 1)
558     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
559
560   /* If we're not removing anything, just return the arguments we were
561      given.  */
562   extra_levels = TMPL_ARGS_DEPTH (args) - n;
563   gcc_assert (extra_levels >= 0);
564   if (extra_levels == 0)
565     return args;
566
567   /* Make a new set of arguments, not containing the outer arguments.  */
568   new_args = make_tree_vec (n);
569   for (i = 1; i <= n; ++i)
570     SET_TMPL_ARGS_LEVEL (new_args, i,
571                          TMPL_ARGS_LEVEL (args, i + extra_levels));
572
573   return new_args;
574 }
575
576 /* The inverse of get_innermost_template_args: Return all but the innermost
577    EXTRA_LEVELS levels of template arguments from the ARGS.  */
578
579 static tree
580 strip_innermost_template_args (tree args, int extra_levels)
581 {
582   tree new_args;
583   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
584   int i;
585
586   gcc_assert (n >= 0);
587
588   /* If N is 1, just return the outermost set of template arguments.  */
589   if (n == 1)
590     return TMPL_ARGS_LEVEL (args, 1);
591
592   /* If we're not removing anything, just return the arguments we were
593      given.  */
594   gcc_assert (extra_levels >= 0);
595   if (extra_levels == 0)
596     return args;
597
598   /* Make a new set of arguments, not containing the inner arguments.  */
599   new_args = make_tree_vec (n);
600   for (i = 1; i <= n; ++i)
601     SET_TMPL_ARGS_LEVEL (new_args, i,
602                          TMPL_ARGS_LEVEL (args, i));
603
604   return new_args;
605 }
606
607 /* We've got a template header coming up; push to a new level for storing
608    the parms.  */
609
610 void
611 begin_template_parm_list (void)
612 {
613   /* We use a non-tag-transparent scope here, which causes pushtag to
614      put tags in this scope, rather than in the enclosing class or
615      namespace scope.  This is the right thing, since we want
616      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
617      global template class, push_template_decl handles putting the
618      TEMPLATE_DECL into top-level scope.  For a nested template class,
619      e.g.:
620
621        template <class T> struct S1 {
622          template <class T> struct S2 {};
623        };
624
625      pushtag contains special code to call pushdecl_with_scope on the
626      TEMPLATE_DECL for S2.  */
627   begin_scope (sk_template_parms, NULL);
628   ++processing_template_decl;
629   ++processing_template_parmlist;
630   note_template_header (0);
631 }
632
633 /* This routine is called when a specialization is declared.  If it is
634    invalid to declare a specialization here, an error is reported and
635    false is returned, otherwise this routine will return true.  */
636
637 static bool
638 check_specialization_scope (void)
639 {
640   tree scope = current_scope ();
641
642   /* [temp.expl.spec]
643
644      An explicit specialization shall be declared in the namespace of
645      which the template is a member, or, for member templates, in the
646      namespace of which the enclosing class or enclosing class
647      template is a member.  An explicit specialization of a member
648      function, member class or static data member of a class template
649      shall be declared in the namespace of which the class template
650      is a member.  */
651   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
652     {
653       error ("explicit specialization in non-namespace scope %qD", scope);
654       return false;
655     }
656
657   /* [temp.expl.spec]
658
659      In an explicit specialization declaration for a member of a class
660      template or a member template that appears in namespace scope,
661      the member template and some of its enclosing class templates may
662      remain unspecialized, except that the declaration shall not
663      explicitly specialize a class member template if its enclosing
664      class templates are not explicitly specialized as well.  */
665   if (current_template_parms)
666     {
667       error ("enclosing class templates are not explicitly specialized");
668       return false;
669     }
670
671   return true;
672 }
673
674 /* We've just seen template <>.  */
675
676 bool
677 begin_specialization (void)
678 {
679   begin_scope (sk_template_spec, NULL);
680   note_template_header (1);
681   return check_specialization_scope ();
682 }
683
684 /* Called at then end of processing a declaration preceded by
685    template<>.  */
686
687 void
688 end_specialization (void)
689 {
690   finish_scope ();
691   reset_specialization ();
692 }
693
694 /* Any template <>'s that we have seen thus far are not referring to a
695    function specialization.  */
696
697 void
698 reset_specialization (void)
699 {
700   processing_specialization = 0;
701   template_header_count = 0;
702 }
703
704 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
705    it was of the form template <>.  */
706
707 static void
708 note_template_header (int specialization)
709 {
710   processing_specialization = specialization;
711   template_header_count++;
712 }
713
714 /* We're beginning an explicit instantiation.  */
715
716 void
717 begin_explicit_instantiation (void)
718 {
719   gcc_assert (!processing_explicit_instantiation);
720   processing_explicit_instantiation = true;
721 }
722
723
724 void
725 end_explicit_instantiation (void)
726 {
727   gcc_assert (processing_explicit_instantiation);
728   processing_explicit_instantiation = false;
729 }
730
731 /* An explicit specialization or partial specialization TMPL is being
732    declared.  Check that the namespace in which the specialization is
733    occurring is permissible.  Returns false iff it is invalid to
734    specialize TMPL in the current namespace.  */
735
736 static bool
737 check_specialization_namespace (tree tmpl)
738 {
739   tree tpl_ns = decl_namespace_context (tmpl);
740
741   /* [tmpl.expl.spec]
742
743      An explicit specialization shall be declared in the namespace of
744      which the template is a member, or, for member templates, in the
745      namespace of which the enclosing class or enclosing class
746      template is a member.  An explicit specialization of a member
747      function, member class or static data member of a class template
748      shall be declared in the namespace of which the class template is
749      a member.  */
750   if (current_scope() != DECL_CONTEXT (tmpl)
751       && !at_namespace_scope_p ())
752     {
753       error ("specialization of %qD must appear at namespace scope", tmpl);
754       return false;
755     }
756   if (is_associated_namespace (current_namespace, tpl_ns))
757     /* Same or super-using namespace.  */
758     return true;
759   else
760     {
761       permerror (input_location, "specialization of %qD in different namespace", tmpl);
762       permerror (input_location, "  from definition of %q+#D", tmpl);
763       return false;
764     }
765 }
766
767 /* SPEC is an explicit instantiation.  Check that it is valid to
768    perform this explicit instantiation in the current namespace.  */
769
770 static void
771 check_explicit_instantiation_namespace (tree spec)
772 {
773   tree ns;
774
775   /* DR 275: An explicit instantiation shall appear in an enclosing
776      namespace of its template.  */
777   ns = decl_namespace_context (spec);
778   if (!is_ancestor (current_namespace, ns))
779     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
780                "(which does not enclose namespace %qD)",
781                spec, current_namespace, ns);
782 }
783
784 /* The TYPE is being declared.  If it is a template type, that means it
785    is a partial specialization.  Do appropriate error-checking.  */
786
787 tree
788 maybe_process_partial_specialization (tree type)
789 {
790   tree context;
791
792   if (type == error_mark_node)
793     return error_mark_node;
794
795   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
796     {
797       error ("name of class shadows template template parameter %qD",
798              TYPE_NAME (type));
799       return error_mark_node;
800     }
801
802   context = TYPE_CONTEXT (type);
803
804   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
805     {
806       /* This is for ordinary explicit specialization and partial
807          specialization of a template class such as:
808
809            template <> class C<int>;
810
811          or:
812
813            template <class T> class C<T*>;
814
815          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
816
817       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
818           && !COMPLETE_TYPE_P (type))
819         {
820           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
821           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
822           if (processing_template_decl)
823             {
824               if (push_template_decl (TYPE_MAIN_DECL (type))
825                   == error_mark_node)
826                 return error_mark_node;
827             }
828         }
829       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
830         error ("specialization of %qT after instantiation", type);
831     }
832   else if (CLASS_TYPE_P (type)
833            && !CLASSTYPE_USE_TEMPLATE (type)
834            && CLASSTYPE_TEMPLATE_INFO (type)
835            && context && CLASS_TYPE_P (context)
836            && CLASSTYPE_TEMPLATE_INFO (context))
837     {
838       /* This is for an explicit specialization of member class
839          template according to [temp.expl.spec/18]:
840
841            template <> template <class U> class C<int>::D;
842
843          The context `C<int>' must be an implicit instantiation.
844          Otherwise this is just a member class template declared
845          earlier like:
846
847            template <> class C<int> { template <class U> class D; };
848            template <> template <class U> class C<int>::D;
849
850          In the first case, `C<int>::D' is a specialization of `C<T>::D'
851          while in the second case, `C<int>::D' is a primary template
852          and `C<T>::D' may not exist.  */
853
854       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
855           && !COMPLETE_TYPE_P (type))
856         {
857           tree t;
858           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
859
860           if (current_namespace
861               != decl_namespace_context (tmpl))
862             {
863               permerror (input_location, "specializing %q#T in different namespace", type);
864               permerror (input_location, "  from definition of %q+#D", tmpl);
865             }
866
867           /* Check for invalid specialization after instantiation:
868
869                template <> template <> class C<int>::D<int>;
870                template <> template <class U> class C<int>::D;  */
871
872           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
873                t; t = TREE_CHAIN (t))
874             {
875               tree inst = TREE_VALUE (t);
876               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst))
877                 {
878                   /* We already have a full specialization of this partial
879                      instantiation.  Reassign it to the new member
880                      specialization template.  */
881                   spec_entry elt;
882                   spec_entry **slot;
883
884                   elt.tmpl = most_general_template (tmpl);
885                   elt.args = CLASSTYPE_TI_ARGS (inst);
886                   elt.spec = inst;
887
888                   htab_remove_elt (type_specializations, &elt);
889
890                   elt.tmpl = tmpl;
891                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
892
893                   slot = (spec_entry **)
894                     htab_find_slot (type_specializations, &elt, INSERT);
895                   *slot = ggc_alloc_spec_entry ();
896                   **slot = elt;
897                 }
898               else if (COMPLETE_OR_OPEN_TYPE_P (inst))
899                 /* But if we've had an implicit instantiation, that's a
900                    problem ([temp.expl.spec]/6).  */
901                 error ("specialization %qT after instantiation %qT",
902                        type, inst);
903             }
904
905           /* Mark TYPE as a specialization.  And as a result, we only
906              have one level of template argument for the innermost
907              class template.  */
908           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
909           CLASSTYPE_TI_ARGS (type)
910             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
911         }
912     }
913   else if (processing_specialization)
914     {
915        /* Someday C++0x may allow for enum template specialization.  */
916       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
917           && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
918         pedwarn (input_location, OPT_pedantic, "template specialization "
919                  "of %qD not allowed by ISO C++", type);
920       else
921         {
922           error ("explicit specialization of non-template %qT", type);
923           return error_mark_node;
924         }
925     }
926
927   return type;
928 }
929
930 /* Returns nonzero if we can optimize the retrieval of specializations
931    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
932    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
933
934 static inline bool
935 optimize_specialization_lookup_p (tree tmpl)
936 {
937   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
938           && DECL_CLASS_SCOPE_P (tmpl)
939           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
940              parameter.  */
941           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
942           /* The optimized lookup depends on the fact that the
943              template arguments for the member function template apply
944              purely to the containing class, which is not true if the
945              containing class is an explicit or partial
946              specialization.  */
947           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
948           && !DECL_MEMBER_TEMPLATE_P (tmpl)
949           && !DECL_CONV_FN_P (tmpl)
950           /* It is possible to have a template that is not a member
951              template and is not a member of a template class:
952
953              template <typename T>
954              struct S { friend A::f(); };
955
956              Here, the friend function is a template, but the context does
957              not have template information.  The optimized lookup relies
958              on having ARGS be the template arguments for both the class
959              and the function template.  */
960           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
961 }
962
963 /* Retrieve the specialization (in the sense of [temp.spec] - a
964    specialization is either an instantiation or an explicit
965    specialization) of TMPL for the given template ARGS.  If there is
966    no such specialization, return NULL_TREE.  The ARGS are a vector of
967    arguments, or a vector of vectors of arguments, in the case of
968    templates with more than one level of parameters.
969
970    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
971    then we search for a partial specialization matching ARGS.  This
972    parameter is ignored if TMPL is not a class template.  */
973
974 static tree
975 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
976 {
977   if (args == error_mark_node)
978     return NULL_TREE;
979
980   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
981
982   /* There should be as many levels of arguments as there are
983      levels of parameters.  */
984   gcc_assert (TMPL_ARGS_DEPTH (args)
985               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
986
987   if (optimize_specialization_lookup_p (tmpl))
988     {
989       tree class_template;
990       tree class_specialization;
991       VEC(tree,gc) *methods;
992       tree fns;
993       int idx;
994
995       /* The template arguments actually apply to the containing
996          class.  Find the class specialization with those
997          arguments.  */
998       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
999       class_specialization
1000         = retrieve_specialization (class_template, args, 0);
1001       if (!class_specialization)
1002         return NULL_TREE;
1003       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
1004          for the specialization.  */
1005       idx = class_method_index_for_fn (class_specialization, tmpl);
1006       if (idx == -1)
1007         return NULL_TREE;
1008       /* Iterate through the methods with the indicated name, looking
1009          for the one that has an instance of TMPL.  */
1010       methods = CLASSTYPE_METHOD_VEC (class_specialization);
1011       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
1012         {
1013           tree fn = OVL_CURRENT (fns);
1014           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1015               /* using-declarations can add base methods to the method vec,
1016                  and we don't want those here.  */
1017               && DECL_CONTEXT (fn) == class_specialization)
1018             return fn;
1019         }
1020       return NULL_TREE;
1021     }
1022   else
1023     {
1024       spec_entry *found;
1025       spec_entry elt;
1026       htab_t specializations;
1027
1028       elt.tmpl = tmpl;
1029       elt.args = args;
1030       elt.spec = NULL_TREE;
1031
1032       if (DECL_CLASS_TEMPLATE_P (tmpl))
1033         specializations = type_specializations;
1034       else
1035         specializations = decl_specializations;
1036
1037       if (hash == 0)
1038         hash = hash_specialization (&elt);
1039       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1040       if (found)
1041         return found->spec;
1042     }
1043
1044   return NULL_TREE;
1045 }
1046
1047 /* Like retrieve_specialization, but for local declarations.  */
1048
1049 static tree
1050 retrieve_local_specialization (tree tmpl)
1051 {
1052   tree spec;
1053
1054   if (local_specializations == NULL)
1055     return NULL_TREE;
1056
1057   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1058                                      htab_hash_pointer (tmpl));
1059   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1060 }
1061
1062 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1063
1064 int
1065 is_specialization_of (tree decl, tree tmpl)
1066 {
1067   tree t;
1068
1069   if (TREE_CODE (decl) == FUNCTION_DECL)
1070     {
1071       for (t = decl;
1072            t != NULL_TREE;
1073            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1074         if (t == tmpl)
1075           return 1;
1076     }
1077   else
1078     {
1079       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1080
1081       for (t = TREE_TYPE (decl);
1082            t != NULL_TREE;
1083            t = CLASSTYPE_USE_TEMPLATE (t)
1084              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1085         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1086           return 1;
1087     }
1088
1089   return 0;
1090 }
1091
1092 /* Returns nonzero iff DECL is a specialization of friend declaration
1093    FRIEND_DECL according to [temp.friend].  */
1094
1095 bool
1096 is_specialization_of_friend (tree decl, tree friend_decl)
1097 {
1098   bool need_template = true;
1099   int template_depth;
1100
1101   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1102               || TREE_CODE (decl) == TYPE_DECL);
1103
1104   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1105      of a template class, we want to check if DECL is a specialization
1106      if this.  */
1107   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1108       && DECL_TEMPLATE_INFO (friend_decl)
1109       && !DECL_USE_TEMPLATE (friend_decl))
1110     {
1111       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1112       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1113       need_template = false;
1114     }
1115   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1116            && !PRIMARY_TEMPLATE_P (friend_decl))
1117     need_template = false;
1118
1119   /* There is nothing to do if this is not a template friend.  */
1120   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1121     return false;
1122
1123   if (is_specialization_of (decl, friend_decl))
1124     return true;
1125
1126   /* [temp.friend/6]
1127      A member of a class template may be declared to be a friend of a
1128      non-template class.  In this case, the corresponding member of
1129      every specialization of the class template is a friend of the
1130      class granting friendship.
1131
1132      For example, given a template friend declaration
1133
1134        template <class T> friend void A<T>::f();
1135
1136      the member function below is considered a friend
1137
1138        template <> struct A<int> {
1139          void f();
1140        };
1141
1142      For this type of template friend, TEMPLATE_DEPTH below will be
1143      nonzero.  To determine if DECL is a friend of FRIEND, we first
1144      check if the enclosing class is a specialization of another.  */
1145
1146   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1147   if (template_depth
1148       && DECL_CLASS_SCOPE_P (decl)
1149       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1150                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1151     {
1152       /* Next, we check the members themselves.  In order to handle
1153          a few tricky cases, such as when FRIEND_DECL's are
1154
1155            template <class T> friend void A<T>::g(T t);
1156            template <class T> template <T t> friend void A<T>::h();
1157
1158          and DECL's are
1159
1160            void A<int>::g(int);
1161            template <int> void A<int>::h();
1162
1163          we need to figure out ARGS, the template arguments from
1164          the context of DECL.  This is required for template substitution
1165          of `T' in the function parameter of `g' and template parameter
1166          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1167
1168       tree context = DECL_CONTEXT (decl);
1169       tree args = NULL_TREE;
1170       int current_depth = 0;
1171
1172       while (current_depth < template_depth)
1173         {
1174           if (CLASSTYPE_TEMPLATE_INFO (context))
1175             {
1176               if (current_depth == 0)
1177                 args = TYPE_TI_ARGS (context);
1178               else
1179                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1180               current_depth++;
1181             }
1182           context = TYPE_CONTEXT (context);
1183         }
1184
1185       if (TREE_CODE (decl) == FUNCTION_DECL)
1186         {
1187           bool is_template;
1188           tree friend_type;
1189           tree decl_type;
1190           tree friend_args_type;
1191           tree decl_args_type;
1192
1193           /* Make sure that both DECL and FRIEND_DECL are templates or
1194              non-templates.  */
1195           is_template = DECL_TEMPLATE_INFO (decl)
1196                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1197           if (need_template ^ is_template)
1198             return false;
1199           else if (is_template)
1200             {
1201               /* If both are templates, check template parameter list.  */
1202               tree friend_parms
1203                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1204                                          args, tf_none);
1205               if (!comp_template_parms
1206                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1207                       friend_parms))
1208                 return false;
1209
1210               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1211             }
1212           else
1213             decl_type = TREE_TYPE (decl);
1214
1215           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1216                                               tf_none, NULL_TREE);
1217           if (friend_type == error_mark_node)
1218             return false;
1219
1220           /* Check if return types match.  */
1221           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1222             return false;
1223
1224           /* Check if function parameter types match, ignoring the
1225              `this' parameter.  */
1226           friend_args_type = TYPE_ARG_TYPES (friend_type);
1227           decl_args_type = TYPE_ARG_TYPES (decl_type);
1228           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1229             friend_args_type = TREE_CHAIN (friend_args_type);
1230           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1231             decl_args_type = TREE_CHAIN (decl_args_type);
1232
1233           return compparms (decl_args_type, friend_args_type);
1234         }
1235       else
1236         {
1237           /* DECL is a TYPE_DECL */
1238           bool is_template;
1239           tree decl_type = TREE_TYPE (decl);
1240
1241           /* Make sure that both DECL and FRIEND_DECL are templates or
1242              non-templates.  */
1243           is_template
1244             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1245               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1246
1247           if (need_template ^ is_template)
1248             return false;
1249           else if (is_template)
1250             {
1251               tree friend_parms;
1252               /* If both are templates, check the name of the two
1253                  TEMPLATE_DECL's first because is_friend didn't.  */
1254               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1255                   != DECL_NAME (friend_decl))
1256                 return false;
1257
1258               /* Now check template parameter list.  */
1259               friend_parms
1260                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1261                                          args, tf_none);
1262               return comp_template_parms
1263                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1264                  friend_parms);
1265             }
1266           else
1267             return (DECL_NAME (decl)
1268                     == DECL_NAME (friend_decl));
1269         }
1270     }
1271   return false;
1272 }
1273
1274 /* Register the specialization SPEC as a specialization of TMPL with
1275    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1276    is actually just a friend declaration.  Returns SPEC, or an
1277    equivalent prior declaration, if available.  */
1278
1279 static tree
1280 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1281                          hashval_t hash)
1282 {
1283   tree fn;
1284   spec_entry **slot = NULL;
1285   spec_entry elt;
1286
1287   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1288
1289   if (TREE_CODE (spec) == FUNCTION_DECL
1290       && uses_template_parms (DECL_TI_ARGS (spec)))
1291     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1292        register it; we want the corresponding TEMPLATE_DECL instead.
1293        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1294        the more obvious `uses_template_parms (spec)' to avoid problems
1295        with default function arguments.  In particular, given
1296        something like this:
1297
1298           template <class T> void f(T t1, T t = T())
1299
1300        the default argument expression is not substituted for in an
1301        instantiation unless and until it is actually needed.  */
1302     return spec;
1303
1304   if (optimize_specialization_lookup_p (tmpl))
1305     /* We don't put these specializations in the hash table, but we might
1306        want to give an error about a mismatch.  */
1307     fn = retrieve_specialization (tmpl, args, 0);
1308   else
1309     {
1310       elt.tmpl = tmpl;
1311       elt.args = args;
1312       elt.spec = spec;
1313
1314       if (hash == 0)
1315         hash = hash_specialization (&elt);
1316
1317       slot = (spec_entry **)
1318         htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1319       if (*slot)
1320         fn = (*slot)->spec;
1321       else
1322         fn = NULL_TREE;
1323     }
1324
1325   /* We can sometimes try to re-register a specialization that we've
1326      already got.  In particular, regenerate_decl_from_template calls
1327      duplicate_decls which will update the specialization list.  But,
1328      we'll still get called again here anyhow.  It's more convenient
1329      to simply allow this than to try to prevent it.  */
1330   if (fn == spec)
1331     return spec;
1332   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1333     {
1334       if (DECL_TEMPLATE_INSTANTIATION (fn))
1335         {
1336           if (DECL_ODR_USED (fn)
1337               || DECL_EXPLICIT_INSTANTIATION (fn))
1338             {
1339               error ("specialization of %qD after instantiation",
1340                      fn);
1341               return error_mark_node;
1342             }
1343           else
1344             {
1345               tree clone;
1346               /* This situation should occur only if the first
1347                  specialization is an implicit instantiation, the
1348                  second is an explicit specialization, and the
1349                  implicit instantiation has not yet been used.  That
1350                  situation can occur if we have implicitly
1351                  instantiated a member function and then specialized
1352                  it later.
1353
1354                  We can also wind up here if a friend declaration that
1355                  looked like an instantiation turns out to be a
1356                  specialization:
1357
1358                    template <class T> void foo(T);
1359                    class S { friend void foo<>(int) };
1360                    template <> void foo(int);
1361
1362                  We transform the existing DECL in place so that any
1363                  pointers to it become pointers to the updated
1364                  declaration.
1365
1366                  If there was a definition for the template, but not
1367                  for the specialization, we want this to look as if
1368                  there were no definition, and vice versa.  */
1369               DECL_INITIAL (fn) = NULL_TREE;
1370               duplicate_decls (spec, fn, is_friend);
1371               /* The call to duplicate_decls will have applied
1372                  [temp.expl.spec]:
1373
1374                    An explicit specialization of a function template
1375                    is inline only if it is explicitly declared to be,
1376                    and independently of whether its function template
1377                    is.
1378
1379                 to the primary function; now copy the inline bits to
1380                 the various clones.  */
1381               FOR_EACH_CLONE (clone, fn)
1382                 {
1383                   DECL_DECLARED_INLINE_P (clone)
1384                     = DECL_DECLARED_INLINE_P (fn);
1385                   DECL_SOURCE_LOCATION (clone)
1386                     = DECL_SOURCE_LOCATION (fn);
1387                 }
1388               check_specialization_namespace (fn);
1389
1390               return fn;
1391             }
1392         }
1393       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1394         {
1395           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1396             /* Dup decl failed, but this is a new definition. Set the
1397                line number so any errors match this new
1398                definition.  */
1399             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1400
1401           return fn;
1402         }
1403     }
1404   else if (fn)
1405     return duplicate_decls (spec, fn, is_friend);
1406
1407   /* A specialization must be declared in the same namespace as the
1408      template it is specializing.  */
1409   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1410       && !check_specialization_namespace (tmpl))
1411     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1412
1413   if (!optimize_specialization_lookup_p (tmpl))
1414     {
1415       gcc_assert (tmpl && args && spec);
1416       *slot = ggc_alloc_spec_entry ();
1417       **slot = elt;
1418       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1419           && PRIMARY_TEMPLATE_P (tmpl)
1420           && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1421         /* TMPL is a forward declaration of a template function; keep a list
1422            of all specializations in case we need to reassign them to a friend
1423            template later in tsubst_friend_function.  */
1424         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1425           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1426     }
1427
1428   return spec;
1429 }
1430
1431 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1432    TMPL and ARGS members, ignores SPEC.  */
1433
1434 static int
1435 eq_specializations (const void *p1, const void *p2)
1436 {
1437   const spec_entry *e1 = (const spec_entry *)p1;
1438   const spec_entry *e2 = (const spec_entry *)p2;
1439
1440   return (e1->tmpl == e2->tmpl
1441           && comp_template_args (e1->args, e2->args));
1442 }
1443
1444 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1445
1446 static hashval_t
1447 hash_tmpl_and_args (tree tmpl, tree args)
1448 {
1449   hashval_t val = DECL_UID (tmpl);
1450   return iterative_hash_template_arg (args, val);
1451 }
1452
1453 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1454    ignoring SPEC.  */
1455
1456 static hashval_t
1457 hash_specialization (const void *p)
1458 {
1459   const spec_entry *e = (const spec_entry *)p;
1460   return hash_tmpl_and_args (e->tmpl, e->args);
1461 }
1462
1463 /* Recursively calculate a hash value for a template argument ARG, for use
1464    in the hash tables of template specializations.  */
1465
1466 hashval_t
1467 iterative_hash_template_arg (tree arg, hashval_t val)
1468 {
1469   unsigned HOST_WIDE_INT i;
1470   enum tree_code code;
1471   char tclass;
1472
1473   if (arg == NULL_TREE)
1474     return iterative_hash_object (arg, val);
1475
1476   if (!TYPE_P (arg))
1477     STRIP_NOPS (arg);
1478
1479   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1480     /* We can get one of these when re-hashing a previous entry in the middle
1481        of substituting into a pack expansion.  Just look through it.  */
1482     arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1483
1484   code = TREE_CODE (arg);
1485   tclass = TREE_CODE_CLASS (code);
1486
1487   val = iterative_hash_object (code, val);
1488
1489   switch (code)
1490     {
1491     case ERROR_MARK:
1492       return val;
1493
1494     case IDENTIFIER_NODE:
1495       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1496
1497     case TREE_VEC:
1498       {
1499         int i, len = TREE_VEC_LENGTH (arg);
1500         for (i = 0; i < len; ++i)
1501           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1502         return val;
1503       }
1504
1505     case TYPE_PACK_EXPANSION:
1506     case EXPR_PACK_EXPANSION:
1507       return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1508
1509     case TYPE_ARGUMENT_PACK:
1510     case NONTYPE_ARGUMENT_PACK:
1511       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1512
1513     case TREE_LIST:
1514       for (; arg; arg = TREE_CHAIN (arg))
1515         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1516       return val;
1517
1518     case OVERLOAD:
1519       for (; arg; arg = OVL_CHAIN (arg))
1520         val = iterative_hash_template_arg (OVL_FUNCTION (arg), val);
1521       return val;
1522
1523     case CONSTRUCTOR:
1524       {
1525         tree field, value;
1526         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1527           {
1528             val = iterative_hash_template_arg (field, val);
1529             val = iterative_hash_template_arg (value, val);
1530           }
1531         return val;
1532       }
1533
1534     case PARM_DECL:
1535       if (!DECL_ARTIFICIAL (arg))
1536         val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1537       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1538
1539     case TARGET_EXPR:
1540       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1541
1542     case PTRMEM_CST:
1543       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1544       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1545
1546     case TEMPLATE_PARM_INDEX:
1547       val = iterative_hash_template_arg
1548         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1549       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1550       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1551
1552     case TRAIT_EXPR:
1553       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1554       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1555       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1556
1557     case BASELINK:
1558       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1559                                          val);
1560       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1561                                           val);
1562
1563     case MODOP_EXPR:
1564       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1565       code = TREE_CODE (TREE_OPERAND (arg, 1));
1566       val = iterative_hash_object (code, val);
1567       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1568
1569     case ARRAY_TYPE:
1570       /* layout_type sets structural equality for arrays of
1571          incomplete type, so we can't rely on the canonical type
1572          for hashing.  */
1573       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1574       return iterative_hash_template_arg (TYPE_DOMAIN (arg), val);
1575
1576     case LAMBDA_EXPR:
1577       /* A lambda can't appear in a template arg, but don't crash on
1578          erroneous input.  */
1579       gcc_assert (seen_error ());
1580       return val;
1581
1582     case CAST_EXPR:
1583     case STATIC_CAST_EXPR:
1584     case REINTERPRET_CAST_EXPR:
1585     case CONST_CAST_EXPR:
1586     case DYNAMIC_CAST_EXPR:
1587     case NEW_EXPR:
1588       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1589       /* Now hash operands as usual.  */
1590       break;
1591
1592     default:
1593       break;
1594     }
1595
1596   switch (tclass)
1597     {
1598     case tcc_type:
1599       if (TYPE_CANONICAL (arg))
1600         return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1601                                       val);
1602       else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1603         return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1604       /* Otherwise just compare the types during lookup.  */
1605       return val;
1606
1607     case tcc_declaration:
1608     case tcc_constant:
1609       return iterative_hash_expr (arg, val);
1610
1611     default:
1612       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1613       {
1614         unsigned n = TREE_OPERAND_LENGTH (arg);
1615         for (i = 0; i < n; ++i)
1616           val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1617         return val;
1618       }
1619     }
1620   gcc_unreachable ();
1621   return 0;
1622 }
1623
1624 /* Unregister the specialization SPEC as a specialization of TMPL.
1625    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1626    if the SPEC was listed as a specialization of TMPL.
1627
1628    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1629
1630 bool
1631 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1632 {
1633   spec_entry **slot;
1634   spec_entry elt;
1635
1636   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1637   elt.args = TI_ARGS (tinfo);
1638   elt.spec = NULL_TREE;
1639
1640   slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1641   if (*slot)
1642     {
1643       gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1644       gcc_assert (new_spec != NULL_TREE);
1645       (*slot)->spec = new_spec;
1646       return 1;
1647     }
1648
1649   return 0;
1650 }
1651
1652 /* Compare an entry in the local specializations hash table P1 (which
1653    is really a pointer to a TREE_LIST) with P2 (which is really a
1654    DECL).  */
1655
1656 static int
1657 eq_local_specializations (const void *p1, const void *p2)
1658 {
1659   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1660 }
1661
1662 /* Hash P1, an entry in the local specializations table.  */
1663
1664 static hashval_t
1665 hash_local_specialization (const void* p1)
1666 {
1667   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1668 }
1669
1670 /* Like register_specialization, but for local declarations.  We are
1671    registering SPEC, an instantiation of TMPL.  */
1672
1673 static void
1674 register_local_specialization (tree spec, tree tmpl)
1675 {
1676   void **slot;
1677
1678   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1679                                    htab_hash_pointer (tmpl), INSERT);
1680   *slot = build_tree_list (spec, tmpl);
1681 }
1682
1683 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1684    specialized class.  */
1685
1686 bool
1687 explicit_class_specialization_p (tree type)
1688 {
1689   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1690     return false;
1691   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1692 }
1693
1694 /* Print the list of functions at FNS, going through all the overloads
1695    for each element of the list.  Alternatively, FNS can not be a
1696    TREE_LIST, in which case it will be printed together with all the
1697    overloads.
1698
1699    MORE and *STR should respectively be FALSE and NULL when the function
1700    is called from the outside.  They are used internally on recursive
1701    calls.  print_candidates manages the two parameters and leaves NULL
1702    in *STR when it ends.  */
1703
1704 static void
1705 print_candidates_1 (tree fns, bool more, const char **str)
1706 {
1707   tree fn, fn2;
1708   char *spaces = NULL;
1709
1710   for (fn = fns; fn; fn = OVL_NEXT (fn))
1711     if (TREE_CODE (fn) == TREE_LIST)
1712       {
1713         gcc_assert (!OVL_NEXT (fn) && !is_overloaded_fn (fn));
1714         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1715           print_candidates_1 (TREE_VALUE (fn2),
1716                               TREE_CHAIN (fn2) || more, str);
1717       }
1718     else
1719       {
1720         if (!*str)
1721           {
1722             /* Pick the prefix string.  */
1723             if (!more && !OVL_NEXT (fns))
1724               {
1725                 error ("candidate is: %+#D", OVL_CURRENT (fn));
1726                 continue;
1727               }
1728
1729             *str = _("candidates are:");
1730             spaces = get_spaces (*str);
1731           }
1732         error ("%s %+#D", *str, OVL_CURRENT (fn));
1733         *str = spaces ? spaces : *str;
1734       }
1735
1736   if (!more)
1737     {
1738       free (spaces);
1739       *str = NULL;
1740     }
1741 }
1742
1743 /* Print the list of candidate FNS in an error message.  */
1744
1745 void
1746 print_candidates (tree fns)
1747 {
1748   const char *str = NULL;
1749   print_candidates_1 (fns, false, &str);
1750   gcc_assert (str == NULL);
1751 }
1752
1753 /* Returns the template (one of the functions given by TEMPLATE_ID)
1754    which can be specialized to match the indicated DECL with the
1755    explicit template args given in TEMPLATE_ID.  The DECL may be
1756    NULL_TREE if none is available.  In that case, the functions in
1757    TEMPLATE_ID are non-members.
1758
1759    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1760    specialization of a member template.
1761
1762    The TEMPLATE_COUNT is the number of references to qualifying
1763    template classes that appeared in the name of the function. See
1764    check_explicit_specialization for a more accurate description.
1765
1766    TSK indicates what kind of template declaration (if any) is being
1767    declared.  TSK_TEMPLATE indicates that the declaration given by
1768    DECL, though a FUNCTION_DECL, has template parameters, and is
1769    therefore a template function.
1770
1771    The template args (those explicitly specified and those deduced)
1772    are output in a newly created vector *TARGS_OUT.
1773
1774    If it is impossible to determine the result, an error message is
1775    issued.  The error_mark_node is returned to indicate failure.  */
1776
1777 static tree
1778 determine_specialization (tree template_id,
1779                           tree decl,
1780                           tree* targs_out,
1781                           int need_member_template,
1782                           int template_count,
1783                           tmpl_spec_kind tsk)
1784 {
1785   tree fns;
1786   tree targs;
1787   tree explicit_targs;
1788   tree candidates = NULL_TREE;
1789   /* A TREE_LIST of templates of which DECL may be a specialization.
1790      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1791      corresponding TREE_PURPOSE is the set of template arguments that,
1792      when used to instantiate the template, would produce a function
1793      with the signature of DECL.  */
1794   tree templates = NULL_TREE;
1795   int header_count;
1796   struct cp_binding_level *b;
1797
1798   *targs_out = NULL_TREE;
1799
1800   if (template_id == error_mark_node || decl == error_mark_node)
1801     return error_mark_node;
1802
1803   fns = TREE_OPERAND (template_id, 0);
1804   explicit_targs = TREE_OPERAND (template_id, 1);
1805
1806   if (fns == error_mark_node)
1807     return error_mark_node;
1808
1809   /* Check for baselinks.  */
1810   if (BASELINK_P (fns))
1811     fns = BASELINK_FUNCTIONS (fns);
1812
1813   if (!is_overloaded_fn (fns))
1814     {
1815       error ("%qD is not a function template", fns);
1816       return error_mark_node;
1817     }
1818
1819   /* Count the number of template headers specified for this
1820      specialization.  */
1821   header_count = 0;
1822   for (b = current_binding_level;
1823        b->kind == sk_template_parms;
1824        b = b->level_chain)
1825     ++header_count;
1826
1827   for (; fns; fns = OVL_NEXT (fns))
1828     {
1829       tree fn = OVL_CURRENT (fns);
1830
1831       if (TREE_CODE (fn) == TEMPLATE_DECL)
1832         {
1833           tree decl_arg_types;
1834           tree fn_arg_types;
1835
1836           /* In case of explicit specialization, we need to check if
1837              the number of template headers appearing in the specialization
1838              is correct. This is usually done in check_explicit_specialization,
1839              but the check done there cannot be exhaustive when specializing
1840              member functions. Consider the following code:
1841
1842              template <> void A<int>::f(int);
1843              template <> template <> void A<int>::f(int);
1844
1845              Assuming that A<int> is not itself an explicit specialization
1846              already, the first line specializes "f" which is a non-template
1847              member function, whilst the second line specializes "f" which
1848              is a template member function. So both lines are syntactically
1849              correct, and check_explicit_specialization does not reject
1850              them.
1851
1852              Here, we can do better, as we are matching the specialization
1853              against the declarations. We count the number of template
1854              headers, and we check if they match TEMPLATE_COUNT + 1
1855              (TEMPLATE_COUNT is the number of qualifying template classes,
1856              plus there must be another header for the member template
1857              itself).
1858
1859              Notice that if header_count is zero, this is not a
1860              specialization but rather a template instantiation, so there
1861              is no check we can perform here.  */
1862           if (header_count && header_count != template_count + 1)
1863             continue;
1864
1865           /* Check that the number of template arguments at the
1866              innermost level for DECL is the same as for FN.  */
1867           if (current_binding_level->kind == sk_template_parms
1868               && !current_binding_level->explicit_spec_p
1869               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1870                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1871                                       (current_template_parms))))
1872             continue;
1873
1874           /* DECL might be a specialization of FN.  */
1875           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1876           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1877
1878           /* For a non-static member function, we need to make sure
1879              that the const qualification is the same.  Since
1880              get_bindings does not try to merge the "this" parameter,
1881              we must do the comparison explicitly.  */
1882           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1883               && !same_type_p (TREE_VALUE (fn_arg_types),
1884                                TREE_VALUE (decl_arg_types)))
1885             continue;
1886
1887           /* Skip the "this" parameter and, for constructors of
1888              classes with virtual bases, the VTT parameter.  A
1889              full specialization of a constructor will have a VTT
1890              parameter, but a template never will.  */ 
1891           decl_arg_types 
1892             = skip_artificial_parms_for (decl, decl_arg_types);
1893           fn_arg_types 
1894             = skip_artificial_parms_for (fn, fn_arg_types);
1895
1896           /* Check that the number of function parameters matches.
1897              For example,
1898                template <class T> void f(int i = 0);
1899                template <> void f<int>();
1900              The specialization f<int> is invalid but is not caught
1901              by get_bindings below.  */
1902           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1903             continue;
1904
1905           /* Function templates cannot be specializations; there are
1906              no partial specializations of functions.  Therefore, if
1907              the type of DECL does not match FN, there is no
1908              match.  */
1909           if (tsk == tsk_template)
1910             {
1911               if (compparms (fn_arg_types, decl_arg_types))
1912                 candidates = tree_cons (NULL_TREE, fn, candidates);
1913               continue;
1914             }
1915
1916           /* See whether this function might be a specialization of this
1917              template.  */
1918           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1919
1920           if (!targs)
1921             /* We cannot deduce template arguments that when used to
1922                specialize TMPL will produce DECL.  */
1923             continue;
1924
1925           /* Save this template, and the arguments deduced.  */
1926           templates = tree_cons (targs, fn, templates);
1927         }
1928       else if (need_member_template)
1929         /* FN is an ordinary member function, and we need a
1930            specialization of a member template.  */
1931         ;
1932       else if (TREE_CODE (fn) != FUNCTION_DECL)
1933         /* We can get IDENTIFIER_NODEs here in certain erroneous
1934            cases.  */
1935         ;
1936       else if (!DECL_FUNCTION_MEMBER_P (fn))
1937         /* This is just an ordinary non-member function.  Nothing can
1938            be a specialization of that.  */
1939         ;
1940       else if (DECL_ARTIFICIAL (fn))
1941         /* Cannot specialize functions that are created implicitly.  */
1942         ;
1943       else
1944         {
1945           tree decl_arg_types;
1946
1947           /* This is an ordinary member function.  However, since
1948              we're here, we can assume it's enclosing class is a
1949              template class.  For example,
1950
1951                template <typename T> struct S { void f(); };
1952                template <> void S<int>::f() {}
1953
1954              Here, S<int>::f is a non-template, but S<int> is a
1955              template class.  If FN has the same type as DECL, we
1956              might be in business.  */
1957
1958           if (!DECL_TEMPLATE_INFO (fn))
1959             /* Its enclosing class is an explicit specialization
1960                of a template class.  This is not a candidate.  */
1961             continue;
1962
1963           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1964                             TREE_TYPE (TREE_TYPE (fn))))
1965             /* The return types differ.  */
1966             continue;
1967
1968           /* Adjust the type of DECL in case FN is a static member.  */
1969           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1970           if (DECL_STATIC_FUNCTION_P (fn)
1971               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1972             decl_arg_types = TREE_CHAIN (decl_arg_types);
1973
1974           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1975                          decl_arg_types))
1976             /* They match!  */
1977             candidates = tree_cons (NULL_TREE, fn, candidates);
1978         }
1979     }
1980
1981   if (templates && TREE_CHAIN (templates))
1982     {
1983       /* We have:
1984
1985            [temp.expl.spec]
1986
1987            It is possible for a specialization with a given function
1988            signature to be instantiated from more than one function
1989            template.  In such cases, explicit specification of the
1990            template arguments must be used to uniquely identify the
1991            function template specialization being specialized.
1992
1993          Note that here, there's no suggestion that we're supposed to
1994          determine which of the candidate templates is most
1995          specialized.  However, we, also have:
1996
1997            [temp.func.order]
1998
1999            Partial ordering of overloaded function template
2000            declarations is used in the following contexts to select
2001            the function template to which a function template
2002            specialization refers:
2003
2004            -- when an explicit specialization refers to a function
2005               template.
2006
2007          So, we do use the partial ordering rules, at least for now.
2008          This extension can only serve to make invalid programs valid,
2009          so it's safe.  And, there is strong anecdotal evidence that
2010          the committee intended the partial ordering rules to apply;
2011          the EDG front end has that behavior, and John Spicer claims
2012          that the committee simply forgot to delete the wording in
2013          [temp.expl.spec].  */
2014       tree tmpl = most_specialized_instantiation (templates);
2015       if (tmpl != error_mark_node)
2016         {
2017           templates = tmpl;
2018           TREE_CHAIN (templates) = NULL_TREE;
2019         }
2020     }
2021
2022   if (templates == NULL_TREE && candidates == NULL_TREE)
2023     {
2024       error ("template-id %qD for %q+D does not match any template "
2025              "declaration", template_id, decl);
2026       if (header_count && header_count != template_count + 1)
2027         inform (input_location, "saw %d %<template<>%>, need %d for "
2028                 "specializing a member function template",
2029                 header_count, template_count + 1);
2030       return error_mark_node;
2031     }
2032   else if ((templates && TREE_CHAIN (templates))
2033            || (candidates && TREE_CHAIN (candidates))
2034            || (templates && candidates))
2035     {
2036       error ("ambiguous template specialization %qD for %q+D",
2037              template_id, decl);
2038       candidates = chainon (candidates, templates);
2039       print_candidates (candidates);
2040       return error_mark_node;
2041     }
2042
2043   /* We have one, and exactly one, match.  */
2044   if (candidates)
2045     {
2046       tree fn = TREE_VALUE (candidates);
2047       *targs_out = copy_node (DECL_TI_ARGS (fn));
2048       /* DECL is a re-declaration or partial instantiation of a template
2049          function.  */
2050       if (TREE_CODE (fn) == TEMPLATE_DECL)
2051         return fn;
2052       /* It was a specialization of an ordinary member function in a
2053          template class.  */
2054       return DECL_TI_TEMPLATE (fn);
2055     }
2056
2057   /* It was a specialization of a template.  */
2058   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2059   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2060     {
2061       *targs_out = copy_node (targs);
2062       SET_TMPL_ARGS_LEVEL (*targs_out,
2063                            TMPL_ARGS_DEPTH (*targs_out),
2064                            TREE_PURPOSE (templates));
2065     }
2066   else
2067     *targs_out = TREE_PURPOSE (templates);
2068   return TREE_VALUE (templates);
2069 }
2070
2071 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2072    but with the default argument values filled in from those in the
2073    TMPL_TYPES.  */
2074
2075 static tree
2076 copy_default_args_to_explicit_spec_1 (tree spec_types,
2077                                       tree tmpl_types)
2078 {
2079   tree new_spec_types;
2080
2081   if (!spec_types)
2082     return NULL_TREE;
2083
2084   if (spec_types == void_list_node)
2085     return void_list_node;
2086
2087   /* Substitute into the rest of the list.  */
2088   new_spec_types =
2089     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2090                                           TREE_CHAIN (tmpl_types));
2091
2092   /* Add the default argument for this parameter.  */
2093   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2094                          TREE_VALUE (spec_types),
2095                          new_spec_types);
2096 }
2097
2098 /* DECL is an explicit specialization.  Replicate default arguments
2099    from the template it specializes.  (That way, code like:
2100
2101      template <class T> void f(T = 3);
2102      template <> void f(double);
2103      void g () { f (); }
2104
2105    works, as required.)  An alternative approach would be to look up
2106    the correct default arguments at the call-site, but this approach
2107    is consistent with how implicit instantiations are handled.  */
2108
2109 static void
2110 copy_default_args_to_explicit_spec (tree decl)
2111 {
2112   tree tmpl;
2113   tree spec_types;
2114   tree tmpl_types;
2115   tree new_spec_types;
2116   tree old_type;
2117   tree new_type;
2118   tree t;
2119   tree object_type = NULL_TREE;
2120   tree in_charge = NULL_TREE;
2121   tree vtt = NULL_TREE;
2122
2123   /* See if there's anything we need to do.  */
2124   tmpl = DECL_TI_TEMPLATE (decl);
2125   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2126   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2127     if (TREE_PURPOSE (t))
2128       break;
2129   if (!t)
2130     return;
2131
2132   old_type = TREE_TYPE (decl);
2133   spec_types = TYPE_ARG_TYPES (old_type);
2134
2135   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2136     {
2137       /* Remove the this pointer, but remember the object's type for
2138          CV quals.  */
2139       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2140       spec_types = TREE_CHAIN (spec_types);
2141       tmpl_types = TREE_CHAIN (tmpl_types);
2142
2143       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2144         {
2145           /* DECL may contain more parameters than TMPL due to the extra
2146              in-charge parameter in constructors and destructors.  */
2147           in_charge = spec_types;
2148           spec_types = TREE_CHAIN (spec_types);
2149         }
2150       if (DECL_HAS_VTT_PARM_P (decl))
2151         {
2152           vtt = spec_types;
2153           spec_types = TREE_CHAIN (spec_types);
2154         }
2155     }
2156
2157   /* Compute the merged default arguments.  */
2158   new_spec_types =
2159     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2160
2161   /* Compute the new FUNCTION_TYPE.  */
2162   if (object_type)
2163     {
2164       if (vtt)
2165         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2166                                          TREE_VALUE (vtt),
2167                                          new_spec_types);
2168
2169       if (in_charge)
2170         /* Put the in-charge parameter back.  */
2171         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2172                                          TREE_VALUE (in_charge),
2173                                          new_spec_types);
2174
2175       new_type = build_method_type_directly (object_type,
2176                                              TREE_TYPE (old_type),
2177                                              new_spec_types);
2178     }
2179   else
2180     new_type = build_function_type (TREE_TYPE (old_type),
2181                                     new_spec_types);
2182   new_type = cp_build_type_attribute_variant (new_type,
2183                                               TYPE_ATTRIBUTES (old_type));
2184   new_type = build_exception_variant (new_type,
2185                                       TYPE_RAISES_EXCEPTIONS (old_type));
2186   TREE_TYPE (decl) = new_type;
2187 }
2188
2189 /* Check to see if the function just declared, as indicated in
2190    DECLARATOR, and in DECL, is a specialization of a function
2191    template.  We may also discover that the declaration is an explicit
2192    instantiation at this point.
2193
2194    Returns DECL, or an equivalent declaration that should be used
2195    instead if all goes well.  Issues an error message if something is
2196    amiss.  Returns error_mark_node if the error is not easily
2197    recoverable.
2198
2199    FLAGS is a bitmask consisting of the following flags:
2200
2201    2: The function has a definition.
2202    4: The function is a friend.
2203
2204    The TEMPLATE_COUNT is the number of references to qualifying
2205    template classes that appeared in the name of the function.  For
2206    example, in
2207
2208      template <class T> struct S { void f(); };
2209      void S<int>::f();
2210
2211    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2212    classes are not counted in the TEMPLATE_COUNT, so that in
2213
2214      template <class T> struct S {};
2215      template <> struct S<int> { void f(); }
2216      template <> void S<int>::f();
2217
2218    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2219    invalid; there should be no template <>.)
2220
2221    If the function is a specialization, it is marked as such via
2222    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2223    is set up correctly, and it is added to the list of specializations
2224    for that template.  */
2225
2226 tree
2227 check_explicit_specialization (tree declarator,
2228                                tree decl,
2229                                int template_count,
2230                                int flags)
2231 {
2232   int have_def = flags & 2;
2233   int is_friend = flags & 4;
2234   int specialization = 0;
2235   int explicit_instantiation = 0;
2236   int member_specialization = 0;
2237   tree ctype = DECL_CLASS_CONTEXT (decl);
2238   tree dname = DECL_NAME (decl);
2239   tmpl_spec_kind tsk;
2240
2241   if (is_friend)
2242     {
2243       if (!processing_specialization)
2244         tsk = tsk_none;
2245       else
2246         tsk = tsk_excessive_parms;
2247     }
2248   else
2249     tsk = current_tmpl_spec_kind (template_count);
2250
2251   switch (tsk)
2252     {
2253     case tsk_none:
2254       if (processing_specialization)
2255         {
2256           specialization = 1;
2257           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2258         }
2259       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2260         {
2261           if (is_friend)
2262             /* This could be something like:
2263
2264                template <class T> void f(T);
2265                class S { friend void f<>(int); }  */
2266             specialization = 1;
2267           else
2268             {
2269               /* This case handles bogus declarations like template <>
2270                  template <class T> void f<int>(); */
2271
2272               error ("template-id %qD in declaration of primary template",
2273                      declarator);
2274               return decl;
2275             }
2276         }
2277       break;
2278
2279     case tsk_invalid_member_spec:
2280       /* The error has already been reported in
2281          check_specialization_scope.  */
2282       return error_mark_node;
2283
2284     case tsk_invalid_expl_inst:
2285       error ("template parameter list used in explicit instantiation");
2286
2287       /* Fall through.  */
2288
2289     case tsk_expl_inst:
2290       if (have_def)
2291         error ("definition provided for explicit instantiation");
2292
2293       explicit_instantiation = 1;
2294       break;
2295
2296     case tsk_excessive_parms:
2297     case tsk_insufficient_parms:
2298       if (tsk == tsk_excessive_parms)
2299         error ("too many template parameter lists in declaration of %qD",
2300                decl);
2301       else if (template_header_count)
2302         error("too few template parameter lists in declaration of %qD", decl);
2303       else
2304         error("explicit specialization of %qD must be introduced by "
2305               "%<template <>%>", decl);
2306
2307       /* Fall through.  */
2308     case tsk_expl_spec:
2309       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2310       if (ctype)
2311         member_specialization = 1;
2312       else
2313         specialization = 1;
2314       break;
2315
2316     case tsk_template:
2317       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2318         {
2319           /* This case handles bogus declarations like template <>
2320              template <class T> void f<int>(); */
2321
2322           if (uses_template_parms (declarator))
2323             error ("function template partial specialization %qD "
2324                    "is not allowed", declarator);
2325           else
2326             error ("template-id %qD in declaration of primary template",
2327                    declarator);
2328           return decl;
2329         }
2330
2331       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2332         /* This is a specialization of a member template, without
2333            specialization the containing class.  Something like:
2334
2335              template <class T> struct S {
2336                template <class U> void f (U);
2337              };
2338              template <> template <class U> void S<int>::f(U) {}
2339
2340            That's a specialization -- but of the entire template.  */
2341         specialization = 1;
2342       break;
2343
2344     default:
2345       gcc_unreachable ();
2346     }
2347
2348   if (specialization || member_specialization)
2349     {
2350       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2351       for (; t; t = TREE_CHAIN (t))
2352         if (TREE_PURPOSE (t))
2353           {
2354             permerror (input_location, 
2355                        "default argument specified in explicit specialization");
2356             break;
2357           }
2358     }
2359
2360   if (specialization || member_specialization || explicit_instantiation)
2361     {
2362       tree tmpl = NULL_TREE;
2363       tree targs = NULL_TREE;
2364
2365       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2366       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2367         {
2368           tree fns;
2369
2370           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2371           if (ctype)
2372             fns = dname;
2373           else
2374             {
2375               /* If there is no class context, the explicit instantiation
2376                  must be at namespace scope.  */
2377               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2378
2379               /* Find the namespace binding, using the declaration
2380                  context.  */
2381               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2382                                            false, true);
2383               if (fns == error_mark_node || !is_overloaded_fn (fns))
2384                 {
2385                   error ("%qD is not a template function", dname);
2386                   fns = error_mark_node;
2387                 }
2388               else
2389                 {
2390                   tree fn = OVL_CURRENT (fns);
2391                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2392                                                 CP_DECL_CONTEXT (fn)))
2393                     error ("%qD is not declared in %qD",
2394                            decl, current_namespace);
2395                 }
2396             }
2397
2398           declarator = lookup_template_function (fns, NULL_TREE);
2399         }
2400
2401       if (declarator == error_mark_node)
2402         return error_mark_node;
2403
2404       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2405         {
2406           if (!explicit_instantiation)
2407             /* A specialization in class scope.  This is invalid,
2408                but the error will already have been flagged by
2409                check_specialization_scope.  */
2410             return error_mark_node;
2411           else
2412             {
2413               /* It's not valid to write an explicit instantiation in
2414                  class scope, e.g.:
2415
2416                    class C { template void f(); }
2417
2418                    This case is caught by the parser.  However, on
2419                    something like:
2420
2421                    template class C { void f(); };
2422
2423                    (which is invalid) we can get here.  The error will be
2424                    issued later.  */
2425               ;
2426             }
2427
2428           return decl;
2429         }
2430       else if (ctype != NULL_TREE
2431                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2432                    IDENTIFIER_NODE))
2433         {
2434           /* Find the list of functions in ctype that have the same
2435              name as the declared function.  */
2436           tree name = TREE_OPERAND (declarator, 0);
2437           tree fns = NULL_TREE;
2438           int idx;
2439
2440           if (constructor_name_p (name, ctype))
2441             {
2442               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2443
2444               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2445                   : !CLASSTYPE_DESTRUCTORS (ctype))
2446                 {
2447                   /* From [temp.expl.spec]:
2448
2449                      If such an explicit specialization for the member
2450                      of a class template names an implicitly-declared
2451                      special member function (clause _special_), the
2452                      program is ill-formed.
2453
2454                      Similar language is found in [temp.explicit].  */
2455                   error ("specialization of implicitly-declared special member function");
2456                   return error_mark_node;
2457                 }
2458
2459               name = is_constructor ? ctor_identifier : dtor_identifier;
2460             }
2461
2462           if (!DECL_CONV_FN_P (decl))
2463             {
2464               idx = lookup_fnfields_1 (ctype, name);
2465               if (idx >= 0)
2466                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2467             }
2468           else
2469             {
2470               VEC(tree,gc) *methods;
2471               tree ovl;
2472
2473               /* For a type-conversion operator, we cannot do a
2474                  name-based lookup.  We might be looking for `operator
2475                  int' which will be a specialization of `operator T'.
2476                  So, we find *all* the conversion operators, and then
2477                  select from them.  */
2478               fns = NULL_TREE;
2479
2480               methods = CLASSTYPE_METHOD_VEC (ctype);
2481               if (methods)
2482                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2483                      VEC_iterate (tree, methods, idx, ovl);
2484                      ++idx)
2485                   {
2486                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2487                       /* There are no more conversion functions.  */
2488                       break;
2489
2490                     /* Glue all these conversion functions together
2491                        with those we already have.  */
2492                     for (; ovl; ovl = OVL_NEXT (ovl))
2493                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2494                   }
2495             }
2496
2497           if (fns == NULL_TREE)
2498             {
2499               error ("no member function %qD declared in %qT", name, ctype);
2500               return error_mark_node;
2501             }
2502           else
2503             TREE_OPERAND (declarator, 0) = fns;
2504         }
2505
2506       /* Figure out what exactly is being specialized at this point.
2507          Note that for an explicit instantiation, even one for a
2508          member function, we cannot tell apriori whether the
2509          instantiation is for a member template, or just a member
2510          function of a template class.  Even if a member template is
2511          being instantiated, the member template arguments may be
2512          elided if they can be deduced from the rest of the
2513          declaration.  */
2514       tmpl = determine_specialization (declarator, decl,
2515                                        &targs,
2516                                        member_specialization,
2517                                        template_count,
2518                                        tsk);
2519
2520       if (!tmpl || tmpl == error_mark_node)
2521         /* We couldn't figure out what this declaration was
2522            specializing.  */
2523         return error_mark_node;
2524       else
2525         {
2526           tree gen_tmpl = most_general_template (tmpl);
2527
2528           if (explicit_instantiation)
2529             {
2530               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2531                  is done by do_decl_instantiation later.  */
2532
2533               int arg_depth = TMPL_ARGS_DEPTH (targs);
2534               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2535
2536               if (arg_depth > parm_depth)
2537                 {
2538                   /* If TMPL is not the most general template (for
2539                      example, if TMPL is a friend template that is
2540                      injected into namespace scope), then there will
2541                      be too many levels of TARGS.  Remove some of them
2542                      here.  */
2543                   int i;
2544                   tree new_targs;
2545
2546                   new_targs = make_tree_vec (parm_depth);
2547                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2548                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2549                       = TREE_VEC_ELT (targs, i);
2550                   targs = new_targs;
2551                 }
2552
2553               return instantiate_template (tmpl, targs, tf_error);
2554             }
2555
2556           /* If we thought that the DECL was a member function, but it
2557              turns out to be specializing a static member function,
2558              make DECL a static member function as well.  */
2559           if (DECL_STATIC_FUNCTION_P (tmpl)
2560               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2561             revert_static_member_fn (decl);
2562
2563           /* If this is a specialization of a member template of a
2564              template class, we want to return the TEMPLATE_DECL, not
2565              the specialization of it.  */
2566           if (tsk == tsk_template)
2567             {
2568               tree result = DECL_TEMPLATE_RESULT (tmpl);
2569               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2570               DECL_INITIAL (result) = NULL_TREE;
2571               if (have_def)
2572                 {
2573                   tree parm;
2574                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2575                   DECL_SOURCE_LOCATION (result)
2576                     = DECL_SOURCE_LOCATION (decl);
2577                   /* We want to use the argument list specified in the
2578                      definition, not in the original declaration.  */
2579                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2580                   for (parm = DECL_ARGUMENTS (result); parm;
2581                        parm = DECL_CHAIN (parm))
2582                     DECL_CONTEXT (parm) = result;
2583                 }
2584               return register_specialization (tmpl, gen_tmpl, targs,
2585                                               is_friend, 0);
2586             }
2587
2588           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2589           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2590
2591           /* Inherit default function arguments from the template
2592              DECL is specializing.  */
2593           copy_default_args_to_explicit_spec (decl);
2594
2595           /* This specialization has the same protection as the
2596              template it specializes.  */
2597           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2598           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2599
2600           /* 7.1.1-1 [dcl.stc]
2601
2602              A storage-class-specifier shall not be specified in an
2603              explicit specialization...
2604
2605              The parser rejects these, so unless action is taken here,
2606              explicit function specializations will always appear with
2607              global linkage.
2608
2609              The action recommended by the C++ CWG in response to C++
2610              defect report 605 is to make the storage class and linkage
2611              of the explicit specialization match the templated function:
2612
2613              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2614            */
2615           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2616             {
2617               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2618               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2619
2620               /* This specialization has the same linkage and visibility as
2621                  the function template it specializes.  */
2622               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2623               if (! TREE_PUBLIC (decl))
2624                 {
2625                   DECL_INTERFACE_KNOWN (decl) = 1;
2626                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2627                 }
2628               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2629               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2630                 {
2631                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2632                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2633                 }
2634             }
2635
2636           /* If DECL is a friend declaration, declared using an
2637              unqualified name, the namespace associated with DECL may
2638              have been set incorrectly.  For example, in:
2639
2640                template <typename T> void f(T);
2641                namespace N {
2642                  struct S { friend void f<int>(int); }
2643                }
2644
2645              we will have set the DECL_CONTEXT for the friend
2646              declaration to N, rather than to the global namespace.  */
2647           if (DECL_NAMESPACE_SCOPE_P (decl))
2648             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2649
2650           if (is_friend && !have_def)
2651             /* This is not really a declaration of a specialization.
2652                It's just the name of an instantiation.  But, it's not
2653                a request for an instantiation, either.  */
2654             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2655           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2656             /* This is indeed a specialization.  In case of constructors
2657                and destructors, we need in-charge and not-in-charge
2658                versions in V3 ABI.  */
2659             clone_function_decl (decl, /*update_method_vec_p=*/0);
2660
2661           /* Register this specialization so that we can find it
2662              again.  */
2663           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2664         }
2665     }
2666
2667   return decl;
2668 }
2669
2670 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2671    parameters.  These are represented in the same format used for
2672    DECL_TEMPLATE_PARMS.  */
2673
2674 int
2675 comp_template_parms (const_tree parms1, const_tree parms2)
2676 {
2677   const_tree p1;
2678   const_tree p2;
2679
2680   if (parms1 == parms2)
2681     return 1;
2682
2683   for (p1 = parms1, p2 = parms2;
2684        p1 != NULL_TREE && p2 != NULL_TREE;
2685        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2686     {
2687       tree t1 = TREE_VALUE (p1);
2688       tree t2 = TREE_VALUE (p2);
2689       int i;
2690
2691       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2692       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2693
2694       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2695         return 0;
2696
2697       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2698         {
2699           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2700           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2701
2702           /* If either of the template parameters are invalid, assume
2703              they match for the sake of error recovery. */
2704           if (parm1 == error_mark_node || parm2 == error_mark_node)
2705             return 1;
2706
2707           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2708             return 0;
2709
2710           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2711               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2712                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2713             continue;
2714           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2715             return 0;
2716         }
2717     }
2718
2719   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2720     /* One set of parameters has more parameters lists than the
2721        other.  */
2722     return 0;
2723
2724   return 1;
2725 }
2726
2727 /* Determine whether PARM is a parameter pack.  */
2728
2729 bool 
2730 template_parameter_pack_p (const_tree parm)
2731 {
2732   /* Determine if we have a non-type template parameter pack.  */
2733   if (TREE_CODE (parm) == PARM_DECL)
2734     return (DECL_TEMPLATE_PARM_P (parm) 
2735             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2736
2737   /* If this is a list of template parameters, we could get a
2738      TYPE_DECL or a TEMPLATE_DECL.  */ 
2739   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2740     parm = TREE_TYPE (parm);
2741
2742   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2743            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2744           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2745 }
2746
2747 /* Determine if T is a function parameter pack.  */
2748
2749 bool
2750 function_parameter_pack_p (const_tree t)
2751 {
2752   if (t && TREE_CODE (t) == PARM_DECL)
2753     return FUNCTION_PARAMETER_PACK_P (t);
2754   return false;
2755 }
2756
2757 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2758    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2759
2760 tree
2761 get_function_template_decl (const_tree primary_func_tmpl_inst)
2762 {
2763   if (! primary_func_tmpl_inst
2764       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2765       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2766     return NULL;
2767
2768   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2769 }
2770
2771 /* Return true iff the function parameter PARAM_DECL was expanded
2772    from the function parameter pack PACK.  */
2773
2774 bool
2775 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2776 {
2777   if (DECL_ARTIFICIAL (param_decl)
2778       || !function_parameter_pack_p (pack))
2779     return false;
2780
2781   /* The parameter pack and its pack arguments have the same
2782      DECL_PARM_INDEX.  */
2783   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2784 }
2785
2786 /* Determine whether ARGS describes a variadic template args list,
2787    i.e., one that is terminated by a template argument pack.  */
2788
2789 static bool 
2790 template_args_variadic_p (tree args)
2791 {
2792   int nargs;
2793   tree last_parm;
2794
2795   if (args == NULL_TREE)
2796     return false;
2797
2798   args = INNERMOST_TEMPLATE_ARGS (args);
2799   nargs = TREE_VEC_LENGTH (args);
2800
2801   if (nargs == 0)
2802     return false;
2803
2804   last_parm = TREE_VEC_ELT (args, nargs - 1);
2805
2806   return ARGUMENT_PACK_P (last_parm);
2807 }
2808
2809 /* Generate a new name for the parameter pack name NAME (an
2810    IDENTIFIER_NODE) that incorporates its */
2811
2812 static tree
2813 make_ith_pack_parameter_name (tree name, int i)
2814 {
2815   /* Munge the name to include the parameter index.  */
2816 #define NUMBUF_LEN 128
2817   char numbuf[NUMBUF_LEN];
2818   char* newname;
2819   int newname_len;
2820
2821   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2822   newname_len = IDENTIFIER_LENGTH (name)
2823                 + strlen (numbuf) + 2;
2824   newname = (char*)alloca (newname_len);
2825   snprintf (newname, newname_len,
2826             "%s#%i", IDENTIFIER_POINTER (name), i);
2827   return get_identifier (newname);
2828 }
2829
2830 /* Return true if T is a primary function
2831    or class template instantiation.  */
2832
2833 bool
2834 primary_template_instantiation_p (const_tree t)
2835 {
2836   if (!t)
2837     return false;
2838
2839   if (TREE_CODE (t) == FUNCTION_DECL)
2840     return DECL_LANG_SPECIFIC (t)
2841            && DECL_TEMPLATE_INSTANTIATION (t)
2842            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2843   else if (CLASS_TYPE_P (t))
2844     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2845            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2846   return false;
2847 }
2848
2849 /* Return true if PARM is a template template parameter.  */
2850
2851 bool
2852 template_template_parameter_p (const_tree parm)
2853 {
2854   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2855 }
2856
2857 /* Return the template parameters of T if T is a
2858    primary template instantiation, NULL otherwise.  */
2859
2860 tree
2861 get_primary_template_innermost_parameters (const_tree t)
2862 {
2863   tree parms = NULL, template_info = NULL;
2864
2865   if ((template_info = get_template_info (t))
2866       && primary_template_instantiation_p (t))
2867     parms = INNERMOST_TEMPLATE_PARMS
2868         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2869
2870   return parms;
2871 }
2872
2873 /* Return the template parameters of the LEVELth level from the full list
2874    of template parameters PARMS.  */
2875
2876 tree
2877 get_template_parms_at_level (tree parms, int level)
2878 {
2879   tree p;
2880   if (!parms
2881       || TREE_CODE (parms) != TREE_LIST
2882       || level > TMPL_PARMS_DEPTH (parms))
2883     return NULL_TREE;
2884
2885   for (p = parms; p; p = TREE_CHAIN (p))
2886     if (TMPL_PARMS_DEPTH (p) == level)
2887       return p;
2888
2889   return NULL_TREE;
2890 }
2891
2892 /* Returns the template arguments of T if T is a template instantiation,
2893    NULL otherwise.  */
2894
2895 tree
2896 get_template_innermost_arguments (const_tree t)
2897 {
2898   tree args = NULL, template_info = NULL;
2899
2900   if ((template_info = get_template_info (t))
2901       && TI_ARGS (template_info))
2902     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2903
2904   return args;
2905 }
2906
2907 /* Return the argument pack elements of T if T is a template argument pack,
2908    NULL otherwise.  */
2909
2910 tree
2911 get_template_argument_pack_elems (const_tree t)
2912 {
2913   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2914       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2915     return NULL;
2916
2917   return ARGUMENT_PACK_ARGS (t);
2918 }
2919
2920 /* Structure used to track the progress of find_parameter_packs_r.  */
2921 struct find_parameter_pack_data 
2922 {
2923   /* TREE_LIST that will contain all of the parameter packs found by
2924      the traversal.  */
2925   tree* parameter_packs;
2926
2927   /* Set of AST nodes that have been visited by the traversal.  */
2928   struct pointer_set_t *visited;
2929 };
2930
2931 /* Identifies all of the argument packs that occur in a template
2932    argument and appends them to the TREE_LIST inside DATA, which is a
2933    find_parameter_pack_data structure. This is a subroutine of
2934    make_pack_expansion and uses_parameter_packs.  */
2935 static tree
2936 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2937 {
2938   tree t = *tp;
2939   struct find_parameter_pack_data* ppd = 
2940     (struct find_parameter_pack_data*)data;
2941   bool parameter_pack_p = false;
2942
2943   /* Identify whether this is a parameter pack or not.  */
2944   switch (TREE_CODE (t))
2945     {
2946     case TEMPLATE_PARM_INDEX:
2947       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2948         parameter_pack_p = true;
2949       break;
2950
2951     case TEMPLATE_TYPE_PARM:
2952     case TEMPLATE_TEMPLATE_PARM:
2953       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2954         parameter_pack_p = true;
2955       break;
2956
2957     case PARM_DECL:
2958       if (FUNCTION_PARAMETER_PACK_P (t))
2959         {
2960           /* We don't want to walk into the type of a PARM_DECL,
2961              because we don't want to see the type parameter pack.  */
2962           *walk_subtrees = 0;
2963           parameter_pack_p = true;
2964         }
2965       break;
2966
2967     default:
2968       /* Not a parameter pack.  */
2969       break;
2970     }
2971
2972   if (parameter_pack_p)
2973     {
2974       /* Add this parameter pack to the list.  */
2975       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2976     }
2977
2978   if (TYPE_P (t))
2979     cp_walk_tree (&TYPE_CONTEXT (t), 
2980                   &find_parameter_packs_r, ppd, ppd->visited);
2981
2982   /* This switch statement will return immediately if we don't find a
2983      parameter pack.  */
2984   switch (TREE_CODE (t)) 
2985     {
2986     case TEMPLATE_PARM_INDEX:
2987       return NULL_TREE;
2988
2989     case BOUND_TEMPLATE_TEMPLATE_PARM:
2990       /* Check the template itself.  */
2991       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2992                     &find_parameter_packs_r, ppd, ppd->visited);
2993       /* Check the template arguments.  */
2994       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2995                     ppd->visited);
2996       *walk_subtrees = 0;
2997       return NULL_TREE;
2998
2999     case TEMPLATE_TYPE_PARM:
3000     case TEMPLATE_TEMPLATE_PARM:
3001       return NULL_TREE;
3002
3003     case PARM_DECL:
3004       return NULL_TREE;
3005
3006     case RECORD_TYPE:
3007       if (TYPE_PTRMEMFUNC_P (t))
3008         return NULL_TREE;
3009       /* Fall through.  */
3010
3011     case UNION_TYPE:
3012     case ENUMERAL_TYPE:
3013       if (TYPE_TEMPLATE_INFO (t))
3014         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
3015                       &find_parameter_packs_r, ppd, ppd->visited);
3016
3017       *walk_subtrees = 0;
3018       return NULL_TREE;
3019
3020     case TEMPLATE_DECL:
3021       cp_walk_tree (&TREE_TYPE (t),
3022                     &find_parameter_packs_r, ppd, ppd->visited);
3023       return NULL_TREE;
3024  
3025     case TYPENAME_TYPE:
3026       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3027                    ppd, ppd->visited);
3028       *walk_subtrees = 0;
3029       return NULL_TREE;
3030       
3031     case TYPE_PACK_EXPANSION:
3032     case EXPR_PACK_EXPANSION:
3033       *walk_subtrees = 0;
3034       return NULL_TREE;
3035
3036     case INTEGER_TYPE:
3037       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
3038                     ppd, ppd->visited);
3039       *walk_subtrees = 0;
3040       return NULL_TREE;
3041
3042     case IDENTIFIER_NODE:
3043       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
3044                     ppd->visited);
3045       *walk_subtrees = 0;
3046       return NULL_TREE;
3047
3048     default:
3049       return NULL_TREE;
3050     }
3051
3052   return NULL_TREE;
3053 }
3054
3055 /* Determines if the expression or type T uses any parameter packs.  */
3056 bool
3057 uses_parameter_packs (tree t)
3058 {
3059   tree parameter_packs = NULL_TREE;
3060   struct find_parameter_pack_data ppd;
3061   ppd.parameter_packs = &parameter_packs;
3062   ppd.visited = pointer_set_create ();
3063   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3064   pointer_set_destroy (ppd.visited);
3065   return parameter_packs != NULL_TREE;
3066 }
3067
3068 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3069    representation a base-class initializer into a parameter pack
3070    expansion. If all goes well, the resulting node will be an
3071    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3072    respectively.  */
3073 tree 
3074 make_pack_expansion (tree arg)
3075 {
3076   tree result;
3077   tree parameter_packs = NULL_TREE;
3078   bool for_types = false;
3079   struct find_parameter_pack_data ppd;
3080
3081   if (!arg || arg == error_mark_node)
3082     return arg;
3083
3084   if (TREE_CODE (arg) == TREE_LIST)
3085     {
3086       /* The only time we will see a TREE_LIST here is for a base
3087          class initializer.  In this case, the TREE_PURPOSE will be a
3088          _TYPE node (representing the base class expansion we're
3089          initializing) and the TREE_VALUE will be a TREE_LIST
3090          containing the initialization arguments. 
3091
3092          The resulting expansion looks somewhat different from most
3093          expansions. Rather than returning just one _EXPANSION, we
3094          return a TREE_LIST whose TREE_PURPOSE is a
3095          TYPE_PACK_EXPANSION containing the bases that will be
3096          initialized.  The TREE_VALUE will be identical to the
3097          original TREE_VALUE, which is a list of arguments that will
3098          be passed to each base.  We do not introduce any new pack
3099          expansion nodes into the TREE_VALUE (although it is possible
3100          that some already exist), because the TREE_PURPOSE and
3101          TREE_VALUE all need to be expanded together with the same
3102          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3103          resulting TREE_PURPOSE will mention the parameter packs in
3104          both the bases and the arguments to the bases.  */
3105       tree purpose;
3106       tree value;
3107       tree parameter_packs = NULL_TREE;
3108
3109       /* Determine which parameter packs will be used by the base
3110          class expansion.  */
3111       ppd.visited = pointer_set_create ();
3112       ppd.parameter_packs = &parameter_packs;
3113       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3114                     &ppd, ppd.visited);
3115
3116       if (parameter_packs == NULL_TREE)
3117         {
3118           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3119           pointer_set_destroy (ppd.visited);
3120           return error_mark_node;
3121         }
3122
3123       if (TREE_VALUE (arg) != void_type_node)
3124         {
3125           /* Collect the sets of parameter packs used in each of the
3126              initialization arguments.  */
3127           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3128             {
3129               /* Determine which parameter packs will be expanded in this
3130                  argument.  */
3131               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3132                             &ppd, ppd.visited);
3133             }
3134         }
3135
3136       pointer_set_destroy (ppd.visited);
3137
3138       /* Create the pack expansion type for the base type.  */
3139       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3140       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3141       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3142
3143       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3144          they will rarely be compared to anything.  */
3145       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3146
3147       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3148     }
3149
3150   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3151     for_types = true;
3152
3153   /* Build the PACK_EXPANSION_* node.  */
3154   result = for_types
3155      ? cxx_make_type (TYPE_PACK_EXPANSION)
3156      : make_node (EXPR_PACK_EXPANSION);
3157   SET_PACK_EXPANSION_PATTERN (result, arg);
3158   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3159     {
3160       /* Propagate type and const-expression information.  */
3161       TREE_TYPE (result) = TREE_TYPE (arg);
3162       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3163     }
3164   else
3165     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3166        they will rarely be compared to anything.  */
3167     SET_TYPE_STRUCTURAL_EQUALITY (result);
3168
3169   /* Determine which parameter packs will be expanded.  */
3170   ppd.parameter_packs = &parameter_packs;
3171   ppd.visited = pointer_set_create ();
3172   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3173   pointer_set_destroy (ppd.visited);
3174
3175   /* Make sure we found some parameter packs.  */
3176   if (parameter_packs == NULL_TREE)
3177     {
3178       if (TYPE_P (arg))
3179         error ("expansion pattern %<%T%> contains no argument packs", arg);
3180       else
3181         error ("expansion pattern %<%E%> contains no argument packs", arg);
3182       return error_mark_node;
3183     }
3184   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3185
3186   return result;
3187 }
3188
3189 /* Checks T for any "bare" parameter packs, which have not yet been
3190    expanded, and issues an error if any are found. This operation can
3191    only be done on full expressions or types (e.g., an expression
3192    statement, "if" condition, etc.), because we could have expressions like:
3193
3194      foo(f(g(h(args)))...)
3195
3196    where "args" is a parameter pack. check_for_bare_parameter_packs
3197    should not be called for the subexpressions args, h(args),
3198    g(h(args)), or f(g(h(args))), because we would produce erroneous
3199    error messages. 
3200
3201    Returns TRUE and emits an error if there were bare parameter packs,
3202    returns FALSE otherwise.  */
3203 bool 
3204 check_for_bare_parameter_packs (tree t)
3205 {
3206   tree parameter_packs = NULL_TREE;
3207   struct find_parameter_pack_data ppd;
3208
3209   if (!processing_template_decl || !t || t == error_mark_node)
3210     return false;
3211
3212   if (TREE_CODE (t) == TYPE_DECL)
3213     t = TREE_TYPE (t);
3214
3215   ppd.parameter_packs = &parameter_packs;
3216   ppd.visited = pointer_set_create ();
3217   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3218   pointer_set_destroy (ppd.visited);
3219
3220   if (parameter_packs) 
3221     {
3222       error ("parameter packs not expanded with %<...%>:");
3223       while (parameter_packs)
3224         {
3225           tree pack = TREE_VALUE (parameter_packs);
3226           tree name = NULL_TREE;
3227
3228           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3229               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3230             name = TYPE_NAME (pack);
3231           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3232             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3233           else
3234             name = DECL_NAME (pack);
3235
3236           if (name)
3237             inform (input_location, "        %qD", name);
3238           else
3239             inform (input_location, "        <anonymous>");
3240
3241           parameter_packs = TREE_CHAIN (parameter_packs);
3242         }
3243
3244       return true;
3245     }
3246
3247   return false;
3248 }
3249
3250 /* Expand any parameter packs that occur in the template arguments in
3251    ARGS.  */
3252 tree
3253 expand_template_argument_pack (tree args)
3254 {
3255   tree result_args = NULL_TREE;
3256   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3257   int num_result_args = -1;
3258   int non_default_args_count = -1;
3259
3260   /* First, determine if we need to expand anything, and the number of
3261      slots we'll need.  */
3262   for (in_arg = 0; in_arg < nargs; ++in_arg)
3263     {
3264       tree arg = TREE_VEC_ELT (args, in_arg);
3265       if (arg == NULL_TREE)
3266         return args;
3267       if (ARGUMENT_PACK_P (arg))
3268         {
3269           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3270           if (num_result_args < 0)
3271             num_result_args = in_arg + num_packed;
3272           else
3273             num_result_args += num_packed;
3274         }
3275       else
3276         {
3277           if (num_result_args >= 0)
3278             num_result_args++;
3279         }
3280     }
3281
3282   /* If no expansion is necessary, we're done.  */
3283   if (num_result_args < 0)
3284     return args;
3285
3286   /* Expand arguments.  */
3287   result_args = make_tree_vec (num_result_args);
3288   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3289     non_default_args_count =
3290       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3291   for (in_arg = 0; in_arg < nargs; ++in_arg)
3292     {
3293       tree arg = TREE_VEC_ELT (args, in_arg);
3294       if (ARGUMENT_PACK_P (arg))
3295         {
3296           tree packed = ARGUMENT_PACK_ARGS (arg);
3297           int i, num_packed = TREE_VEC_LENGTH (packed);
3298           for (i = 0; i < num_packed; ++i, ++out_arg)
3299             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3300           if (non_default_args_count > 0)
3301             non_default_args_count += num_packed;
3302         }
3303       else
3304         {
3305           TREE_VEC_ELT (result_args, out_arg) = arg;
3306           ++out_arg;
3307         }
3308     }
3309   if (non_default_args_count >= 0)
3310     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3311   return result_args;
3312 }
3313
3314 /* Checks if DECL shadows a template parameter.
3315
3316    [temp.local]: A template-parameter shall not be redeclared within its
3317    scope (including nested scopes).
3318
3319    Emits an error and returns TRUE if the DECL shadows a parameter,
3320    returns FALSE otherwise.  */
3321
3322 bool
3323 check_template_shadow (tree decl)
3324 {
3325   tree olddecl;
3326
3327   /* If we're not in a template, we can't possibly shadow a template
3328      parameter.  */
3329   if (!current_template_parms)
3330     return true;
3331
3332   /* Figure out what we're shadowing.  */
3333   if (TREE_CODE (decl) == OVERLOAD)
3334     decl = OVL_CURRENT (decl);
3335   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3336
3337   /* If there's no previous binding for this name, we're not shadowing
3338      anything, let alone a template parameter.  */
3339   if (!olddecl)
3340     return true;
3341
3342   /* If we're not shadowing a template parameter, we're done.  Note
3343      that OLDDECL might be an OVERLOAD (or perhaps even an
3344      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3345      node.  */
3346   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3347     return true;
3348
3349   /* We check for decl != olddecl to avoid bogus errors for using a
3350      name inside a class.  We check TPFI to avoid duplicate errors for
3351      inline member templates.  */
3352   if (decl == olddecl
3353       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3354     return true;
3355
3356   error ("declaration of %q+#D", decl);
3357   error (" shadows template parm %q+#D", olddecl);
3358   return false;
3359 }
3360
3361 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3362    ORIG_LEVEL, DECL, and TYPE.  NUM_SIBLINGS is the total number of
3363    template parameters.  */
3364
3365 static tree
3366 build_template_parm_index (int index,
3367                            int level,
3368                            int orig_level,
3369                            int num_siblings,
3370                            tree decl,
3371                            tree type)
3372 {
3373   tree t = make_node (TEMPLATE_PARM_INDEX);
3374   TEMPLATE_PARM_IDX (t) = index;
3375   TEMPLATE_PARM_LEVEL (t) = level;
3376   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3377   TEMPLATE_PARM_NUM_SIBLINGS (t) = num_siblings;
3378   TEMPLATE_PARM_DECL (t) = decl;
3379   TREE_TYPE (t) = type;
3380   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3381   TREE_READONLY (t) = TREE_READONLY (decl);
3382
3383   return t;
3384 }
3385
3386 /* Find the canonical type parameter for the given template type
3387    parameter.  Returns the canonical type parameter, which may be TYPE
3388    if no such parameter existed.  */
3389
3390 static tree
3391 canonical_type_parameter (tree type)
3392 {
3393   tree list;
3394   int idx = TEMPLATE_TYPE_IDX (type);
3395   if (!canonical_template_parms)
3396     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3397
3398   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3399     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3400
3401   list = VEC_index (tree, canonical_template_parms, idx);
3402   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3403     list = TREE_CHAIN (list);
3404
3405   if (list)
3406     return TREE_VALUE (list);
3407   else
3408     {
3409       VEC_replace(tree, canonical_template_parms, idx,
3410                   tree_cons (NULL_TREE, type, 
3411                              VEC_index (tree, canonical_template_parms, idx)));
3412       return type;
3413     }
3414 }
3415
3416 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3417    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3418    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3419    new one is created.  */
3420
3421 static tree
3422 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3423                             tsubst_flags_t complain)
3424 {
3425   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3426       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3427           != TEMPLATE_PARM_LEVEL (index) - levels)
3428       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3429     {
3430       tree orig_decl = TEMPLATE_PARM_DECL (index);
3431       tree decl, t;
3432
3433       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3434                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3435       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3436       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3437       DECL_ARTIFICIAL (decl) = 1;
3438       SET_DECL_TEMPLATE_PARM_P (decl);
3439
3440       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3441                                      TEMPLATE_PARM_LEVEL (index) - levels,
3442                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3443                                      TEMPLATE_PARM_NUM_SIBLINGS (index),
3444                                      decl, type);
3445       TEMPLATE_PARM_DESCENDANTS (index) = t;
3446       TEMPLATE_PARM_PARAMETER_PACK (t) 
3447         = TEMPLATE_PARM_PARAMETER_PACK (index);
3448
3449         /* Template template parameters need this.  */
3450       if (TREE_CODE (decl) == TEMPLATE_DECL)
3451         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3452           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3453            args, complain);
3454     }
3455
3456   return TEMPLATE_PARM_DESCENDANTS (index);
3457 }
3458
3459 /* Process information from new template parameter PARM and append it
3460    to the LIST being built.  This new parameter is a non-type
3461    parameter iff IS_NON_TYPE is true. This new parameter is a
3462    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
3463    is in PARM_LOC. NUM_TEMPLATE_PARMS is the size of the template
3464    parameter list PARM belongs to. This is used used to create a
3465    proper canonical type for the type of PARM that is to be created,
3466    iff PARM is a type.  If the size is not known, this parameter shall
3467    be set to 0.  */
3468
3469 tree
3470 process_template_parm (tree list, location_t parm_loc, tree parm,
3471                        bool is_non_type, bool is_parameter_pack,
3472                        unsigned num_template_parms)
3473 {
3474   tree decl = 0;
3475   tree defval;
3476   tree err_parm_list;
3477   int idx = 0;
3478
3479   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3480   defval = TREE_PURPOSE (parm);
3481
3482   if (list)
3483     {
3484       tree p = tree_last (list);
3485
3486       if (p && TREE_VALUE (p) != error_mark_node)
3487         {
3488           p = TREE_VALUE (p);
3489           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3490             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3491           else
3492             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3493         }
3494
3495       ++idx;
3496     }
3497   else
3498     idx = 0;
3499
3500   if (is_non_type)
3501     {
3502       parm = TREE_VALUE (parm);
3503
3504       SET_DECL_TEMPLATE_PARM_P (parm);
3505
3506       if (TREE_TYPE (parm) == error_mark_node)
3507         {
3508           err_parm_list = build_tree_list (defval, parm);
3509           TREE_VALUE (err_parm_list) = error_mark_node;
3510            return chainon (list, err_parm_list);
3511         }
3512       else
3513       {
3514         /* [temp.param]
3515
3516            The top-level cv-qualifiers on the template-parameter are
3517            ignored when determining its type.  */
3518         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3519         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3520           {
3521             err_parm_list = build_tree_list (defval, parm);
3522             TREE_VALUE (err_parm_list) = error_mark_node;
3523              return chainon (list, err_parm_list);
3524           }
3525
3526         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3527           {
3528             /* This template parameter is not a parameter pack, but it
3529                should be. Complain about "bare" parameter packs.  */
3530             check_for_bare_parameter_packs (TREE_TYPE (parm));
3531             
3532             /* Recover by calling this a parameter pack.  */
3533             is_parameter_pack = true;
3534           }
3535       }
3536
3537       /* A template parameter is not modifiable.  */
3538       TREE_CONSTANT (parm) = 1;
3539       TREE_READONLY (parm) = 1;
3540       decl = build_decl (parm_loc,
3541                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3542       TREE_CONSTANT (decl) = 1;
3543       TREE_READONLY (decl) = 1;
3544       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3545         = build_template_parm_index (idx, processing_template_decl,
3546                                      processing_template_decl,
3547                                      num_template_parms,
3548                                      decl, TREE_TYPE (parm));
3549
3550       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3551         = is_parameter_pack;
3552     }
3553   else
3554     {
3555       tree t;
3556       parm = TREE_VALUE (TREE_VALUE (parm));
3557
3558       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3559         {
3560           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3561           /* This is for distinguishing between real templates and template
3562              template parameters */
3563           TREE_TYPE (parm) = t;
3564           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3565           decl = parm;
3566         }
3567       else
3568         {
3569           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3570           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3571           decl = build_decl (parm_loc,
3572                              TYPE_DECL, parm, t);
3573         }
3574
3575       TYPE_NAME (t) = decl;
3576       TYPE_STUB_DECL (t) = decl;
3577       parm = decl;
3578       TEMPLATE_TYPE_PARM_INDEX (t)
3579         = build_template_parm_index (idx, processing_template_decl,
3580                                      processing_template_decl,
3581                                      num_template_parms,
3582                                      decl, TREE_TYPE (parm));
3583       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3584       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3585     }
3586   DECL_ARTIFICIAL (decl) = 1;
3587   SET_DECL_TEMPLATE_PARM_P (decl);
3588   pushdecl (decl);
3589   parm = build_tree_list (defval, parm);
3590   return chainon (list, parm);
3591 }
3592
3593 /* The end of a template parameter list has been reached.  Process the
3594    tree list into a parameter vector, converting each parameter into a more
3595    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3596    as PARM_DECLs.  */
3597
3598 tree
3599 end_template_parm_list (tree parms)
3600 {
3601   int nparms;
3602   tree parm, next;
3603   tree saved_parmlist = make_tree_vec (list_length (parms));
3604
3605   current_template_parms
3606     = tree_cons (size_int (processing_template_decl),
3607                  saved_parmlist, current_template_parms);
3608
3609   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3610     {
3611       next = TREE_CHAIN (parm);
3612       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3613       TREE_CHAIN (parm) = NULL_TREE;
3614     }
3615
3616   fixup_template_parms ();
3617
3618   --processing_template_parmlist;
3619
3620   return saved_parmlist;
3621 }
3622
3623 /* Create a new type almost identical to TYPE but which has the
3624    following differences:
3625
3626      1/ T has a new TEMPLATE_PARM_INDEX that carries the new number of
3627      template sibling parameters of T.
3628
3629      2/ T has a new canonical type that matches the new number
3630      of sibling parms.
3631
3632      3/ From now on, T is going to be what lookups referring to the
3633      name of TYPE will return. No lookup should return TYPE anymore.
3634
3635    NUM_PARMS is the new number of sibling parms TYPE belongs to.
3636
3637    This is a subroutine of fixup_template_parms.  */
3638
3639 static tree
3640 fixup_template_type_parm_type (tree type, int num_parms)
3641 {
3642   tree orig_idx = TEMPLATE_TYPE_PARM_INDEX (type), idx;
3643   tree t;
3644   /* This is the decl which name is inserted into the symbol table for
3645      the template parm type. So whenever we lookup the type name, this
3646      is the DECL we get.  */
3647   tree decl;
3648
3649   /* Do not fix up the type twice.  */
3650   if (orig_idx && TEMPLATE_PARM_NUM_SIBLINGS (orig_idx) != 0)
3651     return type;
3652
3653   t = copy_type (type);
3654   decl = TYPE_NAME (t);
3655
3656   TYPE_MAIN_VARIANT (t) = t;
3657   TYPE_NEXT_VARIANT (t)= NULL_TREE;
3658   TYPE_POINTER_TO (t) = 0;
3659   TYPE_REFERENCE_TO (t) = 0;
3660
3661   idx = build_template_parm_index (TEMPLATE_PARM_IDX (orig_idx),
3662                                    TEMPLATE_PARM_LEVEL (orig_idx),
3663                                    TEMPLATE_PARM_ORIG_LEVEL (orig_idx),
3664                                    num_parms,
3665                                    decl, t);
3666   TEMPLATE_PARM_DESCENDANTS (idx) = TEMPLATE_PARM_DESCENDANTS (orig_idx);
3667   TEMPLATE_PARM_PARAMETER_PACK (idx) = TEMPLATE_PARM_PARAMETER_PACK (orig_idx);
3668   TEMPLATE_TYPE_PARM_INDEX (t) = idx;
3669
3670   TYPE_STUB_DECL (t) = decl;
3671   TEMPLATE_TYPE_DECL (t) = decl;
3672   if (TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
3673     TREE_TYPE (DECL_TEMPLATE_RESULT  (decl)) = t;
3674
3675   /* Update the type associated to the type name stored in the symbol
3676      table. Now, whenever the type name is looked up, the resulting
3677      type is properly fixed up.  */
3678   TREE_TYPE (decl) = t;
3679
3680   TYPE_CANONICAL (t) = canonical_type_parameter (t);
3681
3682   return t;
3683 }
3684
3685 /* Create and return a new TEMPLATE_PARM_INDEX that is almost
3686    identical to I, but that is fixed up as to:
3687
3688    1/ carry the number of sibling parms (NUM_PARMS) of the template
3689    parm represented by I.
3690
3691    2/ replace all references to template parm types declared before I
3692    (in the same template parm list as I) by references to template
3693    parm types contained in ARGS. ARGS should contain the list of
3694    template parms that have been fixed up so far, in a form suitable
3695    to be passed to tsubst.
3696
3697    This is a subroutine of fixup_template_parms.  */
3698
3699 static tree
3700 fixup_template_parm_index (tree i, tree args, int num_parms)
3701 {
3702   tree index, decl, type;
3703
3704   if (i == NULL_TREE
3705       || TREE_CODE (i) != TEMPLATE_PARM_INDEX
3706       /* Do not fix up the index twice.  */
3707       || (TEMPLATE_PARM_NUM_SIBLINGS (i) != 0))
3708     return i;
3709
3710   decl = TEMPLATE_PARM_DECL (i);
3711   type = TREE_TYPE (decl);
3712
3713   index = build_template_parm_index (TEMPLATE_PARM_IDX (i),
3714                                      TEMPLATE_PARM_LEVEL (i),
3715                                      TEMPLATE_PARM_ORIG_LEVEL (i),
3716                                      num_parms,
3717                                      decl, type);
3718
3719   TEMPLATE_PARM_DESCENDANTS (index) = TEMPLATE_PARM_DESCENDANTS (i);
3720   TEMPLATE_PARM_PARAMETER_PACK (index) = TEMPLATE_PARM_PARAMETER_PACK (i);
3721
3722   type = tsubst (type, args, tf_none, NULL_TREE);
3723   
3724   TREE_TYPE (decl) = type;
3725   TREE_TYPE (index) = type;
3726
3727   return index;
3728 }
3729
3730 /* 
3731    This is a subroutine of fixup_template_parms.
3732
3733    It computes the canonical type of the type of the template
3734    parameter PARM_DESC and update all references to that type so that
3735    they use the newly computed canonical type. No access check is
3736    performed during the fixup. PARM_DESC is a TREE_LIST which
3737    TREE_VALUE is the template parameter and its TREE_PURPOSE is the
3738    default argument of the template parm if any. IDX is the index of
3739    the template parameter, starting at 0. NUM_PARMS is the number of
3740    template parameters in the set PARM_DESC belongs to. ARGLIST is a
3741    TREE_VEC containing the full set of template parameters in a form
3742    suitable to be passed to substs functions as their ARGS
3743    argument. This is what current_template_args returns for a given
3744    template. The innermost vector of args in ARGLIST is the set of
3745    template parms that have been fixed up so far. This function adds
3746    the fixed up parameter into that vector.  */
3747
3748 static void
3749 fixup_template_parm (tree parm_desc,
3750                      int idx,
3751                      int num_parms,
3752                      tree arglist)
3753 {
3754   tree parm = TREE_VALUE (parm_desc);
3755   tree fixedup_args = INNERMOST_TEMPLATE_ARGS (arglist);
3756
3757   push_deferring_access_checks (dk_no_check);
3758
3759   if (TREE_CODE (parm) == TYPE_DECL)
3760     {
3761       /* PARM is a template type parameter. Fix up its type, add
3762          the fixed-up template parm to the vector of fixed-up
3763          template parms so far, and substitute the fixed-up
3764          template parms into the default argument of this
3765          parameter.  */
3766       tree t =
3767         fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
3768       TREE_TYPE (parm) = t;
3769
3770       TREE_VEC_ELT (fixedup_args, idx) = template_parm_to_arg (parm_desc);
3771     }
3772   else if (TREE_CODE (parm) == TEMPLATE_DECL)
3773     {
3774       /* PARM is a template template parameter. This is going to
3775          be interesting.  */
3776       tree tparms, targs, innermost_args;
3777       int j;
3778
3779       /* First, fix up the type of the parm.  */
3780
3781       tree t =
3782         fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
3783       TREE_TYPE (parm) = t;
3784
3785       TREE_VEC_ELT (fixedup_args, idx) =
3786         template_parm_to_arg (parm_desc);
3787
3788       /* Now we need to substitute the template parm types that
3789          have been fixed up so far into the non-type template
3790          parms of this template template parm. E.g, consider this:
3791
3792          template<class T, template<T u> class TT> class S;
3793
3794          In this case we want to substitute T into the
3795          template parameters of TT.
3796
3797          So let's walk the template parms of PARM here, and
3798          tsubst ARGLIST into into each of the template
3799          parms.   */
3800
3801       /* For this substitution we need to build the full set of
3802          template parameters and use that as arguments for the
3803          tsubsting function.  */
3804       tparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
3805
3806       /* This will contain the innermost parms of PARM into which
3807          we have substituted so far.  */
3808       innermost_args = make_tree_vec (TREE_VEC_LENGTH (tparms));
3809       targs = add_to_template_args (arglist, innermost_args);
3810       for (j = 0; j < TREE_VEC_LENGTH (tparms); ++j)
3811         {
3812           tree parameter;
3813
3814           parameter = TREE_VEC_ELT (tparms, j);
3815
3816           /* INNERMOST_ARGS needs to have at least the same number
3817              of elements as the index PARAMETER, ortherwise
3818              tsubsting into PARAMETER will result in partially
3819              instantiating it, reducing its tempate parm
3820              level. Let's tactically fill INNERMOST_ARGS for that
3821              purpose.  */
3822           TREE_VEC_ELT (innermost_args, j) =
3823             template_parm_to_arg (parameter);
3824
3825           fixup_template_parm (parameter, j,
3826                                TREE_VEC_LENGTH (tparms),
3827                                targs);
3828         }
3829     }
3830   else if (TREE_CODE (parm) == PARM_DECL)
3831     {
3832       /* PARM is a non-type template parameter. We need to:
3833
3834        * Fix up its TEMPLATE_PARM_INDEX to make it carry the
3835        proper number of sibling parameters.
3836
3837        * Make lookups of the template parameter return a reference
3838        to the fixed-up index. No lookup should return references
3839        to the former index anymore.
3840
3841        * Substitute the template parms that got fixed up so far
3842
3843        * into the type of PARM.  */
3844
3845       tree index = DECL_INITIAL (parm);
3846
3847       /* PUSHED_DECL is the decl added to the symbol table with
3848          the name of the parameter. E,g:
3849              
3850          template<class T, T u> //#0
3851          auto my_function(T t) -> decltype(u); //#1
3852
3853          Here, when looking up u at //#1, we get the decl of u
3854          resulting from the declaration in #0. This is what
3855          PUSHED_DECL is. We need to replace the reference to the
3856          old TEMPLATE_PARM_INDEX carried by PUSHED_DECL by the
3857          fixed-up TEMPLATE_PARM_INDEX.  */
3858       tree pushed_decl = TEMPLATE_PARM_DECL (index);
3859
3860       /* Let's fix up the TEMPLATE_PARM_INDEX then. Note that we must
3861          fixup the type of PUSHED_DECL as well and luckily
3862          fixup_template_parm_index does it for us too.  */
3863       tree fixed_up_index =
3864         fixup_template_parm_index (index, arglist, num_parms);
3865
3866       DECL_INITIAL (pushed_decl) = DECL_INITIAL (parm) = fixed_up_index;
3867
3868       /* Add this fixed up PARM to the template parms we've fixed
3869          up so far and use that to substitute the fixed-up
3870          template parms into the type of PARM.  */
3871       TREE_VEC_ELT (fixedup_args, idx) =
3872         template_parm_to_arg (parm_desc);
3873       TREE_TYPE (parm) = tsubst (TREE_TYPE (parm), arglist,
3874                                  tf_none, NULL_TREE);
3875     }
3876
3877   TREE_PURPOSE (parm_desc) =
3878     tsubst_template_arg (TREE_PURPOSE (parm_desc),
3879                          arglist, tf_none, parm);
3880
3881   pop_deferring_access_checks ();
3882 }
3883
3884 /* Walk current the template parms and properly compute the canonical
3885    types of the dependent types created during
3886    cp_parser_template_parameter_list.  */
3887
3888 static void
3889 fixup_template_parms (void)
3890 {
3891   tree arglist;
3892   tree parameter_vec;
3893   tree fixedup_args;
3894   int i, num_parms;
3895
3896   parameter_vec = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3897   if (parameter_vec == NULL_TREE)
3898     return;
3899
3900   num_parms = TREE_VEC_LENGTH (parameter_vec);
3901
3902   /* This vector contains the current innermost template parms that
3903      have been fixed up so far.  The form of FIXEDUP_ARGS is suitable
3904      to be passed to tsubst* functions as their ARGS argument.  */
3905   fixedup_args = make_tree_vec (num_parms);
3906
3907   /* This vector contains the full set of template parms in a form
3908      suitable to be passed to substs functions as their ARGS
3909      argument.  */
3910   arglist = current_template_args ();
3911   arglist = add_outermost_template_args (arglist, fixedup_args);
3912
3913   fixedup_args = INNERMOST_TEMPLATE_ARGS (arglist);
3914
3915   /* Let's do the proper fixup now.  */
3916   for (i = 0; i < num_parms; ++i)
3917     fixup_template_parm (TREE_VEC_ELT (parameter_vec, i),
3918                          i, num_parms, arglist);
3919 }
3920
3921 /* end_template_decl is called after a template declaration is seen.  */
3922
3923 void
3924 end_template_decl (void)
3925 {
3926   reset_specialization ();
3927
3928   if (! processing_template_decl)
3929     return;
3930
3931   /* This matches the pushlevel in begin_template_parm_list.  */
3932   finish_scope ();
3933
3934   --processing_template_decl;
3935   current_template_parms = TREE_CHAIN (current_template_parms);
3936 }
3937
3938 /* Takes a TREE_LIST representing a template parameter and convert it
3939    into an argument suitable to be passed to the type substitution
3940    functions.  Note that If the TREE_LIST contains an error_mark
3941    node, the returned argument is error_mark_node.  */
3942
3943 static tree
3944 template_parm_to_arg (tree t)
3945 {
3946
3947   if (t == NULL_TREE
3948       || TREE_CODE (t) != TREE_LIST)
3949     return t;
3950
3951   if (error_operand_p (TREE_VALUE (t)))
3952     return error_mark_node;
3953
3954   t = TREE_VALUE (t);
3955
3956   if (TREE_CODE (t) == TYPE_DECL
3957       || TREE_CODE (t) == TEMPLATE_DECL)
3958     {
3959       t = TREE_TYPE (t);
3960
3961       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3962         {
3963           /* Turn this argument into a TYPE_ARGUMENT_PACK
3964              with a single element, which expands T.  */
3965           tree vec = make_tree_vec (1);
3966 #ifdef ENABLE_CHECKING
3967           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3968             (vec, TREE_VEC_LENGTH (vec));
3969 #endif
3970           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3971
3972           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3973           SET_ARGUMENT_PACK_ARGS (t, vec);
3974         }
3975     }
3976   else
3977     {
3978       t = DECL_INITIAL (t);
3979
3980       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3981         {
3982           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3983              with a single element, which expands T.  */
3984           tree vec = make_tree_vec (1);
3985           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3986 #ifdef ENABLE_CHECKING
3987           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3988             (vec, TREE_VEC_LENGTH (vec));
3989 #endif
3990           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3991
3992           t  = make_node (NONTYPE_ARGUMENT_PACK);
3993           SET_ARGUMENT_PACK_ARGS (t, vec);
3994           TREE_TYPE (t) = type;
3995         }
3996     }
3997   return t;
3998 }
3999
4000 /* Within the declaration of a template, return all levels of template
4001    parameters that apply.  The template parameters are represented as
4002    a TREE_VEC, in the form documented in cp-tree.h for template
4003    arguments.  */
4004
4005 static tree
4006 current_template_args (void)
4007 {
4008   tree header;
4009   tree args = NULL_TREE;
4010   int length = TMPL_PARMS_DEPTH (current_template_parms);
4011   int l = length;
4012
4013   /* If there is only one level of template parameters, we do not
4014      create a TREE_VEC of TREE_VECs.  Instead, we return a single
4015      TREE_VEC containing the arguments.  */
4016   if (length > 1)
4017     args = make_tree_vec (length);
4018
4019   for (header = current_template_parms; header; header = TREE_CHAIN (header))
4020     {
4021       tree a = copy_node (TREE_VALUE (header));
4022       int i;
4023
4024       TREE_TYPE (a) = NULL_TREE;
4025       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4026         TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4027
4028 #ifdef ENABLE_CHECKING
4029       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4030 #endif
4031
4032       if (length > 1)
4033         TREE_VEC_ELT (args, --l) = a;
4034       else
4035         args = a;
4036     }
4037
4038     if (length > 1 && TREE_VEC_ELT (args, 0) == NULL_TREE)
4039       /* This can happen for template parms of a template template
4040          parameter, e.g:
4041
4042          template<template<class T, class U> class TT> struct S;
4043
4044          Consider the level of the parms of TT; T and U both have
4045          level 2; TT has no template parm of level 1. So in this case
4046          the first element of full_template_args is NULL_TREE. If we
4047          leave it like this TMPL_ARG_DEPTH on args returns 1 instead
4048          of 2. This will make tsubst wrongly consider that T and U
4049          have level 1. Instead, let's create a dummy vector as the
4050          first element of full_template_args so that TMPL_ARG_DEPTH
4051          returns the correct depth for args.  */
4052       TREE_VEC_ELT (args, 0) = make_tree_vec (1);
4053   return args;
4054 }
4055
4056 /* Update the declared TYPE by doing any lookups which were thought to be
4057    dependent, but are not now that we know the SCOPE of the declarator.  */
4058
4059 tree
4060 maybe_update_decl_type (tree orig_type, tree scope)
4061 {
4062   tree type = orig_type;
4063
4064   if (type == NULL_TREE)
4065     return type;
4066
4067   if (TREE_CODE (orig_type) == TYPE_DECL)
4068     type = TREE_TYPE (type);
4069
4070   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4071       && dependent_type_p (type)
4072       /* Don't bother building up the args in this case.  */
4073       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4074     {
4075       /* tsubst in the args corresponding to the template parameters,
4076          including auto if present.  Most things will be unchanged, but
4077          make_typename_type and tsubst_qualified_id will resolve
4078          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4079       tree args = current_template_args ();
4080       tree auto_node = type_uses_auto (type);
4081       tree pushed;
4082       if (auto_node)
4083         {
4084           tree auto_vec = make_tree_vec (1);
4085           TREE_VEC_ELT (auto_vec, 0) = auto_node;
4086           args = add_to_template_args (args, auto_vec);
4087         }
4088       pushed = push_scope (scope);
4089       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4090       if (pushed)
4091         pop_scope (scope);
4092     }
4093
4094   if (type == error_mark_node)
4095     return orig_type;
4096
4097   if (TREE_CODE (orig_type) == TYPE_DECL)
4098     {
4099       if (same_type_p (type, TREE_TYPE (orig_type)))
4100         type = orig_type;
4101       else
4102         type = TYPE_NAME (type);
4103     }
4104   return type;
4105 }
4106
4107 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4108    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
4109    a member template.  Used by push_template_decl below.  */
4110
4111 static tree
4112 build_template_decl (tree decl, tree parms, bool member_template_p)
4113 {
4114   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4115   DECL_TEMPLATE_PARMS (tmpl) = parms;
4116   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4117   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4118
4119   return tmpl;
4120 }
4121
4122 struct template_parm_data
4123 {
4124   /* The level of the template parameters we are currently
4125      processing.  */
4126   int level;
4127
4128   /* The index of the specialization argument we are currently
4129      processing.  */
4130   int current_arg;
4131
4132   /* An array whose size is the number of template parameters.  The
4133      elements are nonzero if the parameter has been used in any one
4134      of the arguments processed so far.  */
4135   int* parms;
4136
4137   /* An array whose size is the number of template arguments.  The
4138      elements are nonzero if the argument makes use of template
4139      parameters of this level.  */
4140   int* arg_uses_template_parms;
4141 };
4142
4143 /* Subroutine of push_template_decl used to see if each template
4144    parameter in a partial specialization is used in the explicit
4145    argument list.  If T is of the LEVEL given in DATA (which is
4146    treated as a template_parm_data*), then DATA->PARMS is marked
4147    appropriately.  */
4148
4149 static int
4150 mark_template_parm (tree t, void* data)
4151 {
4152   int level;
4153   int idx;
4154   struct template_parm_data* tpd = (struct template_parm_data*) data;
4155
4156   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4157     {
4158       level = TEMPLATE_PARM_LEVEL (t);
4159       idx = TEMPLATE_PARM_IDX (t);
4160     }
4161   else
4162     {
4163       level = TEMPLATE_TYPE_LEVEL (t);
4164       idx = TEMPLATE_TYPE_IDX (t);
4165     }
4166
4167   if (level == tpd->level)
4168     {
4169       tpd->parms[idx] = 1;
4170       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4171     }
4172
4173   /* Return zero so that for_each_template_parm will continue the
4174      traversal of the tree; we want to mark *every* template parm.  */
4175   return 0;
4176 }
4177
4178 /* Process the partial specialization DECL.  */
4179
4180 static tree
4181 process_partial_specialization (tree decl)
4182 {
4183   tree type = TREE_TYPE (decl);
4184   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
4185   tree specargs = CLASSTYPE_TI_ARGS (type);
4186   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4187   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4188   tree inner_parms;
4189   tree inst;
4190   int nargs = TREE_VEC_LENGTH (inner_args);
4191   int ntparms;
4192   int  i;
4193   bool did_error_intro = false;
4194   struct template_parm_data tpd;
4195   struct template_parm_data tpd2;
4196
4197   gcc_assert (current_template_parms);
4198
4199   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4200   ntparms = TREE_VEC_LENGTH (inner_parms);
4201
4202   /* We check that each of the template parameters given in the
4203      partial specialization is used in the argument list to the
4204      specialization.  For example:
4205
4206        template <class T> struct S;
4207        template <class T> struct S<T*>;
4208
4209      The second declaration is OK because `T*' uses the template
4210      parameter T, whereas
4211
4212        template <class T> struct S<int>;
4213
4214      is no good.  Even trickier is:
4215
4216        template <class T>
4217        struct S1
4218        {
4219           template <class U>
4220           struct S2;
4221           template <class U>
4222           struct S2<T>;
4223        };
4224
4225      The S2<T> declaration is actually invalid; it is a
4226      full-specialization.  Of course,
4227
4228           template <class U>
4229           struct S2<T (*)(U)>;
4230
4231      or some such would have been OK.  */
4232   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4233   tpd.parms = XALLOCAVEC (int, ntparms);
4234   memset (tpd.parms, 0, sizeof (int) * ntparms);
4235
4236   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4237   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4238   for (i = 0; i < nargs; ++i)
4239     {
4240       tpd.current_arg = i;
4241       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4242                               &mark_template_parm,
4243                               &tpd,
4244                               NULL,
4245                               /*include_nondeduced_p=*/false);
4246     }
4247   for (i = 0; i < ntparms; ++i)
4248     if (tpd.parms[i] == 0)
4249       {
4250         /* One of the template parms was not used in the
4251            specialization.  */
4252         if (!did_error_intro)
4253           {
4254             error ("template parameters not used in partial specialization:");
4255             did_error_intro = true;
4256           }
4257
4258         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
4259       }
4260
4261   if (did_error_intro)
4262     return error_mark_node;
4263
4264   /* [temp.class.spec]
4265
4266      The argument list of the specialization shall not be identical to
4267      the implicit argument list of the primary template.  */
4268   if (comp_template_args
4269       (inner_args,
4270        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
4271                                                    (maintmpl)))))
4272     error ("partial specialization %qT does not specialize any template arguments", type);
4273
4274   /* [temp.class.spec]
4275
4276      A partially specialized non-type argument expression shall not
4277      involve template parameters of the partial specialization except
4278      when the argument expression is a simple identifier.
4279
4280      The type of a template parameter corresponding to a specialized
4281      non-type argument shall not be dependent on a parameter of the
4282      specialization. 
4283
4284      Also, we verify that pack expansions only occur at the
4285      end of the argument list.  */
4286   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
4287   tpd2.parms = 0;
4288   for (i = 0; i < nargs; ++i)
4289     {
4290       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
4291       tree arg = TREE_VEC_ELT (inner_args, i);
4292       tree packed_args = NULL_TREE;
4293       int j, len = 1;
4294
4295       if (ARGUMENT_PACK_P (arg))
4296         {
4297           /* Extract the arguments from the argument pack. We'll be
4298              iterating over these in the following loop.  */
4299           packed_args = ARGUMENT_PACK_ARGS (arg);
4300           len = TREE_VEC_LENGTH (packed_args);
4301         }
4302
4303       for (j = 0; j < len; j++)
4304         {
4305           if (packed_args)
4306             /* Get the Jth argument in the parameter pack.  */
4307             arg = TREE_VEC_ELT (packed_args, j);
4308
4309           if (PACK_EXPANSION_P (arg))
4310             {
4311               /* Pack expansions must come at the end of the
4312                  argument list.  */
4313               if ((packed_args && j < len - 1)
4314                   || (!packed_args && i < nargs - 1))
4315                 {
4316                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4317                     error ("parameter pack argument %qE must be at the "
4318                            "end of the template argument list", arg);
4319                   else
4320                     error ("parameter pack argument %qT must be at the "
4321                            "end of the template argument list", arg);
4322                 }
4323             }
4324
4325           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4326             /* We only care about the pattern.  */
4327             arg = PACK_EXPANSION_PATTERN (arg);
4328
4329           if (/* These first two lines are the `non-type' bit.  */
4330               !TYPE_P (arg)
4331               && TREE_CODE (arg) != TEMPLATE_DECL
4332               /* This next line is the `argument expression is not just a
4333                  simple identifier' condition and also the `specialized
4334                  non-type argument' bit.  */
4335               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
4336             {
4337               if ((!packed_args && tpd.arg_uses_template_parms[i])
4338                   || (packed_args && uses_template_parms (arg)))
4339                 error ("template argument %qE involves template parameter(s)",
4340                        arg);
4341               else 
4342                 {
4343                   /* Look at the corresponding template parameter,
4344                      marking which template parameters its type depends
4345                      upon.  */
4346                   tree type = TREE_TYPE (parm);
4347
4348                   if (!tpd2.parms)
4349                     {
4350                       /* We haven't yet initialized TPD2.  Do so now.  */
4351                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4352                       /* The number of parameters here is the number in the
4353                          main template, which, as checked in the assertion
4354                          above, is NARGS.  */
4355                       tpd2.parms = XALLOCAVEC (int, nargs);
4356                       tpd2.level = 
4357                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4358                     }
4359
4360                   /* Mark the template parameters.  But this time, we're
4361                      looking for the template parameters of the main
4362                      template, not in the specialization.  */
4363                   tpd2.current_arg = i;
4364                   tpd2.arg_uses_template_parms[i] = 0;
4365                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4366                   for_each_template_parm (type,
4367                                           &mark_template_parm,
4368                                           &tpd2,
4369                                           NULL,
4370                                           /*include_nondeduced_p=*/false);
4371
4372                   if (tpd2.arg_uses_template_parms [i])
4373                     {
4374                       /* The type depended on some template parameters.
4375                          If they are fully specialized in the
4376                          specialization, that's OK.  */
4377                       int j;
4378                       int count = 0;
4379                       for (j = 0; j < nargs; ++j)
4380                         if (tpd2.parms[j] != 0
4381                             && tpd.arg_uses_template_parms [j])
4382                           ++count;
4383                       if (count != 0)
4384                         error_n (input_location, count,
4385                                  "type %qT of template argument %qE depends "
4386                                  "on a template parameter",
4387                                  "type %qT of template argument %qE depends "
4388                                  "on template parameters",
4389                                  type,
4390                                  arg);
4391                     }
4392                 }
4393             }
4394         }
4395     }
4396
4397   /* We should only get here once.  */
4398   gcc_assert (!COMPLETE_TYPE_P (type));
4399
4400   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4401     = tree_cons (specargs, inner_parms,
4402                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4403   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4404
4405   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
4406        inst = TREE_CHAIN (inst))
4407     {
4408       tree inst_type = TREE_VALUE (inst);
4409       if (COMPLETE_TYPE_P (inst_type)
4410           && CLASSTYPE_IMPLICIT_INSTANTIATION (inst_type))
4411         {
4412           tree spec = most_specialized_class (inst_type, maintmpl, tf_none);
4413           if (spec && TREE_TYPE (spec) == type)
4414             permerror (input_location,
4415                        "partial specialization of %qT after instantiation "
4416                        "of %qT", type, inst_type);
4417         }
4418     }
4419
4420   return decl;
4421 }
4422
4423 /* Check that a template declaration's use of default arguments and
4424    parameter packs is not invalid.  Here, PARMS are the template
4425    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
4426    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
4427    specialization.
4428    
4429
4430    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4431    declaration (but not a definition); 1 indicates a declaration, 2
4432    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4433    emitted for extraneous default arguments.
4434
4435    Returns TRUE if there were no errors found, FALSE otherwise. */
4436
4437 bool
4438 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
4439                          int is_partial, int is_friend_decl)
4440 {
4441   const char *msg;
4442   int last_level_to_check;
4443   tree parm_level;
4444   bool no_errors = true;
4445
4446   /* [temp.param]
4447
4448      A default template-argument shall not be specified in a
4449      function template declaration or a function template definition, nor
4450      in the template-parameter-list of the definition of a member of a
4451      class template.  */
4452
4453   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
4454     /* You can't have a function template declaration in a local
4455        scope, nor you can you define a member of a class template in a
4456        local scope.  */
4457     return true;
4458
4459   if (current_class_type
4460       && !TYPE_BEING_DEFINED (current_class_type)
4461       && DECL_LANG_SPECIFIC (decl)
4462       && DECL_DECLARES_FUNCTION_P (decl)
4463       /* If this is either a friend defined in the scope of the class
4464          or a member function.  */
4465       && (DECL_FUNCTION_MEMBER_P (decl)
4466           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4467           : DECL_FRIEND_CONTEXT (decl)
4468           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4469           : false)
4470       /* And, if it was a member function, it really was defined in
4471          the scope of the class.  */
4472       && (!DECL_FUNCTION_MEMBER_P (decl)
4473           || DECL_INITIALIZED_IN_CLASS_P (decl)))
4474     /* We already checked these parameters when the template was
4475        declared, so there's no need to do it again now.  This function
4476        was defined in class scope, but we're processing it's body now
4477        that the class is complete.  */
4478     return true;
4479
4480   /* Core issue 226 (C++0x only): the following only applies to class
4481      templates.  */
4482   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
4483     {
4484       /* [temp.param]
4485
4486          If a template-parameter has a default template-argument, all
4487          subsequent template-parameters shall have a default
4488          template-argument supplied.  */
4489       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4490         {
4491           tree inner_parms = TREE_VALUE (parm_level);
4492           int ntparms = TREE_VEC_LENGTH (inner_parms);
4493           int seen_def_arg_p = 0;
4494           int i;
4495
4496           for (i = 0; i < ntparms; ++i)
4497             {
4498               tree parm = TREE_VEC_ELT (inner_parms, i);
4499
4500               if (parm == error_mark_node)
4501                 continue;
4502
4503               if (TREE_PURPOSE (parm))
4504                 seen_def_arg_p = 1;
4505               else if (seen_def_arg_p
4506                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4507                 {
4508                   error ("no default argument for %qD", TREE_VALUE (parm));
4509                   /* For better subsequent error-recovery, we indicate that
4510                      there should have been a default argument.  */
4511                   TREE_PURPOSE (parm) = error_mark_node;
4512                   no_errors = false;
4513                 }
4514               else if (is_primary
4515                        && !is_partial
4516                        && !is_friend_decl
4517                        /* Don't complain about an enclosing partial
4518                           specialization.  */
4519                        && parm_level == parms
4520                        && TREE_CODE (decl) == TYPE_DECL
4521                        && i < ntparms - 1
4522                        && template_parameter_pack_p (TREE_VALUE (parm)))
4523                 {
4524                   /* A primary class template can only have one
4525                      parameter pack, at the end of the template
4526                      parameter list.  */
4527
4528                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4529                     error ("parameter pack %qE must be at the end of the"
4530                            " template parameter list", TREE_VALUE (parm));
4531                   else
4532                     error ("parameter pack %qT must be at the end of the"
4533                            " template parameter list", 
4534                            TREE_TYPE (TREE_VALUE (parm)));
4535
4536                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4537                     = error_mark_node;
4538                   no_errors = false;
4539                 }
4540             }
4541         }
4542     }
4543
4544   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4545       || is_partial 
4546       || !is_primary
4547       || is_friend_decl)
4548     /* For an ordinary class template, default template arguments are
4549        allowed at the innermost level, e.g.:
4550          template <class T = int>
4551          struct S {};
4552        but, in a partial specialization, they're not allowed even
4553        there, as we have in [temp.class.spec]:
4554
4555          The template parameter list of a specialization shall not
4556          contain default template argument values.
4557
4558        So, for a partial specialization, or for a function template
4559        (in C++98/C++03), we look at all of them.  */
4560     ;
4561   else
4562     /* But, for a primary class template that is not a partial
4563        specialization we look at all template parameters except the
4564        innermost ones.  */
4565     parms = TREE_CHAIN (parms);
4566
4567   /* Figure out what error message to issue.  */
4568   if (is_friend_decl == 2)
4569     msg = G_("default template arguments may not be used in function template "
4570              "friend re-declaration");
4571   else if (is_friend_decl)
4572     msg = G_("default template arguments may not be used in function template "
4573              "friend declarations");
4574   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4575     msg = G_("default template arguments may not be used in function templates "
4576              "without -std=c++0x or -std=gnu++0x");
4577   else if (is_partial)
4578     msg = G_("default template arguments may not be used in "
4579              "partial specializations");
4580   else
4581     msg = G_("default argument for template parameter for class enclosing %qD");
4582
4583   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4584     /* If we're inside a class definition, there's no need to
4585        examine the parameters to the class itself.  On the one
4586        hand, they will be checked when the class is defined, and,
4587        on the other, default arguments are valid in things like:
4588          template <class T = double>
4589          struct S { template <class U> void f(U); };
4590        Here the default argument for `S' has no bearing on the
4591        declaration of `f'.  */
4592     last_level_to_check = template_class_depth (current_class_type) + 1;
4593   else
4594     /* Check everything.  */
4595     last_level_to_check = 0;
4596
4597   for (parm_level = parms;
4598        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4599        parm_level = TREE_CHAIN (parm_level))
4600     {
4601       tree inner_parms = TREE_VALUE (parm_level);
4602       int i;
4603       int ntparms;
4604
4605       ntparms = TREE_VEC_LENGTH (inner_parms);
4606       for (i = 0; i < ntparms; ++i)
4607         {
4608           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4609             continue;
4610
4611           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4612             {
4613               if (msg)
4614                 {
4615                   no_errors = false;
4616                   if (is_friend_decl == 2)
4617                     return no_errors;
4618
4619                   error (msg, decl);
4620                   msg = 0;
4621                 }
4622
4623               /* Clear out the default argument so that we are not
4624                  confused later.  */
4625               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4626             }
4627         }
4628
4629       /* At this point, if we're still interested in issuing messages,
4630          they must apply to classes surrounding the object declared.  */
4631       if (msg)
4632         msg = G_("default argument for template parameter for class "
4633                  "enclosing %qD");
4634     }
4635
4636   return no_errors;
4637 }
4638
4639 /* Worker for push_template_decl_real, called via
4640    for_each_template_parm.  DATA is really an int, indicating the
4641    level of the parameters we are interested in.  If T is a template
4642    parameter of that level, return nonzero.  */
4643
4644 static int
4645 template_parm_this_level_p (tree t, void* data)
4646 {
4647   int this_level = *(int *)data;
4648   int level;
4649
4650   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4651     level = TEMPLATE_PARM_LEVEL (t);
4652   else
4653     level = TEMPLATE_TYPE_LEVEL (t);
4654   return level == this_level;
4655 }
4656
4657 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4658    parameters given by current_template_args, or reuses a
4659    previously existing one, if appropriate.  Returns the DECL, or an
4660    equivalent one, if it is replaced via a call to duplicate_decls.
4661
4662    If IS_FRIEND is true, DECL is a friend declaration.  */
4663
4664 tree
4665 push_template_decl_real (tree decl, bool is_friend)
4666 {
4667   tree tmpl;
4668   tree args;
4669   tree info;
4670   tree ctx;
4671   int primary;
4672   int is_partial;
4673   int new_template_p = 0;
4674   /* True if the template is a member template, in the sense of
4675      [temp.mem].  */
4676   bool member_template_p = false;
4677
4678   if (decl == error_mark_node || !current_template_parms)
4679     return error_mark_node;
4680
4681   /* See if this is a partial specialization.  */
4682   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4683                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4684                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4685
4686   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4687     is_friend = true;
4688
4689   if (is_friend)
4690     /* For a friend, we want the context of the friend function, not
4691        the type of which it is a friend.  */
4692     ctx = CP_DECL_CONTEXT (decl);
4693   else if (CP_DECL_CONTEXT (decl)
4694            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4695     /* In the case of a virtual function, we want the class in which
4696        it is defined.  */
4697     ctx = CP_DECL_CONTEXT (decl);
4698   else
4699     /* Otherwise, if we're currently defining some class, the DECL
4700        is assumed to be a member of the class.  */
4701     ctx = current_scope ();
4702
4703   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4704     ctx = NULL_TREE;
4705
4706   if (!DECL_CONTEXT (decl))
4707     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4708
4709   /* See if this is a primary template.  */
4710   if (is_friend && ctx)
4711     /* A friend template that specifies a class context, i.e.
4712          template <typename T> friend void A<T>::f();
4713        is not primary.  */
4714     primary = 0;
4715   else
4716     primary = template_parm_scope_p ();
4717
4718   if (primary)
4719     {
4720       if (DECL_CLASS_SCOPE_P (decl))
4721         member_template_p = true;
4722       if (TREE_CODE (decl) == TYPE_DECL
4723           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4724         {
4725           error ("template class without a name");
4726           return error_mark_node;
4727         }
4728       else if (TREE_CODE (decl) == FUNCTION_DECL)
4729         {
4730           if (DECL_DESTRUCTOR_P (decl))
4731             {
4732               /* [temp.mem]
4733
4734                  A destructor shall not be a member template.  */
4735               error ("destructor %qD declared as member template", decl);
4736               return error_mark_node;
4737             }
4738           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4739               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
4740                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4741                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4742                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4743                       == void_list_node)))
4744             {
4745               /* [basic.stc.dynamic.allocation]
4746
4747                  An allocation function can be a function
4748                  template. ... Template allocation functions shall
4749                  have two or more parameters.  */
4750               error ("invalid template declaration of %qD", decl);
4751               return error_mark_node;
4752             }
4753         }
4754       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4755                && CLASS_TYPE_P (TREE_TYPE (decl)))
4756         /* OK */;
4757       else
4758         {
4759           error ("template declaration of %q#D", decl);
4760           return error_mark_node;
4761         }
4762     }
4763
4764   /* Check to see that the rules regarding the use of default
4765      arguments are not being violated.  */
4766   check_default_tmpl_args (decl, current_template_parms,
4767                            primary, is_partial, /*is_friend_decl=*/0);
4768
4769   /* Ensure that there are no parameter packs in the type of this
4770      declaration that have not been expanded.  */
4771   if (TREE_CODE (decl) == FUNCTION_DECL)
4772     {
4773       /* Check each of the arguments individually to see if there are
4774          any bare parameter packs.  */
4775       tree type = TREE_TYPE (decl);
4776       tree arg = DECL_ARGUMENTS (decl);
4777       tree argtype = TYPE_ARG_TYPES (type);
4778
4779       while (arg && argtype)
4780         {
4781           if (!FUNCTION_PARAMETER_PACK_P (arg)
4782               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4783             {
4784             /* This is a PARM_DECL that contains unexpanded parameter
4785                packs. We have already complained about this in the
4786                check_for_bare_parameter_packs call, so just replace
4787                these types with ERROR_MARK_NODE.  */
4788               TREE_TYPE (arg) = error_mark_node;
4789               TREE_VALUE (argtype) = error_mark_node;
4790             }
4791
4792           arg = DECL_CHAIN (arg);
4793           argtype = TREE_CHAIN (argtype);
4794         }
4795
4796       /* Check for bare parameter packs in the return type and the
4797          exception specifiers.  */
4798       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4799         /* Errors were already issued, set return type to int
4800            as the frontend doesn't expect error_mark_node as
4801            the return type.  */
4802         TREE_TYPE (type) = integer_type_node;
4803       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4804         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4805     }
4806   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4807     {
4808       TREE_TYPE (decl) = error_mark_node;
4809       return error_mark_node;
4810     }
4811
4812   if (is_partial)
4813     return process_partial_specialization (decl);
4814
4815   args = current_template_args ();
4816
4817   if (!ctx
4818       || TREE_CODE (ctx) == FUNCTION_DECL
4819       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4820       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4821     {
4822       if (DECL_LANG_SPECIFIC (decl)
4823           && DECL_TEMPLATE_INFO (decl)
4824           && DECL_TI_TEMPLATE (decl))
4825         tmpl = DECL_TI_TEMPLATE (decl);
4826       /* If DECL is a TYPE_DECL for a class-template, then there won't
4827          be DECL_LANG_SPECIFIC.  The information equivalent to
4828          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4829       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4830                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4831                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4832         {
4833           /* Since a template declaration already existed for this
4834              class-type, we must be redeclaring it here.  Make sure
4835              that the redeclaration is valid.  */
4836           redeclare_class_template (TREE_TYPE (decl),
4837                                     current_template_parms);
4838           /* We don't need to create a new TEMPLATE_DECL; just use the
4839              one we already had.  */
4840           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4841         }
4842       else
4843         {
4844           tmpl = build_template_decl (decl, current_template_parms,
4845                                       member_template_p);
4846           new_template_p = 1;
4847
4848           if (DECL_LANG_SPECIFIC (decl)
4849               && DECL_TEMPLATE_SPECIALIZATION (decl))
4850             {
4851               /* A specialization of a member template of a template
4852                  class.  */
4853               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4854               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4855               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4856             }
4857         }
4858     }
4859   else
4860     {
4861       tree a, t, current, parms;
4862       int i;
4863       tree tinfo = get_template_info (decl);
4864
4865       if (!tinfo)
4866         {
4867           error ("template definition of non-template %q#D", decl);
4868           return error_mark_node;
4869         }
4870
4871       tmpl = TI_TEMPLATE (tinfo);
4872
4873       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4874           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4875           && DECL_TEMPLATE_SPECIALIZATION (decl)
4876           && DECL_MEMBER_TEMPLATE_P (tmpl))
4877         {
4878           tree new_tmpl;
4879
4880           /* The declaration is a specialization of a member
4881              template, declared outside the class.  Therefore, the
4882              innermost template arguments will be NULL, so we
4883              replace them with the arguments determined by the
4884              earlier call to check_explicit_specialization.  */
4885           args = DECL_TI_ARGS (decl);
4886
4887           new_tmpl
4888             = build_template_decl (decl, current_template_parms,
4889                                    member_template_p);
4890           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4891           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4892           DECL_TI_TEMPLATE (decl) = new_tmpl;
4893           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4894           DECL_TEMPLATE_INFO (new_tmpl)
4895             = build_template_info (tmpl, args);
4896
4897           register_specialization (new_tmpl,
4898                                    most_general_template (tmpl),
4899                                    args,
4900                                    is_friend, 0);
4901           return decl;
4902         }
4903
4904       /* Make sure the template headers we got make sense.  */
4905
4906       parms = DECL_TEMPLATE_PARMS (tmpl);
4907       i = TMPL_PARMS_DEPTH (parms);
4908       if (TMPL_ARGS_DEPTH (args) != i)
4909         {
4910           error ("expected %d levels of template parms for %q#D, got %d",
4911                  i, decl, TMPL_ARGS_DEPTH (args));
4912         }
4913       else
4914         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4915           {
4916             a = TMPL_ARGS_LEVEL (args, i);
4917             t = INNERMOST_TEMPLATE_PARMS (parms);
4918
4919             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4920               {
4921                 if (current == decl)
4922                   error ("got %d template parameters for %q#D",
4923                          TREE_VEC_LENGTH (a), decl);
4924                 else
4925                   error ("got %d template parameters for %q#T",
4926                          TREE_VEC_LENGTH (a), current);
4927                 error ("  but %d required", TREE_VEC_LENGTH (t));
4928                 return error_mark_node;
4929               }
4930
4931             if (current == decl)
4932               current = ctx;
4933             else if (current == NULL_TREE)
4934               /* Can happen in erroneous input.  */
4935               break;
4936             else
4937               current = (TYPE_P (current)
4938                          ? TYPE_CONTEXT (current)
4939                          : DECL_CONTEXT (current));
4940           }
4941
4942       /* Check that the parms are used in the appropriate qualifying scopes
4943          in the declarator.  */
4944       if (!comp_template_args
4945           (TI_ARGS (tinfo),
4946            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4947         {
4948           error ("\
4949 template arguments to %qD do not match original template %qD",
4950                  decl, DECL_TEMPLATE_RESULT (tmpl));
4951           if (!uses_template_parms (TI_ARGS (tinfo)))
4952             inform (input_location, "use template<> for an explicit specialization");
4953           /* Avoid crash in import_export_decl.  */
4954           DECL_INTERFACE_KNOWN (decl) = 1;
4955           return error_mark_node;
4956         }
4957     }
4958
4959   DECL_TEMPLATE_RESULT (tmpl) = decl;
4960   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4961
4962   /* Push template declarations for global functions and types.  Note
4963      that we do not try to push a global template friend declared in a
4964      template class; such a thing may well depend on the template
4965      parameters of the class.  */
4966   if (new_template_p && !ctx
4967       && !(is_friend && template_class_depth (current_class_type) > 0))
4968     {
4969       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4970       if (tmpl == error_mark_node)
4971         return error_mark_node;
4972
4973       /* Hide template friend classes that haven't been declared yet.  */
4974       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4975         {
4976           DECL_ANTICIPATED (tmpl) = 1;
4977           DECL_FRIEND_P (tmpl) = 1;
4978         }
4979     }
4980
4981   if (primary)
4982     {
4983       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4984       int i;
4985
4986       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4987       if (DECL_CONV_FN_P (tmpl))
4988         {
4989           int depth = TMPL_PARMS_DEPTH (parms);
4990
4991           /* It is a conversion operator. See if the type converted to
4992              depends on innermost template operands.  */
4993
4994           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4995                                          depth))
4996             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4997         }
4998
4999       /* Give template template parms a DECL_CONTEXT of the template
5000          for which they are a parameter.  */
5001       parms = INNERMOST_TEMPLATE_PARMS (parms);
5002       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
5003         {
5004           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5005           if (TREE_CODE (parm) == TEMPLATE_DECL)
5006             DECL_CONTEXT (parm) = tmpl;
5007         }
5008     }
5009
5010   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
5011      back to its most general template.  If TMPL is a specialization,
5012      ARGS may only have the innermost set of arguments.  Add the missing
5013      argument levels if necessary.  */
5014   if (DECL_TEMPLATE_INFO (tmpl))
5015     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
5016
5017   info = build_template_info (tmpl, args);
5018
5019   if (DECL_IMPLICIT_TYPEDEF_P (decl))
5020     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
5021   else if (DECL_LANG_SPECIFIC (decl))
5022     DECL_TEMPLATE_INFO (decl) = info;
5023
5024   return DECL_TEMPLATE_RESULT (tmpl);
5025 }
5026
5027 tree
5028 push_template_decl (tree decl)
5029 {
5030   return push_template_decl_real (decl, false);
5031 }
5032
5033 /* Called when a class template TYPE is redeclared with the indicated
5034    template PARMS, e.g.:
5035
5036      template <class T> struct S;
5037      template <class T> struct S {};  */
5038
5039 bool
5040 redeclare_class_template (tree type, tree parms)
5041 {
5042   tree tmpl;
5043   tree tmpl_parms;
5044   int i;
5045
5046   if (!TYPE_TEMPLATE_INFO (type))
5047     {
5048       error ("%qT is not a template type", type);
5049       return false;
5050     }
5051
5052   tmpl = TYPE_TI_TEMPLATE (type);
5053   if (!PRIMARY_TEMPLATE_P (tmpl))
5054     /* The type is nested in some template class.  Nothing to worry
5055        about here; there are no new template parameters for the nested
5056        type.  */
5057     return true;
5058
5059   if (!parms)
5060     {
5061       error ("template specifiers not specified in declaration of %qD",
5062              tmpl);
5063       return false;
5064     }
5065
5066   parms = INNERMOST_TEMPLATE_PARMS (parms);
5067   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
5068
5069   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
5070     {
5071       error_n (input_location, TREE_VEC_LENGTH (parms),
5072                "redeclared with %d template parameter",
5073                "redeclared with %d template parameters",
5074                TREE_VEC_LENGTH (parms));
5075       inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
5076                 "previous declaration %q+D used %d template parameter",
5077                 "previous declaration %q+D used %d template parameters",
5078                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
5079       return false;
5080     }
5081
5082   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
5083     {
5084       tree tmpl_parm;
5085       tree parm;
5086       tree tmpl_default;
5087       tree parm_default;
5088
5089       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
5090           || TREE_VEC_ELT (parms, i) == error_mark_node)
5091         continue;
5092
5093       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
5094       if (tmpl_parm == error_mark_node)
5095         return false;
5096
5097       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5098       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
5099       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
5100
5101       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
5102          TEMPLATE_DECL.  */
5103       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
5104           || (TREE_CODE (tmpl_parm) != TYPE_DECL
5105               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
5106           || (TREE_CODE (tmpl_parm) != PARM_DECL
5107               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
5108                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
5109           || (TREE_CODE (tmpl_parm) == PARM_DECL
5110               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
5111                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
5112         {
5113           error ("template parameter %q+#D", tmpl_parm);
5114           error ("redeclared here as %q#D", parm);
5115           return false;
5116         }
5117
5118       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
5119         {
5120           /* We have in [temp.param]:
5121
5122              A template-parameter may not be given default arguments
5123              by two different declarations in the same scope.  */
5124           error_at (input_location, "redefinition of default argument for %q#D", parm);
5125           inform (DECL_SOURCE_LOCATION (tmpl_parm),
5126                   "original definition appeared here");
5127           return false;
5128         }
5129
5130       if (parm_default != NULL_TREE)
5131         /* Update the previous template parameters (which are the ones
5132            that will really count) with the new default value.  */
5133         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
5134       else if (tmpl_default != NULL_TREE)
5135         /* Update the new parameters, too; they'll be used as the
5136            parameters for any members.  */
5137         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
5138     }
5139
5140     return true;
5141 }
5142
5143 /* Simplify EXPR if it is a non-dependent expression.  Returns the
5144    (possibly simplified) expression.  */
5145
5146 static tree
5147 fold_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
5148 {
5149   if (expr == NULL_TREE)
5150     return NULL_TREE;
5151
5152   /* If we're in a template, but EXPR isn't value dependent, simplify
5153      it.  We're supposed to treat:
5154
5155        template <typename T> void f(T[1 + 1]);
5156        template <typename T> void f(T[2]);
5157
5158      as two declarations of the same function, for example.  */
5159   if (processing_template_decl
5160       && !type_dependent_expression_p (expr)
5161       && !value_dependent_expression_p (expr))
5162     {
5163       HOST_WIDE_INT saved_processing_template_decl;
5164
5165       saved_processing_template_decl = processing_template_decl;
5166       processing_template_decl = 0;
5167       expr = tsubst_copy_and_build (expr,
5168                                     /*args=*/NULL_TREE,
5169                                     complain,
5170                                     /*in_decl=*/NULL_TREE,
5171                                     /*function_p=*/false,
5172                                     /*integral_constant_expression_p=*/true);
5173       processing_template_decl = saved_processing_template_decl;
5174     }
5175   return expr;
5176 }
5177
5178 tree
5179 fold_non_dependent_expr (tree expr)
5180 {
5181   return fold_non_dependent_expr_sfinae (expr, tf_error);
5182 }
5183
5184 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
5185    must be a function or a pointer-to-function type, as specified
5186    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
5187    and check that the resulting function has external linkage.  */
5188
5189 static tree
5190 convert_nontype_argument_function (tree type, tree expr)
5191 {
5192   tree fns = expr;
5193   tree fn, fn_no_ptr;
5194
5195   fn = instantiate_type (type, fns, tf_none);
5196   if (fn == error_mark_node)
5197     return error_mark_node;
5198
5199   fn_no_ptr = fn;
5200   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
5201     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
5202   if (TREE_CODE (fn_no_ptr) == BASELINK)
5203     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
5204  
5205   /* [temp.arg.nontype]/1
5206
5207      A template-argument for a non-type, non-template template-parameter
5208      shall be one of:
5209      [...]
5210      -- the address of an object or function with external linkage.  */
5211   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
5212     {
5213       error ("%qE is not a valid template argument for type %qT "
5214              "because function %qD has not external linkage",
5215              expr, type, fn_no_ptr);
5216       return NULL_TREE;
5217     }
5218
5219   return fn;
5220 }
5221
5222 /* Subroutine of convert_nontype_argument.
5223    Check if EXPR of type TYPE is a valid pointer-to-member constant.
5224    Emit an error otherwise.  */
5225
5226 static bool
5227 check_valid_ptrmem_cst_expr (tree type, tree expr,
5228                              tsubst_flags_t complain)
5229 {
5230   STRIP_NOPS (expr);
5231   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
5232     return true;
5233   if (complain & tf_error)
5234     {
5235       error ("%qE is not a valid template argument for type %qT",
5236              expr, type);
5237       error ("it must be a pointer-to-member of the form `&X::Y'");
5238     }
5239   return false;
5240 }
5241
5242 /* Returns TRUE iff the address of OP is value-dependent.
5243
5244    14.6.2.4 [temp.dep.temp]:
5245    A non-integral non-type template-argument is dependent if its type is
5246    dependent or it has either of the following forms
5247      qualified-id
5248      & qualified-id
5249    and contains a nested-name-specifier which specifies a class-name that
5250    names a dependent type.
5251
5252    We generalize this to just say that the address of a member of a
5253    dependent class is value-dependent; the above doesn't cover the
5254    address of a static data member named with an unqualified-id.  */
5255
5256 static bool
5257 has_value_dependent_address (tree op)
5258 {
5259   /* We could use get_inner_reference here, but there's no need;
5260      this is only relevant for template non-type arguments, which
5261      can only be expressed as &id-expression.  */
5262   if (DECL_P (op))
5263     {
5264       tree ctx = CP_DECL_CONTEXT (op);
5265       if (TYPE_P (ctx) && dependent_type_p (ctx))
5266         return true;
5267     }
5268
5269   return false;
5270 }
5271
5272 /* Attempt to convert the non-type template parameter EXPR to the
5273    indicated TYPE.  If the conversion is successful, return the
5274    converted value.  If the conversion is unsuccessful, return
5275    NULL_TREE if we issued an error message, or error_mark_node if we
5276    did not.  We issue error messages for out-and-out bad template
5277    parameters, but not simply because the conversion failed, since we
5278    might be just trying to do argument deduction.  Both TYPE and EXPR
5279    must be non-dependent.
5280
5281    The conversion follows the special rules described in
5282    [temp.arg.nontype], and it is much more strict than an implicit
5283    conversion.
5284
5285    This function is called twice for each template argument (see
5286    lookup_template_class for a more accurate description of this
5287    problem). This means that we need to handle expressions which
5288    are not valid in a C++ source, but can be created from the
5289    first call (for instance, casts to perform conversions). These
5290    hacks can go away after we fix the double coercion problem.  */
5291
5292 static tree
5293 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
5294 {
5295   tree expr_type;
5296
5297   /* Detect immediately string literals as invalid non-type argument.
5298      This special-case is not needed for correctness (we would easily
5299      catch this later), but only to provide better diagnostic for this
5300      common user mistake. As suggested by DR 100, we do not mention
5301      linkage issues in the diagnostic as this is not the point.  */
5302   /* FIXME we're making this OK.  */
5303   if (TREE_CODE (expr) == STRING_CST)
5304     {
5305       if (complain & tf_error)
5306         error ("%qE is not a valid template argument for type %qT "
5307                "because string literals can never be used in this context",
5308                expr, type);
5309       return NULL_TREE;
5310     }
5311
5312   /* Add the ADDR_EXPR now for the benefit of
5313      value_dependent_expression_p.  */
5314   if (TYPE_PTROBV_P (type))
5315     expr = decay_conversion (expr);
5316
5317   /* If we are in a template, EXPR may be non-dependent, but still
5318      have a syntactic, rather than semantic, form.  For example, EXPR
5319      might be a SCOPE_REF, rather than the VAR_DECL to which the
5320      SCOPE_REF refers.  Preserving the qualifying scope is necessary
5321      so that access checking can be performed when the template is
5322      instantiated -- but here we need the resolved form so that we can
5323      convert the argument.  */
5324   if (TYPE_REF_OBJ_P (type)
5325       && has_value_dependent_address (expr))
5326     /* If we want the address and it's value-dependent, don't fold.  */;
5327   else if (!type_unknown_p (expr))
5328     expr = fold_non_dependent_expr_sfinae (expr, complain);
5329   if (error_operand_p (expr))
5330     return error_mark_node;
5331   expr_type = TREE_TYPE (expr);
5332   if (TREE_CODE (type) == REFERENCE_TYPE)
5333     expr = mark_lvalue_use (expr);
5334   else
5335     expr = mark_rvalue_use (expr);
5336
5337   /* HACK: Due to double coercion, we can get a
5338      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
5339      which is the tree that we built on the first call (see
5340      below when coercing to reference to object or to reference to
5341      function). We just strip everything and get to the arg.
5342      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
5343      for examples.  */
5344   if (TREE_CODE (expr) == NOP_EXPR)
5345     {
5346       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
5347         {
5348           /* ??? Maybe we could use convert_from_reference here, but we
5349              would need to relax its constraints because the NOP_EXPR
5350              could actually change the type to something more cv-qualified,
5351              and this is not folded by convert_from_reference.  */
5352           tree addr = TREE_OPERAND (expr, 0);
5353           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
5354           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
5355           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
5356           gcc_assert (same_type_ignoring_top_level_qualifiers_p
5357                       (TREE_TYPE (expr_type),
5358                        TREE_TYPE (TREE_TYPE (addr))));
5359
5360           expr = TREE_OPERAND (addr, 0);
5361           expr_type = TREE_TYPE (expr);
5362         }
5363
5364       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
5365          parameter is a pointer to object, through decay and
5366          qualification conversion. Let's strip everything.  */
5367       else if (TYPE_PTROBV_P (type))
5368         {
5369           STRIP_NOPS (expr);
5370           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
5371           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
5372           /* Skip the ADDR_EXPR only if it is part of the decay for
5373              an array. Otherwise, it is part of the original argument
5374              in the source code.  */
5375           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
5376             expr = TREE_OPERAND (expr, 0);
5377           expr_type = TREE_TYPE (expr);
5378         }
5379     }
5380
5381   /* [temp.arg.nontype]/5, bullet 1
5382
5383      For a non-type template-parameter of integral or enumeration type,
5384      integral promotions (_conv.prom_) and integral conversions
5385      (_conv.integral_) are applied.  */
5386   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5387     {
5388       tree t = build_integral_nontype_arg_conv (type, expr, complain);
5389       t = maybe_constant_value (t);
5390       if (t != error_mark_node)
5391         expr = t;
5392
5393       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
5394         return error_mark_node;
5395
5396       /* Notice that there are constant expressions like '4 % 0' which
5397          do not fold into integer constants.  */
5398       if (TREE_CODE (expr) != INTEGER_CST)
5399         {
5400           if (complain & tf_error)
5401             {
5402               error ("%qE is not a valid template argument for type %qT "
5403                      "because it is a non-constant expression", expr, type);
5404               cxx_constant_value (expr);
5405             }
5406           return NULL_TREE;
5407         }
5408     }
5409   /* [temp.arg.nontype]/5, bullet 2
5410
5411      For a non-type template-parameter of type pointer to object,
5412      qualification conversions (_conv.qual_) and the array-to-pointer
5413      conversion (_conv.array_) are applied.  */
5414   else if (TYPE_PTROBV_P (type))
5415     {
5416       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
5417
5418          A template-argument for a non-type, non-template template-parameter
5419          shall be one of: [...]
5420
5421          -- the name of a non-type template-parameter;
5422          -- the address of an object or function with external linkage, [...]
5423             expressed as "& id-expression" where the & is optional if the name
5424             refers to a function or array, or if the corresponding
5425             template-parameter is a reference.
5426
5427         Here, we do not care about functions, as they are invalid anyway
5428         for a parameter of type pointer-to-object.  */
5429
5430       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
5431         /* Non-type template parameters are OK.  */
5432         ;
5433       else if (TREE_CODE (expr) != ADDR_EXPR
5434                && TREE_CODE (expr_type) != ARRAY_TYPE)
5435         {
5436           if (TREE_CODE (expr) == VAR_DECL)
5437             {
5438               error ("%qD is not a valid template argument "
5439                      "because %qD is a variable, not the address of "
5440                      "a variable",
5441                      expr, expr);
5442               return NULL_TREE;
5443             }
5444           /* Other values, like integer constants, might be valid
5445              non-type arguments of some other type.  */
5446           return error_mark_node;
5447         }
5448       else
5449         {
5450           tree decl;
5451
5452           decl = ((TREE_CODE (expr) == ADDR_EXPR)
5453                   ? TREE_OPERAND (expr, 0) : expr);
5454           if (TREE_CODE (decl) != VAR_DECL)
5455             {
5456               error ("%qE is not a valid template argument of type %qT "
5457                      "because %qE is not a variable",
5458                      expr, type, decl);
5459               return NULL_TREE;
5460             }
5461           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
5462             {
5463               error ("%qE is not a valid template argument of type %qT "
5464                      "because %qD does not have external linkage",
5465                      expr, type, decl);
5466               return NULL_TREE;
5467             }
5468         }
5469
5470       expr = decay_conversion (expr);
5471       if (expr == error_mark_node)
5472         return error_mark_node;
5473
5474       expr = perform_qualification_conversions (type, expr);
5475       if (expr == error_mark_node)
5476         return error_mark_node;
5477     }
5478   /* [temp.arg.nontype]/5, bullet 3
5479
5480      For a non-type template-parameter of type reference to object, no
5481      conversions apply. The type referred to by the reference may be more
5482      cv-qualified than the (otherwise identical) type of the
5483      template-argument. The template-parameter is bound directly to the
5484      template-argument, which must be an lvalue.  */
5485   else if (TYPE_REF_OBJ_P (type))
5486     {
5487       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5488                                                       expr_type))
5489         return error_mark_node;
5490
5491       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5492         {
5493           error ("%qE is not a valid template argument for type %qT "
5494                  "because of conflicts in cv-qualification", expr, type);
5495           return NULL_TREE;
5496         }
5497
5498       if (!real_lvalue_p (expr))
5499         {
5500           error ("%qE is not a valid template argument for type %qT "
5501                  "because it is not an lvalue", expr, type);
5502           return NULL_TREE;
5503         }
5504
5505       /* [temp.arg.nontype]/1
5506
5507          A template-argument for a non-type, non-template template-parameter
5508          shall be one of: [...]
5509
5510          -- the address of an object or function with external linkage.  */
5511       if (TREE_CODE (expr) == INDIRECT_REF
5512           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5513         {
5514           expr = TREE_OPERAND (expr, 0);
5515           if (DECL_P (expr))
5516             {
5517               error ("%q#D is not a valid template argument for type %qT "
5518                      "because a reference variable does not have a constant "
5519                      "address", expr, type);
5520               return NULL_TREE;
5521             }
5522         }
5523
5524       if (!DECL_P (expr))
5525         {
5526           error ("%qE is not a valid template argument for type %qT "
5527                  "because it is not an object with external linkage",
5528                  expr, type);
5529           return NULL_TREE;
5530         }
5531
5532       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5533         {
5534           error ("%qE is not a valid template argument for type %qT "
5535                  "because object %qD has not external linkage",
5536                  expr, type, expr);
5537           return NULL_TREE;
5538         }
5539
5540       expr = build_nop (type, build_address (expr));
5541     }
5542   /* [temp.arg.nontype]/5, bullet 4
5543
5544      For a non-type template-parameter of type pointer to function, only
5545      the function-to-pointer conversion (_conv.func_) is applied. If the
5546      template-argument represents a set of overloaded functions (or a
5547      pointer to such), the matching function is selected from the set
5548      (_over.over_).  */
5549   else if (TYPE_PTRFN_P (type))
5550     {
5551       /* If the argument is a template-id, we might not have enough
5552          context information to decay the pointer.  */
5553       if (!type_unknown_p (expr_type))
5554         {
5555           expr = decay_conversion (expr);
5556           if (expr == error_mark_node)
5557             return error_mark_node;
5558         }
5559
5560       expr = convert_nontype_argument_function (type, expr);
5561       if (!expr || expr == error_mark_node)
5562         return expr;
5563
5564       if (TREE_CODE (expr) != ADDR_EXPR)
5565         {
5566           error ("%qE is not a valid template argument for type %qT", expr, type);
5567           error ("it must be the address of a function with external linkage");
5568           return NULL_TREE;
5569         }
5570     }
5571   /* [temp.arg.nontype]/5, bullet 5
5572
5573      For a non-type template-parameter of type reference to function, no
5574      conversions apply. If the template-argument represents a set of
5575      overloaded functions, the matching function is selected from the set
5576      (_over.over_).  */
5577   else if (TYPE_REFFN_P (type))
5578     {
5579       if (TREE_CODE (expr) == ADDR_EXPR)
5580         {
5581           error ("%qE is not a valid template argument for type %qT "
5582                  "because it is a pointer", expr, type);
5583           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5584           return NULL_TREE;
5585         }
5586
5587       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5588       if (!expr || expr == error_mark_node)
5589         return expr;
5590
5591       expr = build_nop (type, build_address (expr));
5592     }
5593   /* [temp.arg.nontype]/5, bullet 6
5594
5595      For a non-type template-parameter of type pointer to member function,
5596      no conversions apply. If the template-argument represents a set of
5597      overloaded member functions, the matching member function is selected
5598      from the set (_over.over_).  */
5599   else if (TYPE_PTRMEMFUNC_P (type))
5600     {
5601       expr = instantiate_type (type, expr, tf_none);
5602       if (expr == error_mark_node)
5603         return error_mark_node;
5604
5605       /* [temp.arg.nontype] bullet 1 says the pointer to member
5606          expression must be a pointer-to-member constant.  */
5607       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5608         return error_mark_node;
5609
5610       /* There is no way to disable standard conversions in
5611          resolve_address_of_overloaded_function (called by
5612          instantiate_type). It is possible that the call succeeded by
5613          converting &B::I to &D::I (where B is a base of D), so we need
5614          to reject this conversion here.
5615
5616          Actually, even if there was a way to disable standard conversions,
5617          it would still be better to reject them here so that we can
5618          provide a superior diagnostic.  */
5619       if (!same_type_p (TREE_TYPE (expr), type))
5620         {
5621           error ("%qE is not a valid template argument for type %qT "
5622                  "because it is of type %qT", expr, type,
5623                  TREE_TYPE (expr));
5624           /* If we are just one standard conversion off, explain.  */
5625           if (can_convert (type, TREE_TYPE (expr)))
5626             inform (input_location,
5627                     "standard conversions are not allowed in this context");
5628           return NULL_TREE;
5629         }
5630     }
5631   /* [temp.arg.nontype]/5, bullet 7
5632
5633      For a non-type template-parameter of type pointer to data member,
5634      qualification conversions (_conv.qual_) are applied.  */
5635   else if (TYPE_PTRMEM_P (type))
5636     {
5637       /* [temp.arg.nontype] bullet 1 says the pointer to member
5638          expression must be a pointer-to-member constant.  */
5639       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5640         return error_mark_node;
5641
5642       expr = perform_qualification_conversions (type, expr);
5643       if (expr == error_mark_node)
5644         return expr;
5645     }
5646   /* A template non-type parameter must be one of the above.  */
5647   else
5648     gcc_unreachable ();
5649
5650   /* Sanity check: did we actually convert the argument to the
5651      right type?  */
5652   gcc_assert (same_type_ignoring_top_level_qualifiers_p
5653               (type, TREE_TYPE (expr)));
5654   return expr;
5655 }
5656
5657 /* Subroutine of coerce_template_template_parms, which returns 1 if
5658    PARM_PARM and ARG_PARM match using the rule for the template
5659    parameters of template template parameters. Both PARM and ARG are
5660    template parameters; the rest of the arguments are the same as for
5661    coerce_template_template_parms.
5662  */
5663 static int
5664 coerce_template_template_parm (tree parm,
5665                               tree arg,
5666                               tsubst_flags_t complain,
5667                               tree in_decl,
5668                               tree outer_args)
5669 {
5670   if (arg == NULL_TREE || arg == error_mark_node
5671       || parm == NULL_TREE || parm == error_mark_node)
5672     return 0;
5673   
5674   if (TREE_CODE (arg) != TREE_CODE (parm))
5675     return 0;
5676   
5677   switch (TREE_CODE (parm))
5678     {
5679     case TEMPLATE_DECL:
5680       /* We encounter instantiations of templates like
5681          template <template <template <class> class> class TT>
5682          class C;  */
5683       {
5684         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5685         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5686         
5687         if (!coerce_template_template_parms
5688             (parmparm, argparm, complain, in_decl, outer_args))
5689           return 0;
5690       }
5691       /* Fall through.  */
5692       
5693     case TYPE_DECL:
5694       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5695           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5696         /* Argument is a parameter pack but parameter is not.  */
5697         return 0;
5698       break;
5699       
5700     case PARM_DECL:
5701       /* The tsubst call is used to handle cases such as
5702          
5703            template <int> class C {};
5704            template <class T, template <T> class TT> class D {};
5705            D<int, C> d;
5706
5707          i.e. the parameter list of TT depends on earlier parameters.  */
5708       if (!uses_template_parms (TREE_TYPE (arg))
5709           && !same_type_p
5710                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5711                  TREE_TYPE (arg)))
5712         return 0;
5713       
5714       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5715           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5716         /* Argument is a parameter pack but parameter is not.  */
5717         return 0;
5718       
5719       break;
5720
5721     default:
5722       gcc_unreachable ();
5723     }
5724
5725   return 1;
5726 }
5727
5728
5729 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5730    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5731    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5732    or PARM_DECL.
5733
5734    Consider the example:
5735      template <class T> class A;
5736      template<template <class U> class TT> class B;
5737
5738    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5739    the parameters to A, and OUTER_ARGS contains A.  */
5740
5741 static int
5742 coerce_template_template_parms (tree parm_parms,
5743                                 tree arg_parms,
5744                                 tsubst_flags_t complain,
5745                                 tree in_decl,
5746                                 tree outer_args)
5747 {
5748   int nparms, nargs, i;
5749   tree parm, arg;
5750   int variadic_p = 0;
5751
5752   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5753   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5754
5755   nparms = TREE_VEC_LENGTH (parm_parms);
5756   nargs = TREE_VEC_LENGTH (arg_parms);
5757
5758   /* Determine whether we have a parameter pack at the end of the
5759      template template parameter's template parameter list.  */
5760   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5761     {
5762       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5763       
5764       if (parm == error_mark_node)
5765         return 0;
5766
5767       switch (TREE_CODE (parm))
5768         {
5769         case TEMPLATE_DECL:
5770         case TYPE_DECL:
5771           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5772             variadic_p = 1;
5773           break;
5774           
5775         case PARM_DECL:
5776           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5777             variadic_p = 1;
5778           break;
5779           
5780         default:
5781           gcc_unreachable ();
5782         }
5783     }
5784  
5785   if (nargs != nparms
5786       && !(variadic_p && nargs >= nparms - 1))
5787     return 0;
5788
5789   /* Check all of the template parameters except the parameter pack at
5790      the end (if any).  */
5791   for (i = 0; i < nparms - variadic_p; ++i)
5792     {
5793       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5794           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5795         continue;
5796
5797       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5798       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5799
5800       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5801                                           outer_args))
5802         return 0;
5803
5804     }
5805
5806   if (variadic_p)
5807     {
5808       /* Check each of the template parameters in the template
5809          argument against the template parameter pack at the end of
5810          the template template parameter.  */
5811       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5812         return 0;
5813
5814       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5815
5816       for (; i < nargs; ++i)
5817         {
5818           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5819             continue;
5820  
5821           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5822  
5823           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5824                                               outer_args))
5825             return 0;
5826         }
5827     }
5828
5829   return 1;
5830 }
5831
5832 /* Verifies that the deduced template arguments (in TARGS) for the
5833    template template parameters (in TPARMS) represent valid bindings,
5834    by comparing the template parameter list of each template argument
5835    to the template parameter list of its corresponding template
5836    template parameter, in accordance with DR150. This
5837    routine can only be called after all template arguments have been
5838    deduced. It will return TRUE if all of the template template
5839    parameter bindings are okay, FALSE otherwise.  */
5840 bool 
5841 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5842 {
5843   int i, ntparms = TREE_VEC_LENGTH (tparms);
5844   bool ret = true;
5845
5846   /* We're dealing with template parms in this process.  */
5847   ++processing_template_decl;
5848
5849   targs = INNERMOST_TEMPLATE_ARGS (targs);
5850
5851   for (i = 0; i < ntparms; ++i)
5852     {
5853       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5854       tree targ = TREE_VEC_ELT (targs, i);
5855
5856       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5857         {
5858           tree packed_args = NULL_TREE;
5859           int idx, len = 1;
5860
5861           if (ARGUMENT_PACK_P (targ))
5862             {
5863               /* Look inside the argument pack.  */
5864               packed_args = ARGUMENT_PACK_ARGS (targ);
5865               len = TREE_VEC_LENGTH (packed_args);
5866             }
5867
5868           for (idx = 0; idx < len; ++idx)
5869             {
5870               tree targ_parms = NULL_TREE;
5871
5872               if (packed_args)
5873                 /* Extract the next argument from the argument
5874                    pack.  */
5875                 targ = TREE_VEC_ELT (packed_args, idx);
5876
5877               if (PACK_EXPANSION_P (targ))
5878                 /* Look at the pattern of the pack expansion.  */
5879                 targ = PACK_EXPANSION_PATTERN (targ);
5880
5881               /* Extract the template parameters from the template
5882                  argument.  */
5883               if (TREE_CODE (targ) == TEMPLATE_DECL)
5884                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5885               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5886                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5887
5888               /* Verify that we can coerce the template template
5889                  parameters from the template argument to the template
5890                  parameter.  This requires an exact match.  */
5891               if (targ_parms
5892                   && !coerce_template_template_parms
5893                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5894                         targ_parms,
5895                         tf_none,
5896                         tparm,
5897                         targs))
5898                 {
5899                   ret = false;
5900                   goto out;
5901                 }
5902             }
5903         }
5904     }
5905
5906  out:
5907
5908   --processing_template_decl;
5909   return ret;
5910 }
5911
5912 /* Convert the indicated template ARG as necessary to match the
5913    indicated template PARM.  Returns the converted ARG, or
5914    error_mark_node if the conversion was unsuccessful.  Error and
5915    warning messages are issued under control of COMPLAIN.  This
5916    conversion is for the Ith parameter in the parameter list.  ARGS is
5917    the full set of template arguments deduced so far.  */
5918
5919 static tree
5920 convert_template_argument (tree parm,
5921                            tree arg,
5922                            tree args,
5923                            tsubst_flags_t complain,
5924                            int i,
5925                            tree in_decl)
5926 {
5927   tree orig_arg;
5928   tree val;
5929   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5930
5931   if (TREE_CODE (arg) == TREE_LIST
5932       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5933     {
5934       /* The template argument was the name of some
5935          member function.  That's usually
5936          invalid, but static members are OK.  In any
5937          case, grab the underlying fields/functions
5938          and issue an error later if required.  */
5939       orig_arg = TREE_VALUE (arg);
5940       TREE_TYPE (arg) = unknown_type_node;
5941     }
5942
5943   orig_arg = arg;
5944
5945   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5946   requires_type = (TREE_CODE (parm) == TYPE_DECL
5947                    || requires_tmpl_type);
5948
5949   /* When determining whether an argument pack expansion is a template,
5950      look at the pattern.  */
5951   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5952     arg = PACK_EXPANSION_PATTERN (arg);
5953
5954   /* Deal with an injected-class-name used as a template template arg.  */
5955   if (requires_tmpl_type && CLASS_TYPE_P (arg))
5956     {
5957       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
5958       if (TREE_CODE (t) == TEMPLATE_DECL)
5959         {
5960           if (complain & tf_warning_or_error)
5961             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
5962                      " used as template template argument", TYPE_NAME (arg));
5963           else if (flag_pedantic_errors)
5964             t = arg;
5965
5966           arg = t;
5967         }
5968     }
5969
5970   is_tmpl_type = 
5971     ((TREE_CODE (arg) == TEMPLATE_DECL
5972       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5973      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5974      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5975
5976   if (is_tmpl_type
5977       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5978           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5979     arg = TYPE_STUB_DECL (arg);
5980
5981   is_type = TYPE_P (arg) || is_tmpl_type;
5982
5983   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
5984       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
5985     {
5986       permerror (input_location, "to refer to a type member of a template parameter, "
5987                  "use %<typename %E%>", orig_arg);
5988
5989       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
5990                                      TREE_OPERAND (arg, 1),
5991                                      typename_type,
5992                                      complain & tf_error);
5993       arg = orig_arg;
5994       is_type = 1;
5995     }
5996   if (is_type != requires_type)
5997     {
5998       if (in_decl)
5999         {
6000           if (complain & tf_error)
6001             {
6002               error ("type/value mismatch at argument %d in template "
6003                      "parameter list for %qD",
6004                      i + 1, in_decl);
6005               if (is_type)
6006                 error ("  expected a constant of type %qT, got %qT",
6007                        TREE_TYPE (parm),
6008                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
6009               else if (requires_tmpl_type)
6010                 error ("  expected a class template, got %qE", orig_arg);
6011               else
6012                 error ("  expected a type, got %qE", orig_arg);
6013             }
6014         }
6015       return error_mark_node;
6016     }
6017   if (is_tmpl_type ^ requires_tmpl_type)
6018     {
6019       if (in_decl && (complain & tf_error))
6020         {
6021           error ("type/value mismatch at argument %d in template "
6022                  "parameter list for %qD",
6023                  i + 1, in_decl);
6024           if (is_tmpl_type)
6025             error ("  expected a type, got %qT", DECL_NAME (arg));
6026           else
6027             error ("  expected a class template, got %qT", orig_arg);
6028         }
6029       return error_mark_node;
6030     }
6031
6032   if (is_type)
6033     {
6034       if (requires_tmpl_type)
6035         {
6036           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
6037             /* The number of argument required is not known yet.
6038                Just accept it for now.  */
6039             val = TREE_TYPE (arg);
6040           else
6041             {
6042               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
6043               tree argparm;
6044
6045               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
6046
6047               if (coerce_template_template_parms (parmparm, argparm,
6048                                                   complain, in_decl,
6049                                                   args))
6050                 {
6051                   val = arg;
6052
6053                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
6054                      TEMPLATE_DECL.  */
6055                   if (val != error_mark_node)
6056                     {
6057                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
6058                         val = TREE_TYPE (val);
6059                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
6060                         val = make_pack_expansion (val);
6061                     }
6062                 }
6063               else
6064                 {
6065                   if (in_decl && (complain & tf_error))
6066                     {
6067                       error ("type/value mismatch at argument %d in "
6068                              "template parameter list for %qD",
6069                              i + 1, in_decl);
6070                       error ("  expected a template of type %qD, got %qT",
6071                              parm, orig_arg);
6072                     }
6073
6074                   val = error_mark_node;
6075                 }
6076             }
6077         }
6078       else
6079         val = orig_arg;
6080       /* We only form one instance of each template specialization.
6081          Therefore, if we use a non-canonical variant (i.e., a
6082          typedef), any future messages referring to the type will use
6083          the typedef, which is confusing if those future uses do not
6084          themselves also use the typedef.  */
6085       if (TYPE_P (val))
6086         val = strip_typedefs (val);
6087     }
6088   else
6089     {
6090       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
6091
6092       if (invalid_nontype_parm_type_p (t, complain))
6093         return error_mark_node;
6094
6095       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
6096         {
6097           if (same_type_p (t, TREE_TYPE (orig_arg)))
6098             val = orig_arg;
6099           else
6100             {
6101               /* Not sure if this is reachable, but it doesn't hurt
6102                  to be robust.  */
6103               error ("type mismatch in nontype parameter pack");
6104               val = error_mark_node;
6105             }
6106         }
6107       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
6108         /* We used to call digest_init here.  However, digest_init
6109            will report errors, which we don't want when complain
6110            is zero.  More importantly, digest_init will try too
6111            hard to convert things: for example, `0' should not be
6112            converted to pointer type at this point according to
6113            the standard.  Accepting this is not merely an
6114            extension, since deciding whether or not these
6115            conversions can occur is part of determining which
6116            function template to call, or whether a given explicit
6117            argument specification is valid.  */
6118         val = convert_nontype_argument (t, orig_arg, complain);
6119       else
6120         val = orig_arg;
6121
6122       if (val == NULL_TREE)
6123         val = error_mark_node;
6124       else if (val == error_mark_node && (complain & tf_error))
6125         error ("could not convert template argument %qE to %qT",  orig_arg, t);
6126
6127       if (TREE_CODE (val) == SCOPE_REF)
6128         {
6129           /* Strip typedefs from the SCOPE_REF.  */
6130           tree type = strip_typedefs (TREE_TYPE (val));
6131           tree scope = strip_typedefs (TREE_OPERAND (val, 0));
6132           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
6133                                       QUALIFIED_NAME_IS_TEMPLATE (val));
6134         }
6135     }
6136
6137   return val;
6138 }
6139
6140 /* Coerces the remaining template arguments in INNER_ARGS (from
6141    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
6142    Returns the coerced argument pack. PARM_IDX is the position of this
6143    parameter in the template parameter list. ARGS is the original
6144    template argument list.  */
6145 static tree
6146 coerce_template_parameter_pack (tree parms,
6147                                 int parm_idx,
6148                                 tree args,
6149                                 tree inner_args,
6150                                 int arg_idx,
6151                                 tree new_args,
6152                                 int* lost,
6153                                 tree in_decl,
6154                                 tsubst_flags_t complain)
6155 {
6156   tree parm = TREE_VEC_ELT (parms, parm_idx);
6157   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6158   tree packed_args;
6159   tree argument_pack;
6160   tree packed_types = NULL_TREE;
6161
6162   if (arg_idx > nargs)
6163     arg_idx = nargs;
6164
6165   packed_args = make_tree_vec (nargs - arg_idx);
6166
6167   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
6168       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
6169     {
6170       /* When the template parameter is a non-type template
6171          parameter pack whose type uses parameter packs, we need
6172          to look at each of the template arguments
6173          separately. Build a vector of the types for these
6174          non-type template parameters in PACKED_TYPES.  */
6175       tree expansion 
6176         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
6177       packed_types = tsubst_pack_expansion (expansion, args,
6178                                             complain, in_decl);
6179
6180       if (packed_types == error_mark_node)
6181         return error_mark_node;
6182
6183       /* Check that we have the right number of arguments.  */
6184       if (arg_idx < nargs
6185           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
6186           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
6187         {
6188           int needed_parms 
6189             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
6190           error ("wrong number of template arguments (%d, should be %d)",
6191                  nargs, needed_parms);
6192           return error_mark_node;
6193         }
6194
6195       /* If we aren't able to check the actual arguments now
6196          (because they haven't been expanded yet), we can at least
6197          verify that all of the types used for the non-type
6198          template parameter pack are, in fact, valid for non-type
6199          template parameters.  */
6200       if (arg_idx < nargs 
6201           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
6202         {
6203           int j, len = TREE_VEC_LENGTH (packed_types);
6204           for (j = 0; j < len; ++j)
6205             {
6206               tree t = TREE_VEC_ELT (packed_types, j);
6207               if (invalid_nontype_parm_type_p (t, complain))
6208                 return error_mark_node;
6209             }
6210         }
6211     }
6212
6213   /* Convert the remaining arguments, which will be a part of the
6214      parameter pack "parm".  */
6215   for (; arg_idx < nargs; ++arg_idx)
6216     {
6217       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
6218       tree actual_parm = TREE_VALUE (parm);
6219
6220       if (packed_types && !PACK_EXPANSION_P (arg))
6221         {
6222           /* When we have a vector of types (corresponding to the
6223              non-type template parameter pack that uses parameter
6224              packs in its type, as mention above), and the
6225              argument is not an expansion (which expands to a
6226              currently unknown number of arguments), clone the
6227              parm and give it the next type in PACKED_TYPES.  */
6228           actual_parm = copy_node (actual_parm);
6229           TREE_TYPE (actual_parm) = 
6230             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
6231         }
6232
6233       if (arg != error_mark_node)
6234         arg = convert_template_argument (actual_parm, 
6235                                          arg, new_args, complain, parm_idx,
6236                                          in_decl);
6237       if (arg == error_mark_node)
6238         (*lost)++;
6239       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
6240     }
6241
6242   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
6243       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
6244     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
6245   else
6246     {
6247       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
6248       TREE_TYPE (argument_pack) 
6249         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
6250       TREE_CONSTANT (argument_pack) = 1;
6251     }
6252
6253   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
6254 #ifdef ENABLE_CHECKING
6255   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
6256                                        TREE_VEC_LENGTH (packed_args));
6257 #endif
6258   return argument_pack;
6259 }
6260
6261 /* Convert all template arguments to their appropriate types, and
6262    return a vector containing the innermost resulting template
6263    arguments.  If any error occurs, return error_mark_node. Error and
6264    warning messages are issued under control of COMPLAIN.
6265
6266    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
6267    for arguments not specified in ARGS.  Otherwise, if
6268    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
6269    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
6270    USE_DEFAULT_ARGS is false, then all arguments must be specified in
6271    ARGS.  */
6272
6273 static tree
6274 coerce_template_parms (tree parms,
6275                        tree args,
6276                        tree in_decl,
6277                        tsubst_flags_t complain,
6278                        bool require_all_args,
6279                        bool use_default_args)
6280 {
6281   int nparms, nargs, parm_idx, arg_idx, lost = 0;
6282   tree inner_args;
6283   tree new_args;
6284   tree new_inner_args;
6285   int saved_unevaluated_operand;
6286   int saved_inhibit_evaluation_warnings;
6287
6288   /* When used as a boolean value, indicates whether this is a
6289      variadic template parameter list. Since it's an int, we can also
6290      subtract it from nparms to get the number of non-variadic
6291      parameters.  */
6292   int variadic_p = 0;
6293
6294   if (args == error_mark_node)
6295     return error_mark_node;
6296
6297   nparms = TREE_VEC_LENGTH (parms);
6298
6299   /* Determine if there are any parameter packs.  */
6300   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
6301     {
6302       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
6303       if (template_parameter_pack_p (tparm))
6304         ++variadic_p;
6305     }
6306
6307   inner_args = INNERMOST_TEMPLATE_ARGS (args);
6308   /* If there are 0 or 1 parameter packs, we need to expand any argument
6309      packs so that we can deduce a parameter pack from some non-packed args
6310      followed by an argument pack, as in variadic85.C.  If there are more
6311      than that, we need to leave argument packs intact so the arguments are
6312      assigned to the right parameter packs.  This should only happen when
6313      dealing with a nested class inside a partial specialization of a class
6314      template, as in variadic92.C.  */
6315   if (variadic_p <= 1)
6316     inner_args = expand_template_argument_pack (inner_args);
6317
6318   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6319   if ((nargs > nparms && !variadic_p)
6320       || (nargs < nparms - variadic_p
6321           && require_all_args
6322           && (!use_default_args
6323               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
6324                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
6325     {
6326       if (complain & tf_error)
6327         {
6328           if (variadic_p)
6329             {
6330               --nparms;
6331               error ("wrong number of template arguments "
6332                      "(%d, should be %d or more)", nargs, nparms);
6333             }
6334           else
6335              error ("wrong number of template arguments "
6336                     "(%d, should be %d)", nargs, nparms);
6337
6338           if (in_decl)
6339             error ("provided for %q+D", in_decl);
6340         }
6341
6342       return error_mark_node;
6343     }
6344
6345   /* We need to evaluate the template arguments, even though this
6346      template-id may be nested within a "sizeof".  */
6347   saved_unevaluated_operand = cp_unevaluated_operand;
6348   cp_unevaluated_operand = 0;
6349   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
6350   c_inhibit_evaluation_warnings = 0;
6351   new_inner_args = make_tree_vec (nparms);
6352   new_args = add_outermost_template_args (args, new_inner_args);
6353   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
6354     {
6355       tree arg;
6356       tree parm;
6357
6358       /* Get the Ith template parameter.  */
6359       parm = TREE_VEC_ELT (parms, parm_idx);
6360  
6361       if (parm == error_mark_node)
6362       {
6363         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
6364         continue;
6365       }
6366
6367       /* Calculate the next argument.  */
6368       if (arg_idx < nargs)
6369         arg = TREE_VEC_ELT (inner_args, arg_idx);
6370       else
6371         arg = NULL_TREE;
6372
6373       if (template_parameter_pack_p (TREE_VALUE (parm))
6374           && !(arg && ARGUMENT_PACK_P (arg)))
6375         {
6376           /* All remaining arguments will be placed in the
6377              template parameter pack PARM.  */
6378           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
6379                                                 inner_args, arg_idx,
6380                                                 new_args, &lost,
6381                                                 in_decl, complain);
6382
6383           /* Store this argument.  */
6384           if (arg == error_mark_node)
6385             lost++;
6386           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
6387
6388           /* We are done with all of the arguments.  */
6389           arg_idx = nargs;
6390           
6391           continue;
6392         }
6393       else if (arg)
6394         {
6395           if (PACK_EXPANSION_P (arg))
6396             {
6397               if (complain & tf_error)
6398                 {
6399                   /* FIXME this restriction was removed by N2555; see
6400                      bug 35722.  */
6401                   /* If ARG is a pack expansion, but PARM is not a
6402                      template parameter pack (if it were, we would have
6403                      handled it above), we're trying to expand into a
6404                      fixed-length argument list.  */
6405                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
6406                     sorry ("cannot expand %<%E%> into a fixed-length "
6407                            "argument list", arg);
6408                   else
6409                     sorry ("cannot expand %<%T%> into a fixed-length "
6410                            "argument list", arg);
6411                 }
6412               return error_mark_node;
6413             }
6414         }
6415       else if (require_all_args)
6416         {
6417           /* There must be a default arg in this case.  */
6418           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
6419                                      complain, in_decl);
6420           /* The position of the first default template argument,
6421              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
6422              Record that.  */
6423           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6424             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
6425         }
6426       else
6427         break;
6428
6429       if (arg == error_mark_node)
6430         {
6431           if (complain & tf_error)
6432             error ("template argument %d is invalid", arg_idx + 1);
6433         }
6434       else if (!arg)
6435         /* This only occurs if there was an error in the template
6436            parameter list itself (which we would already have
6437            reported) that we are trying to recover from, e.g., a class
6438            template with a parameter list such as
6439            template<typename..., typename>.  */
6440         return error_mark_node;
6441       else
6442         arg = convert_template_argument (TREE_VALUE (parm),
6443                                          arg, new_args, complain, 
6444                                          parm_idx, in_decl);
6445
6446       if (arg == error_mark_node)
6447         lost++;
6448       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6449     }
6450   cp_unevaluated_operand = saved_unevaluated_operand;
6451   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6452
6453   if (lost)
6454     return error_mark_node;
6455
6456 #ifdef ENABLE_CHECKING
6457   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6458     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6459                                          TREE_VEC_LENGTH (new_inner_args));
6460 #endif
6461
6462   return new_inner_args;
6463 }
6464
6465 /* Returns 1 if template args OT and NT are equivalent.  */
6466
6467 static int
6468 template_args_equal (tree ot, tree nt)
6469 {
6470   if (nt == ot)
6471     return 1;
6472
6473   if (TREE_CODE (nt) == TREE_VEC)
6474     /* For member templates */
6475     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6476   else if (PACK_EXPANSION_P (ot))
6477     return PACK_EXPANSION_P (nt) 
6478       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6479                               PACK_EXPANSION_PATTERN (nt));
6480   else if (ARGUMENT_PACK_P (ot))
6481     {
6482       int i, len;
6483       tree opack, npack;
6484
6485       if (!ARGUMENT_PACK_P (nt))
6486         return 0;
6487
6488       opack = ARGUMENT_PACK_ARGS (ot);
6489       npack = ARGUMENT_PACK_ARGS (nt);
6490       len = TREE_VEC_LENGTH (opack);
6491       if (TREE_VEC_LENGTH (npack) != len)
6492         return 0;
6493       for (i = 0; i < len; ++i)
6494         if (!template_args_equal (TREE_VEC_ELT (opack, i),
6495                                   TREE_VEC_ELT (npack, i)))
6496           return 0;
6497       return 1;
6498     }
6499   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6500     {
6501       /* We get here probably because we are in the middle of substituting
6502          into the pattern of a pack expansion. In that case the
6503          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6504          interested in. So we want to use the initial pack argument for
6505          the comparison.  */
6506       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6507       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6508         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6509       return template_args_equal (ot, nt);
6510     }
6511   else if (TYPE_P (nt))
6512     return TYPE_P (ot) && same_type_p (ot, nt);
6513   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6514     return 0;
6515   else
6516     return cp_tree_equal (ot, nt);
6517 }
6518
6519 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6520    of template arguments.  Returns 0 otherwise.  */
6521
6522 int
6523 comp_template_args (tree oldargs, tree newargs)
6524 {
6525   int i;
6526
6527   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6528     return 0;
6529
6530   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6531     {
6532       tree nt = TREE_VEC_ELT (newargs, i);
6533       tree ot = TREE_VEC_ELT (oldargs, i);
6534
6535       if (! template_args_equal (ot, nt))
6536         return 0;
6537     }
6538   return 1;
6539 }
6540
6541 static void
6542 add_pending_template (tree d)
6543 {
6544   tree ti = (TYPE_P (d)
6545              ? CLASSTYPE_TEMPLATE_INFO (d)
6546              : DECL_TEMPLATE_INFO (d));
6547   struct pending_template *pt;
6548   int level;
6549
6550   if (TI_PENDING_TEMPLATE_FLAG (ti))
6551     return;
6552
6553   /* We are called both from instantiate_decl, where we've already had a
6554      tinst_level pushed, and instantiate_template, where we haven't.
6555      Compensate.  */
6556   level = !current_tinst_level || current_tinst_level->decl != d;
6557
6558   if (level)
6559     push_tinst_level (d);
6560
6561   pt = ggc_alloc_pending_template ();
6562   pt->next = NULL;
6563   pt->tinst = current_tinst_level;
6564   if (last_pending_template)
6565     last_pending_template->next = pt;
6566   else
6567     pending_templates = pt;
6568
6569   last_pending_template = pt;
6570
6571   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6572
6573   if (level)
6574     pop_tinst_level ();
6575 }
6576
6577
6578 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6579    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6580    documentation for TEMPLATE_ID_EXPR.  */
6581
6582 tree
6583 lookup_template_function (tree fns, tree arglist)
6584 {
6585   tree type;
6586
6587   if (fns == error_mark_node || arglist == error_mark_node)
6588     return error_mark_node;
6589
6590   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6591   gcc_assert (fns && (is_overloaded_fn (fns)
6592                       || TREE_CODE (fns) == IDENTIFIER_NODE));
6593
6594   if (BASELINK_P (fns))
6595     {
6596       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6597                                          unknown_type_node,
6598                                          BASELINK_FUNCTIONS (fns),
6599                                          arglist);
6600       return fns;
6601     }
6602
6603   type = TREE_TYPE (fns);
6604   if (TREE_CODE (fns) == OVERLOAD || !type)
6605     type = unknown_type_node;
6606
6607   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6608 }
6609
6610 /* Within the scope of a template class S<T>, the name S gets bound
6611    (in build_self_reference) to a TYPE_DECL for the class, not a
6612    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6613    or one of its enclosing classes, and that type is a template,
6614    return the associated TEMPLATE_DECL.  Otherwise, the original
6615    DECL is returned.
6616
6617    Also handle the case when DECL is a TREE_LIST of ambiguous
6618    injected-class-names from different bases.  */
6619
6620 tree
6621 maybe_get_template_decl_from_type_decl (tree decl)
6622 {
6623   if (decl == NULL_TREE)
6624     return decl;
6625
6626   /* DR 176: A lookup that finds an injected-class-name (10.2
6627      [class.member.lookup]) can result in an ambiguity in certain cases
6628      (for example, if it is found in more than one base class). If all of
6629      the injected-class-names that are found refer to specializations of
6630      the same class template, and if the name is followed by a
6631      template-argument-list, the reference refers to the class template
6632      itself and not a specialization thereof, and is not ambiguous.  */
6633   if (TREE_CODE (decl) == TREE_LIST)
6634     {
6635       tree t, tmpl = NULL_TREE;
6636       for (t = decl; t; t = TREE_CHAIN (t))
6637         {
6638           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6639           if (!tmpl)
6640             tmpl = elt;
6641           else if (tmpl != elt)
6642             break;
6643         }
6644       if (tmpl && t == NULL_TREE)
6645         return tmpl;
6646       else
6647         return decl;
6648     }
6649
6650   return (decl != NULL_TREE
6651           && DECL_SELF_REFERENCE_P (decl)
6652           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
6653     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
6654 }
6655
6656 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
6657    parameters, find the desired type.
6658
6659    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
6660
6661    IN_DECL, if non-NULL, is the template declaration we are trying to
6662    instantiate.
6663
6664    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
6665    the class we are looking up.
6666
6667    Issue error and warning messages under control of COMPLAIN.
6668
6669    If the template class is really a local class in a template
6670    function, then the FUNCTION_CONTEXT is the function in which it is
6671    being instantiated.
6672
6673    ??? Note that this function is currently called *twice* for each
6674    template-id: the first time from the parser, while creating the
6675    incomplete type (finish_template_type), and the second type during the
6676    real instantiation (instantiate_template_class). This is surely something
6677    that we want to avoid. It also causes some problems with argument
6678    coercion (see convert_nontype_argument for more information on this).  */
6679
6680 tree
6681 lookup_template_class (tree d1,
6682                        tree arglist,
6683                        tree in_decl,
6684                        tree context,
6685                        int entering_scope,
6686                        tsubst_flags_t complain)
6687 {
6688   tree templ = NULL_TREE, parmlist;
6689   tree t;
6690   spec_entry **slot;
6691   spec_entry *entry;
6692   spec_entry elt;
6693   hashval_t hash;
6694
6695   timevar_push (TV_NAME_LOOKUP);
6696
6697   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6698     {
6699       tree value = innermost_non_namespace_value (d1);
6700       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6701         templ = value;
6702       else
6703         {
6704           if (context)
6705             push_decl_namespace (context);
6706           templ = lookup_name (d1);
6707           templ = maybe_get_template_decl_from_type_decl (templ);
6708           if (context)
6709             pop_decl_namespace ();
6710         }
6711       if (templ)
6712         context = DECL_CONTEXT (templ);
6713     }
6714   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6715     {
6716       tree type = TREE_TYPE (d1);
6717
6718       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6719          an implicit typename for the second A.  Deal with it.  */
6720       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6721         type = TREE_TYPE (type);
6722
6723       if (CLASSTYPE_TEMPLATE_INFO (type))
6724         {
6725           templ = CLASSTYPE_TI_TEMPLATE (type);
6726           d1 = DECL_NAME (templ);
6727         }
6728     }
6729   else if (TREE_CODE (d1) == ENUMERAL_TYPE
6730            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6731     {
6732       templ = TYPE_TI_TEMPLATE (d1);
6733       d1 = DECL_NAME (templ);
6734     }
6735   else if (TREE_CODE (d1) == TEMPLATE_DECL
6736            && DECL_TEMPLATE_RESULT (d1)
6737            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6738     {
6739       templ = d1;
6740       d1 = DECL_NAME (templ);
6741       context = DECL_CONTEXT (templ);
6742     }
6743
6744   /* Issue an error message if we didn't find a template.  */
6745   if (! templ)
6746     {
6747       if (complain & tf_error)
6748         error ("%qT is not a template", d1);
6749       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6750     }
6751
6752   if (TREE_CODE (templ) != TEMPLATE_DECL
6753          /* Make sure it's a user visible template, if it was named by
6754             the user.  */
6755       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6756           && !PRIMARY_TEMPLATE_P (templ)))
6757     {
6758       if (complain & tf_error)
6759         {
6760           error ("non-template type %qT used as a template", d1);
6761           if (in_decl)
6762             error ("for template declaration %q+D", in_decl);
6763         }
6764       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6765     }
6766
6767   complain &= ~tf_user;
6768
6769   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6770     {
6771       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6772          template arguments */
6773
6774       tree parm;
6775       tree arglist2;
6776       tree outer;
6777
6778       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6779
6780       /* Consider an example where a template template parameter declared as
6781
6782            template <class T, class U = std::allocator<T> > class TT
6783
6784          The template parameter level of T and U are one level larger than
6785          of TT.  To proper process the default argument of U, say when an
6786          instantiation `TT<int>' is seen, we need to build the full
6787          arguments containing {int} as the innermost level.  Outer levels,
6788          available when not appearing as default template argument, can be
6789          obtained from the arguments of the enclosing template.
6790
6791          Suppose that TT is later substituted with std::vector.  The above
6792          instantiation is `TT<int, std::allocator<T> >' with TT at
6793          level 1, and T at level 2, while the template arguments at level 1
6794          becomes {std::vector} and the inner level 2 is {int}.  */
6795
6796       outer = DECL_CONTEXT (templ);
6797       if (outer)
6798         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
6799       else if (current_template_parms)
6800         /* This is an argument of the current template, so we haven't set
6801            DECL_CONTEXT yet.  */
6802         outer = current_template_args ();
6803
6804       if (outer)
6805         arglist = add_to_template_args (outer, arglist);
6806
6807       arglist2 = coerce_template_parms (parmlist, arglist, templ,
6808                                         complain,
6809                                         /*require_all_args=*/true,
6810                                         /*use_default_args=*/true);
6811       if (arglist2 == error_mark_node
6812           || (!uses_template_parms (arglist2)
6813               && check_instantiated_args (templ, arglist2, complain)))
6814         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6815
6816       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
6817       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
6818     }
6819   else
6820     {
6821       tree template_type = TREE_TYPE (templ);
6822       tree gen_tmpl;
6823       tree type_decl;
6824       tree found = NULL_TREE;
6825       int arg_depth;
6826       int parm_depth;
6827       int is_dependent_type;
6828       int use_partial_inst_tmpl = false;
6829
6830       gen_tmpl = most_general_template (templ);
6831       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
6832       parm_depth = TMPL_PARMS_DEPTH (parmlist);
6833       arg_depth = TMPL_ARGS_DEPTH (arglist);
6834
6835       if (arg_depth == 1 && parm_depth > 1)
6836         {
6837           /* We've been given an incomplete set of template arguments.
6838              For example, given:
6839
6840                template <class T> struct S1 {
6841                  template <class U> struct S2 {};
6842                  template <class U> struct S2<U*> {};
6843                 };
6844
6845              we will be called with an ARGLIST of `U*', but the
6846              TEMPLATE will be `template <class T> template
6847              <class U> struct S1<T>::S2'.  We must fill in the missing
6848              arguments.  */
6849           arglist
6850             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
6851                                            arglist);
6852           arg_depth = TMPL_ARGS_DEPTH (arglist);
6853         }
6854
6855       /* Now we should have enough arguments.  */
6856       gcc_assert (parm_depth == arg_depth);
6857
6858       /* From here on, we're only interested in the most general
6859          template.  */
6860
6861       /* Calculate the BOUND_ARGS.  These will be the args that are
6862          actually tsubst'd into the definition to create the
6863          instantiation.  */
6864       if (parm_depth > 1)
6865         {
6866           /* We have multiple levels of arguments to coerce, at once.  */
6867           int i;
6868           int saved_depth = TMPL_ARGS_DEPTH (arglist);
6869
6870           tree bound_args = make_tree_vec (parm_depth);
6871
6872           for (i = saved_depth,
6873                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
6874                i > 0 && t != NULL_TREE;
6875                --i, t = TREE_CHAIN (t))
6876             {
6877               tree a;
6878               if (i == saved_depth)
6879                 a = coerce_template_parms (TREE_VALUE (t),
6880                                            arglist, gen_tmpl,
6881                                            complain,
6882                                            /*require_all_args=*/true,
6883                                            /*use_default_args=*/true);
6884               else
6885                 /* Outer levels should have already been coerced.  */
6886                 a = TMPL_ARGS_LEVEL (arglist, i);
6887
6888               /* Don't process further if one of the levels fails.  */
6889               if (a == error_mark_node)
6890                 {
6891                   /* Restore the ARGLIST to its full size.  */
6892                   TREE_VEC_LENGTH (arglist) = saved_depth;
6893                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6894                 }
6895
6896               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6897
6898               /* We temporarily reduce the length of the ARGLIST so
6899                  that coerce_template_parms will see only the arguments
6900                  corresponding to the template parameters it is
6901                  examining.  */
6902               TREE_VEC_LENGTH (arglist)--;
6903             }
6904
6905           /* Restore the ARGLIST to its full size.  */
6906           TREE_VEC_LENGTH (arglist) = saved_depth;
6907
6908           arglist = bound_args;
6909         }
6910       else
6911         arglist
6912           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6913                                    INNERMOST_TEMPLATE_ARGS (arglist),
6914                                    gen_tmpl,
6915                                    complain,
6916                                    /*require_all_args=*/true,
6917                                    /*use_default_args=*/true);
6918
6919       if (arglist == error_mark_node)
6920         /* We were unable to bind the arguments.  */
6921         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6922
6923       /* In the scope of a template class, explicit references to the
6924          template class refer to the type of the template, not any
6925          instantiation of it.  For example, in:
6926
6927            template <class T> class C { void f(C<T>); }
6928
6929          the `C<T>' is just the same as `C'.  Outside of the
6930          class, however, such a reference is an instantiation.  */
6931       if ((entering_scope
6932            || !PRIMARY_TEMPLATE_P (gen_tmpl)
6933            || currently_open_class (template_type))
6934           /* comp_template_args is expensive, check it last.  */
6935           && comp_template_args (TYPE_TI_ARGS (template_type),
6936                                  arglist))
6937         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, template_type);
6938
6939       /* If we already have this specialization, return it.  */
6940       elt.tmpl = gen_tmpl;
6941       elt.args = arglist;
6942       hash = hash_specialization (&elt);
6943       entry = (spec_entry *) htab_find_with_hash (type_specializations,
6944                                                   &elt, hash);
6945
6946       if (entry)
6947         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->spec);
6948
6949       is_dependent_type = uses_template_parms (arglist);
6950
6951       /* If the deduced arguments are invalid, then the binding
6952          failed.  */
6953       if (!is_dependent_type
6954           && check_instantiated_args (gen_tmpl,
6955                                       INNERMOST_TEMPLATE_ARGS (arglist),
6956                                       complain))
6957         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6958
6959       if (!is_dependent_type
6960           && !PRIMARY_TEMPLATE_P (gen_tmpl)
6961           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
6962           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6963         {
6964           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6965                                       DECL_NAME (gen_tmpl),
6966                                       /*tag_scope=*/ts_global);
6967           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
6968         }
6969
6970       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
6971                         complain, in_decl);
6972       if (!context)
6973         context = global_namespace;
6974
6975       /* Create the type.  */
6976       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
6977         {
6978           if (!is_dependent_type)
6979             {
6980               set_current_access_from_decl (TYPE_NAME (template_type));
6981               t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
6982                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
6983                                       arglist, complain, in_decl),
6984                               SCOPED_ENUM_P (template_type), NULL);
6985             }
6986           else
6987             {
6988               /* We don't want to call start_enum for this type, since
6989                  the values for the enumeration constants may involve
6990                  template parameters.  And, no one should be interested
6991                  in the enumeration constants for such a type.  */
6992               t = cxx_make_type (ENUMERAL_TYPE);
6993               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
6994             }
6995           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
6996         }
6997       else
6998         {
6999           t = make_class_type (TREE_CODE (template_type));
7000           CLASSTYPE_DECLARED_CLASS (t)
7001             = CLASSTYPE_DECLARED_CLASS (template_type);
7002           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
7003           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
7004
7005           /* A local class.  Make sure the decl gets registered properly.  */
7006           if (context == current_function_decl)
7007             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
7008
7009           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
7010             /* This instantiation is another name for the primary
7011                template type. Set the TYPE_CANONICAL field
7012                appropriately. */
7013             TYPE_CANONICAL (t) = template_type;
7014           else if (any_template_arguments_need_structural_equality_p (arglist))
7015             /* Some of the template arguments require structural
7016                equality testing, so this template class requires
7017                structural equality testing. */
7018             SET_TYPE_STRUCTURAL_EQUALITY (t);
7019         }
7020
7021       /* If we called start_enum or pushtag above, this information
7022          will already be set up.  */
7023       if (!TYPE_NAME (t))
7024         {
7025           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
7026
7027           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
7028           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
7029           DECL_SOURCE_LOCATION (type_decl)
7030             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
7031         }
7032       else
7033         type_decl = TYPE_NAME (t);
7034
7035       TREE_PRIVATE (type_decl)
7036         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
7037       TREE_PROTECTED (type_decl)
7038         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
7039       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
7040         {
7041           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
7042           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
7043         }
7044
7045       /* Let's consider the explicit specialization of a member
7046          of a class template specialization that is implicitely instantiated,
7047          e.g.:
7048              template<class T>
7049              struct S
7050              {
7051                template<class U> struct M {}; //#0
7052              };
7053
7054              template<>
7055              template<>
7056              struct S<int>::M<char> //#1
7057              {
7058                int i;
7059              };
7060         [temp.expl.spec]/4 says this is valid.
7061
7062         In this case, when we write:
7063         S<int>::M<char> m;
7064
7065         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
7066         the one of #0.
7067
7068         When we encounter #1, we want to store the partial instantiation
7069         of M (template<class T> S<int>::M<T>) in it's CLASSTYPE_TI_TEMPLATE.
7070
7071         For all cases other than this "explicit specialization of member of a
7072         class template", we just want to store the most general template into
7073         the CLASSTYPE_TI_TEMPLATE of M.
7074
7075         This case of "explicit specialization of member of a class template"
7076         only happens when:
7077         1/ the enclosing class is an instantiation of, and therefore not
7078         the same as, the context of the most general template, and
7079         2/ we aren't looking at the partial instantiation itself, i.e.
7080         the innermost arguments are not the same as the innermost parms of
7081         the most general template.
7082
7083         So it's only when 1/ and 2/ happens that we want to use the partial
7084         instantiation of the member template in lieu of its most general
7085         template.  */
7086
7087       if (PRIMARY_TEMPLATE_P (gen_tmpl)
7088           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
7089           /* the enclosing class must be an instantiation...  */
7090           && CLASS_TYPE_P (context)
7091           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
7092         {
7093           tree partial_inst_args;
7094           TREE_VEC_LENGTH (arglist)--;
7095           ++processing_template_decl;
7096           partial_inst_args =
7097             tsubst (INNERMOST_TEMPLATE_ARGS
7098                         (CLASSTYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
7099                     arglist, complain, NULL_TREE);
7100           --processing_template_decl;
7101           TREE_VEC_LENGTH (arglist)++;
7102           use_partial_inst_tmpl =
7103             /*...and we must not be looking at the partial instantiation
7104              itself. */
7105             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
7106                                  partial_inst_args);
7107         }
7108
7109       if (!use_partial_inst_tmpl)
7110         /* This case is easy; there are no member templates involved.  */
7111         found = gen_tmpl;
7112       else
7113         {
7114           /* This is a full instantiation of a member template.  Find
7115              the partial instantiation of which this is an instance.  */
7116
7117           /* Temporarily reduce by one the number of levels in the ARGLIST
7118              so as to avoid comparing the last set of arguments.  */
7119           TREE_VEC_LENGTH (arglist)--;
7120           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
7121           TREE_VEC_LENGTH (arglist)++;
7122           found = CLASSTYPE_TI_TEMPLATE (found);
7123         }
7124
7125       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
7126
7127       elt.spec = t;
7128       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
7129                                                        &elt, hash, INSERT);
7130       *slot = ggc_alloc_spec_entry ();
7131       **slot = elt;
7132
7133       /* Note this use of the partial instantiation so we can check it
7134          later in maybe_process_partial_specialization.  */
7135       DECL_TEMPLATE_INSTANTIATIONS (templ)
7136         = tree_cons (arglist, t,
7137                      DECL_TEMPLATE_INSTANTIATIONS (templ));
7138
7139       if (TREE_CODE (t) == ENUMERAL_TYPE && !is_dependent_type)
7140         /* Now that the type has been registered on the instantiations
7141            list, we set up the enumerators.  Because the enumeration
7142            constants may involve the enumeration type itself, we make
7143            sure to register the type first, and then create the
7144            constants.  That way, doing tsubst_expr for the enumeration
7145            constants won't result in recursive calls here; we'll find
7146            the instantiation and exit above.  */
7147         tsubst_enum (template_type, t, arglist);
7148
7149       if (is_dependent_type)
7150         /* If the type makes use of template parameters, the
7151            code that generates debugging information will crash.  */
7152         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
7153
7154       /* Possibly limit visibility based on template args.  */
7155       TREE_PUBLIC (type_decl) = 1;
7156       determine_visibility (type_decl);
7157
7158       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
7159     }
7160   timevar_pop (TV_NAME_LOOKUP);
7161 }
7162 \f
7163 struct pair_fn_data
7164 {
7165   tree_fn_t fn;
7166   void *data;
7167   /* True when we should also visit template parameters that occur in
7168      non-deduced contexts.  */
7169   bool include_nondeduced_p;
7170   struct pointer_set_t *visited;
7171 };
7172
7173 /* Called from for_each_template_parm via walk_tree.  */
7174
7175 static tree
7176 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
7177 {
7178   tree t = *tp;
7179   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
7180   tree_fn_t fn = pfd->fn;
7181   void *data = pfd->data;
7182
7183   if (TYPE_P (t)
7184       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
7185       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
7186                                  pfd->include_nondeduced_p))
7187     return error_mark_node;
7188
7189   switch (TREE_CODE (t))
7190     {
7191     case RECORD_TYPE:
7192       if (TYPE_PTRMEMFUNC_P (t))
7193         break;
7194       /* Fall through.  */
7195
7196     case UNION_TYPE:
7197     case ENUMERAL_TYPE:
7198       if (!TYPE_TEMPLATE_INFO (t))
7199         *walk_subtrees = 0;
7200       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
7201                                        fn, data, pfd->visited, 
7202                                        pfd->include_nondeduced_p))
7203         return error_mark_node;
7204       break;
7205
7206     case INTEGER_TYPE:
7207       if (for_each_template_parm (TYPE_MIN_VALUE (t),
7208                                   fn, data, pfd->visited, 
7209                                   pfd->include_nondeduced_p)
7210           || for_each_template_parm (TYPE_MAX_VALUE (t),
7211                                      fn, data, pfd->visited,
7212                                      pfd->include_nondeduced_p))
7213         return error_mark_node;
7214       break;
7215
7216     case METHOD_TYPE:
7217       /* Since we're not going to walk subtrees, we have to do this
7218          explicitly here.  */
7219       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
7220                                   pfd->visited, pfd->include_nondeduced_p))
7221         return error_mark_node;
7222       /* Fall through.  */
7223
7224     case FUNCTION_TYPE:
7225       /* Check the return type.  */
7226       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7227                                   pfd->include_nondeduced_p))
7228         return error_mark_node;
7229
7230       /* Check the parameter types.  Since default arguments are not
7231          instantiated until they are needed, the TYPE_ARG_TYPES may
7232          contain expressions that involve template parameters.  But,
7233          no-one should be looking at them yet.  And, once they're
7234          instantiated, they don't contain template parameters, so
7235          there's no point in looking at them then, either.  */
7236       {
7237         tree parm;
7238
7239         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
7240           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
7241                                       pfd->visited, pfd->include_nondeduced_p))
7242             return error_mark_node;
7243
7244         /* Since we've already handled the TYPE_ARG_TYPES, we don't
7245            want walk_tree walking into them itself.  */
7246         *walk_subtrees = 0;
7247       }
7248       break;
7249
7250     case TYPEOF_TYPE:
7251       if (pfd->include_nondeduced_p
7252           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
7253                                      pfd->visited, 
7254                                      pfd->include_nondeduced_p))
7255         return error_mark_node;
7256       break;
7257
7258     case FUNCTION_DECL:
7259     case VAR_DECL:
7260       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
7261           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
7262                                      pfd->visited, pfd->include_nondeduced_p))
7263         return error_mark_node;
7264       /* Fall through.  */
7265
7266     case PARM_DECL:
7267     case CONST_DECL:
7268       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
7269           && for_each_template_parm (DECL_INITIAL (t), fn, data,
7270                                      pfd->visited, pfd->include_nondeduced_p))
7271         return error_mark_node;
7272       if (DECL_CONTEXT (t)
7273           && pfd->include_nondeduced_p
7274           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
7275                                      pfd->visited, pfd->include_nondeduced_p))
7276         return error_mark_node;
7277       break;
7278
7279     case BOUND_TEMPLATE_TEMPLATE_PARM:
7280       /* Record template parameters such as `T' inside `TT<T>'.  */
7281       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
7282                                   pfd->include_nondeduced_p))
7283         return error_mark_node;
7284       /* Fall through.  */
7285
7286     case TEMPLATE_TEMPLATE_PARM:
7287     case TEMPLATE_TYPE_PARM:
7288     case TEMPLATE_PARM_INDEX:
7289       if (fn && (*fn)(t, data))
7290         return error_mark_node;
7291       else if (!fn)
7292         return error_mark_node;
7293       break;
7294
7295     case TEMPLATE_DECL:
7296       /* A template template parameter is encountered.  */
7297       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
7298           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7299                                      pfd->include_nondeduced_p))
7300         return error_mark_node;
7301
7302       /* Already substituted template template parameter */
7303       *walk_subtrees = 0;
7304       break;
7305
7306     case TYPENAME_TYPE:
7307       if (!fn
7308           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
7309                                      data, pfd->visited, 
7310                                      pfd->include_nondeduced_p))
7311         return error_mark_node;
7312       break;
7313
7314     case CONSTRUCTOR:
7315       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
7316           && pfd->include_nondeduced_p
7317           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
7318                                      (TREE_TYPE (t)), fn, data,
7319                                      pfd->visited, pfd->include_nondeduced_p))
7320         return error_mark_node;
7321       break;
7322
7323     case INDIRECT_REF:
7324     case COMPONENT_REF:
7325       /* If there's no type, then this thing must be some expression
7326          involving template parameters.  */
7327       if (!fn && !TREE_TYPE (t))
7328         return error_mark_node;
7329       break;
7330
7331     case MODOP_EXPR:
7332     case CAST_EXPR:
7333     case REINTERPRET_CAST_EXPR:
7334     case CONST_CAST_EXPR:
7335     case STATIC_CAST_EXPR:
7336     case DYNAMIC_CAST_EXPR:
7337     case ARROW_EXPR:
7338     case DOTSTAR_EXPR:
7339     case TYPEID_EXPR:
7340     case PSEUDO_DTOR_EXPR:
7341       if (!fn)
7342         return error_mark_node;
7343       break;
7344
7345     default:
7346       break;
7347     }
7348
7349   /* We didn't find any template parameters we liked.  */
7350   return NULL_TREE;
7351 }
7352
7353 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
7354    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
7355    call FN with the parameter and the DATA.
7356    If FN returns nonzero, the iteration is terminated, and
7357    for_each_template_parm returns 1.  Otherwise, the iteration
7358    continues.  If FN never returns a nonzero value, the value
7359    returned by for_each_template_parm is 0.  If FN is NULL, it is
7360    considered to be the function which always returns 1.
7361
7362    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
7363    parameters that occur in non-deduced contexts.  When false, only
7364    visits those template parameters that can be deduced.  */
7365
7366 static int
7367 for_each_template_parm (tree t, tree_fn_t fn, void* data,
7368                         struct pointer_set_t *visited,
7369                         bool include_nondeduced_p)
7370 {
7371   struct pair_fn_data pfd;
7372   int result;
7373
7374   /* Set up.  */
7375   pfd.fn = fn;
7376   pfd.data = data;
7377   pfd.include_nondeduced_p = include_nondeduced_p;
7378
7379   /* Walk the tree.  (Conceptually, we would like to walk without
7380      duplicates, but for_each_template_parm_r recursively calls
7381      for_each_template_parm, so we would need to reorganize a fair
7382      bit to use walk_tree_without_duplicates, so we keep our own
7383      visited list.)  */
7384   if (visited)
7385     pfd.visited = visited;
7386   else
7387     pfd.visited = pointer_set_create ();
7388   result = cp_walk_tree (&t,
7389                          for_each_template_parm_r,
7390                          &pfd,
7391                          pfd.visited) != NULL_TREE;
7392
7393   /* Clean up.  */
7394   if (!visited)
7395     {
7396       pointer_set_destroy (pfd.visited);
7397       pfd.visited = 0;
7398     }
7399
7400   return result;
7401 }
7402
7403 /* Returns true if T depends on any template parameter.  */
7404
7405 int
7406 uses_template_parms (tree t)
7407 {
7408   bool dependent_p;
7409   int saved_processing_template_decl;
7410
7411   saved_processing_template_decl = processing_template_decl;
7412   if (!saved_processing_template_decl)
7413     processing_template_decl = 1;
7414   if (TYPE_P (t))
7415     dependent_p = dependent_type_p (t);
7416   else if (TREE_CODE (t) == TREE_VEC)
7417     dependent_p = any_dependent_template_arguments_p (t);
7418   else if (TREE_CODE (t) == TREE_LIST)
7419     dependent_p = (uses_template_parms (TREE_VALUE (t))
7420                    || uses_template_parms (TREE_CHAIN (t)));
7421   else if (TREE_CODE (t) == TYPE_DECL)
7422     dependent_p = dependent_type_p (TREE_TYPE (t));
7423   else if (DECL_P (t)
7424            || EXPR_P (t)
7425            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
7426            || TREE_CODE (t) == OVERLOAD
7427            || TREE_CODE (t) == BASELINK
7428            || TREE_CODE (t) == IDENTIFIER_NODE
7429            || TREE_CODE (t) == TRAIT_EXPR
7430            || TREE_CODE (t) == CONSTRUCTOR
7431            || CONSTANT_CLASS_P (t))
7432     dependent_p = (type_dependent_expression_p (t)
7433                    || value_dependent_expression_p (t));
7434   else
7435     {
7436       gcc_assert (t == error_mark_node);
7437       dependent_p = false;
7438     }
7439
7440   processing_template_decl = saved_processing_template_decl;
7441
7442   return dependent_p;
7443 }
7444
7445 /* Returns true if T depends on any template parameter with level LEVEL.  */
7446
7447 int
7448 uses_template_parms_level (tree t, int level)
7449 {
7450   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
7451                                  /*include_nondeduced_p=*/true);
7452 }
7453
7454 static int tinst_depth;
7455 extern int max_tinst_depth;
7456 #ifdef GATHER_STATISTICS
7457 int depth_reached;
7458 #endif
7459 static int tinst_level_tick;
7460 static int last_template_error_tick;
7461
7462 /* We're starting to instantiate D; record the template instantiation context
7463    for diagnostics and to restore it later.  */
7464
7465 int
7466 push_tinst_level (tree d)
7467 {
7468   struct tinst_level *new_level;
7469
7470   if (tinst_depth >= max_tinst_depth)
7471     {
7472       /* If the instantiation in question still has unbound template parms,
7473          we don't really care if we can't instantiate it, so just return.
7474          This happens with base instantiation for implicit `typename'.  */
7475       if (uses_template_parms (d))
7476         return 0;
7477
7478       last_template_error_tick = tinst_level_tick;
7479       error ("template instantiation depth exceeds maximum of %d (use "
7480              "-ftemplate-depth= to increase the maximum) instantiating %qD",
7481              max_tinst_depth, d);
7482
7483       print_instantiation_context ();
7484
7485       return 0;
7486     }
7487
7488   new_level = ggc_alloc_tinst_level ();
7489   new_level->decl = d;
7490   new_level->locus = input_location;
7491   new_level->in_system_header_p = in_system_header;
7492   new_level->next = current_tinst_level;
7493   current_tinst_level = new_level;
7494
7495   ++tinst_depth;
7496 #ifdef GATHER_STATISTICS
7497   if (tinst_depth > depth_reached)
7498     depth_reached = tinst_depth;
7499 #endif
7500
7501   ++tinst_level_tick;
7502   return 1;
7503 }
7504
7505 /* We're done instantiating this template; return to the instantiation
7506    context.  */
7507
7508 void
7509 pop_tinst_level (void)
7510 {
7511   /* Restore the filename and line number stashed away when we started
7512      this instantiation.  */
7513   input_location = current_tinst_level->locus;
7514   current_tinst_level = current_tinst_level->next;
7515   --tinst_depth;
7516   ++tinst_level_tick;
7517 }
7518
7519 /* We're instantiating a deferred template; restore the template
7520    instantiation context in which the instantiation was requested, which
7521    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
7522
7523 static tree
7524 reopen_tinst_level (struct tinst_level *level)
7525 {
7526   struct tinst_level *t;
7527
7528   tinst_depth = 0;
7529   for (t = level; t; t = t->next)
7530     ++tinst_depth;
7531
7532   current_tinst_level = level;
7533   pop_tinst_level ();
7534   return level->decl;
7535 }
7536
7537 /* Returns the TINST_LEVEL which gives the original instantiation
7538    context.  */
7539
7540 struct tinst_level *
7541 outermost_tinst_level (void)
7542 {
7543   struct tinst_level *level = current_tinst_level;
7544   if (level)
7545     while (level->next)
7546       level = level->next;
7547   return level;
7548 }
7549
7550 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
7551
7552 bool
7553 parameter_of_template_p (tree parm, tree templ)
7554 {
7555   tree parms;
7556   int i;
7557
7558   if (!parm || !templ)
7559     return false;
7560
7561   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
7562   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7563
7564   parms = DECL_TEMPLATE_PARMS (templ);
7565   parms = INNERMOST_TEMPLATE_PARMS (parms);
7566
7567   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
7568     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
7569       return true;
7570
7571   return false;
7572 }
7573
7574 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
7575    vector of template arguments, as for tsubst.
7576
7577    Returns an appropriate tsubst'd friend declaration.  */
7578
7579 static tree
7580 tsubst_friend_function (tree decl, tree args)
7581 {
7582   tree new_friend;
7583
7584   if (TREE_CODE (decl) == FUNCTION_DECL
7585       && DECL_TEMPLATE_INSTANTIATION (decl)
7586       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
7587     /* This was a friend declared with an explicit template
7588        argument list, e.g.:
7589
7590        friend void f<>(T);
7591
7592        to indicate that f was a template instantiation, not a new
7593        function declaration.  Now, we have to figure out what
7594        instantiation of what template.  */
7595     {
7596       tree template_id, arglist, fns;
7597       tree new_args;
7598       tree tmpl;
7599       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
7600
7601       /* Friend functions are looked up in the containing namespace scope.
7602          We must enter that scope, to avoid finding member functions of the
7603          current class with same name.  */
7604       push_nested_namespace (ns);
7605       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
7606                          tf_warning_or_error, NULL_TREE,
7607                          /*integral_constant_expression_p=*/false);
7608       pop_nested_namespace (ns);
7609       arglist = tsubst (DECL_TI_ARGS (decl), args,
7610                         tf_warning_or_error, NULL_TREE);
7611       template_id = lookup_template_function (fns, arglist);
7612
7613       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7614       tmpl = determine_specialization (template_id, new_friend,
7615                                        &new_args,
7616                                        /*need_member_template=*/0,
7617                                        TREE_VEC_LENGTH (args),
7618                                        tsk_none);
7619       return instantiate_template (tmpl, new_args, tf_error);
7620     }
7621
7622   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7623
7624   /* The NEW_FRIEND will look like an instantiation, to the
7625      compiler, but is not an instantiation from the point of view of
7626      the language.  For example, we might have had:
7627
7628      template <class T> struct S {
7629        template <class U> friend void f(T, U);
7630      };
7631
7632      Then, in S<int>, template <class U> void f(int, U) is not an
7633      instantiation of anything.  */
7634   if (new_friend == error_mark_node)
7635     return error_mark_node;
7636
7637   DECL_USE_TEMPLATE (new_friend) = 0;
7638   if (TREE_CODE (decl) == TEMPLATE_DECL)
7639     {
7640       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
7641       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
7642         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
7643     }
7644
7645   /* The mangled name for the NEW_FRIEND is incorrect.  The function
7646      is not a template instantiation and should not be mangled like
7647      one.  Therefore, we forget the mangling here; we'll recompute it
7648      later if we need it.  */
7649   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
7650     {
7651       SET_DECL_RTL (new_friend, NULL);
7652       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
7653     }
7654
7655   if (DECL_NAMESPACE_SCOPE_P (new_friend))
7656     {
7657       tree old_decl;
7658       tree new_friend_template_info;
7659       tree new_friend_result_template_info;
7660       tree ns;
7661       int  new_friend_is_defn;
7662
7663       /* We must save some information from NEW_FRIEND before calling
7664          duplicate decls since that function will free NEW_FRIEND if
7665          possible.  */
7666       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
7667       new_friend_is_defn =
7668             (DECL_INITIAL (DECL_TEMPLATE_RESULT
7669                            (template_for_substitution (new_friend)))
7670              != NULL_TREE);
7671       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
7672         {
7673           /* This declaration is a `primary' template.  */
7674           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
7675
7676           new_friend_result_template_info
7677             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
7678         }
7679       else
7680         new_friend_result_template_info = NULL_TREE;
7681
7682       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
7683       if (new_friend_is_defn)
7684         DECL_INITIAL (new_friend) = error_mark_node;
7685
7686       /* Inside pushdecl_namespace_level, we will push into the
7687          current namespace. However, the friend function should go
7688          into the namespace of the template.  */
7689       ns = decl_namespace_context (new_friend);
7690       push_nested_namespace (ns);
7691       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
7692       pop_nested_namespace (ns);
7693
7694       if (old_decl == error_mark_node)
7695         return error_mark_node;
7696
7697       if (old_decl != new_friend)
7698         {
7699           /* This new friend declaration matched an existing
7700              declaration.  For example, given:
7701
7702                template <class T> void f(T);
7703                template <class U> class C {
7704                  template <class T> friend void f(T) {}
7705                };
7706
7707              the friend declaration actually provides the definition
7708              of `f', once C has been instantiated for some type.  So,
7709              old_decl will be the out-of-class template declaration,
7710              while new_friend is the in-class definition.
7711
7712              But, if `f' was called before this point, the
7713              instantiation of `f' will have DECL_TI_ARGS corresponding
7714              to `T' but not to `U', references to which might appear
7715              in the definition of `f'.  Previously, the most general
7716              template for an instantiation of `f' was the out-of-class
7717              version; now it is the in-class version.  Therefore, we
7718              run through all specialization of `f', adding to their
7719              DECL_TI_ARGS appropriately.  In particular, they need a
7720              new set of outer arguments, corresponding to the
7721              arguments for this class instantiation.
7722
7723              The same situation can arise with something like this:
7724
7725                friend void f(int);
7726                template <class T> class C {
7727                  friend void f(T) {}
7728                };
7729
7730              when `C<int>' is instantiated.  Now, `f(int)' is defined
7731              in the class.  */
7732
7733           if (!new_friend_is_defn)
7734             /* On the other hand, if the in-class declaration does
7735                *not* provide a definition, then we don't want to alter
7736                existing definitions.  We can just leave everything
7737                alone.  */
7738             ;
7739           else
7740             {
7741               tree new_template = TI_TEMPLATE (new_friend_template_info);
7742               tree new_args = TI_ARGS (new_friend_template_info);
7743
7744               /* Overwrite whatever template info was there before, if
7745                  any, with the new template information pertaining to
7746                  the declaration.  */
7747               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
7748
7749               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
7750                 {
7751                   /* We should have called reregister_specialization in
7752                      duplicate_decls.  */
7753                   gcc_assert (retrieve_specialization (new_template,
7754                                                        new_args, 0)
7755                               == old_decl);
7756
7757                   /* Instantiate it if the global has already been used.  */
7758                   if (DECL_ODR_USED (old_decl))
7759                     instantiate_decl (old_decl, /*defer_ok=*/true,
7760                                       /*expl_inst_class_mem_p=*/false);
7761                 }
7762               else
7763                 {
7764                   tree t;
7765
7766                   /* Indicate that the old function template is a partial
7767                      instantiation.  */
7768                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
7769                     = new_friend_result_template_info;
7770
7771                   gcc_assert (new_template
7772                               == most_general_template (new_template));
7773                   gcc_assert (new_template != old_decl);
7774
7775                   /* Reassign any specializations already in the hash table
7776                      to the new more general template, and add the
7777                      additional template args.  */
7778                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
7779                        t != NULL_TREE;
7780                        t = TREE_CHAIN (t))
7781                     {
7782                       tree spec = TREE_VALUE (t);
7783                       spec_entry elt;
7784
7785                       elt.tmpl = old_decl;
7786                       elt.args = DECL_TI_ARGS (spec);
7787                       elt.spec = NULL_TREE;
7788
7789                       htab_remove_elt (decl_specializations, &elt);
7790
7791                       DECL_TI_ARGS (spec)
7792                         = add_outermost_template_args (new_args,
7793                                                        DECL_TI_ARGS (spec));
7794
7795                       register_specialization
7796                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
7797
7798                     }
7799                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
7800                 }
7801             }
7802
7803           /* The information from NEW_FRIEND has been merged into OLD_DECL
7804              by duplicate_decls.  */
7805           new_friend = old_decl;
7806         }
7807     }
7808   else
7809     {
7810       tree context = DECL_CONTEXT (new_friend);
7811       bool dependent_p;
7812
7813       /* In the code
7814            template <class T> class C {
7815              template <class U> friend void C1<U>::f (); // case 1
7816              friend void C2<T>::f ();                    // case 2
7817            };
7818          we only need to make sure CONTEXT is a complete type for
7819          case 2.  To distinguish between the two cases, we note that
7820          CONTEXT of case 1 remains dependent type after tsubst while
7821          this isn't true for case 2.  */
7822       ++processing_template_decl;
7823       dependent_p = dependent_type_p (context);
7824       --processing_template_decl;
7825
7826       if (!dependent_p
7827           && !complete_type_or_else (context, NULL_TREE))
7828         return error_mark_node;
7829
7830       if (COMPLETE_TYPE_P (context))
7831         {
7832           /* Check to see that the declaration is really present, and,
7833              possibly obtain an improved declaration.  */
7834           tree fn = check_classfn (context,
7835                                    new_friend, NULL_TREE);
7836
7837           if (fn)
7838             new_friend = fn;
7839         }
7840     }
7841
7842   return new_friend;
7843 }
7844
7845 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
7846    template arguments, as for tsubst.
7847
7848    Returns an appropriate tsubst'd friend type or error_mark_node on
7849    failure.  */
7850
7851 static tree
7852 tsubst_friend_class (tree friend_tmpl, tree args)
7853 {
7854   tree friend_type;
7855   tree tmpl;
7856   tree context;
7857
7858   context = CP_DECL_CONTEXT (friend_tmpl);
7859
7860   if (context != global_namespace)
7861     {
7862       if (TREE_CODE (context) == NAMESPACE_DECL)
7863         push_nested_namespace (context);
7864       else
7865         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
7866     }
7867
7868   /* Look for a class template declaration.  We look for hidden names
7869      because two friend declarations of the same template are the
7870      same.  For example, in:
7871
7872        struct A { 
7873          template <typename> friend class F;
7874        };
7875        template <typename> struct B { 
7876          template <typename> friend class F;
7877        };
7878
7879      both F templates are the same.  */
7880   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
7881                            /*block_p=*/true, 0, 
7882                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
7883
7884   /* But, if we don't find one, it might be because we're in a
7885      situation like this:
7886
7887        template <class T>
7888        struct S {
7889          template <class U>
7890          friend struct S;
7891        };
7892
7893      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
7894      for `S<int>', not the TEMPLATE_DECL.  */
7895   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
7896     {
7897       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
7898       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
7899     }
7900
7901   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
7902     {
7903       /* The friend template has already been declared.  Just
7904          check to see that the declarations match, and install any new
7905          default parameters.  We must tsubst the default parameters,
7906          of course.  We only need the innermost template parameters
7907          because that is all that redeclare_class_template will look
7908          at.  */
7909       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
7910           > TMPL_ARGS_DEPTH (args))
7911         {
7912           tree parms;
7913           location_t saved_input_location;
7914           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
7915                                          args, tf_warning_or_error);
7916
7917           saved_input_location = input_location;
7918           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
7919           redeclare_class_template (TREE_TYPE (tmpl), parms);
7920           input_location = saved_input_location;
7921           
7922         }
7923
7924       friend_type = TREE_TYPE (tmpl);
7925     }
7926   else
7927     {
7928       /* The friend template has not already been declared.  In this
7929          case, the instantiation of the template class will cause the
7930          injection of this template into the global scope.  */
7931       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7932       if (tmpl == error_mark_node)
7933         return error_mark_node;
7934
7935       /* The new TMPL is not an instantiation of anything, so we
7936          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7937          the new type because that is supposed to be the corresponding
7938          template decl, i.e., TMPL.  */
7939       DECL_USE_TEMPLATE (tmpl) = 0;
7940       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7941       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7942       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7943         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7944
7945       /* Inject this template into the global scope.  */
7946       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7947     }
7948
7949   if (context != global_namespace)
7950     {
7951       if (TREE_CODE (context) == NAMESPACE_DECL)
7952         pop_nested_namespace (context);
7953       else
7954         pop_nested_class ();
7955     }
7956
7957   return friend_type;
7958 }
7959
7960 /* Returns zero if TYPE cannot be completed later due to circularity.
7961    Otherwise returns one.  */
7962
7963 static int
7964 can_complete_type_without_circularity (tree type)
7965 {
7966   if (type == NULL_TREE || type == error_mark_node)
7967     return 0;
7968   else if (COMPLETE_TYPE_P (type))
7969     return 1;
7970   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
7971     return can_complete_type_without_circularity (TREE_TYPE (type));
7972   else if (CLASS_TYPE_P (type)
7973            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
7974     return 0;
7975   else
7976     return 1;
7977 }
7978
7979 /* Apply any attributes which had to be deferred until instantiation
7980    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
7981    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
7982
7983 static void
7984 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
7985                                 tree args, tsubst_flags_t complain, tree in_decl)
7986 {
7987   tree last_dep = NULL_TREE;
7988   tree t;
7989   tree *p;
7990
7991   for (t = attributes; t; t = TREE_CHAIN (t))
7992     if (ATTR_IS_DEPENDENT (t))
7993       {
7994         last_dep = t;
7995         attributes = copy_list (attributes);
7996         break;
7997       }
7998
7999   if (DECL_P (*decl_p))
8000     {
8001       if (TREE_TYPE (*decl_p) == error_mark_node)
8002         return;
8003       p = &DECL_ATTRIBUTES (*decl_p);
8004     }
8005   else
8006     p = &TYPE_ATTRIBUTES (*decl_p);
8007
8008   if (last_dep)
8009     {
8010       tree late_attrs = NULL_TREE;
8011       tree *q = &late_attrs;
8012
8013       for (*p = attributes; *p; )
8014         {
8015           t = *p;
8016           if (ATTR_IS_DEPENDENT (t))
8017             {
8018               *p = TREE_CHAIN (t);
8019               TREE_CHAIN (t) = NULL_TREE;
8020               /* If the first attribute argument is an identifier, don't
8021                  pass it through tsubst.  Attributes like mode, format,
8022                  cleanup and several target specific attributes expect it
8023                  unmodified.  */
8024               if (TREE_VALUE (t)
8025                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
8026                   && TREE_VALUE (TREE_VALUE (t))
8027                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
8028                       == IDENTIFIER_NODE))
8029                 {
8030                   tree chain
8031                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
8032                                    in_decl,
8033                                    /*integral_constant_expression_p=*/false);
8034                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
8035                     TREE_VALUE (t)
8036                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
8037                                    chain);
8038                 }
8039               else
8040                 TREE_VALUE (t)
8041                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
8042                                  /*integral_constant_expression_p=*/false);
8043               *q = t;
8044               q = &TREE_CHAIN (t);
8045             }
8046           else
8047             p = &TREE_CHAIN (t);
8048         }
8049
8050       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
8051     }
8052 }
8053
8054 /* Perform (or defer) access check for typedefs that were referenced
8055    from within the template TMPL code.
8056    This is a subroutine of instantiate_template and instantiate_class_template.
8057    TMPL is the template to consider and TARGS is the list of arguments of
8058    that template.  */
8059
8060 static void
8061 perform_typedefs_access_check (tree tmpl, tree targs)
8062 {
8063   location_t saved_location;
8064   int i;
8065   qualified_typedef_usage_t *iter;
8066
8067   if (!tmpl
8068       || (!CLASS_TYPE_P (tmpl)
8069           && TREE_CODE (tmpl) != FUNCTION_DECL))
8070     return;
8071
8072   saved_location = input_location;
8073   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
8074                     get_types_needing_access_check (tmpl),
8075                     i, iter)
8076     {
8077       tree type_decl = iter->typedef_decl;
8078       tree type_scope = iter->context;
8079
8080       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
8081         continue;
8082
8083       if (uses_template_parms (type_decl))
8084         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
8085       if (uses_template_parms (type_scope))
8086         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
8087
8088       /* Make access check error messages point to the location
8089          of the use of the typedef.  */
8090       input_location = iter->locus;
8091       perform_or_defer_access_check (TYPE_BINFO (type_scope),
8092                                      type_decl, type_decl);
8093     }
8094     input_location = saved_location;
8095 }
8096
8097 tree
8098 instantiate_class_template (tree type)
8099 {
8100   tree templ, args, pattern, t, member;
8101   tree typedecl;
8102   tree pbinfo;
8103   tree base_list;
8104   unsigned int saved_maximum_field_alignment;
8105
8106   if (type == error_mark_node)
8107     return error_mark_node;
8108
8109   if (COMPLETE_OR_OPEN_TYPE_P (type)
8110       || uses_template_parms (type))
8111     return type;
8112
8113   /* Figure out which template is being instantiated.  */
8114   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
8115   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
8116
8117   /* Determine what specialization of the original template to
8118      instantiate.  */
8119   t = most_specialized_class (type, templ, tf_warning_or_error);
8120   if (t == error_mark_node)
8121     {
8122       TYPE_BEING_DEFINED (type) = 1;
8123       return error_mark_node;
8124     }
8125   else if (t)
8126     {
8127       /* This TYPE is actually an instantiation of a partial
8128          specialization.  We replace the innermost set of ARGS with
8129          the arguments appropriate for substitution.  For example,
8130          given:
8131
8132            template <class T> struct S {};
8133            template <class T> struct S<T*> {};
8134
8135          and supposing that we are instantiating S<int*>, ARGS will
8136          presently be {int*} -- but we need {int}.  */
8137       pattern = TREE_TYPE (t);
8138       args = TREE_PURPOSE (t);
8139     }
8140   else
8141     {
8142       pattern = TREE_TYPE (templ);
8143       args = CLASSTYPE_TI_ARGS (type);
8144     }
8145
8146   /* If the template we're instantiating is incomplete, then clearly
8147      there's nothing we can do.  */
8148   if (!COMPLETE_TYPE_P (pattern))
8149     return type;
8150
8151   /* If we've recursively instantiated too many templates, stop.  */
8152   if (! push_tinst_level (type))
8153     return type;
8154
8155   /* Now we're really doing the instantiation.  Mark the type as in
8156      the process of being defined.  */
8157   TYPE_BEING_DEFINED (type) = 1;
8158
8159   /* We may be in the middle of deferred access check.  Disable
8160      it now.  */
8161   push_deferring_access_checks (dk_no_deferred);
8162
8163   push_to_top_level ();
8164   /* Use #pragma pack from the template context.  */
8165   saved_maximum_field_alignment = maximum_field_alignment;
8166   maximum_field_alignment = TYPE_PRECISION (pattern);
8167
8168   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
8169
8170   /* Set the input location to the most specialized template definition.
8171      This is needed if tsubsting causes an error.  */
8172   typedecl = TYPE_MAIN_DECL (pattern);
8173   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
8174     DECL_SOURCE_LOCATION (typedecl);
8175
8176   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
8177   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
8178   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
8179   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
8180   TYPE_HAS_COPY_ASSIGN (type) = TYPE_HAS_COPY_ASSIGN (pattern);
8181   TYPE_HAS_CONST_COPY_ASSIGN (type) = TYPE_HAS_CONST_COPY_ASSIGN (pattern);
8182   TYPE_HAS_COPY_CTOR (type) = TYPE_HAS_COPY_CTOR (pattern);
8183   TYPE_HAS_CONST_COPY_CTOR (type) = TYPE_HAS_CONST_COPY_CTOR (pattern);
8184   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
8185   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
8186   TYPE_PACKED (type) = TYPE_PACKED (pattern);
8187   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
8188   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
8189   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
8190   if (ANON_AGGR_TYPE_P (pattern))
8191     SET_ANON_AGGR_TYPE_P (type);
8192   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
8193     {
8194       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
8195       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
8196     }
8197
8198   pbinfo = TYPE_BINFO (pattern);
8199
8200   /* We should never instantiate a nested class before its enclosing
8201      class; we need to look up the nested class by name before we can
8202      instantiate it, and that lookup should instantiate the enclosing
8203      class.  */
8204   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
8205               || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
8206
8207   base_list = NULL_TREE;
8208   if (BINFO_N_BASE_BINFOS (pbinfo))
8209     {
8210       tree pbase_binfo;
8211       tree pushed_scope;
8212       int i;
8213
8214       /* We must enter the scope containing the type, as that is where
8215          the accessibility of types named in dependent bases are
8216          looked up from.  */
8217       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
8218
8219       /* Substitute into each of the bases to determine the actual
8220          basetypes.  */
8221       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
8222         {
8223           tree base;
8224           tree access = BINFO_BASE_ACCESS (pbinfo, i);
8225           tree expanded_bases = NULL_TREE;
8226           int idx, len = 1;
8227
8228           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
8229             {
8230               expanded_bases = 
8231                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
8232                                        args, tf_error, NULL_TREE);
8233               if (expanded_bases == error_mark_node)
8234                 continue;
8235
8236               len = TREE_VEC_LENGTH (expanded_bases);
8237             }
8238
8239           for (idx = 0; idx < len; idx++)
8240             {
8241               if (expanded_bases)
8242                 /* Extract the already-expanded base class.  */
8243                 base = TREE_VEC_ELT (expanded_bases, idx);
8244               else
8245                 /* Substitute to figure out the base class.  */
8246                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
8247                                NULL_TREE);
8248
8249               if (base == error_mark_node)
8250                 continue;
8251
8252               base_list = tree_cons (access, base, base_list);
8253               if (BINFO_VIRTUAL_P (pbase_binfo))
8254                 TREE_TYPE (base_list) = integer_type_node;
8255             }
8256         }
8257
8258       /* The list is now in reverse order; correct that.  */
8259       base_list = nreverse (base_list);
8260
8261       if (pushed_scope)
8262         pop_scope (pushed_scope);
8263     }
8264   /* Now call xref_basetypes to set up all the base-class
8265      information.  */
8266   xref_basetypes (type, base_list);
8267
8268   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
8269                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
8270                                   args, tf_error, NULL_TREE);
8271   fixup_attribute_variants (type);
8272
8273   /* Now that our base classes are set up, enter the scope of the
8274      class, so that name lookups into base classes, etc. will work
8275      correctly.  This is precisely analogous to what we do in
8276      begin_class_definition when defining an ordinary non-template
8277      class, except we also need to push the enclosing classes.  */
8278   push_nested_class (type);
8279
8280   /* Now members are processed in the order of declaration.  */
8281   for (member = CLASSTYPE_DECL_LIST (pattern);
8282        member; member = TREE_CHAIN (member))
8283     {
8284       tree t = TREE_VALUE (member);
8285
8286       if (TREE_PURPOSE (member))
8287         {
8288           if (TYPE_P (t))
8289             {
8290               /* Build new CLASSTYPE_NESTED_UTDS.  */
8291
8292               tree newtag;
8293               bool class_template_p;
8294
8295               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
8296                                   && TYPE_LANG_SPECIFIC (t)
8297                                   && CLASSTYPE_IS_TEMPLATE (t));
8298               /* If the member is a class template, then -- even after
8299                  substitution -- there may be dependent types in the
8300                  template argument list for the class.  We increment
8301                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
8302                  that function will assume that no types are dependent
8303                  when outside of a template.  */
8304               if (class_template_p)
8305                 ++processing_template_decl;
8306               newtag = tsubst (t, args, tf_error, NULL_TREE);
8307               if (class_template_p)
8308                 --processing_template_decl;
8309               if (newtag == error_mark_node)
8310                 continue;
8311
8312               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
8313                 {
8314                   tree name = TYPE_IDENTIFIER (t);
8315
8316                   if (class_template_p)
8317                     /* Unfortunately, lookup_template_class sets
8318                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
8319                        instantiation (i.e., for the type of a member
8320                        template class nested within a template class.)
8321                        This behavior is required for
8322                        maybe_process_partial_specialization to work
8323                        correctly, but is not accurate in this case;
8324                        the TAG is not an instantiation of anything.
8325                        (The corresponding TEMPLATE_DECL is an
8326                        instantiation, but the TYPE is not.) */
8327                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
8328
8329                   /* Now, we call pushtag to put this NEWTAG into the scope of
8330                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
8331                      pushtag calling push_template_decl.  We don't have to do
8332                      this for enums because it will already have been done in
8333                      tsubst_enum.  */
8334                   if (name)
8335                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
8336                   pushtag (name, newtag, /*tag_scope=*/ts_current);
8337                 }
8338             }
8339           else if (TREE_CODE (t) == FUNCTION_DECL
8340                    || DECL_FUNCTION_TEMPLATE_P (t))
8341             {
8342               /* Build new TYPE_METHODS.  */
8343               tree r;
8344
8345               if (TREE_CODE (t) == TEMPLATE_DECL)
8346                 ++processing_template_decl;
8347               r = tsubst (t, args, tf_error, NULL_TREE);
8348               if (TREE_CODE (t) == TEMPLATE_DECL)
8349                 --processing_template_decl;
8350               set_current_access_from_decl (r);
8351               finish_member_declaration (r);
8352             }
8353           else
8354             {
8355               /* Build new TYPE_FIELDS.  */
8356               if (TREE_CODE (t) == STATIC_ASSERT)
8357                 {
8358                   tree condition = 
8359                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
8360                                  tf_warning_or_error, NULL_TREE,
8361                                  /*integral_constant_expression_p=*/true);
8362                   finish_static_assert (condition,
8363                                         STATIC_ASSERT_MESSAGE (t), 
8364                                         STATIC_ASSERT_SOURCE_LOCATION (t),
8365                                         /*member_p=*/true);
8366                 }
8367               else if (TREE_CODE (t) != CONST_DECL)
8368                 {
8369                   tree r;
8370
8371                   /* The file and line for this declaration, to
8372                      assist in error message reporting.  Since we
8373                      called push_tinst_level above, we don't need to
8374                      restore these.  */
8375                   input_location = DECL_SOURCE_LOCATION (t);
8376
8377                   if (TREE_CODE (t) == TEMPLATE_DECL)
8378                     ++processing_template_decl;
8379                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
8380                   if (TREE_CODE (t) == TEMPLATE_DECL)
8381                     --processing_template_decl;
8382                   if (TREE_CODE (r) == VAR_DECL)
8383                     {
8384                       /* In [temp.inst]:
8385
8386                            [t]he initialization (and any associated
8387                            side-effects) of a static data member does
8388                            not occur unless the static data member is
8389                            itself used in a way that requires the
8390                            definition of the static data member to
8391                            exist.
8392
8393                          Therefore, we do not substitute into the
8394                          initialized for the static data member here.  */
8395                       finish_static_data_member_decl
8396                         (r,
8397                          /*init=*/NULL_TREE,
8398                          /*init_const_expr_p=*/false,
8399                          /*asmspec_tree=*/NULL_TREE,
8400                          /*flags=*/0);
8401                       if (DECL_INITIALIZED_IN_CLASS_P (r))
8402                         check_static_variable_definition (r, TREE_TYPE (r));
8403                     }
8404                   else if (TREE_CODE (r) == FIELD_DECL)
8405                     {
8406                       /* Determine whether R has a valid type and can be
8407                          completed later.  If R is invalid, then it is
8408                          replaced by error_mark_node so that it will not be
8409                          added to TYPE_FIELDS.  */
8410                       tree rtype = TREE_TYPE (r);
8411                       if (can_complete_type_without_circularity (rtype))
8412                         complete_type (rtype);
8413
8414                       if (!COMPLETE_TYPE_P (rtype))
8415                         {
8416                           cxx_incomplete_type_error (r, rtype);
8417                           r = error_mark_node;
8418                         }
8419                     }
8420
8421                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
8422                      such a thing will already have been added to the field
8423                      list by tsubst_enum in finish_member_declaration in the
8424                      CLASSTYPE_NESTED_UTDS case above.  */
8425                   if (!(TREE_CODE (r) == TYPE_DECL
8426                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
8427                         && DECL_ARTIFICIAL (r)))
8428                     {
8429                       set_current_access_from_decl (r);
8430                       finish_member_declaration (r);
8431                     }
8432                 }
8433             }
8434         }
8435       else
8436         {
8437           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
8438             {
8439               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
8440
8441               tree friend_type = t;
8442               bool adjust_processing_template_decl = false;
8443
8444               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8445                 {
8446                   /* template <class T> friend class C;  */
8447                   friend_type = tsubst_friend_class (friend_type, args);
8448                   adjust_processing_template_decl = true;
8449                 }
8450               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
8451                 {
8452                   /* template <class T> friend class C::D;  */
8453                   friend_type = tsubst (friend_type, args,
8454                                         tf_warning_or_error, NULL_TREE);
8455                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8456                     friend_type = TREE_TYPE (friend_type);
8457                   adjust_processing_template_decl = true;
8458                 }
8459               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
8460                 {
8461                   /* This could be either
8462
8463                        friend class T::C;
8464
8465                      when dependent_type_p is false or
8466
8467                        template <class U> friend class T::C;
8468
8469                      otherwise.  */
8470                   friend_type = tsubst (friend_type, args,
8471                                         tf_warning_or_error, NULL_TREE);
8472                   /* Bump processing_template_decl for correct
8473                      dependent_type_p calculation.  */
8474                   ++processing_template_decl;
8475                   if (dependent_type_p (friend_type))
8476                     adjust_processing_template_decl = true;
8477                   --processing_template_decl;
8478                 }
8479               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
8480                        && hidden_name_p (TYPE_NAME (friend_type)))
8481                 {
8482                   /* friend class C;
8483
8484                      where C hasn't been declared yet.  Let's lookup name
8485                      from namespace scope directly, bypassing any name that
8486                      come from dependent base class.  */
8487                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
8488
8489                   /* The call to xref_tag_from_type does injection for friend
8490                      classes.  */
8491                   push_nested_namespace (ns);
8492                   friend_type =
8493                     xref_tag_from_type (friend_type, NULL_TREE,
8494                                         /*tag_scope=*/ts_current);
8495                   pop_nested_namespace (ns);
8496                 }
8497               else if (uses_template_parms (friend_type))
8498                 /* friend class C<T>;  */
8499                 friend_type = tsubst (friend_type, args,
8500                                       tf_warning_or_error, NULL_TREE);
8501               /* Otherwise it's
8502
8503                    friend class C;
8504
8505                  where C is already declared or
8506
8507                    friend class C<int>;
8508
8509                  We don't have to do anything in these cases.  */
8510
8511               if (adjust_processing_template_decl)
8512                 /* Trick make_friend_class into realizing that the friend
8513                    we're adding is a template, not an ordinary class.  It's
8514                    important that we use make_friend_class since it will
8515                    perform some error-checking and output cross-reference
8516                    information.  */
8517                 ++processing_template_decl;
8518
8519               if (friend_type != error_mark_node)
8520                 make_friend_class (type, friend_type, /*complain=*/false);
8521
8522               if (adjust_processing_template_decl)
8523                 --processing_template_decl;
8524             }
8525           else
8526             {
8527               /* Build new DECL_FRIENDLIST.  */
8528               tree r;
8529
8530               /* The file and line for this declaration, to
8531                  assist in error message reporting.  Since we
8532                  called push_tinst_level above, we don't need to
8533                  restore these.  */
8534               input_location = DECL_SOURCE_LOCATION (t);
8535
8536               if (TREE_CODE (t) == TEMPLATE_DECL)
8537                 {
8538                   ++processing_template_decl;
8539                   push_deferring_access_checks (dk_no_check);
8540                 }
8541
8542               r = tsubst_friend_function (t, args);
8543               add_friend (type, r, /*complain=*/false);
8544               if (TREE_CODE (t) == TEMPLATE_DECL)
8545                 {
8546                   pop_deferring_access_checks ();
8547                   --processing_template_decl;
8548                 }
8549             }
8550         }
8551     }
8552
8553   /* Set the file and line number information to whatever is given for
8554      the class itself.  This puts error messages involving generated
8555      implicit functions at a predictable point, and the same point
8556      that would be used for non-template classes.  */
8557   input_location = DECL_SOURCE_LOCATION (typedecl);
8558
8559   unreverse_member_declarations (type);
8560   finish_struct_1 (type);
8561   TYPE_BEING_DEFINED (type) = 0;
8562
8563   /* We don't instantiate default arguments for member functions.  14.7.1:
8564
8565      The implicit instantiation of a class template specialization causes
8566      the implicit instantiation of the declarations, but not of the
8567      definitions or default arguments, of the class member functions,
8568      member classes, static data members and member templates....  */
8569
8570   /* Some typedefs referenced from within the template code need to be access
8571      checked at template instantiation time, i.e now. These types were
8572      added to the template at parsing time. Let's get those and perform
8573      the access checks then.  */
8574   perform_typedefs_access_check (pattern, args);
8575   perform_deferred_access_checks ();
8576   pop_nested_class ();
8577   maximum_field_alignment = saved_maximum_field_alignment;
8578   pop_from_top_level ();
8579   pop_deferring_access_checks ();
8580   pop_tinst_level ();
8581
8582   /* The vtable for a template class can be emitted in any translation
8583      unit in which the class is instantiated.  When there is no key
8584      method, however, finish_struct_1 will already have added TYPE to
8585      the keyed_classes list.  */
8586   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
8587     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
8588
8589   return type;
8590 }
8591
8592 static tree
8593 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8594 {
8595   tree r;
8596
8597   if (!t)
8598     r = t;
8599   else if (TYPE_P (t))
8600     r = tsubst (t, args, complain, in_decl);
8601   else
8602     {
8603       if (!(complain & tf_warning))
8604         ++c_inhibit_evaluation_warnings;
8605       r = tsubst_expr (t, args, complain, in_decl,
8606                        /*integral_constant_expression_p=*/true);
8607       if (!(complain & tf_warning))
8608         --c_inhibit_evaluation_warnings;
8609     }
8610   return r;
8611 }
8612
8613 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
8614    NONTYPE_ARGUMENT_PACK.  */
8615
8616 static tree
8617 make_fnparm_pack (tree spec_parm)
8618 {
8619   /* Collect all of the extra "packed" parameters into an
8620      argument pack.  */
8621   tree parmvec;
8622   tree parmtypevec;
8623   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
8624   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
8625   int i, len = list_length (spec_parm);
8626
8627   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
8628   parmvec = make_tree_vec (len);
8629   parmtypevec = make_tree_vec (len);
8630   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
8631     {
8632       TREE_VEC_ELT (parmvec, i) = spec_parm;
8633       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
8634     }
8635
8636   /* Build the argument packs.  */
8637   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
8638   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
8639   TREE_TYPE (argpack) = argtypepack;
8640
8641   return argpack;
8642 }        
8643
8644 /* Substitute ARGS into T, which is an pack expansion
8645    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
8646    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
8647    (if only a partial substitution could be performed) or
8648    ERROR_MARK_NODE if there was an error.  */
8649 tree
8650 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
8651                        tree in_decl)
8652 {
8653   tree pattern;
8654   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
8655   int i, len = -1;
8656   tree result;
8657   int incomplete = 0;
8658   htab_t saved_local_specializations = NULL;
8659
8660   gcc_assert (PACK_EXPANSION_P (t));
8661   pattern = PACK_EXPANSION_PATTERN (t);
8662
8663   /* Determine the argument packs that will instantiate the parameter
8664      packs used in the expansion expression. While we're at it,
8665      compute the number of arguments to be expanded and make sure it
8666      is consistent.  */
8667   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
8668        pack = TREE_CHAIN (pack))
8669     {
8670       tree parm_pack = TREE_VALUE (pack);
8671       tree arg_pack = NULL_TREE;
8672       tree orig_arg = NULL_TREE;
8673
8674       if (TREE_CODE (parm_pack) == PARM_DECL)
8675         {
8676           if (!cp_unevaluated_operand)
8677             arg_pack = retrieve_local_specialization (parm_pack);
8678           else
8679             {
8680               /* We can't rely on local_specializations for a parameter
8681                  name used later in a function declaration (such as in a
8682                  late-specified return type).  Even if it exists, it might
8683                  have the wrong value for a recursive call.  Just make a
8684                  dummy decl, since it's only used for its type.  */
8685               arg_pack = tsubst_decl (parm_pack, args, complain);
8686               arg_pack = make_fnparm_pack (arg_pack);
8687             }
8688         }
8689       else
8690         {
8691           int level, idx, levels;
8692           template_parm_level_and_index (parm_pack, &level, &idx);
8693
8694           levels = TMPL_ARGS_DEPTH (args);
8695           if (level <= levels)
8696             arg_pack = TMPL_ARG (args, level, idx);
8697         }
8698
8699       orig_arg = arg_pack;
8700       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
8701         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
8702       
8703       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
8704         /* This can only happen if we forget to expand an argument
8705            pack somewhere else. Just return an error, silently.  */
8706         {
8707           result = make_tree_vec (1);
8708           TREE_VEC_ELT (result, 0) = error_mark_node;
8709           return result;
8710         }
8711
8712       if (arg_pack
8713           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
8714           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
8715         {
8716           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
8717           tree pattern = PACK_EXPANSION_PATTERN (expansion);
8718           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
8719               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
8720             /* The argument pack that the parameter maps to is just an
8721                expansion of the parameter itself, such as one would
8722                find in the implicit typedef of a class inside the
8723                class itself.  Consider this parameter "unsubstituted",
8724                so that we will maintain the outer pack expansion.  */
8725             arg_pack = NULL_TREE;
8726         }
8727           
8728       if (arg_pack)
8729         {
8730           int my_len = 
8731             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
8732
8733           /* It's all-or-nothing with incomplete argument packs.  */
8734           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8735             return error_mark_node;
8736           
8737           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8738             incomplete = 1;
8739
8740           if (len < 0)
8741             len = my_len;
8742           else if (len != my_len)
8743             {
8744               if (incomplete)
8745                 /* We got explicit args for some packs but not others;
8746                    do nothing now and try again after deduction.  */
8747                 return t;
8748               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
8749                 error ("mismatched argument pack lengths while expanding "
8750                        "%<%T%>",
8751                        pattern);
8752               else
8753                 error ("mismatched argument pack lengths while expanding "
8754                        "%<%E%>",
8755                        pattern);
8756               return error_mark_node;
8757             }
8758
8759           /* Keep track of the parameter packs and their corresponding
8760              argument packs.  */
8761           packs = tree_cons (parm_pack, arg_pack, packs);
8762           TREE_TYPE (packs) = orig_arg;
8763         }
8764       else
8765         /* We can't substitute for this parameter pack.  */
8766         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
8767                                          TREE_VALUE (pack),
8768                                          unsubstituted_packs);
8769     }
8770
8771   /* We cannot expand this expansion expression, because we don't have
8772      all of the argument packs we need. Substitute into the pattern
8773      and return a PACK_EXPANSION_*. The caller will need to deal with
8774      that.  */
8775   if (unsubstituted_packs)
8776     {
8777       tree new_pat;
8778       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8779         new_pat = tsubst_expr (pattern, args, complain, in_decl,
8780                                /*integral_constant_expression_p=*/false);
8781       else
8782         new_pat = tsubst (pattern, args, complain, in_decl);
8783       return make_pack_expansion (new_pat);
8784     }
8785
8786   /* We could not find any argument packs that work.  */
8787   if (len < 0)
8788     return error_mark_node;
8789
8790   if (cp_unevaluated_operand)
8791     {
8792       /* We're in a late-specified return type, so create our own local
8793          specializations table; the current table is either NULL or (in the
8794          case of recursive unification) might have bindings that we don't
8795          want to use or alter.  */
8796       saved_local_specializations = local_specializations;
8797       local_specializations = htab_create (37,
8798                                            hash_local_specialization,
8799                                            eq_local_specializations,
8800                                            NULL);
8801     }
8802
8803   /* For each argument in each argument pack, substitute into the
8804      pattern.  */
8805   result = make_tree_vec (len + incomplete);
8806   for (i = 0; i < len + incomplete; ++i)
8807     {
8808       /* For parameter pack, change the substitution of the parameter
8809          pack to the ith argument in its argument pack, then expand
8810          the pattern.  */
8811       for (pack = packs; pack; pack = TREE_CHAIN (pack))
8812         {
8813           tree parm = TREE_PURPOSE (pack);
8814
8815           if (TREE_CODE (parm) == PARM_DECL)
8816             {
8817               /* Select the Ith argument from the pack.  */
8818               tree arg = make_node (ARGUMENT_PACK_SELECT);
8819               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
8820               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
8821               mark_used (parm);
8822               register_local_specialization (arg, parm);
8823             }
8824           else
8825             {
8826               tree value = parm;
8827               int idx, level;
8828               template_parm_level_and_index (parm, &level, &idx);
8829               
8830               if (i < len) 
8831                 {
8832                   /* Select the Ith argument from the pack. */
8833                   value = make_node (ARGUMENT_PACK_SELECT);
8834                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
8835                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
8836                 }
8837
8838               /* Update the corresponding argument.  */
8839               TMPL_ARG (args, level, idx) = value;
8840             }
8841         }
8842
8843       /* Substitute into the PATTERN with the altered arguments.  */
8844       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8845         TREE_VEC_ELT (result, i) = 
8846           tsubst_expr (pattern, args, complain, in_decl,
8847                        /*integral_constant_expression_p=*/false);
8848       else
8849         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
8850
8851       if (i == len)
8852         /* When we have incomplete argument packs, the last "expanded"
8853            result is itself a pack expansion, which allows us
8854            to deduce more arguments.  */
8855         TREE_VEC_ELT (result, i) = 
8856           make_pack_expansion (TREE_VEC_ELT (result, i));
8857
8858       if (TREE_VEC_ELT (result, i) == error_mark_node)
8859         {
8860           result = error_mark_node;
8861           break;
8862         }
8863     }
8864
8865   /* Update ARGS to restore the substitution from parameter packs to
8866      their argument packs.  */
8867   for (pack = packs; pack; pack = TREE_CHAIN (pack))
8868     {
8869       tree parm = TREE_PURPOSE (pack);
8870
8871       if (TREE_CODE (parm) == PARM_DECL)
8872         register_local_specialization (TREE_TYPE (pack), parm);
8873       else
8874         {
8875           int idx, level;
8876           template_parm_level_and_index (parm, &level, &idx);
8877           
8878           /* Update the corresponding argument.  */
8879           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
8880             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
8881               TREE_TYPE (pack);
8882           else
8883             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
8884         }
8885     }
8886
8887   if (saved_local_specializations)
8888     {
8889       htab_delete (local_specializations);
8890       local_specializations = saved_local_specializations;
8891     }
8892   
8893   return result;
8894 }
8895
8896 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
8897    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
8898    parameter packs; all parms generated from a function parameter pack will
8899    have the same DECL_PARM_INDEX.  */
8900
8901 tree
8902 get_pattern_parm (tree parm, tree tmpl)
8903 {
8904   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
8905   tree patparm;
8906
8907   if (DECL_ARTIFICIAL (parm))
8908     {
8909       for (patparm = DECL_ARGUMENTS (pattern);
8910            patparm; patparm = DECL_CHAIN (patparm))
8911         if (DECL_ARTIFICIAL (patparm)
8912             && DECL_NAME (parm) == DECL_NAME (patparm))
8913           break;
8914     }
8915   else
8916     {
8917       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
8918       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
8919       gcc_assert (DECL_PARM_INDEX (patparm)
8920                   == DECL_PARM_INDEX (parm));
8921     }
8922
8923   return patparm;
8924 }
8925
8926 /* Substitute ARGS into the vector or list of template arguments T.  */
8927
8928 static tree
8929 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8930 {
8931   tree orig_t = t;
8932   int len = TREE_VEC_LENGTH (t);
8933   int need_new = 0, i, expanded_len_adjust = 0, out;
8934   tree *elts = XALLOCAVEC (tree, len);
8935
8936   for (i = 0; i < len; i++)
8937     {
8938       tree orig_arg = TREE_VEC_ELT (t, i);
8939       tree new_arg;
8940
8941       if (TREE_CODE (orig_arg) == TREE_VEC)
8942         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
8943       else if (PACK_EXPANSION_P (orig_arg))
8944         {
8945           /* Substitute into an expansion expression.  */
8946           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
8947
8948           if (TREE_CODE (new_arg) == TREE_VEC)
8949             /* Add to the expanded length adjustment the number of
8950                expanded arguments. We subtract one from this
8951                measurement, because the argument pack expression
8952                itself is already counted as 1 in
8953                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
8954                the argument pack is empty.  */
8955             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
8956         }
8957       else if (ARGUMENT_PACK_P (orig_arg))
8958         {
8959           /* Substitute into each of the arguments.  */
8960           new_arg = TYPE_P (orig_arg)
8961             ? cxx_make_type (TREE_CODE (orig_arg))
8962             : make_node (TREE_CODE (orig_arg));
8963           
8964           SET_ARGUMENT_PACK_ARGS (
8965             new_arg,
8966             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
8967                                   args, complain, in_decl));
8968
8969           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
8970             new_arg = error_mark_node;
8971
8972           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
8973             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
8974                                           complain, in_decl);
8975             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
8976
8977             if (TREE_TYPE (new_arg) == error_mark_node)
8978               new_arg = error_mark_node;
8979           }
8980         }
8981       else
8982         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
8983
8984       if (new_arg == error_mark_node)
8985         return error_mark_node;
8986
8987       elts[i] = new_arg;
8988       if (new_arg != orig_arg)
8989         need_new = 1;
8990     }
8991
8992   if (!need_new)
8993     return t;
8994
8995   /* Make space for the expanded arguments coming from template
8996      argument packs.  */
8997   t = make_tree_vec (len + expanded_len_adjust);
8998   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
8999      arguments for a member template.
9000      In that case each TREE_VEC in ORIG_T represents a level of template
9001      arguments, and ORIG_T won't carry any non defaulted argument count.
9002      It will rather be the nested TREE_VECs that will carry one.
9003      In other words, ORIG_T carries a non defaulted argument count only
9004      if it doesn't contain any nested TREE_VEC.  */
9005   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
9006     {
9007       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
9008       count += expanded_len_adjust;
9009       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
9010     }
9011   for (i = 0, out = 0; i < len; i++)
9012     {
9013       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
9014            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
9015           && TREE_CODE (elts[i]) == TREE_VEC)
9016         {
9017           int idx;
9018
9019           /* Now expand the template argument pack "in place".  */
9020           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
9021             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
9022         }
9023       else
9024         {
9025           TREE_VEC_ELT (t, out) = elts[i];
9026           out++;
9027         }
9028     }
9029
9030   return t;
9031 }
9032
9033 /* Return the result of substituting ARGS into the template parameters
9034    given by PARMS.  If there are m levels of ARGS and m + n levels of
9035    PARMS, then the result will contain n levels of PARMS.  For
9036    example, if PARMS is `template <class T> template <class U>
9037    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
9038    result will be `template <int*, double, class V>'.  */
9039
9040 static tree
9041 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
9042 {
9043   tree r = NULL_TREE;
9044   tree* new_parms;
9045
9046   /* When substituting into a template, we must set
9047      PROCESSING_TEMPLATE_DECL as the template parameters may be
9048      dependent if they are based on one-another, and the dependency
9049      predicates are short-circuit outside of templates.  */
9050   ++processing_template_decl;
9051
9052   for (new_parms = &r;
9053        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
9054        new_parms = &(TREE_CHAIN (*new_parms)),
9055          parms = TREE_CHAIN (parms))
9056     {
9057       tree new_vec =
9058         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
9059       int i;
9060
9061       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
9062         {
9063           tree tuple;
9064
9065           if (parms == error_mark_node)
9066             continue;
9067
9068           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
9069
9070           if (tuple == error_mark_node)
9071             continue;
9072
9073           TREE_VEC_ELT (new_vec, i) =
9074             tsubst_template_parm (tuple, args, complain);
9075         }
9076
9077       *new_parms =
9078         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
9079                              - TMPL_ARGS_DEPTH (args)),
9080                    new_vec, NULL_TREE);
9081     }
9082
9083   --processing_template_decl;
9084
9085   return r;
9086 }
9087
9088 /* Return the result of substituting ARGS into one template parameter
9089    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
9090    parameter and which TREE_PURPOSE is the default argument of the
9091    template parameter.  */
9092
9093 static tree
9094 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
9095 {
9096   tree default_value, parm_decl;
9097
9098   if (args == NULL_TREE
9099       || t == NULL_TREE
9100       || t == error_mark_node)
9101     return t;
9102
9103   gcc_assert (TREE_CODE (t) == TREE_LIST);
9104
9105   default_value = TREE_PURPOSE (t);
9106   parm_decl = TREE_VALUE (t);
9107
9108   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
9109   if (TREE_CODE (parm_decl) == PARM_DECL
9110       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
9111     parm_decl = error_mark_node;
9112   default_value = tsubst_template_arg (default_value, args,
9113                                        complain, NULL_TREE);
9114
9115   return build_tree_list (default_value, parm_decl);
9116 }
9117
9118 /* Substitute the ARGS into the indicated aggregate (or enumeration)
9119    type T.  If T is not an aggregate or enumeration type, it is
9120    handled as if by tsubst.  IN_DECL is as for tsubst.  If
9121    ENTERING_SCOPE is nonzero, T is the context for a template which
9122    we are presently tsubst'ing.  Return the substituted value.  */
9123
9124 static tree
9125 tsubst_aggr_type (tree t,
9126                   tree args,
9127                   tsubst_flags_t complain,
9128                   tree in_decl,
9129                   int entering_scope)
9130 {
9131   if (t == NULL_TREE)
9132     return NULL_TREE;
9133
9134   switch (TREE_CODE (t))
9135     {
9136     case RECORD_TYPE:
9137       if (TYPE_PTRMEMFUNC_P (t))
9138         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
9139
9140       /* Else fall through.  */
9141     case ENUMERAL_TYPE:
9142     case UNION_TYPE:
9143       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
9144         {
9145           tree argvec;
9146           tree context;
9147           tree r;
9148           int saved_unevaluated_operand;
9149           int saved_inhibit_evaluation_warnings;
9150
9151           /* In "sizeof(X<I>)" we need to evaluate "I".  */
9152           saved_unevaluated_operand = cp_unevaluated_operand;
9153           cp_unevaluated_operand = 0;
9154           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
9155           c_inhibit_evaluation_warnings = 0;
9156
9157           /* First, determine the context for the type we are looking
9158              up.  */
9159           context = TYPE_CONTEXT (t);
9160           if (context)
9161             {
9162               context = tsubst_aggr_type (context, args, complain,
9163                                           in_decl, /*entering_scope=*/1);
9164               /* If context is a nested class inside a class template,
9165                  it may still need to be instantiated (c++/33959).  */
9166               if (TYPE_P (context))
9167                 context = complete_type (context);
9168             }
9169
9170           /* Then, figure out what arguments are appropriate for the
9171              type we are trying to find.  For example, given:
9172
9173                template <class T> struct S;
9174                template <class T, class U> void f(T, U) { S<U> su; }
9175
9176              and supposing that we are instantiating f<int, double>,
9177              then our ARGS will be {int, double}, but, when looking up
9178              S we only want {double}.  */
9179           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
9180                                          complain, in_decl);
9181           if (argvec == error_mark_node)
9182             r = error_mark_node;
9183           else
9184             {
9185               r = lookup_template_class (t, argvec, in_decl, context,
9186                                          entering_scope, complain);
9187               r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
9188             }
9189
9190           cp_unevaluated_operand = saved_unevaluated_operand;
9191           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
9192
9193           return r;
9194         }
9195       else
9196         /* This is not a template type, so there's nothing to do.  */
9197         return t;
9198
9199     default:
9200       return tsubst (t, args, complain, in_decl);
9201     }
9202 }
9203
9204 /* Substitute into the default argument ARG (a default argument for
9205    FN), which has the indicated TYPE.  */
9206
9207 tree
9208 tsubst_default_argument (tree fn, tree type, tree arg)
9209 {
9210   tree saved_class_ptr = NULL_TREE;
9211   tree saved_class_ref = NULL_TREE;
9212
9213   /* This can happen in invalid code.  */
9214   if (TREE_CODE (arg) == DEFAULT_ARG)
9215     return arg;
9216
9217   /* This default argument came from a template.  Instantiate the
9218      default argument here, not in tsubst.  In the case of
9219      something like:
9220
9221        template <class T>
9222        struct S {
9223          static T t();
9224          void f(T = t());
9225        };
9226
9227      we must be careful to do name lookup in the scope of S<T>,
9228      rather than in the current class.  */
9229   push_access_scope (fn);
9230   /* The "this" pointer is not valid in a default argument.  */
9231   if (cfun)
9232     {
9233       saved_class_ptr = current_class_ptr;
9234       cp_function_chain->x_current_class_ptr = NULL_TREE;
9235       saved_class_ref = current_class_ref;
9236       cp_function_chain->x_current_class_ref = NULL_TREE;
9237     }
9238
9239   push_deferring_access_checks(dk_no_deferred);
9240   /* The default argument expression may cause implicitly defined
9241      member functions to be synthesized, which will result in garbage
9242      collection.  We must treat this situation as if we were within
9243      the body of function so as to avoid collecting live data on the
9244      stack.  */
9245   ++function_depth;
9246   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
9247                      tf_warning_or_error, NULL_TREE,
9248                      /*integral_constant_expression_p=*/false);
9249   --function_depth;
9250   pop_deferring_access_checks();
9251
9252   /* Restore the "this" pointer.  */
9253   if (cfun)
9254     {
9255       cp_function_chain->x_current_class_ptr = saved_class_ptr;
9256       cp_function_chain->x_current_class_ref = saved_class_ref;
9257     }
9258
9259   /* Make sure the default argument is reasonable.  */
9260   arg = check_default_argument (type, arg);
9261
9262   pop_access_scope (fn);
9263
9264   return arg;
9265 }
9266
9267 /* Substitute into all the default arguments for FN.  */
9268
9269 static void
9270 tsubst_default_arguments (tree fn)
9271 {
9272   tree arg;
9273   tree tmpl_args;
9274
9275   tmpl_args = DECL_TI_ARGS (fn);
9276
9277   /* If this function is not yet instantiated, we certainly don't need
9278      its default arguments.  */
9279   if (uses_template_parms (tmpl_args))
9280     return;
9281   /* Don't do this again for clones.  */
9282   if (DECL_CLONED_FUNCTION_P (fn))
9283     return;
9284
9285   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
9286        arg;
9287        arg = TREE_CHAIN (arg))
9288     if (TREE_PURPOSE (arg))
9289       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
9290                                                     TREE_VALUE (arg),
9291                                                     TREE_PURPOSE (arg));
9292 }
9293
9294 /* Substitute the ARGS into the T, which is a _DECL.  Return the
9295    result of the substitution.  Issue error and warning messages under
9296    control of COMPLAIN.  */
9297
9298 static tree
9299 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
9300 {
9301 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
9302   location_t saved_loc;
9303   tree r = NULL_TREE;
9304   tree in_decl = t;
9305   hashval_t hash = 0;
9306
9307   /* Set the filename and linenumber to improve error-reporting.  */
9308   saved_loc = input_location;
9309   input_location = DECL_SOURCE_LOCATION (t);
9310
9311   switch (TREE_CODE (t))
9312     {
9313     case TEMPLATE_DECL:
9314       {
9315         /* We can get here when processing a member function template,
9316            member class template, or template template parameter.  */
9317         tree decl = DECL_TEMPLATE_RESULT (t);
9318         tree spec;
9319         tree tmpl_args;
9320         tree full_args;
9321
9322         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9323           {
9324             /* Template template parameter is treated here.  */
9325             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9326             if (new_type == error_mark_node)
9327               RETURN (error_mark_node);
9328
9329             r = copy_decl (t);
9330             DECL_CHAIN (r) = NULL_TREE;
9331             TREE_TYPE (r) = new_type;
9332             DECL_TEMPLATE_RESULT (r)
9333               = build_decl (DECL_SOURCE_LOCATION (decl),
9334                             TYPE_DECL, DECL_NAME (decl), new_type);
9335             DECL_TEMPLATE_PARMS (r)
9336               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9337                                        complain);
9338             TYPE_NAME (new_type) = r;
9339             break;
9340           }
9341
9342         /* We might already have an instance of this template.
9343            The ARGS are for the surrounding class type, so the
9344            full args contain the tsubst'd args for the context,
9345            plus the innermost args from the template decl.  */
9346         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
9347           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
9348           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
9349         /* Because this is a template, the arguments will still be
9350            dependent, even after substitution.  If
9351            PROCESSING_TEMPLATE_DECL is not set, the dependency
9352            predicates will short-circuit.  */
9353         ++processing_template_decl;
9354         full_args = tsubst_template_args (tmpl_args, args,
9355                                           complain, in_decl);
9356         --processing_template_decl;
9357         if (full_args == error_mark_node)
9358           RETURN (error_mark_node);
9359
9360         /* If this is a default template template argument,
9361            tsubst might not have changed anything.  */
9362         if (full_args == tmpl_args)
9363           RETURN (t);
9364
9365         hash = hash_tmpl_and_args (t, full_args);
9366         spec = retrieve_specialization (t, full_args, hash);
9367         if (spec != NULL_TREE)
9368           {
9369             r = spec;
9370             break;
9371           }
9372
9373         /* Make a new template decl.  It will be similar to the
9374            original, but will record the current template arguments.
9375            We also create a new function declaration, which is just
9376            like the old one, but points to this new template, rather
9377            than the old one.  */
9378         r = copy_decl (t);
9379         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
9380         DECL_CHAIN (r) = NULL_TREE;
9381
9382         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
9383
9384         if (TREE_CODE (decl) == TYPE_DECL)
9385           {
9386             tree new_type;
9387             ++processing_template_decl;
9388             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9389             --processing_template_decl;
9390             if (new_type == error_mark_node)
9391               RETURN (error_mark_node);
9392
9393             TREE_TYPE (r) = new_type;
9394             CLASSTYPE_TI_TEMPLATE (new_type) = r;
9395             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
9396             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
9397             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
9398           }
9399         else
9400           {
9401             tree new_decl;
9402             ++processing_template_decl;
9403             new_decl = tsubst (decl, args, complain, in_decl);
9404             --processing_template_decl;
9405             if (new_decl == error_mark_node)
9406               RETURN (error_mark_node);
9407
9408             DECL_TEMPLATE_RESULT (r) = new_decl;
9409             DECL_TI_TEMPLATE (new_decl) = r;
9410             TREE_TYPE (r) = TREE_TYPE (new_decl);
9411             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
9412             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
9413           }
9414
9415         SET_DECL_IMPLICIT_INSTANTIATION (r);
9416         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
9417         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
9418
9419         /* The template parameters for this new template are all the
9420            template parameters for the old template, except the
9421            outermost level of parameters.  */
9422         DECL_TEMPLATE_PARMS (r)
9423           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9424                                    complain);
9425
9426         if (PRIMARY_TEMPLATE_P (t))
9427           DECL_PRIMARY_TEMPLATE (r) = r;
9428
9429         if (TREE_CODE (decl) != TYPE_DECL)
9430           /* Record this non-type partial instantiation.  */
9431           register_specialization (r, t,
9432                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
9433                                    false, hash);
9434       }
9435       break;
9436
9437     case FUNCTION_DECL:
9438       {
9439         tree ctx;
9440         tree argvec = NULL_TREE;
9441         tree *friends;
9442         tree gen_tmpl;
9443         tree type;
9444         int member;
9445         int args_depth;
9446         int parms_depth;
9447
9448         /* Nobody should be tsubst'ing into non-template functions.  */
9449         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
9450
9451         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
9452           {
9453             tree spec;
9454             bool dependent_p;
9455
9456             /* If T is not dependent, just return it.  We have to
9457                increment PROCESSING_TEMPLATE_DECL because
9458                value_dependent_expression_p assumes that nothing is
9459                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
9460             ++processing_template_decl;
9461             dependent_p = value_dependent_expression_p (t);
9462             --processing_template_decl;
9463             if (!dependent_p)
9464               RETURN (t);
9465
9466             /* Calculate the most general template of which R is a
9467                specialization, and the complete set of arguments used to
9468                specialize R.  */
9469             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
9470             argvec = tsubst_template_args (DECL_TI_ARGS
9471                                           (DECL_TEMPLATE_RESULT
9472                                                  (DECL_TI_TEMPLATE (t))),
9473                                            args, complain, in_decl);
9474
9475             /* Check to see if we already have this specialization.  */
9476             hash = hash_tmpl_and_args (gen_tmpl, argvec);
9477             spec = retrieve_specialization (gen_tmpl, argvec, hash);
9478
9479             if (spec)
9480               {
9481                 r = spec;
9482                 break;
9483               }
9484
9485             /* We can see more levels of arguments than parameters if
9486                there was a specialization of a member template, like
9487                this:
9488
9489                  template <class T> struct S { template <class U> void f(); }
9490                  template <> template <class U> void S<int>::f(U);
9491
9492                Here, we'll be substituting into the specialization,
9493                because that's where we can find the code we actually
9494                want to generate, but we'll have enough arguments for
9495                the most general template.
9496
9497                We also deal with the peculiar case:
9498
9499                  template <class T> struct S {
9500                    template <class U> friend void f();
9501                  };
9502                  template <class U> void f() {}
9503                  template S<int>;
9504                  template void f<double>();
9505
9506                Here, the ARGS for the instantiation of will be {int,
9507                double}.  But, we only need as many ARGS as there are
9508                levels of template parameters in CODE_PATTERN.  We are
9509                careful not to get fooled into reducing the ARGS in
9510                situations like:
9511
9512                  template <class T> struct S { template <class U> void f(U); }
9513                  template <class T> template <> void S<T>::f(int) {}
9514
9515                which we can spot because the pattern will be a
9516                specialization in this case.  */
9517             args_depth = TMPL_ARGS_DEPTH (args);
9518             parms_depth =
9519               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
9520             if (args_depth > parms_depth
9521                 && !DECL_TEMPLATE_SPECIALIZATION (t))
9522               args = get_innermost_template_args (args, parms_depth);
9523           }
9524         else
9525           {
9526             /* This special case arises when we have something like this:
9527
9528                  template <class T> struct S {
9529                    friend void f<int>(int, double);
9530                  };
9531
9532                Here, the DECL_TI_TEMPLATE for the friend declaration
9533                will be an IDENTIFIER_NODE.  We are being called from
9534                tsubst_friend_function, and we want only to create a
9535                new decl (R) with appropriate types so that we can call
9536                determine_specialization.  */
9537             gen_tmpl = NULL_TREE;
9538           }
9539
9540         if (DECL_CLASS_SCOPE_P (t))
9541           {
9542             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
9543               member = 2;
9544             else
9545               member = 1;
9546             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
9547                                     complain, t, /*entering_scope=*/1);
9548           }
9549         else
9550           {
9551             member = 0;
9552             ctx = DECL_CONTEXT (t);
9553           }
9554         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9555         if (type == error_mark_node)
9556           RETURN (error_mark_node);
9557
9558         /* We do NOT check for matching decls pushed separately at this
9559            point, as they may not represent instantiations of this
9560            template, and in any case are considered separate under the
9561            discrete model.  */
9562         r = copy_decl (t);
9563         DECL_USE_TEMPLATE (r) = 0;
9564         TREE_TYPE (r) = type;
9565         /* Clear out the mangled name and RTL for the instantiation.  */
9566         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9567         SET_DECL_RTL (r, NULL);
9568         /* Leave DECL_INITIAL set on deleted instantiations.  */
9569         if (!DECL_DELETED_FN (r))
9570           DECL_INITIAL (r) = NULL_TREE;
9571         DECL_CONTEXT (r) = ctx;
9572
9573         if (member && DECL_CONV_FN_P (r))
9574           /* Type-conversion operator.  Reconstruct the name, in
9575              case it's the name of one of the template's parameters.  */
9576           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
9577
9578         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
9579                                      complain, t);
9580         DECL_RESULT (r) = NULL_TREE;
9581
9582         TREE_STATIC (r) = 0;
9583         TREE_PUBLIC (r) = TREE_PUBLIC (t);
9584         DECL_EXTERNAL (r) = 1;
9585         /* If this is an instantiation of a function with internal
9586            linkage, we already know what object file linkage will be
9587            assigned to the instantiation.  */
9588         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
9589         DECL_DEFER_OUTPUT (r) = 0;
9590         DECL_CHAIN (r) = NULL_TREE;
9591         DECL_PENDING_INLINE_INFO (r) = 0;
9592         DECL_PENDING_INLINE_P (r) = 0;
9593         DECL_SAVED_TREE (r) = NULL_TREE;
9594         DECL_STRUCT_FUNCTION (r) = NULL;
9595         TREE_USED (r) = 0;
9596         /* We'll re-clone as appropriate in instantiate_template.  */
9597         DECL_CLONED_FUNCTION (r) = NULL_TREE;
9598
9599         /* If we aren't complaining now, return on error before we register
9600            the specialization so that we'll complain eventually.  */
9601         if ((complain & tf_error) == 0
9602             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9603             && !grok_op_properties (r, /*complain=*/false))
9604           RETURN (error_mark_node);
9605
9606         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
9607            this in the special friend case mentioned above where
9608            GEN_TMPL is NULL.  */
9609         if (gen_tmpl)
9610           {
9611             DECL_TEMPLATE_INFO (r)
9612               = build_template_info (gen_tmpl, argvec);
9613             SET_DECL_IMPLICIT_INSTANTIATION (r);
9614             register_specialization (r, gen_tmpl, argvec, false, hash);
9615
9616             /* We're not supposed to instantiate default arguments
9617                until they are called, for a template.  But, for a
9618                declaration like:
9619
9620                  template <class T> void f ()
9621                  { extern void g(int i = T()); }
9622
9623                we should do the substitution when the template is
9624                instantiated.  We handle the member function case in
9625                instantiate_class_template since the default arguments
9626                might refer to other members of the class.  */
9627             if (!member
9628                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
9629                 && !uses_template_parms (argvec))
9630               tsubst_default_arguments (r);
9631           }
9632         else
9633           DECL_TEMPLATE_INFO (r) = NULL_TREE;
9634
9635         /* Copy the list of befriending classes.  */
9636         for (friends = &DECL_BEFRIENDING_CLASSES (r);
9637              *friends;
9638              friends = &TREE_CHAIN (*friends))
9639           {
9640             *friends = copy_node (*friends);
9641             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
9642                                             args, complain,
9643                                             in_decl);
9644           }
9645
9646         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
9647           {
9648             maybe_retrofit_in_chrg (r);
9649             if (DECL_CONSTRUCTOR_P (r))
9650               grok_ctor_properties (ctx, r);
9651             /* If this is an instantiation of a member template, clone it.
9652                If it isn't, that'll be handled by
9653                clone_constructors_and_destructors.  */
9654             if (PRIMARY_TEMPLATE_P (gen_tmpl))
9655               clone_function_decl (r, /*update_method_vec_p=*/0);
9656           }
9657         else if ((complain & tf_error) != 0
9658                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9659                  && !grok_op_properties (r, /*complain=*/true))
9660           RETURN (error_mark_node);
9661
9662         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
9663           SET_DECL_FRIEND_CONTEXT (r,
9664                                    tsubst (DECL_FRIEND_CONTEXT (t),
9665                                             args, complain, in_decl));
9666
9667         /* Possibly limit visibility based on template args.  */
9668         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9669         if (DECL_VISIBILITY_SPECIFIED (t))
9670           {
9671             DECL_VISIBILITY_SPECIFIED (r) = 0;
9672             DECL_ATTRIBUTES (r)
9673               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9674           }
9675         determine_visibility (r);
9676         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
9677             && !processing_template_decl)
9678           defaulted_late_check (r);
9679
9680         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9681                                         args, complain, in_decl);
9682       }
9683       break;
9684
9685     case PARM_DECL:
9686       {
9687         tree type = NULL_TREE;
9688         int i, len = 1;
9689         tree expanded_types = NULL_TREE;
9690         tree prev_r = NULL_TREE;
9691         tree first_r = NULL_TREE;
9692
9693         if (FUNCTION_PARAMETER_PACK_P (t))
9694           {
9695             /* If there is a local specialization that isn't a
9696                parameter pack, it means that we're doing a "simple"
9697                substitution from inside tsubst_pack_expansion. Just
9698                return the local specialization (which will be a single
9699                parm).  */
9700             tree spec = retrieve_local_specialization (t);
9701             if (spec 
9702                 && TREE_CODE (spec) == PARM_DECL
9703                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
9704               RETURN (spec);
9705
9706             /* Expand the TYPE_PACK_EXPANSION that provides the types for
9707                the parameters in this function parameter pack.  */
9708             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
9709                                                     complain, in_decl);
9710             if (TREE_CODE (expanded_types) == TREE_VEC)
9711               {
9712                 len = TREE_VEC_LENGTH (expanded_types);
9713
9714                 /* Zero-length parameter packs are boring. Just substitute
9715                    into the chain.  */
9716                 if (len == 0)
9717                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
9718                                   TREE_CHAIN (t)));
9719               }
9720             else
9721               {
9722                 /* All we did was update the type. Make a note of that.  */
9723                 type = expanded_types;
9724                 expanded_types = NULL_TREE;
9725               }
9726           }
9727
9728         /* Loop through all of the parameter's we'll build. When T is
9729            a function parameter pack, LEN is the number of expanded
9730            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
9731         r = NULL_TREE;
9732         for (i = 0; i < len; ++i)
9733           {
9734             prev_r = r;
9735             r = copy_node (t);
9736             if (DECL_TEMPLATE_PARM_P (t))
9737               SET_DECL_TEMPLATE_PARM_P (r);
9738
9739             /* An argument of a function parameter pack is not a parameter
9740                pack.  */
9741             FUNCTION_PARAMETER_PACK_P (r) = false;
9742
9743             if (expanded_types)
9744               /* We're on the Ith parameter of the function parameter
9745                  pack.  */
9746               {
9747                 /* Get the Ith type.  */
9748                 type = TREE_VEC_ELT (expanded_types, i);
9749
9750                 if (DECL_NAME (r))
9751                   /* Rename the parameter to include the index.  */
9752                   DECL_NAME (r) =
9753                     make_ith_pack_parameter_name (DECL_NAME (r), i);
9754               }
9755             else if (!type)
9756               /* We're dealing with a normal parameter.  */
9757               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9758
9759             type = type_decays_to (type);
9760             TREE_TYPE (r) = type;
9761             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9762
9763             if (DECL_INITIAL (r))
9764               {
9765                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
9766                   DECL_INITIAL (r) = TREE_TYPE (r);
9767                 else
9768                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
9769                                              complain, in_decl);
9770               }
9771
9772             DECL_CONTEXT (r) = NULL_TREE;
9773
9774             if (!DECL_TEMPLATE_PARM_P (r))
9775               DECL_ARG_TYPE (r) = type_passed_as (type);
9776
9777             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9778                                             args, complain, in_decl);
9779
9780             /* Keep track of the first new parameter we
9781                generate. That's what will be returned to the
9782                caller.  */
9783             if (!first_r)
9784               first_r = r;
9785
9786             /* Build a proper chain of parameters when substituting
9787                into a function parameter pack.  */
9788             if (prev_r)
9789               DECL_CHAIN (prev_r) = r;
9790           }
9791
9792         if (DECL_CHAIN (t))
9793           DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
9794                                    complain, DECL_CHAIN (t));
9795
9796         /* FIRST_R contains the start of the chain we've built.  */
9797         r = first_r;
9798       }
9799       break;
9800
9801     case FIELD_DECL:
9802       {
9803         tree type;
9804
9805         r = copy_decl (t);
9806         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9807         if (type == error_mark_node)
9808           RETURN (error_mark_node);
9809         TREE_TYPE (r) = type;
9810         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9811
9812         /* DECL_INITIAL gives the number of bits in a bit-field.  */
9813         DECL_INITIAL (r)
9814           = tsubst_expr (DECL_INITIAL (t), args,
9815                          complain, in_decl,
9816                          /*integral_constant_expression_p=*/true);
9817         /* We don't have to set DECL_CONTEXT here; it is set by
9818            finish_member_declaration.  */
9819         DECL_CHAIN (r) = NULL_TREE;
9820         if (VOID_TYPE_P (type))
9821           error ("instantiation of %q+D as type %qT", r, type);
9822
9823         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9824                                         args, complain, in_decl);
9825       }
9826       break;
9827
9828     case USING_DECL:
9829       /* We reach here only for member using decls.  */
9830       if (DECL_DEPENDENT_P (t))
9831         {
9832           r = do_class_using_decl
9833             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
9834              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
9835           if (!r)
9836             r = error_mark_node;
9837           else
9838             {
9839               TREE_PROTECTED (r) = TREE_PROTECTED (t);
9840               TREE_PRIVATE (r) = TREE_PRIVATE (t);
9841             }
9842         }
9843       else
9844         {
9845           r = copy_node (t);
9846           DECL_CHAIN (r) = NULL_TREE;
9847         }
9848       break;
9849
9850     case TYPE_DECL:
9851     case VAR_DECL:
9852       {
9853         tree argvec = NULL_TREE;
9854         tree gen_tmpl = NULL_TREE;
9855         tree spec;
9856         tree tmpl = NULL_TREE;
9857         tree ctx;
9858         tree type = NULL_TREE;
9859         bool local_p;
9860
9861         if (TREE_CODE (t) == TYPE_DECL
9862             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
9863           {
9864             /* If this is the canonical decl, we don't have to
9865                mess with instantiations, and often we can't (for
9866                typename, template type parms and such).  Note that
9867                TYPE_NAME is not correct for the above test if
9868                we've copied the type for a typedef.  */
9869             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9870             if (type == error_mark_node)
9871               RETURN (error_mark_node);
9872             r = TYPE_NAME (type);
9873             break;
9874           }
9875
9876         /* Check to see if we already have the specialization we
9877            need.  */
9878         spec = NULL_TREE;
9879         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
9880           {
9881             /* T is a static data member or namespace-scope entity.
9882                We have to substitute into namespace-scope variables
9883                (even though such entities are never templates) because
9884                of cases like:
9885                
9886                  template <class T> void f() { extern T t; }
9887
9888                where the entity referenced is not known until
9889                instantiation time.  */
9890             local_p = false;
9891             ctx = DECL_CONTEXT (t);
9892             if (DECL_CLASS_SCOPE_P (t))
9893               {
9894                 ctx = tsubst_aggr_type (ctx, args,
9895                                         complain,
9896                                         in_decl, /*entering_scope=*/1);
9897                 /* If CTX is unchanged, then T is in fact the
9898                    specialization we want.  That situation occurs when
9899                    referencing a static data member within in its own
9900                    class.  We can use pointer equality, rather than
9901                    same_type_p, because DECL_CONTEXT is always
9902                    canonical.  */
9903                 if (ctx == DECL_CONTEXT (t))
9904                   spec = t;
9905               }
9906
9907             if (!spec)
9908               {
9909                 tmpl = DECL_TI_TEMPLATE (t);
9910                 gen_tmpl = most_general_template (tmpl);
9911                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
9912                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
9913                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
9914               }
9915           }
9916         else
9917           {
9918             /* A local variable.  */
9919             local_p = true;
9920             /* Subsequent calls to pushdecl will fill this in.  */
9921             ctx = NULL_TREE;
9922             spec = retrieve_local_specialization (t);
9923           }
9924         /* If we already have the specialization we need, there is
9925            nothing more to do.  */ 
9926         if (spec)
9927           {
9928             r = spec;
9929             break;
9930           }
9931
9932         /* Create a new node for the specialization we need.  */
9933         r = copy_decl (t);
9934         if (type == NULL_TREE)
9935           {
9936             if (is_typedef_decl (t))
9937               type = DECL_ORIGINAL_TYPE (t);
9938             else
9939               type = TREE_TYPE (t);
9940             if (TREE_CODE (t) == VAR_DECL && VAR_HAD_UNKNOWN_BOUND (t))
9941               type = strip_array_domain (type);
9942             type = tsubst (type, args, complain, in_decl);
9943           }
9944         if (TREE_CODE (r) == VAR_DECL)
9945           {
9946             /* Even if the original location is out of scope, the
9947                newly substituted one is not.  */
9948             DECL_DEAD_FOR_LOCAL (r) = 0;
9949             DECL_INITIALIZED_P (r) = 0;
9950             DECL_TEMPLATE_INSTANTIATED (r) = 0;
9951             if (type == error_mark_node)
9952               RETURN (error_mark_node);
9953             if (TREE_CODE (type) == FUNCTION_TYPE)
9954               {
9955                 /* It may seem that this case cannot occur, since:
9956
9957                      typedef void f();
9958                      void g() { f x; }
9959
9960                    declares a function, not a variable.  However:
9961       
9962                      typedef void f();
9963                      template <typename T> void g() { T t; }
9964                      template void g<f>();
9965
9966                    is an attempt to declare a variable with function
9967                    type.  */
9968                 error ("variable %qD has function type",
9969                        /* R is not yet sufficiently initialized, so we
9970                           just use its name.  */
9971                        DECL_NAME (r));
9972                 RETURN (error_mark_node);
9973               }
9974             type = complete_type (type);
9975             /* Wait until cp_finish_decl to set this again, to handle
9976                circular dependency (template/instantiate6.C). */
9977             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
9978             type = check_var_type (DECL_NAME (r), type);
9979
9980             if (DECL_HAS_VALUE_EXPR_P (t))
9981               {
9982                 tree ve = DECL_VALUE_EXPR (t);
9983                 ve = tsubst_expr (ve, args, complain, in_decl,
9984                                   /*constant_expression_p=*/false);
9985                 SET_DECL_VALUE_EXPR (r, ve);
9986               }
9987           }
9988         else if (DECL_SELF_REFERENCE_P (t))
9989           SET_DECL_SELF_REFERENCE_P (r);
9990         TREE_TYPE (r) = type;
9991         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9992         DECL_CONTEXT (r) = ctx;
9993         /* Clear out the mangled name and RTL for the instantiation.  */
9994         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9995         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9996           SET_DECL_RTL (r, NULL);
9997         /* The initializer must not be expanded until it is required;
9998            see [temp.inst].  */
9999         DECL_INITIAL (r) = NULL_TREE;
10000         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10001           SET_DECL_RTL (r, NULL);
10002         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
10003         if (TREE_CODE (r) == VAR_DECL)
10004           {
10005             /* Possibly limit visibility based on template args.  */
10006             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10007             if (DECL_VISIBILITY_SPECIFIED (t))
10008               {
10009                 DECL_VISIBILITY_SPECIFIED (r) = 0;
10010                 DECL_ATTRIBUTES (r)
10011                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10012               }
10013             determine_visibility (r);
10014           }
10015
10016         if (!local_p)
10017           {
10018             /* A static data member declaration is always marked
10019                external when it is declared in-class, even if an
10020                initializer is present.  We mimic the non-template
10021                processing here.  */
10022             DECL_EXTERNAL (r) = 1;
10023
10024             register_specialization (r, gen_tmpl, argvec, false, hash);
10025             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
10026             SET_DECL_IMPLICIT_INSTANTIATION (r);
10027           }
10028         else if (cp_unevaluated_operand)
10029           {
10030             /* We're substituting this var in a decltype outside of its
10031                scope, such as for a lambda return type.  Don't add it to
10032                local_specializations, do perform auto deduction.  */
10033             tree auto_node = type_uses_auto (type);
10034             tree init
10035               = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
10036                              /*constant_expression_p=*/false);
10037
10038             if (auto_node && init && describable_type (init))
10039               {
10040                 type = do_auto_deduction (type, init, auto_node);
10041                 TREE_TYPE (r) = type;
10042               }
10043           }
10044         else
10045           register_local_specialization (r, t);
10046
10047         DECL_CHAIN (r) = NULL_TREE;
10048
10049         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
10050                                         /*flags=*/0,
10051                                         args, complain, in_decl);
10052
10053         /* Preserve a typedef that names a type.  */
10054         if (is_typedef_decl (r))
10055           {
10056             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
10057             set_underlying_type (r);
10058           }
10059
10060         layout_decl (r, 0);
10061       }
10062       break;
10063
10064     default:
10065       gcc_unreachable ();
10066     }
10067 #undef RETURN
10068
10069  out:
10070   /* Restore the file and line information.  */
10071   input_location = saved_loc;
10072
10073   return r;
10074 }
10075
10076 /* Substitute into the ARG_TYPES of a function type.  */
10077
10078 static tree
10079 tsubst_arg_types (tree arg_types,
10080                   tree args,
10081                   tsubst_flags_t complain,
10082                   tree in_decl)
10083 {
10084   tree remaining_arg_types;
10085   tree type = NULL_TREE;
10086   int i = 1;
10087   tree expanded_args = NULL_TREE;
10088   tree default_arg;
10089
10090   if (!arg_types || arg_types == void_list_node)
10091     return arg_types;
10092
10093   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
10094                                           args, complain, in_decl);
10095   if (remaining_arg_types == error_mark_node)
10096     return error_mark_node;
10097
10098   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
10099     {
10100       /* For a pack expansion, perform substitution on the
10101          entire expression. Later on, we'll handle the arguments
10102          one-by-one.  */
10103       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
10104                                             args, complain, in_decl);
10105
10106       if (TREE_CODE (expanded_args) == TREE_VEC)
10107         /* So that we'll spin through the parameters, one by one.  */
10108         i = TREE_VEC_LENGTH (expanded_args);
10109       else
10110         {
10111           /* We only partially substituted into the parameter
10112              pack. Our type is TYPE_PACK_EXPANSION.  */
10113           type = expanded_args;
10114           expanded_args = NULL_TREE;
10115         }
10116     }
10117
10118   while (i > 0) {
10119     --i;
10120     
10121     if (expanded_args)
10122       type = TREE_VEC_ELT (expanded_args, i);
10123     else if (!type)
10124       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
10125
10126     if (type == error_mark_node)
10127       return error_mark_node;
10128     if (VOID_TYPE_P (type))
10129       {
10130         if (complain & tf_error)
10131           {
10132             error ("invalid parameter type %qT", type);
10133             if (in_decl)
10134               error ("in declaration %q+D", in_decl);
10135           }
10136         return error_mark_node;
10137     }
10138     
10139     /* Do array-to-pointer, function-to-pointer conversion, and ignore
10140        top-level qualifiers as required.  */
10141     type = TYPE_MAIN_VARIANT (type_decays_to (type));
10142
10143     /* We do not substitute into default arguments here.  The standard
10144        mandates that they be instantiated only when needed, which is
10145        done in build_over_call.  */
10146     default_arg = TREE_PURPOSE (arg_types);
10147
10148     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
10149       {
10150         /* We've instantiated a template before its default arguments
10151            have been parsed.  This can happen for a nested template
10152            class, and is not an error unless we require the default
10153            argument in a call of this function.  */
10154         remaining_arg_types = 
10155           tree_cons (default_arg, type, remaining_arg_types);
10156         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
10157                        remaining_arg_types);
10158       }
10159     else
10160       remaining_arg_types = 
10161         hash_tree_cons (default_arg, type, remaining_arg_types);
10162   }
10163         
10164   return remaining_arg_types;
10165 }
10166
10167 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
10168    *not* handle the exception-specification for FNTYPE, because the
10169    initial substitution of explicitly provided template parameters
10170    during argument deduction forbids substitution into the
10171    exception-specification:
10172
10173      [temp.deduct]
10174
10175      All references in the function type of the function template to  the
10176      corresponding template parameters are replaced by the specified tem-
10177      plate argument values.  If a substitution in a template parameter or
10178      in  the function type of the function template results in an invalid
10179      type, type deduction fails.  [Note: The equivalent  substitution  in
10180      exception specifications is done only when the function is instanti-
10181      ated, at which point a program is  ill-formed  if  the  substitution
10182      results in an invalid type.]  */
10183
10184 static tree
10185 tsubst_function_type (tree t,
10186                       tree args,
10187                       tsubst_flags_t complain,
10188                       tree in_decl)
10189 {
10190   tree return_type;
10191   tree arg_types;
10192   tree fntype;
10193
10194   /* The TYPE_CONTEXT is not used for function/method types.  */
10195   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
10196
10197   /* Substitute the return type.  */
10198   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10199   if (return_type == error_mark_node)
10200     return error_mark_node;
10201   /* The standard does not presently indicate that creation of a
10202      function type with an invalid return type is a deduction failure.
10203      However, that is clearly analogous to creating an array of "void"
10204      or a reference to a reference.  This is core issue #486.  */
10205   if (TREE_CODE (return_type) == ARRAY_TYPE
10206       || TREE_CODE (return_type) == FUNCTION_TYPE)
10207     {
10208       if (complain & tf_error)
10209         {
10210           if (TREE_CODE (return_type) == ARRAY_TYPE)
10211             error ("function returning an array");
10212           else
10213             error ("function returning a function");
10214         }
10215       return error_mark_node;
10216     }
10217
10218   /* Substitute the argument types.  */
10219   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
10220                                 complain, in_decl);
10221   if (arg_types == error_mark_node)
10222     return error_mark_node;
10223
10224   /* Construct a new type node and return it.  */
10225   if (TREE_CODE (t) == FUNCTION_TYPE)
10226     {
10227       fntype = build_function_type (return_type, arg_types);
10228       fntype = apply_memfn_quals (fntype, type_memfn_quals (t));
10229     }
10230   else
10231     {
10232       tree r = TREE_TYPE (TREE_VALUE (arg_types));
10233       if (! MAYBE_CLASS_TYPE_P (r))
10234         {
10235           /* [temp.deduct]
10236
10237              Type deduction may fail for any of the following
10238              reasons:
10239
10240              -- Attempting to create "pointer to member of T" when T
10241              is not a class type.  */
10242           if (complain & tf_error)
10243             error ("creating pointer to member function of non-class type %qT",
10244                       r);
10245           return error_mark_node;
10246         }
10247
10248       fntype = build_method_type_directly (r, return_type,
10249                                            TREE_CHAIN (arg_types));
10250     }
10251   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
10252
10253   return fntype;
10254 }
10255
10256 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
10257    ARGS into that specification, and return the substituted
10258    specification.  If there is no specification, return NULL_TREE.  */
10259
10260 static tree
10261 tsubst_exception_specification (tree fntype,
10262                                 tree args,
10263                                 tsubst_flags_t complain,
10264                                 tree in_decl)
10265 {
10266   tree specs;
10267   tree new_specs;
10268
10269   specs = TYPE_RAISES_EXCEPTIONS (fntype);
10270   new_specs = NULL_TREE;
10271   if (specs && TREE_PURPOSE (specs))
10272     {
10273       /* A noexcept-specifier.  */
10274       new_specs = tsubst_copy_and_build
10275         (TREE_PURPOSE (specs), args, complain, in_decl, /*function_p=*/false,
10276          /*integral_constant_expression_p=*/true);
10277       new_specs = build_noexcept_spec (new_specs, complain);
10278     }
10279   else if (specs)
10280     {
10281       if (! TREE_VALUE (specs))
10282         new_specs = specs;
10283       else
10284         while (specs)
10285           {
10286             tree spec;
10287             int i, len = 1;
10288             tree expanded_specs = NULL_TREE;
10289
10290             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
10291               {
10292                 /* Expand the pack expansion type.  */
10293                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
10294                                                        args, complain,
10295                                                        in_decl);
10296
10297                 if (expanded_specs == error_mark_node)
10298                   return error_mark_node;
10299                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
10300                   len = TREE_VEC_LENGTH (expanded_specs);
10301                 else
10302                   {
10303                     /* We're substituting into a member template, so
10304                        we got a TYPE_PACK_EXPANSION back.  Add that
10305                        expansion and move on.  */
10306                     gcc_assert (TREE_CODE (expanded_specs) 
10307                                 == TYPE_PACK_EXPANSION);
10308                     new_specs = add_exception_specifier (new_specs,
10309                                                          expanded_specs,
10310                                                          complain);
10311                     specs = TREE_CHAIN (specs);
10312                     continue;
10313                   }
10314               }
10315
10316             for (i = 0; i < len; ++i)
10317               {
10318                 if (expanded_specs)
10319                   spec = TREE_VEC_ELT (expanded_specs, i);
10320                 else
10321                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
10322                 if (spec == error_mark_node)
10323                   return spec;
10324                 new_specs = add_exception_specifier (new_specs, spec, 
10325                                                      complain);
10326               }
10327
10328             specs = TREE_CHAIN (specs);
10329           }
10330     }
10331   return new_specs;
10332 }
10333
10334 /* Take the tree structure T and replace template parameters used
10335    therein with the argument vector ARGS.  IN_DECL is an associated
10336    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
10337    Issue error and warning messages under control of COMPLAIN.  Note
10338    that we must be relatively non-tolerant of extensions here, in
10339    order to preserve conformance; if we allow substitutions that
10340    should not be allowed, we may allow argument deductions that should
10341    not succeed, and therefore report ambiguous overload situations
10342    where there are none.  In theory, we could allow the substitution,
10343    but indicate that it should have failed, and allow our caller to
10344    make sure that the right thing happens, but we don't try to do this
10345    yet.
10346
10347    This function is used for dealing with types, decls and the like;
10348    for expressions, use tsubst_expr or tsubst_copy.  */
10349
10350 tree
10351 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10352 {
10353   enum tree_code code;
10354   tree type, r;
10355
10356   if (t == NULL_TREE || t == error_mark_node
10357       || t == integer_type_node
10358       || t == void_type_node
10359       || t == char_type_node
10360       || t == unknown_type_node
10361       || TREE_CODE (t) == NAMESPACE_DECL
10362       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
10363     return t;
10364
10365   if (DECL_P (t))
10366     return tsubst_decl (t, args, complain);
10367
10368   if (args == NULL_TREE)
10369     return t;
10370
10371   code = TREE_CODE (t);
10372
10373   if (code == IDENTIFIER_NODE)
10374     type = IDENTIFIER_TYPE_VALUE (t);
10375   else
10376     type = TREE_TYPE (t);
10377
10378   gcc_assert (type != unknown_type_node);
10379
10380   /* Reuse typedefs.  We need to do this to handle dependent attributes,
10381      such as attribute aligned.  */
10382   if (TYPE_P (t)
10383       && typedef_variant_p (t))
10384     {
10385       tree decl = TYPE_NAME (t);
10386       
10387       if (DECL_CLASS_SCOPE_P (decl)
10388           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
10389           && uses_template_parms (DECL_CONTEXT (decl)))
10390         {
10391           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
10392           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
10393           r = retrieve_specialization (tmpl, gen_args, 0);
10394         }
10395       else if (DECL_FUNCTION_SCOPE_P (decl)
10396                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
10397                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
10398         r = retrieve_local_specialization (decl);
10399       else
10400         /* The typedef is from a non-template context.  */
10401         return t;
10402
10403       if (r)
10404         {
10405           r = TREE_TYPE (r);
10406           r = cp_build_qualified_type_real
10407             (r, cp_type_quals (t) | cp_type_quals (r),
10408              complain | tf_ignore_bad_quals);
10409           return r;
10410         }
10411       /* Else we must be instantiating the typedef, so fall through.  */
10412     }
10413
10414   if (type
10415       && code != TYPENAME_TYPE
10416       && code != TEMPLATE_TYPE_PARM
10417       && code != IDENTIFIER_NODE
10418       && code != FUNCTION_TYPE
10419       && code != METHOD_TYPE)
10420     type = tsubst (type, args, complain, in_decl);
10421   if (type == error_mark_node)
10422     return error_mark_node;
10423
10424   switch (code)
10425     {
10426     case RECORD_TYPE:
10427     case UNION_TYPE:
10428     case ENUMERAL_TYPE:
10429       return tsubst_aggr_type (t, args, complain, in_decl,
10430                                /*entering_scope=*/0);
10431
10432     case ERROR_MARK:
10433     case IDENTIFIER_NODE:
10434     case VOID_TYPE:
10435     case REAL_TYPE:
10436     case COMPLEX_TYPE:
10437     case VECTOR_TYPE:
10438     case BOOLEAN_TYPE:
10439     case NULLPTR_TYPE:
10440     case LANG_TYPE:
10441       return t;
10442
10443     case INTEGER_TYPE:
10444       if (t == integer_type_node)
10445         return t;
10446
10447       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
10448           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
10449         return t;
10450
10451       {
10452         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
10453
10454         max = tsubst_expr (omax, args, complain, in_decl,
10455                            /*integral_constant_expression_p=*/false);
10456
10457         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
10458            needed.  */
10459         if (TREE_CODE (max) == NOP_EXPR
10460             && TREE_SIDE_EFFECTS (omax)
10461             && !TREE_TYPE (max))
10462           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
10463
10464         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
10465            with TREE_SIDE_EFFECTS that indicates this is not an integral
10466            constant expression.  */
10467         if (processing_template_decl
10468             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
10469           {
10470             gcc_assert (TREE_CODE (max) == NOP_EXPR);
10471             TREE_SIDE_EFFECTS (max) = 1;
10472           }
10473
10474         return compute_array_index_type (NULL_TREE, max, complain);
10475       }
10476
10477     case TEMPLATE_TYPE_PARM:
10478     case TEMPLATE_TEMPLATE_PARM:
10479     case BOUND_TEMPLATE_TEMPLATE_PARM:
10480     case TEMPLATE_PARM_INDEX:
10481       {
10482         int idx;
10483         int level;
10484         int levels;
10485         tree arg = NULL_TREE;
10486
10487         r = NULL_TREE;
10488
10489         gcc_assert (TREE_VEC_LENGTH (args) > 0);
10490         template_parm_level_and_index (t, &level, &idx); 
10491
10492         levels = TMPL_ARGS_DEPTH (args);
10493         if (level <= levels)
10494           {
10495             arg = TMPL_ARG (args, level, idx);
10496
10497             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
10498               /* See through ARGUMENT_PACK_SELECT arguments. */
10499               arg = ARGUMENT_PACK_SELECT_ARG (arg);
10500           }
10501
10502         if (arg == error_mark_node)
10503           return error_mark_node;
10504         else if (arg != NULL_TREE)
10505           {
10506             if (ARGUMENT_PACK_P (arg))
10507               /* If ARG is an argument pack, we don't actually want to
10508                  perform a substitution here, because substitutions
10509                  for argument packs are only done
10510                  element-by-element. We can get to this point when
10511                  substituting the type of a non-type template
10512                  parameter pack, when that type actually contains
10513                  template parameter packs from an outer template, e.g.,
10514
10515                  template<typename... Types> struct A {
10516                    template<Types... Values> struct B { };
10517                  };  */
10518               return t;
10519
10520             if (code == TEMPLATE_TYPE_PARM)
10521               {
10522                 int quals;
10523                 gcc_assert (TYPE_P (arg));
10524
10525                 quals = cp_type_quals (arg) | cp_type_quals (t);
10526                   
10527                 return cp_build_qualified_type_real
10528                   (arg, quals, complain | tf_ignore_bad_quals);
10529               }
10530             else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
10531               {
10532                 /* We are processing a type constructed from a
10533                    template template parameter.  */
10534                 tree argvec = tsubst (TYPE_TI_ARGS (t),
10535                                       args, complain, in_decl);
10536                 if (argvec == error_mark_node)
10537                   return error_mark_node;
10538
10539                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
10540                    are resolving nested-types in the signature of a
10541                    member function templates.  Otherwise ARG is a
10542                    TEMPLATE_DECL and is the real template to be
10543                    instantiated.  */
10544                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
10545                   arg = TYPE_NAME (arg);
10546
10547                 r = lookup_template_class (arg,
10548                                            argvec, in_decl,
10549                                            DECL_CONTEXT (arg),
10550                                             /*entering_scope=*/0,
10551                                            complain);
10552                 return cp_build_qualified_type_real
10553                   (r, cp_type_quals (t), complain);
10554               }
10555             else
10556               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
10557               return unshare_expr (arg);
10558           }
10559
10560         if (level == 1)
10561           /* This can happen during the attempted tsubst'ing in
10562              unify.  This means that we don't yet have any information
10563              about the template parameter in question.  */
10564           return t;
10565
10566         /* If we get here, we must have been looking at a parm for a
10567            more deeply nested template.  Make a new version of this
10568            template parameter, but with a lower level.  */
10569         switch (code)
10570           {
10571           case TEMPLATE_TYPE_PARM:
10572           case TEMPLATE_TEMPLATE_PARM:
10573           case BOUND_TEMPLATE_TEMPLATE_PARM:
10574             if (cp_type_quals (t))
10575               {
10576                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
10577                 r = cp_build_qualified_type_real
10578                   (r, cp_type_quals (t),
10579                    complain | (code == TEMPLATE_TYPE_PARM
10580                                ? tf_ignore_bad_quals : 0));
10581               }
10582             else
10583               {
10584                 r = copy_type (t);
10585                 TEMPLATE_TYPE_PARM_INDEX (r)
10586                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
10587                                                 r, levels, args, complain);
10588                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
10589                 TYPE_MAIN_VARIANT (r) = r;
10590                 TYPE_POINTER_TO (r) = NULL_TREE;
10591                 TYPE_REFERENCE_TO (r) = NULL_TREE;
10592
10593                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
10594                   /* We have reduced the level of the template
10595                      template parameter, but not the levels of its
10596                      template parameters, so canonical_type_parameter
10597                      will not be able to find the canonical template
10598                      template parameter for this level. Thus, we
10599                      require structural equality checking to compare
10600                      TEMPLATE_TEMPLATE_PARMs. */
10601                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10602                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
10603                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10604                 else
10605                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
10606
10607                 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
10608                   {
10609                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
10610                                           complain, in_decl);
10611                     if (argvec == error_mark_node)
10612                       return error_mark_node;
10613
10614                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
10615                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
10616                   }
10617               }
10618             break;
10619
10620           case TEMPLATE_PARM_INDEX:
10621             r = reduce_template_parm_level (t, type, levels, args, complain);
10622             break;
10623
10624           default:
10625             gcc_unreachable ();
10626           }
10627
10628         return r;
10629       }
10630
10631     case TREE_LIST:
10632       {
10633         tree purpose, value, chain;
10634
10635         if (t == void_list_node)
10636           return t;
10637
10638         purpose = TREE_PURPOSE (t);
10639         if (purpose)
10640           {
10641             purpose = tsubst (purpose, args, complain, in_decl);
10642             if (purpose == error_mark_node)
10643               return error_mark_node;
10644           }
10645         value = TREE_VALUE (t);
10646         if (value)
10647           {
10648             value = tsubst (value, args, complain, in_decl);
10649             if (value == error_mark_node)
10650               return error_mark_node;
10651           }
10652         chain = TREE_CHAIN (t);
10653         if (chain && chain != void_type_node)
10654           {
10655             chain = tsubst (chain, args, complain, in_decl);
10656             if (chain == error_mark_node)
10657               return error_mark_node;
10658           }
10659         if (purpose == TREE_PURPOSE (t)
10660             && value == TREE_VALUE (t)
10661             && chain == TREE_CHAIN (t))
10662           return t;
10663         return hash_tree_cons (purpose, value, chain);
10664       }
10665
10666     case TREE_BINFO:
10667       /* We should never be tsubsting a binfo.  */
10668       gcc_unreachable ();
10669
10670     case TREE_VEC:
10671       /* A vector of template arguments.  */
10672       gcc_assert (!type);
10673       return tsubst_template_args (t, args, complain, in_decl);
10674
10675     case POINTER_TYPE:
10676     case REFERENCE_TYPE:
10677       {
10678         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
10679           return t;
10680
10681         /* [temp.deduct]
10682
10683            Type deduction may fail for any of the following
10684            reasons:
10685
10686            -- Attempting to create a pointer to reference type.
10687            -- Attempting to create a reference to a reference type or
10688               a reference to void.
10689
10690           Core issue 106 says that creating a reference to a reference
10691           during instantiation is no longer a cause for failure. We
10692           only enforce this check in strict C++98 mode.  */
10693         if ((TREE_CODE (type) == REFERENCE_TYPE
10694              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
10695             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
10696           {
10697             static location_t last_loc;
10698
10699             /* We keep track of the last time we issued this error
10700                message to avoid spewing a ton of messages during a
10701                single bad template instantiation.  */
10702             if (complain & tf_error
10703                 && last_loc != input_location)
10704               {
10705                 if (TREE_CODE (type) == VOID_TYPE)
10706                   error ("forming reference to void");
10707                else if (code == POINTER_TYPE)
10708                  error ("forming pointer to reference type %qT", type);
10709                else
10710                   error ("forming reference to reference type %qT", type);
10711                 last_loc = input_location;
10712               }
10713
10714             return error_mark_node;
10715           }
10716         else if (code == POINTER_TYPE)
10717           {
10718             r = build_pointer_type (type);
10719             if (TREE_CODE (type) == METHOD_TYPE)
10720               r = build_ptrmemfunc_type (r);
10721           }
10722         else if (TREE_CODE (type) == REFERENCE_TYPE)
10723           /* In C++0x, during template argument substitution, when there is an
10724              attempt to create a reference to a reference type, reference
10725              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
10726
10727              "If a template-argument for a template-parameter T names a type
10728              that is a reference to a type A, an attempt to create the type
10729              'lvalue reference to cv T' creates the type 'lvalue reference to
10730              A,' while an attempt to create the type type rvalue reference to
10731              cv T' creates the type T"
10732           */
10733           r = cp_build_reference_type
10734               (TREE_TYPE (type),
10735                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
10736         else
10737           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
10738         r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
10739
10740         if (r != error_mark_node)
10741           /* Will this ever be needed for TYPE_..._TO values?  */
10742           layout_type (r);
10743
10744         return r;
10745       }
10746     case OFFSET_TYPE:
10747       {
10748         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
10749         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
10750           {
10751             /* [temp.deduct]
10752
10753                Type deduction may fail for any of the following
10754                reasons:
10755
10756                -- Attempting to create "pointer to member of T" when T
10757                   is not a class type.  */
10758             if (complain & tf_error)
10759               error ("creating pointer to member of non-class type %qT", r);
10760             return error_mark_node;
10761           }
10762         if (TREE_CODE (type) == REFERENCE_TYPE)
10763           {
10764             if (complain & tf_error)
10765               error ("creating pointer to member reference type %qT", type);
10766             return error_mark_node;
10767           }
10768         if (TREE_CODE (type) == VOID_TYPE)
10769           {
10770             if (complain & tf_error)
10771               error ("creating pointer to member of type void");
10772             return error_mark_node;
10773           }
10774         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
10775         if (TREE_CODE (type) == FUNCTION_TYPE)
10776           {
10777             /* The type of the implicit object parameter gets its
10778                cv-qualifiers from the FUNCTION_TYPE. */
10779             tree memptr;
10780             tree method_type = build_memfn_type (type, r, type_memfn_quals (type));
10781             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
10782             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
10783                                                  complain);
10784           }
10785         else
10786           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
10787                                                cp_type_quals (t),
10788                                                complain);
10789       }
10790     case FUNCTION_TYPE:
10791     case METHOD_TYPE:
10792       {
10793         tree fntype;
10794         tree specs;
10795         fntype = tsubst_function_type (t, args, complain, in_decl);
10796         if (fntype == error_mark_node)
10797           return error_mark_node;
10798
10799         /* Substitute the exception specification.  */
10800         specs = tsubst_exception_specification (t, args, complain,
10801                                                 in_decl);
10802         if (specs == error_mark_node)
10803           return error_mark_node;
10804         if (specs)
10805           fntype = build_exception_variant (fntype, specs);
10806         return fntype;
10807       }
10808     case ARRAY_TYPE:
10809       {
10810         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
10811         if (domain == error_mark_node)
10812           return error_mark_node;
10813
10814         /* As an optimization, we avoid regenerating the array type if
10815            it will obviously be the same as T.  */
10816         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
10817           return t;
10818
10819         /* These checks should match the ones in grokdeclarator.
10820
10821            [temp.deduct]
10822
10823            The deduction may fail for any of the following reasons:
10824
10825            -- Attempting to create an array with an element type that
10826               is void, a function type, or a reference type, or [DR337]
10827               an abstract class type.  */
10828         if (TREE_CODE (type) == VOID_TYPE
10829             || TREE_CODE (type) == FUNCTION_TYPE
10830             || TREE_CODE (type) == REFERENCE_TYPE)
10831           {
10832             if (complain & tf_error)
10833               error ("creating array of %qT", type);
10834             return error_mark_node;
10835           }
10836         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
10837           {
10838             if (complain & tf_error)
10839               error ("creating array of %qT, which is an abstract class type",
10840                      type);
10841             return error_mark_node;
10842           }
10843
10844         r = build_cplus_array_type (type, domain);
10845
10846         if (TYPE_USER_ALIGN (t))
10847           {
10848             TYPE_ALIGN (r) = TYPE_ALIGN (t);
10849             TYPE_USER_ALIGN (r) = 1;
10850           }
10851
10852         return r;
10853       }
10854
10855     case TYPENAME_TYPE:
10856       {
10857         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10858                                      in_decl, /*entering_scope=*/1);
10859         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
10860                               complain, in_decl);
10861
10862         if (ctx == error_mark_node || f == error_mark_node)
10863           return error_mark_node;
10864
10865         if (!MAYBE_CLASS_TYPE_P (ctx))
10866           {
10867             if (complain & tf_error)
10868               error ("%qT is not a class, struct, or union type", ctx);
10869             return error_mark_node;
10870           }
10871         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
10872           {
10873             /* Normally, make_typename_type does not require that the CTX
10874                have complete type in order to allow things like:
10875
10876                  template <class T> struct S { typename S<T>::X Y; };
10877
10878                But, such constructs have already been resolved by this
10879                point, so here CTX really should have complete type, unless
10880                it's a partial instantiation.  */
10881             ctx = complete_type (ctx);
10882             if (!COMPLETE_TYPE_P (ctx))
10883               {
10884                 if (complain & tf_error)
10885                   cxx_incomplete_type_error (NULL_TREE, ctx);
10886                 return error_mark_node;
10887               }
10888           }
10889
10890         f = make_typename_type (ctx, f, typename_type,
10891                                 (complain & tf_error) | tf_keep_type_decl);
10892         if (f == error_mark_node)
10893           return f;
10894         if (TREE_CODE (f) == TYPE_DECL)
10895           {
10896             complain |= tf_ignore_bad_quals;
10897             f = TREE_TYPE (f);
10898           }
10899
10900         if (TREE_CODE (f) != TYPENAME_TYPE)
10901           {
10902             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
10903               error ("%qT resolves to %qT, which is not an enumeration type",
10904                      t, f);
10905             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
10906               error ("%qT resolves to %qT, which is is not a class type",
10907                      t, f);
10908           }
10909
10910         return cp_build_qualified_type_real
10911           (f, cp_type_quals (f) | cp_type_quals (t), complain);
10912       }
10913
10914     case UNBOUND_CLASS_TEMPLATE:
10915       {
10916         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10917                                      in_decl, /*entering_scope=*/1);
10918         tree name = TYPE_IDENTIFIER (t);
10919         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
10920
10921         if (ctx == error_mark_node || name == error_mark_node)
10922           return error_mark_node;
10923
10924         if (parm_list)
10925           parm_list = tsubst_template_parms (parm_list, args, complain);
10926         return make_unbound_class_template (ctx, name, parm_list, complain);
10927       }
10928
10929     case TYPEOF_TYPE:
10930       {
10931         tree type;
10932
10933         ++cp_unevaluated_operand;
10934         ++c_inhibit_evaluation_warnings;
10935
10936         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
10937                             complain, in_decl,
10938                             /*integral_constant_expression_p=*/false);
10939
10940         --cp_unevaluated_operand;
10941         --c_inhibit_evaluation_warnings;
10942
10943         type = finish_typeof (type);
10944         return cp_build_qualified_type_real (type,
10945                                              cp_type_quals (t)
10946                                              | cp_type_quals (type),
10947                                              complain);
10948       }
10949
10950     case DECLTYPE_TYPE:
10951       {
10952         tree type;
10953
10954         ++cp_unevaluated_operand;
10955         ++c_inhibit_evaluation_warnings;
10956
10957         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
10958                             complain, in_decl,
10959                             /*integral_constant_expression_p=*/false);
10960
10961         --cp_unevaluated_operand;
10962         --c_inhibit_evaluation_warnings;
10963
10964         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
10965           type = lambda_capture_field_type (type);
10966         else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
10967           type = lambda_return_type (type);
10968         else
10969           type = finish_decltype_type
10970             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
10971         return cp_build_qualified_type_real (type,
10972                                              cp_type_quals (t)
10973                                              | cp_type_quals (type),
10974                                              complain);
10975       }
10976
10977     case TYPE_ARGUMENT_PACK:
10978     case NONTYPE_ARGUMENT_PACK:
10979       {
10980         tree r = TYPE_P (t) ? cxx_make_type (code) : make_node (code);
10981         tree packed_out = 
10982           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
10983                                 args,
10984                                 complain,
10985                                 in_decl);
10986         SET_ARGUMENT_PACK_ARGS (r, packed_out);
10987
10988         /* For template nontype argument packs, also substitute into
10989            the type.  */
10990         if (code == NONTYPE_ARGUMENT_PACK)
10991           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
10992
10993         return r;
10994       }
10995       break;
10996
10997     case INTEGER_CST:
10998     case REAL_CST:
10999     case STRING_CST:
11000     case PLUS_EXPR:
11001     case MINUS_EXPR:
11002     case NEGATE_EXPR:
11003     case NOP_EXPR:
11004     case INDIRECT_REF:
11005     case ADDR_EXPR:
11006     case CALL_EXPR:
11007     case ARRAY_REF:
11008     case SCOPE_REF:
11009       /* We should use one of the expression tsubsts for these codes.  */
11010       gcc_unreachable ();
11011
11012     default:
11013       sorry ("use of %qs in template", tree_code_name [(int) code]);
11014       return error_mark_node;
11015     }
11016 }
11017
11018 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
11019    type of the expression on the left-hand side of the "." or "->"
11020    operator.  */
11021
11022 static tree
11023 tsubst_baselink (tree baselink, tree object_type,
11024                  tree args, tsubst_flags_t complain, tree in_decl)
11025 {
11026     tree name;
11027     tree qualifying_scope;
11028     tree fns;
11029     tree optype;
11030     tree template_args = 0;
11031     bool template_id_p = false;
11032
11033     /* A baselink indicates a function from a base class.  Both the
11034        BASELINK_ACCESS_BINFO and the base class referenced may
11035        indicate bases of the template class, rather than the
11036        instantiated class.  In addition, lookups that were not
11037        ambiguous before may be ambiguous now.  Therefore, we perform
11038        the lookup again.  */
11039     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
11040     qualifying_scope = tsubst (qualifying_scope, args,
11041                                complain, in_decl);
11042     fns = BASELINK_FUNCTIONS (baselink);
11043     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
11044     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
11045       {
11046         template_id_p = true;
11047         template_args = TREE_OPERAND (fns, 1);
11048         fns = TREE_OPERAND (fns, 0);
11049         if (template_args)
11050           template_args = tsubst_template_args (template_args, args,
11051                                                 complain, in_decl);
11052       }
11053     name = DECL_NAME (get_first_fn (fns));
11054     if (IDENTIFIER_TYPENAME_P (name))
11055       name = mangle_conv_op_name_for_type (optype);
11056     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
11057     if (!baselink)
11058       return error_mark_node;
11059
11060     /* If lookup found a single function, mark it as used at this
11061        point.  (If it lookup found multiple functions the one selected
11062        later by overload resolution will be marked as used at that
11063        point.)  */
11064     if (BASELINK_P (baselink))
11065       fns = BASELINK_FUNCTIONS (baselink);
11066     if (!template_id_p && !really_overloaded_fn (fns))
11067       mark_used (OVL_CURRENT (fns));
11068
11069     /* Add back the template arguments, if present.  */
11070     if (BASELINK_P (baselink) && template_id_p)
11071       BASELINK_FUNCTIONS (baselink)
11072         = build_nt (TEMPLATE_ID_EXPR,
11073                     BASELINK_FUNCTIONS (baselink),
11074                     template_args);
11075     /* Update the conversion operator type.  */
11076     BASELINK_OPTYPE (baselink) = optype;
11077
11078     if (!object_type)
11079       object_type = current_class_type;
11080     return adjust_result_of_qualified_name_lookup (baselink,
11081                                                    qualifying_scope,
11082                                                    object_type);
11083 }
11084
11085 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
11086    true if the qualified-id will be a postfix-expression in-and-of
11087    itself; false if more of the postfix-expression follows the
11088    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
11089    of "&".  */
11090
11091 static tree
11092 tsubst_qualified_id (tree qualified_id, tree args,
11093                      tsubst_flags_t complain, tree in_decl,
11094                      bool done, bool address_p)
11095 {
11096   tree expr;
11097   tree scope;
11098   tree name;
11099   bool is_template;
11100   tree template_args;
11101
11102   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
11103
11104   /* Figure out what name to look up.  */
11105   name = TREE_OPERAND (qualified_id, 1);
11106   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
11107     {
11108       is_template = true;
11109       template_args = TREE_OPERAND (name, 1);
11110       if (template_args)
11111         template_args = tsubst_template_args (template_args, args,
11112                                               complain, in_decl);
11113       name = TREE_OPERAND (name, 0);
11114     }
11115   else
11116     {
11117       is_template = false;
11118       template_args = NULL_TREE;
11119     }
11120
11121   /* Substitute into the qualifying scope.  When there are no ARGS, we
11122      are just trying to simplify a non-dependent expression.  In that
11123      case the qualifying scope may be dependent, and, in any case,
11124      substituting will not help.  */
11125   scope = TREE_OPERAND (qualified_id, 0);
11126   if (args)
11127     {
11128       scope = tsubst (scope, args, complain, in_decl);
11129       expr = tsubst_copy (name, args, complain, in_decl);
11130     }
11131   else
11132     expr = name;
11133
11134   if (dependent_scope_p (scope))
11135     return build_qualified_name (NULL_TREE, scope, expr,
11136                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
11137
11138   if (!BASELINK_P (name) && !DECL_P (expr))
11139     {
11140       if (TREE_CODE (expr) == BIT_NOT_EXPR)
11141         {
11142           /* A BIT_NOT_EXPR is used to represent a destructor.  */
11143           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
11144             {
11145               error ("qualifying type %qT does not match destructor name ~%qT",
11146                      scope, TREE_OPERAND (expr, 0));
11147               expr = error_mark_node;
11148             }
11149           else
11150             expr = lookup_qualified_name (scope, complete_dtor_identifier,
11151                                           /*is_type_p=*/0, false);
11152         }
11153       else
11154         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
11155       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
11156                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
11157         {
11158           if (complain & tf_error)
11159             {
11160               error ("dependent-name %qE is parsed as a non-type, but "
11161                      "instantiation yields a type", qualified_id);
11162               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
11163             }
11164           return error_mark_node;
11165         }
11166     }
11167
11168   if (DECL_P (expr))
11169     {
11170       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
11171                                            scope);
11172       /* Remember that there was a reference to this entity.  */
11173       mark_used (expr);
11174     }
11175
11176   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
11177     {
11178       if (complain & tf_error)
11179         qualified_name_lookup_error (scope,
11180                                      TREE_OPERAND (qualified_id, 1),
11181                                      expr, input_location);
11182       return error_mark_node;
11183     }
11184
11185   if (is_template)
11186     expr = lookup_template_function (expr, template_args);
11187
11188   if (expr == error_mark_node && complain & tf_error)
11189     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
11190                                  expr, input_location);
11191   else if (TYPE_P (scope))
11192     {
11193       expr = (adjust_result_of_qualified_name_lookup
11194               (expr, scope, current_class_type));
11195       expr = (finish_qualified_id_expr
11196               (scope, expr, done, address_p,
11197                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
11198                /*template_arg_p=*/false));
11199     }
11200
11201   /* Expressions do not generally have reference type.  */
11202   if (TREE_CODE (expr) != SCOPE_REF
11203       /* However, if we're about to form a pointer-to-member, we just
11204          want the referenced member referenced.  */
11205       && TREE_CODE (expr) != OFFSET_REF)
11206     expr = convert_from_reference (expr);
11207
11208   return expr;
11209 }
11210
11211 /* Like tsubst, but deals with expressions.  This function just replaces
11212    template parms; to finish processing the resultant expression, use
11213    tsubst_expr.  */
11214
11215 static tree
11216 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11217 {
11218   enum tree_code code;
11219   tree r;
11220
11221   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
11222     return t;
11223
11224   code = TREE_CODE (t);
11225
11226   switch (code)
11227     {
11228     case PARM_DECL:
11229       r = retrieve_local_specialization (t);
11230
11231       if (r == NULL)
11232         {
11233           tree c;
11234           /* This can happen for a parameter name used later in a function
11235              declaration (such as in a late-specified return type).  Just
11236              make a dummy decl, since it's only used for its type.  */
11237           gcc_assert (cp_unevaluated_operand != 0);
11238           /* We copy T because want to tsubst the PARM_DECL only,
11239              not the following PARM_DECLs that are chained to T.  */
11240           c = copy_node (t);
11241           r = tsubst_decl (c, args, complain);
11242           /* Give it the template pattern as its context; its true context
11243              hasn't been instantiated yet and this is good enough for
11244              mangling.  */
11245           DECL_CONTEXT (r) = DECL_CONTEXT (t);
11246         }
11247       
11248       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
11249         r = ARGUMENT_PACK_SELECT_ARG (r);
11250       mark_used (r);
11251       return r;
11252
11253     case CONST_DECL:
11254       {
11255         tree enum_type;
11256         tree v;
11257
11258         if (DECL_TEMPLATE_PARM_P (t))
11259           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
11260         /* There is no need to substitute into namespace-scope
11261            enumerators.  */
11262         if (DECL_NAMESPACE_SCOPE_P (t))
11263           return t;
11264         /* If ARGS is NULL, then T is known to be non-dependent.  */
11265         if (args == NULL_TREE)
11266           return integral_constant_value (t);
11267
11268         /* Unfortunately, we cannot just call lookup_name here.
11269            Consider:
11270
11271              template <int I> int f() {
11272              enum E { a = I };
11273              struct S { void g() { E e = a; } };
11274              };
11275
11276            When we instantiate f<7>::S::g(), say, lookup_name is not
11277            clever enough to find f<7>::a.  */
11278         enum_type
11279           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
11280                               /*entering_scope=*/0);
11281
11282         for (v = TYPE_VALUES (enum_type);
11283              v != NULL_TREE;
11284              v = TREE_CHAIN (v))
11285           if (TREE_PURPOSE (v) == DECL_NAME (t))
11286             return TREE_VALUE (v);
11287
11288           /* We didn't find the name.  That should never happen; if
11289              name-lookup found it during preliminary parsing, we
11290              should find it again here during instantiation.  */
11291         gcc_unreachable ();
11292       }
11293       return t;
11294
11295     case FIELD_DECL:
11296       if (DECL_CONTEXT (t))
11297         {
11298           tree ctx;
11299
11300           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
11301                                   /*entering_scope=*/1);
11302           if (ctx != DECL_CONTEXT (t))
11303             {
11304               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
11305               if (!r)
11306                 {
11307                   if (complain & tf_error)
11308                     error ("using invalid field %qD", t);
11309                   return error_mark_node;
11310                 }
11311               return r;
11312             }
11313         }
11314
11315       return t;
11316
11317     case VAR_DECL:
11318     case FUNCTION_DECL:
11319       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
11320           || local_variable_p (t))
11321         t = tsubst (t, args, complain, in_decl);
11322       mark_used (t);
11323       return t;
11324
11325     case OVERLOAD:
11326       /* An OVERLOAD will always be a non-dependent overload set; an
11327          overload set from function scope will just be represented with an
11328          IDENTIFIER_NODE, and from class scope with a BASELINK.  */
11329       gcc_assert (!uses_template_parms (t));
11330       return t;
11331
11332     case BASELINK:
11333       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
11334
11335     case TEMPLATE_DECL:
11336       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11337         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
11338                        args, complain, in_decl);
11339       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
11340         return tsubst (t, args, complain, in_decl);
11341       else if (DECL_CLASS_SCOPE_P (t)
11342                && uses_template_parms (DECL_CONTEXT (t)))
11343         {
11344           /* Template template argument like the following example need
11345              special treatment:
11346
11347                template <template <class> class TT> struct C {};
11348                template <class T> struct D {
11349                  template <class U> struct E {};
11350                  C<E> c;                                // #1
11351                };
11352                D<int> d;                                // #2
11353
11354              We are processing the template argument `E' in #1 for
11355              the template instantiation #2.  Originally, `E' is a
11356              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
11357              have to substitute this with one having context `D<int>'.  */
11358
11359           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
11360           return lookup_field (context, DECL_NAME(t), 0, false);
11361         }
11362       else
11363         /* Ordinary template template argument.  */
11364         return t;
11365
11366     case CAST_EXPR:
11367     case REINTERPRET_CAST_EXPR:
11368     case CONST_CAST_EXPR:
11369     case STATIC_CAST_EXPR:
11370     case DYNAMIC_CAST_EXPR:
11371     case NOP_EXPR:
11372       return build1
11373         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11374          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11375
11376     case SIZEOF_EXPR:
11377       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11378         {
11379           /* We only want to compute the number of arguments.  */
11380           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
11381                                                 complain, in_decl);
11382           int len = 0;
11383
11384           if (TREE_CODE (expanded) == TREE_VEC)
11385             len = TREE_VEC_LENGTH (expanded);
11386
11387           if (expanded == error_mark_node)
11388             return error_mark_node;
11389           else if (PACK_EXPANSION_P (expanded)
11390                    || (TREE_CODE (expanded) == TREE_VEC
11391                        && len > 0
11392                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
11393             {
11394               if (TREE_CODE (expanded) == TREE_VEC)
11395                 expanded = TREE_VEC_ELT (expanded, len - 1);
11396
11397               if (TYPE_P (expanded))
11398                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
11399                                                    complain & tf_error);
11400               else
11401                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
11402                                                    complain & tf_error);
11403             }
11404           else
11405             return build_int_cst (size_type_node, len);
11406         }
11407       /* Fall through */
11408
11409     case INDIRECT_REF:
11410     case NEGATE_EXPR:
11411     case TRUTH_NOT_EXPR:
11412     case BIT_NOT_EXPR:
11413     case ADDR_EXPR:
11414     case UNARY_PLUS_EXPR:      /* Unary + */
11415     case ALIGNOF_EXPR:
11416     case AT_ENCODE_EXPR:
11417     case ARROW_EXPR:
11418     case THROW_EXPR:
11419     case TYPEID_EXPR:
11420     case REALPART_EXPR:
11421     case IMAGPART_EXPR:
11422       return build1
11423         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11424          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11425
11426     case COMPONENT_REF:
11427       {
11428         tree object;
11429         tree name;
11430
11431         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
11432         name = TREE_OPERAND (t, 1);
11433         if (TREE_CODE (name) == BIT_NOT_EXPR)
11434           {
11435             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11436                                 complain, in_decl);
11437             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11438           }
11439         else if (TREE_CODE (name) == SCOPE_REF
11440                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
11441           {
11442             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
11443                                      complain, in_decl);
11444             name = TREE_OPERAND (name, 1);
11445             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11446                                 complain, in_decl);
11447             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11448             name = build_qualified_name (/*type=*/NULL_TREE,
11449                                          base, name,
11450                                          /*template_p=*/false);
11451           }
11452         else if (TREE_CODE (name) == BASELINK)
11453           name = tsubst_baselink (name,
11454                                   non_reference (TREE_TYPE (object)),
11455                                   args, complain,
11456                                   in_decl);
11457         else
11458           name = tsubst_copy (name, args, complain, in_decl);
11459         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
11460       }
11461
11462     case PLUS_EXPR:
11463     case MINUS_EXPR:
11464     case MULT_EXPR:
11465     case TRUNC_DIV_EXPR:
11466     case CEIL_DIV_EXPR:
11467     case FLOOR_DIV_EXPR:
11468     case ROUND_DIV_EXPR:
11469     case EXACT_DIV_EXPR:
11470     case BIT_AND_EXPR:
11471     case BIT_IOR_EXPR:
11472     case BIT_XOR_EXPR:
11473     case TRUNC_MOD_EXPR:
11474     case FLOOR_MOD_EXPR:
11475     case TRUTH_ANDIF_EXPR:
11476     case TRUTH_ORIF_EXPR:
11477     case TRUTH_AND_EXPR:
11478     case TRUTH_OR_EXPR:
11479     case RSHIFT_EXPR:
11480     case LSHIFT_EXPR:
11481     case RROTATE_EXPR:
11482     case LROTATE_EXPR:
11483     case EQ_EXPR:
11484     case NE_EXPR:
11485     case MAX_EXPR:
11486     case MIN_EXPR:
11487     case LE_EXPR:
11488     case GE_EXPR:
11489     case LT_EXPR:
11490     case GT_EXPR:
11491     case COMPOUND_EXPR:
11492     case DOTSTAR_EXPR:
11493     case MEMBER_REF:
11494     case PREDECREMENT_EXPR:
11495     case PREINCREMENT_EXPR:
11496     case POSTDECREMENT_EXPR:
11497     case POSTINCREMENT_EXPR:
11498       return build_nt
11499         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11500          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11501
11502     case SCOPE_REF:
11503       return build_qualified_name (/*type=*/NULL_TREE,
11504                                    tsubst_copy (TREE_OPERAND (t, 0),
11505                                                 args, complain, in_decl),
11506                                    tsubst_copy (TREE_OPERAND (t, 1),
11507                                                 args, complain, in_decl),
11508                                    QUALIFIED_NAME_IS_TEMPLATE (t));
11509
11510     case ARRAY_REF:
11511       return build_nt
11512         (ARRAY_REF,
11513          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11514          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11515          NULL_TREE, NULL_TREE);
11516
11517     case CALL_EXPR:
11518       {
11519         int n = VL_EXP_OPERAND_LENGTH (t);
11520         tree result = build_vl_exp (CALL_EXPR, n);
11521         int i;
11522         for (i = 0; i < n; i++)
11523           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
11524                                              complain, in_decl);
11525         return result;
11526       }
11527
11528     case COND_EXPR:
11529     case MODOP_EXPR:
11530     case PSEUDO_DTOR_EXPR:
11531       {
11532         r = build_nt
11533           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11534            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11535            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11536         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11537         return r;
11538       }
11539
11540     case NEW_EXPR:
11541       {
11542         r = build_nt
11543         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11544          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11545          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11546         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
11547         return r;
11548       }
11549
11550     case DELETE_EXPR:
11551       {
11552         r = build_nt
11553         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11554          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11555         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
11556         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
11557         return r;
11558       }
11559
11560     case TEMPLATE_ID_EXPR:
11561       {
11562         /* Substituted template arguments */
11563         tree fn = TREE_OPERAND (t, 0);
11564         tree targs = TREE_OPERAND (t, 1);
11565
11566         fn = tsubst_copy (fn, args, complain, in_decl);
11567         if (targs)
11568           targs = tsubst_template_args (targs, args, complain, in_decl);
11569
11570         return lookup_template_function (fn, targs);
11571       }
11572
11573     case TREE_LIST:
11574       {
11575         tree purpose, value, chain;
11576
11577         if (t == void_list_node)
11578           return t;
11579
11580         purpose = TREE_PURPOSE (t);
11581         if (purpose)
11582           purpose = tsubst_copy (purpose, args, complain, in_decl);
11583         value = TREE_VALUE (t);
11584         if (value)
11585           value = tsubst_copy (value, args, complain, in_decl);
11586         chain = TREE_CHAIN (t);
11587         if (chain && chain != void_type_node)
11588           chain = tsubst_copy (chain, args, complain, in_decl);
11589         if (purpose == TREE_PURPOSE (t)
11590             && value == TREE_VALUE (t)
11591             && chain == TREE_CHAIN (t))
11592           return t;
11593         return tree_cons (purpose, value, chain);
11594       }
11595
11596     case RECORD_TYPE:
11597     case UNION_TYPE:
11598     case ENUMERAL_TYPE:
11599     case INTEGER_TYPE:
11600     case TEMPLATE_TYPE_PARM:
11601     case TEMPLATE_TEMPLATE_PARM:
11602     case BOUND_TEMPLATE_TEMPLATE_PARM:
11603     case TEMPLATE_PARM_INDEX:
11604     case POINTER_TYPE:
11605     case REFERENCE_TYPE:
11606     case OFFSET_TYPE:
11607     case FUNCTION_TYPE:
11608     case METHOD_TYPE:
11609     case ARRAY_TYPE:
11610     case TYPENAME_TYPE:
11611     case UNBOUND_CLASS_TEMPLATE:
11612     case TYPEOF_TYPE:
11613     case DECLTYPE_TYPE:
11614     case TYPE_DECL:
11615       return tsubst (t, args, complain, in_decl);
11616
11617     case IDENTIFIER_NODE:
11618       if (IDENTIFIER_TYPENAME_P (t))
11619         {
11620           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11621           return mangle_conv_op_name_for_type (new_type);
11622         }
11623       else
11624         return t;
11625
11626     case CONSTRUCTOR:
11627       /* This is handled by tsubst_copy_and_build.  */
11628       gcc_unreachable ();
11629
11630     case VA_ARG_EXPR:
11631       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
11632                                           in_decl),
11633                              tsubst (TREE_TYPE (t), args, complain, in_decl));
11634
11635     case CLEANUP_POINT_EXPR:
11636       /* We shouldn't have built any of these during initial template
11637          generation.  Instead, they should be built during instantiation
11638          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
11639       gcc_unreachable ();
11640
11641     case OFFSET_REF:
11642       r = build2
11643         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11644          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11645          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11646       PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
11647       mark_used (TREE_OPERAND (r, 1));
11648       return r;
11649
11650     case EXPR_PACK_EXPANSION:
11651       error ("invalid use of pack expansion expression");
11652       return error_mark_node;
11653
11654     case NONTYPE_ARGUMENT_PACK:
11655       error ("use %<...%> to expand argument pack");
11656       return error_mark_node;
11657
11658     case INTEGER_CST:
11659     case REAL_CST:
11660     case STRING_CST:
11661     case COMPLEX_CST:
11662       {
11663         /* Instantiate any typedefs in the type.  */
11664         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11665         r = fold_convert (type, t);
11666         gcc_assert (TREE_CODE (r) == code);
11667         return r;
11668       }
11669
11670     case PTRMEM_CST:
11671       /* These can sometimes show up in a partial instantiation, but never
11672          involve template parms.  */
11673       gcc_assert (!uses_template_parms (t));
11674       return t;
11675
11676     default:
11677       gcc_unreachable ();
11678     }
11679 }
11680
11681 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
11682
11683 static tree
11684 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
11685                     tree in_decl)
11686 {
11687   tree new_clauses = NULL, nc, oc;
11688
11689   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
11690     {
11691       nc = copy_node (oc);
11692       OMP_CLAUSE_CHAIN (nc) = new_clauses;
11693       new_clauses = nc;
11694
11695       switch (OMP_CLAUSE_CODE (nc))
11696         {
11697         case OMP_CLAUSE_LASTPRIVATE:
11698           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
11699             {
11700               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
11701               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
11702                            in_decl, /*integral_constant_expression_p=*/false);
11703               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
11704                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
11705             }
11706           /* FALLTHRU */
11707         case OMP_CLAUSE_PRIVATE:
11708         case OMP_CLAUSE_SHARED:
11709         case OMP_CLAUSE_FIRSTPRIVATE:
11710         case OMP_CLAUSE_REDUCTION:
11711         case OMP_CLAUSE_COPYIN:
11712         case OMP_CLAUSE_COPYPRIVATE:
11713         case OMP_CLAUSE_IF:
11714         case OMP_CLAUSE_NUM_THREADS:
11715         case OMP_CLAUSE_SCHEDULE:
11716         case OMP_CLAUSE_COLLAPSE:
11717           OMP_CLAUSE_OPERAND (nc, 0)
11718             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
11719                            in_decl, /*integral_constant_expression_p=*/false);
11720           break;
11721         case OMP_CLAUSE_NOWAIT:
11722         case OMP_CLAUSE_ORDERED:
11723         case OMP_CLAUSE_DEFAULT:
11724         case OMP_CLAUSE_UNTIED:
11725           break;
11726         default:
11727           gcc_unreachable ();
11728         }
11729     }
11730
11731   return finish_omp_clauses (nreverse (new_clauses));
11732 }
11733
11734 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
11735
11736 static tree
11737 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
11738                           tree in_decl)
11739 {
11740 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
11741
11742   tree purpose, value, chain;
11743
11744   if (t == NULL)
11745     return t;
11746
11747   if (TREE_CODE (t) != TREE_LIST)
11748     return tsubst_copy_and_build (t, args, complain, in_decl,
11749                                   /*function_p=*/false,
11750                                   /*integral_constant_expression_p=*/false);
11751
11752   if (t == void_list_node)
11753     return t;
11754
11755   purpose = TREE_PURPOSE (t);
11756   if (purpose)
11757     purpose = RECUR (purpose);
11758   value = TREE_VALUE (t);
11759   if (value && TREE_CODE (value) != LABEL_DECL)
11760     value = RECUR (value);
11761   chain = TREE_CHAIN (t);
11762   if (chain && chain != void_type_node)
11763     chain = RECUR (chain);
11764   return tree_cons (purpose, value, chain);
11765 #undef RECUR
11766 }
11767
11768 /* Substitute one OMP_FOR iterator.  */
11769
11770 static void
11771 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
11772                          tree condv, tree incrv, tree *clauses,
11773                          tree args, tsubst_flags_t complain, tree in_decl,
11774                          bool integral_constant_expression_p)
11775 {
11776 #define RECUR(NODE)                             \
11777   tsubst_expr ((NODE), args, complain, in_decl, \
11778                integral_constant_expression_p)
11779   tree decl, init, cond, incr, auto_node;
11780
11781   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
11782   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
11783   decl = RECUR (TREE_OPERAND (init, 0));
11784   init = TREE_OPERAND (init, 1);
11785   auto_node = type_uses_auto (TREE_TYPE (decl));
11786   if (auto_node && init)
11787     {
11788       tree init_expr = init;
11789       if (TREE_CODE (init_expr) == DECL_EXPR)
11790         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
11791       init_expr = RECUR (init_expr);
11792       TREE_TYPE (decl)
11793         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
11794     }
11795   gcc_assert (!type_dependent_expression_p (decl));
11796
11797   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
11798     {
11799       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
11800       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11801       if (TREE_CODE (incr) == MODIFY_EXPR)
11802         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
11803                                     RECUR (TREE_OPERAND (incr, 1)),
11804                                     complain);
11805       else
11806         incr = RECUR (incr);
11807       TREE_VEC_ELT (declv, i) = decl;
11808       TREE_VEC_ELT (initv, i) = init;
11809       TREE_VEC_ELT (condv, i) = cond;
11810       TREE_VEC_ELT (incrv, i) = incr;
11811       return;
11812     }
11813
11814   if (init && TREE_CODE (init) != DECL_EXPR)
11815     {
11816       tree c;
11817       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
11818         {
11819           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
11820                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
11821               && OMP_CLAUSE_DECL (c) == decl)
11822             break;
11823           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
11824                    && OMP_CLAUSE_DECL (c) == decl)
11825             error ("iteration variable %qD should not be firstprivate", decl);
11826           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
11827                    && OMP_CLAUSE_DECL (c) == decl)
11828             error ("iteration variable %qD should not be reduction", decl);
11829         }
11830       if (c == NULL)
11831         {
11832           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
11833           OMP_CLAUSE_DECL (c) = decl;
11834           c = finish_omp_clauses (c);
11835           if (c)
11836             {
11837               OMP_CLAUSE_CHAIN (c) = *clauses;
11838               *clauses = c;
11839             }
11840         }
11841     }
11842   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
11843   if (COMPARISON_CLASS_P (cond))
11844     cond = build2 (TREE_CODE (cond), boolean_type_node,
11845                    RECUR (TREE_OPERAND (cond, 0)),
11846                    RECUR (TREE_OPERAND (cond, 1)));
11847   else
11848     cond = RECUR (cond);
11849   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11850   switch (TREE_CODE (incr))
11851     {
11852     case PREINCREMENT_EXPR:
11853     case PREDECREMENT_EXPR:
11854     case POSTINCREMENT_EXPR:
11855     case POSTDECREMENT_EXPR:
11856       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
11857                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
11858       break;
11859     case MODIFY_EXPR:
11860       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11861           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11862         {
11863           tree rhs = TREE_OPERAND (incr, 1);
11864           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11865                          RECUR (TREE_OPERAND (incr, 0)),
11866                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11867                                  RECUR (TREE_OPERAND (rhs, 0)),
11868                                  RECUR (TREE_OPERAND (rhs, 1))));
11869         }
11870       else
11871         incr = RECUR (incr);
11872       break;
11873     case MODOP_EXPR:
11874       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11875           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11876         {
11877           tree lhs = RECUR (TREE_OPERAND (incr, 0));
11878           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
11879                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
11880                                  TREE_TYPE (decl), lhs,
11881                                  RECUR (TREE_OPERAND (incr, 2))));
11882         }
11883       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
11884                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
11885                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
11886         {
11887           tree rhs = TREE_OPERAND (incr, 2);
11888           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11889                          RECUR (TREE_OPERAND (incr, 0)),
11890                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11891                                  RECUR (TREE_OPERAND (rhs, 0)),
11892                                  RECUR (TREE_OPERAND (rhs, 1))));
11893         }
11894       else
11895         incr = RECUR (incr);
11896       break;
11897     default:
11898       incr = RECUR (incr);
11899       break;
11900     }
11901
11902   TREE_VEC_ELT (declv, i) = decl;
11903   TREE_VEC_ELT (initv, i) = init;
11904   TREE_VEC_ELT (condv, i) = cond;
11905   TREE_VEC_ELT (incrv, i) = incr;
11906 #undef RECUR
11907 }
11908
11909 /* Like tsubst_copy for expressions, etc. but also does semantic
11910    processing.  */
11911
11912 static tree
11913 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
11914              bool integral_constant_expression_p)
11915 {
11916 #define RECUR(NODE)                             \
11917   tsubst_expr ((NODE), args, complain, in_decl, \
11918                integral_constant_expression_p)
11919
11920   tree stmt, tmp;
11921
11922   if (t == NULL_TREE || t == error_mark_node)
11923     return t;
11924
11925   if (EXPR_HAS_LOCATION (t))
11926     input_location = EXPR_LOCATION (t);
11927   if (STATEMENT_CODE_P (TREE_CODE (t)))
11928     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
11929
11930   switch (TREE_CODE (t))
11931     {
11932     case STATEMENT_LIST:
11933       {
11934         tree_stmt_iterator i;
11935         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
11936           RECUR (tsi_stmt (i));
11937         break;
11938       }
11939
11940     case CTOR_INITIALIZER:
11941       finish_mem_initializers (tsubst_initializer_list
11942                                (TREE_OPERAND (t, 0), args));
11943       break;
11944
11945     case RETURN_EXPR:
11946       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
11947       break;
11948
11949     case EXPR_STMT:
11950       tmp = RECUR (EXPR_STMT_EXPR (t));
11951       if (EXPR_STMT_STMT_EXPR_RESULT (t))
11952         finish_stmt_expr_expr (tmp, cur_stmt_expr);
11953       else
11954         finish_expr_stmt (tmp);
11955       break;
11956
11957     case USING_STMT:
11958       do_using_directive (USING_STMT_NAMESPACE (t));
11959       break;
11960
11961     case DECL_EXPR:
11962       {
11963         tree decl, pattern_decl;
11964         tree init;
11965
11966         pattern_decl = decl = DECL_EXPR_DECL (t);
11967         if (TREE_CODE (decl) == LABEL_DECL)
11968           finish_label_decl (DECL_NAME (decl));
11969         else if (TREE_CODE (decl) == USING_DECL)
11970           {
11971             tree scope = USING_DECL_SCOPE (decl);
11972             tree name = DECL_NAME (decl);
11973             tree decl;
11974
11975             scope = tsubst (scope, args, complain, in_decl);
11976             decl = lookup_qualified_name (scope, name,
11977                                           /*is_type_p=*/false,
11978                                           /*complain=*/false);
11979             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
11980               qualified_name_lookup_error (scope, name, decl, input_location);
11981             else
11982               do_local_using_decl (decl, scope, name);
11983           }
11984         else
11985           {
11986             init = DECL_INITIAL (decl);
11987             decl = tsubst (decl, args, complain, in_decl);
11988             if (decl != error_mark_node)
11989               {
11990                 /* By marking the declaration as instantiated, we avoid
11991                    trying to instantiate it.  Since instantiate_decl can't
11992                    handle local variables, and since we've already done
11993                    all that needs to be done, that's the right thing to
11994                    do.  */
11995                 if (TREE_CODE (decl) == VAR_DECL)
11996                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11997                 if (TREE_CODE (decl) == VAR_DECL
11998                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
11999                   /* Anonymous aggregates are a special case.  */
12000                   finish_anon_union (decl);
12001                 else
12002                   {
12003                     int const_init = false;
12004                     maybe_push_decl (decl);
12005                     if (TREE_CODE (decl) == VAR_DECL
12006                         && DECL_PRETTY_FUNCTION_P (decl))
12007                       {
12008                         /* For __PRETTY_FUNCTION__ we have to adjust the
12009                            initializer.  */
12010                         const char *const name
12011                           = cxx_printable_name (current_function_decl, 2);
12012                         init = cp_fname_init (name, &TREE_TYPE (decl));
12013                       }
12014                     else
12015                       {
12016                         tree t = RECUR (init);
12017
12018                         if (init && !t)
12019                           {
12020                             /* If we had an initializer but it
12021                                instantiated to nothing,
12022                                value-initialize the object.  This will
12023                                only occur when the initializer was a
12024                                pack expansion where the parameter packs
12025                                used in that expansion were of length
12026                                zero.  */
12027                             init = build_value_init (TREE_TYPE (decl),
12028                                                      complain);
12029                             if (TREE_CODE (init) == AGGR_INIT_EXPR)
12030                               init = get_target_expr (init);
12031                           }
12032                         else
12033                           init = t;
12034                       }
12035
12036                     if (TREE_CODE (decl) == VAR_DECL)
12037                       const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
12038                                     (pattern_decl));
12039                     cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
12040                   }
12041               }
12042           }
12043
12044         /* A DECL_EXPR can also be used as an expression, in the condition
12045            clause of an if/for/while construct.  */
12046         return decl;
12047       }
12048
12049     case FOR_STMT:
12050       stmt = begin_for_stmt ();
12051       RECUR (FOR_INIT_STMT (t));
12052       finish_for_init_stmt (stmt);
12053       tmp = RECUR (FOR_COND (t));
12054       finish_for_cond (tmp, stmt);
12055       tmp = RECUR (FOR_EXPR (t));
12056       finish_for_expr (tmp, stmt);
12057       RECUR (FOR_BODY (t));
12058       finish_for_stmt (stmt);
12059       break;
12060
12061     case RANGE_FOR_STMT:
12062       {
12063         tree decl, expr;
12064         stmt = begin_for_stmt ();
12065         decl = RANGE_FOR_DECL (t);
12066         decl = tsubst (decl, args, complain, in_decl);
12067         maybe_push_decl (decl);
12068         expr = RECUR (RANGE_FOR_EXPR (t));
12069         stmt = cp_convert_range_for (stmt, decl, expr);
12070         RECUR (RANGE_FOR_BODY (t));
12071         finish_for_stmt (stmt);
12072       }
12073       break;
12074
12075     case WHILE_STMT:
12076       stmt = begin_while_stmt ();
12077       tmp = RECUR (WHILE_COND (t));
12078       finish_while_stmt_cond (tmp, stmt);
12079       RECUR (WHILE_BODY (t));
12080       finish_while_stmt (stmt);
12081       break;
12082
12083     case DO_STMT:
12084       stmt = begin_do_stmt ();
12085       RECUR (DO_BODY (t));
12086       finish_do_body (stmt);
12087       tmp = RECUR (DO_COND (t));
12088       finish_do_stmt (tmp, stmt);
12089       break;
12090
12091     case IF_STMT:
12092       stmt = begin_if_stmt ();
12093       tmp = RECUR (IF_COND (t));
12094       finish_if_stmt_cond (tmp, stmt);
12095       RECUR (THEN_CLAUSE (t));
12096       finish_then_clause (stmt);
12097
12098       if (ELSE_CLAUSE (t))
12099         {
12100           begin_else_clause (stmt);
12101           RECUR (ELSE_CLAUSE (t));
12102           finish_else_clause (stmt);
12103         }
12104
12105       finish_if_stmt (stmt);
12106       break;
12107
12108     case BIND_EXPR:
12109       if (BIND_EXPR_BODY_BLOCK (t))
12110         stmt = begin_function_body ();
12111       else
12112         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
12113                                     ? BCS_TRY_BLOCK : 0);
12114
12115       RECUR (BIND_EXPR_BODY (t));
12116
12117       if (BIND_EXPR_BODY_BLOCK (t))
12118         finish_function_body (stmt);
12119       else
12120         finish_compound_stmt (stmt);
12121       break;
12122
12123     case BREAK_STMT:
12124       finish_break_stmt ();
12125       break;
12126
12127     case CONTINUE_STMT:
12128       finish_continue_stmt ();
12129       break;
12130
12131     case SWITCH_STMT:
12132       stmt = begin_switch_stmt ();
12133       tmp = RECUR (SWITCH_STMT_COND (t));
12134       finish_switch_cond (tmp, stmt);
12135       RECUR (SWITCH_STMT_BODY (t));
12136       finish_switch_stmt (stmt);
12137       break;
12138
12139     case CASE_LABEL_EXPR:
12140       finish_case_label (EXPR_LOCATION (t),
12141                          RECUR (CASE_LOW (t)),
12142                          RECUR (CASE_HIGH (t)));
12143       break;
12144
12145     case LABEL_EXPR:
12146       {
12147         tree decl = LABEL_EXPR_LABEL (t);
12148         tree label;
12149
12150         label = finish_label_stmt (DECL_NAME (decl));
12151         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
12152           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
12153       }
12154       break;
12155
12156     case GOTO_EXPR:
12157       tmp = GOTO_DESTINATION (t);
12158       if (TREE_CODE (tmp) != LABEL_DECL)
12159         /* Computed goto's must be tsubst'd into.  On the other hand,
12160            non-computed gotos must not be; the identifier in question
12161            will have no binding.  */
12162         tmp = RECUR (tmp);
12163       else
12164         tmp = DECL_NAME (tmp);
12165       finish_goto_stmt (tmp);
12166       break;
12167
12168     case ASM_EXPR:
12169       tmp = finish_asm_stmt
12170         (ASM_VOLATILE_P (t),
12171          RECUR (ASM_STRING (t)),
12172          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
12173          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
12174          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
12175          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
12176       {
12177         tree asm_expr = tmp;
12178         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
12179           asm_expr = TREE_OPERAND (asm_expr, 0);
12180         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
12181       }
12182       break;
12183
12184     case TRY_BLOCK:
12185       if (CLEANUP_P (t))
12186         {
12187           stmt = begin_try_block ();
12188           RECUR (TRY_STMTS (t));
12189           finish_cleanup_try_block (stmt);
12190           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
12191         }
12192       else
12193         {
12194           tree compound_stmt = NULL_TREE;
12195
12196           if (FN_TRY_BLOCK_P (t))
12197             stmt = begin_function_try_block (&compound_stmt);
12198           else
12199             stmt = begin_try_block ();
12200
12201           RECUR (TRY_STMTS (t));
12202
12203           if (FN_TRY_BLOCK_P (t))
12204             finish_function_try_block (stmt);
12205           else
12206             finish_try_block (stmt);
12207
12208           RECUR (TRY_HANDLERS (t));
12209           if (FN_TRY_BLOCK_P (t))
12210             finish_function_handler_sequence (stmt, compound_stmt);
12211           else
12212             finish_handler_sequence (stmt);
12213         }
12214       break;
12215
12216     case HANDLER:
12217       {
12218         tree decl = HANDLER_PARMS (t);
12219
12220         if (decl)
12221           {
12222             decl = tsubst (decl, args, complain, in_decl);
12223             /* Prevent instantiate_decl from trying to instantiate
12224                this variable.  We've already done all that needs to be
12225                done.  */
12226             if (decl != error_mark_node)
12227               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12228           }
12229         stmt = begin_handler ();
12230         finish_handler_parms (decl, stmt);
12231         RECUR (HANDLER_BODY (t));
12232         finish_handler (stmt);
12233       }
12234       break;
12235
12236     case TAG_DEFN:
12237       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12238       break;
12239
12240     case STATIC_ASSERT:
12241       {
12242         tree condition = 
12243           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
12244                        args,
12245                        complain, in_decl,
12246                        /*integral_constant_expression_p=*/true);
12247         finish_static_assert (condition,
12248                               STATIC_ASSERT_MESSAGE (t),
12249                               STATIC_ASSERT_SOURCE_LOCATION (t),
12250                               /*member_p=*/false);
12251       }
12252       break;
12253
12254     case OMP_PARALLEL:
12255       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
12256                                 args, complain, in_decl);
12257       stmt = begin_omp_parallel ();
12258       RECUR (OMP_PARALLEL_BODY (t));
12259       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
12260         = OMP_PARALLEL_COMBINED (t);
12261       break;
12262
12263     case OMP_TASK:
12264       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
12265                                 args, complain, in_decl);
12266       stmt = begin_omp_task ();
12267       RECUR (OMP_TASK_BODY (t));
12268       finish_omp_task (tmp, stmt);
12269       break;
12270
12271     case OMP_FOR:
12272       {
12273         tree clauses, body, pre_body;
12274         tree declv, initv, condv, incrv;
12275         int i;
12276
12277         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
12278                                       args, complain, in_decl);
12279         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12280         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12281         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12282         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12283
12284         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
12285           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
12286                                    &clauses, args, complain, in_decl,
12287                                    integral_constant_expression_p);
12288
12289         stmt = begin_omp_structured_block ();
12290
12291         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
12292           if (TREE_VEC_ELT (initv, i) == NULL
12293               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
12294             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
12295           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
12296             {
12297               tree init = RECUR (TREE_VEC_ELT (initv, i));
12298               gcc_assert (init == TREE_VEC_ELT (declv, i));
12299               TREE_VEC_ELT (initv, i) = NULL_TREE;
12300             }
12301           else
12302             {
12303               tree decl_expr = TREE_VEC_ELT (initv, i);
12304               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
12305               gcc_assert (init != NULL);
12306               TREE_VEC_ELT (initv, i) = RECUR (init);
12307               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
12308               RECUR (decl_expr);
12309               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
12310             }
12311
12312         pre_body = push_stmt_list ();
12313         RECUR (OMP_FOR_PRE_BODY (t));
12314         pre_body = pop_stmt_list (pre_body);
12315
12316         body = push_stmt_list ();
12317         RECUR (OMP_FOR_BODY (t));
12318         body = pop_stmt_list (body);
12319
12320         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
12321                             body, pre_body, clauses);
12322
12323         add_stmt (finish_omp_structured_block (stmt));
12324       }
12325       break;
12326
12327     case OMP_SECTIONS:
12328     case OMP_SINGLE:
12329       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
12330       stmt = push_stmt_list ();
12331       RECUR (OMP_BODY (t));
12332       stmt = pop_stmt_list (stmt);
12333
12334       t = copy_node (t);
12335       OMP_BODY (t) = stmt;
12336       OMP_CLAUSES (t) = tmp;
12337       add_stmt (t);
12338       break;
12339
12340     case OMP_SECTION:
12341     case OMP_CRITICAL:
12342     case OMP_MASTER:
12343     case OMP_ORDERED:
12344       stmt = push_stmt_list ();
12345       RECUR (OMP_BODY (t));
12346       stmt = pop_stmt_list (stmt);
12347
12348       t = copy_node (t);
12349       OMP_BODY (t) = stmt;
12350       add_stmt (t);
12351       break;
12352
12353     case OMP_ATOMIC:
12354       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
12355       {
12356         tree op1 = TREE_OPERAND (t, 1);
12357         tree lhs = RECUR (TREE_OPERAND (op1, 0));
12358         tree rhs = RECUR (TREE_OPERAND (op1, 1));
12359         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
12360       }
12361       break;
12362
12363     case EXPR_PACK_EXPANSION:
12364       error ("invalid use of pack expansion expression");
12365       return error_mark_node;
12366
12367     case NONTYPE_ARGUMENT_PACK:
12368       error ("use %<...%> to expand argument pack");
12369       return error_mark_node;
12370
12371     default:
12372       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
12373
12374       return tsubst_copy_and_build (t, args, complain, in_decl,
12375                                     /*function_p=*/false,
12376                                     integral_constant_expression_p);
12377     }
12378
12379   return NULL_TREE;
12380 #undef RECUR
12381 }
12382
12383 /* T is a postfix-expression that is not being used in a function
12384    call.  Return the substituted version of T.  */
12385
12386 static tree
12387 tsubst_non_call_postfix_expression (tree t, tree args,
12388                                     tsubst_flags_t complain,
12389                                     tree in_decl)
12390 {
12391   if (TREE_CODE (t) == SCOPE_REF)
12392     t = tsubst_qualified_id (t, args, complain, in_decl,
12393                              /*done=*/false, /*address_p=*/false);
12394   else
12395     t = tsubst_copy_and_build (t, args, complain, in_decl,
12396                                /*function_p=*/false,
12397                                /*integral_constant_expression_p=*/false);
12398
12399   return t;
12400 }
12401
12402 /* Like tsubst but deals with expressions and performs semantic
12403    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
12404
12405 tree
12406 tsubst_copy_and_build (tree t,
12407                        tree args,
12408                        tsubst_flags_t complain,
12409                        tree in_decl,
12410                        bool function_p,
12411                        bool integral_constant_expression_p)
12412 {
12413 #define RECUR(NODE)                                             \
12414   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
12415                          /*function_p=*/false,                  \
12416                          integral_constant_expression_p)
12417
12418   tree op1;
12419
12420   if (t == NULL_TREE || t == error_mark_node)
12421     return t;
12422
12423   switch (TREE_CODE (t))
12424     {
12425     case USING_DECL:
12426       t = DECL_NAME (t);
12427       /* Fall through.  */
12428     case IDENTIFIER_NODE:
12429       {
12430         tree decl;
12431         cp_id_kind idk;
12432         bool non_integral_constant_expression_p;
12433         const char *error_msg;
12434
12435         if (IDENTIFIER_TYPENAME_P (t))
12436           {
12437             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12438             t = mangle_conv_op_name_for_type (new_type);
12439           }
12440
12441         /* Look up the name.  */
12442         decl = lookup_name (t);
12443
12444         /* By convention, expressions use ERROR_MARK_NODE to indicate
12445            failure, not NULL_TREE.  */
12446         if (decl == NULL_TREE)
12447           decl = error_mark_node;
12448
12449         decl = finish_id_expression (t, decl, NULL_TREE,
12450                                      &idk,
12451                                      integral_constant_expression_p,
12452                                      /*allow_non_integral_constant_expression_p=*/false,
12453                                      &non_integral_constant_expression_p,
12454                                      /*template_p=*/false,
12455                                      /*done=*/true,
12456                                      /*address_p=*/false,
12457                                      /*template_arg_p=*/false,
12458                                      &error_msg,
12459                                      input_location);
12460         if (error_msg)
12461           error (error_msg);
12462         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
12463           decl = unqualified_name_lookup_error (decl);
12464         return decl;
12465       }
12466
12467     case TEMPLATE_ID_EXPR:
12468       {
12469         tree object;
12470         tree templ = RECUR (TREE_OPERAND (t, 0));
12471         tree targs = TREE_OPERAND (t, 1);
12472
12473         if (targs)
12474           targs = tsubst_template_args (targs, args, complain, in_decl);
12475
12476         if (TREE_CODE (templ) == COMPONENT_REF)
12477           {
12478             object = TREE_OPERAND (templ, 0);
12479             templ = TREE_OPERAND (templ, 1);
12480           }
12481         else
12482           object = NULL_TREE;
12483         templ = lookup_template_function (templ, targs);
12484
12485         if (object)
12486           return build3 (COMPONENT_REF, TREE_TYPE (templ),
12487                          object, templ, NULL_TREE);
12488         else
12489           return baselink_for_fns (templ);
12490       }
12491
12492     case INDIRECT_REF:
12493       {
12494         tree r = RECUR (TREE_OPERAND (t, 0));
12495
12496         if (REFERENCE_REF_P (t))
12497           {
12498             /* A type conversion to reference type will be enclosed in
12499                such an indirect ref, but the substitution of the cast
12500                will have also added such an indirect ref.  */
12501             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
12502               r = convert_from_reference (r);
12503           }
12504         else
12505           r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
12506         return r;
12507       }
12508
12509     case NOP_EXPR:
12510       return build_nop
12511         (tsubst (TREE_TYPE (t), args, complain, in_decl),
12512          RECUR (TREE_OPERAND (t, 0)));
12513
12514     case CAST_EXPR:
12515     case REINTERPRET_CAST_EXPR:
12516     case CONST_CAST_EXPR:
12517     case DYNAMIC_CAST_EXPR:
12518     case STATIC_CAST_EXPR:
12519       {
12520         tree type;
12521         tree op;
12522
12523         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12524         if (integral_constant_expression_p
12525             && !cast_valid_in_integral_constant_expression_p (type))
12526           {
12527             if (complain & tf_error)
12528               error ("a cast to a type other than an integral or "
12529                      "enumeration type cannot appear in a constant-expression");
12530             return error_mark_node; 
12531           }
12532
12533         op = RECUR (TREE_OPERAND (t, 0));
12534
12535         switch (TREE_CODE (t))
12536           {
12537           case CAST_EXPR:
12538             return build_functional_cast (type, op, complain);
12539           case REINTERPRET_CAST_EXPR:
12540             return build_reinterpret_cast (type, op, complain);
12541           case CONST_CAST_EXPR:
12542             return build_const_cast (type, op, complain);
12543           case DYNAMIC_CAST_EXPR:
12544             return build_dynamic_cast (type, op, complain);
12545           case STATIC_CAST_EXPR:
12546             return build_static_cast (type, op, complain);
12547           default:
12548             gcc_unreachable ();
12549           }
12550       }
12551
12552     case POSTDECREMENT_EXPR:
12553     case POSTINCREMENT_EXPR:
12554       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12555                                                 args, complain, in_decl);
12556       return build_x_unary_op (TREE_CODE (t), op1, complain);
12557
12558     case PREDECREMENT_EXPR:
12559     case PREINCREMENT_EXPR:
12560     case NEGATE_EXPR:
12561     case BIT_NOT_EXPR:
12562     case ABS_EXPR:
12563     case TRUTH_NOT_EXPR:
12564     case UNARY_PLUS_EXPR:  /* Unary + */
12565     case REALPART_EXPR:
12566     case IMAGPART_EXPR:
12567       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
12568                                complain);
12569
12570     case ADDR_EXPR:
12571       op1 = TREE_OPERAND (t, 0);
12572       if (TREE_CODE (op1) == LABEL_DECL)
12573         return finish_label_address_expr (DECL_NAME (op1),
12574                                           EXPR_LOCATION (op1));
12575       if (TREE_CODE (op1) == SCOPE_REF)
12576         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
12577                                    /*done=*/true, /*address_p=*/true);
12578       else
12579         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
12580                                                   in_decl);
12581       return build_x_unary_op (ADDR_EXPR, op1, complain);
12582
12583     case PLUS_EXPR:
12584     case MINUS_EXPR:
12585     case MULT_EXPR:
12586     case TRUNC_DIV_EXPR:
12587     case CEIL_DIV_EXPR:
12588     case FLOOR_DIV_EXPR:
12589     case ROUND_DIV_EXPR:
12590     case EXACT_DIV_EXPR:
12591     case BIT_AND_EXPR:
12592     case BIT_IOR_EXPR:
12593     case BIT_XOR_EXPR:
12594     case TRUNC_MOD_EXPR:
12595     case FLOOR_MOD_EXPR:
12596     case TRUTH_ANDIF_EXPR:
12597     case TRUTH_ORIF_EXPR:
12598     case TRUTH_AND_EXPR:
12599     case TRUTH_OR_EXPR:
12600     case RSHIFT_EXPR:
12601     case LSHIFT_EXPR:
12602     case RROTATE_EXPR:
12603     case LROTATE_EXPR:
12604     case EQ_EXPR:
12605     case NE_EXPR:
12606     case MAX_EXPR:
12607     case MIN_EXPR:
12608     case LE_EXPR:
12609     case GE_EXPR:
12610     case LT_EXPR:
12611     case GT_EXPR:
12612     case MEMBER_REF:
12613     case DOTSTAR_EXPR:
12614       return build_x_binary_op
12615         (TREE_CODE (t),
12616          RECUR (TREE_OPERAND (t, 0)),
12617          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
12618           ? ERROR_MARK
12619           : TREE_CODE (TREE_OPERAND (t, 0))),
12620          RECUR (TREE_OPERAND (t, 1)),
12621          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
12622           ? ERROR_MARK
12623           : TREE_CODE (TREE_OPERAND (t, 1))),
12624          /*overloaded_p=*/NULL,
12625          complain);
12626
12627     case SCOPE_REF:
12628       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
12629                                   /*address_p=*/false);
12630     case ARRAY_REF:
12631       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12632                                                 args, complain, in_decl);
12633       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
12634
12635     case SIZEOF_EXPR:
12636       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
12637         return tsubst_copy (t, args, complain, in_decl);
12638       /* Fall through */
12639       
12640     case ALIGNOF_EXPR:
12641       op1 = TREE_OPERAND (t, 0);
12642       if (!args)
12643         {
12644           /* When there are no ARGS, we are trying to evaluate a
12645              non-dependent expression from the parser.  Trying to do
12646              the substitutions may not work.  */
12647           if (!TYPE_P (op1))
12648             op1 = TREE_TYPE (op1);
12649         }
12650       else
12651         {
12652           ++cp_unevaluated_operand;
12653           ++c_inhibit_evaluation_warnings;
12654           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12655                                        /*function_p=*/false,
12656                                        /*integral_constant_expression_p=*/false);
12657           --cp_unevaluated_operand;
12658           --c_inhibit_evaluation_warnings;
12659         }
12660       if (TYPE_P (op1))
12661         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
12662                                            complain & tf_error);
12663       else
12664         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
12665                                            complain & tf_error);
12666
12667     case AT_ENCODE_EXPR:
12668       {
12669         op1 = TREE_OPERAND (t, 0);
12670         ++cp_unevaluated_operand;
12671         ++c_inhibit_evaluation_warnings;
12672         op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12673                                      /*function_p=*/false,
12674                                      /*integral_constant_expression_p=*/false);
12675         --cp_unevaluated_operand;
12676         --c_inhibit_evaluation_warnings;
12677         return objc_build_encode_expr (op1);
12678       }
12679
12680     case NOEXCEPT_EXPR:
12681       op1 = TREE_OPERAND (t, 0);
12682       ++cp_unevaluated_operand;
12683       ++c_inhibit_evaluation_warnings;
12684       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12685                                    /*function_p=*/false,
12686                                    /*integral_constant_expression_p=*/false);
12687       --cp_unevaluated_operand;
12688       --c_inhibit_evaluation_warnings;
12689       return finish_noexcept_expr (op1, complain);
12690
12691     case MODOP_EXPR:
12692       {
12693         tree r = build_x_modify_expr
12694           (RECUR (TREE_OPERAND (t, 0)),
12695            TREE_CODE (TREE_OPERAND (t, 1)),
12696            RECUR (TREE_OPERAND (t, 2)),
12697            complain);
12698         /* TREE_NO_WARNING must be set if either the expression was
12699            parenthesized or it uses an operator such as >>= rather
12700            than plain assignment.  In the former case, it was already
12701            set and must be copied.  In the latter case,
12702            build_x_modify_expr sets it and it must not be reset
12703            here.  */
12704         if (TREE_NO_WARNING (t))
12705           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12706         return r;
12707       }
12708
12709     case ARROW_EXPR:
12710       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12711                                                 args, complain, in_decl);
12712       /* Remember that there was a reference to this entity.  */
12713       if (DECL_P (op1))
12714         mark_used (op1);
12715       return build_x_arrow (op1);
12716
12717     case NEW_EXPR:
12718       {
12719         tree placement = RECUR (TREE_OPERAND (t, 0));
12720         tree init = RECUR (TREE_OPERAND (t, 3));
12721         VEC(tree,gc) *placement_vec;
12722         VEC(tree,gc) *init_vec;
12723         tree ret;
12724
12725         if (placement == NULL_TREE)
12726           placement_vec = NULL;
12727         else
12728           {
12729             placement_vec = make_tree_vector ();
12730             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
12731               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
12732           }
12733
12734         /* If there was an initializer in the original tree, but it
12735            instantiated to an empty list, then we should pass a
12736            non-NULL empty vector to tell build_new that it was an
12737            empty initializer() rather than no initializer.  This can
12738            only happen when the initializer is a pack expansion whose
12739            parameter packs are of length zero.  */
12740         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
12741           init_vec = NULL;
12742         else
12743           {
12744             init_vec = make_tree_vector ();
12745             if (init == void_zero_node)
12746               gcc_assert (init_vec != NULL);
12747             else
12748               {
12749                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
12750                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
12751               }
12752           }
12753
12754         ret = build_new (&placement_vec,
12755                          tsubst (TREE_OPERAND (t, 1), args, complain, in_decl),
12756                          RECUR (TREE_OPERAND (t, 2)),
12757                          &init_vec,
12758                          NEW_EXPR_USE_GLOBAL (t),
12759                          complain);
12760
12761         if (placement_vec != NULL)
12762           release_tree_vector (placement_vec);
12763         if (init_vec != NULL)
12764           release_tree_vector (init_vec);
12765
12766         return ret;
12767       }
12768
12769     case DELETE_EXPR:
12770      return delete_sanity
12771        (RECUR (TREE_OPERAND (t, 0)),
12772         RECUR (TREE_OPERAND (t, 1)),
12773         DELETE_EXPR_USE_VEC (t),
12774         DELETE_EXPR_USE_GLOBAL (t));
12775
12776     case COMPOUND_EXPR:
12777       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
12778                                     RECUR (TREE_OPERAND (t, 1)),
12779                                     complain);
12780
12781     case CALL_EXPR:
12782       {
12783         tree function;
12784         VEC(tree,gc) *call_args;
12785         unsigned int nargs, i;
12786         bool qualified_p;
12787         bool koenig_p;
12788         tree ret;
12789
12790         function = CALL_EXPR_FN (t);
12791         /* When we parsed the expression,  we determined whether or
12792            not Koenig lookup should be performed.  */
12793         koenig_p = KOENIG_LOOKUP_P (t);
12794         if (TREE_CODE (function) == SCOPE_REF)
12795           {
12796             qualified_p = true;
12797             function = tsubst_qualified_id (function, args, complain, in_decl,
12798                                             /*done=*/false,
12799                                             /*address_p=*/false);
12800           }
12801         else
12802           {
12803             if (TREE_CODE (function) == COMPONENT_REF)
12804               {
12805                 tree op = TREE_OPERAND (function, 1);
12806
12807                 qualified_p = (TREE_CODE (op) == SCOPE_REF
12808                                || (BASELINK_P (op)
12809                                    && BASELINK_QUALIFIED_P (op)));
12810               }
12811             else
12812               qualified_p = false;
12813
12814             function = tsubst_copy_and_build (function, args, complain,
12815                                               in_decl,
12816                                               !qualified_p,
12817                                               integral_constant_expression_p);
12818
12819             if (BASELINK_P (function))
12820               qualified_p = true;
12821           }
12822
12823         nargs = call_expr_nargs (t);
12824         call_args = make_tree_vector ();
12825         for (i = 0; i < nargs; ++i)
12826           {
12827             tree arg = CALL_EXPR_ARG (t, i);
12828
12829             if (!PACK_EXPANSION_P (arg))
12830               VEC_safe_push (tree, gc, call_args,
12831                              RECUR (CALL_EXPR_ARG (t, i)));
12832             else
12833               {
12834                 /* Expand the pack expansion and push each entry onto
12835                    CALL_ARGS.  */
12836                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
12837                 if (TREE_CODE (arg) == TREE_VEC)
12838                   {
12839                     unsigned int len, j;
12840
12841                     len = TREE_VEC_LENGTH (arg);
12842                     for (j = 0; j < len; ++j)
12843                       {
12844                         tree value = TREE_VEC_ELT (arg, j);
12845                         if (value != NULL_TREE)
12846                           value = convert_from_reference (value);
12847                         VEC_safe_push (tree, gc, call_args, value);
12848                       }
12849                   }
12850                 else
12851                   {
12852                     /* A partial substitution.  Add one entry.  */
12853                     VEC_safe_push (tree, gc, call_args, arg);
12854                   }
12855               }
12856           }
12857
12858         /* We do not perform argument-dependent lookup if normal
12859            lookup finds a non-function, in accordance with the
12860            expected resolution of DR 218.  */
12861         if (koenig_p
12862             && ((is_overloaded_fn (function)
12863                  /* If lookup found a member function, the Koenig lookup is
12864                     not appropriate, even if an unqualified-name was used
12865                     to denote the function.  */
12866                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
12867                 || TREE_CODE (function) == IDENTIFIER_NODE)
12868             /* Only do this when substitution turns a dependent call
12869                into a non-dependent call.  */
12870             && type_dependent_expression_p_push (t)
12871             && !any_type_dependent_arguments_p (call_args))
12872           function = perform_koenig_lookup (function, call_args, false);
12873
12874         if (TREE_CODE (function) == IDENTIFIER_NODE)
12875           {
12876             unqualified_name_lookup_error (function);
12877             release_tree_vector (call_args);
12878             return error_mark_node;
12879           }
12880
12881         /* Remember that there was a reference to this entity.  */
12882         if (DECL_P (function))
12883           mark_used (function);
12884
12885         if (TREE_CODE (function) == OFFSET_REF)
12886           ret = build_offset_ref_call_from_tree (function, &call_args);
12887         else if (TREE_CODE (function) == COMPONENT_REF)
12888           {
12889             tree instance = TREE_OPERAND (function, 0);
12890             tree fn = TREE_OPERAND (function, 1);
12891
12892             if (processing_template_decl
12893                 && (type_dependent_expression_p (instance)
12894                     || (!BASELINK_P (fn)
12895                         && TREE_CODE (fn) != FIELD_DECL)
12896                     || type_dependent_expression_p (fn)
12897                     || any_type_dependent_arguments_p (call_args)))
12898               ret = build_nt_call_vec (function, call_args);
12899             else if (!BASELINK_P (fn))
12900               ret = finish_call_expr (function, &call_args,
12901                                        /*disallow_virtual=*/false,
12902                                        /*koenig_p=*/false,
12903                                        complain);
12904             else
12905               ret = (build_new_method_call
12906                       (instance, fn,
12907                        &call_args, NULL_TREE,
12908                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
12909                        /*fn_p=*/NULL,
12910                        complain));
12911           }
12912         else
12913           ret = finish_call_expr (function, &call_args,
12914                                   /*disallow_virtual=*/qualified_p,
12915                                   koenig_p,
12916                                   complain);
12917
12918         release_tree_vector (call_args);
12919
12920         return ret;
12921       }
12922
12923     case COND_EXPR:
12924       return build_x_conditional_expr
12925         (RECUR (TREE_OPERAND (t, 0)),
12926          RECUR (TREE_OPERAND (t, 1)),
12927          RECUR (TREE_OPERAND (t, 2)),
12928          complain);
12929
12930     case PSEUDO_DTOR_EXPR:
12931       return finish_pseudo_destructor_expr
12932         (RECUR (TREE_OPERAND (t, 0)),
12933          RECUR (TREE_OPERAND (t, 1)),
12934          RECUR (TREE_OPERAND (t, 2)));
12935
12936     case TREE_LIST:
12937       {
12938         tree purpose, value, chain;
12939
12940         if (t == void_list_node)
12941           return t;
12942
12943         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
12944             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
12945           {
12946             /* We have pack expansions, so expand those and
12947                create a new list out of it.  */
12948             tree purposevec = NULL_TREE;
12949             tree valuevec = NULL_TREE;
12950             tree chain;
12951             int i, len = -1;
12952
12953             /* Expand the argument expressions.  */
12954             if (TREE_PURPOSE (t))
12955               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
12956                                                  complain, in_decl);
12957             if (TREE_VALUE (t))
12958               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
12959                                                complain, in_decl);
12960
12961             /* Build the rest of the list.  */
12962             chain = TREE_CHAIN (t);
12963             if (chain && chain != void_type_node)
12964               chain = RECUR (chain);
12965
12966             /* Determine the number of arguments.  */
12967             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
12968               {
12969                 len = TREE_VEC_LENGTH (purposevec);
12970                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
12971               }
12972             else if (TREE_CODE (valuevec) == TREE_VEC)
12973               len = TREE_VEC_LENGTH (valuevec);
12974             else
12975               {
12976                 /* Since we only performed a partial substitution into
12977                    the argument pack, we only return a single list
12978                    node.  */
12979                 if (purposevec == TREE_PURPOSE (t)
12980                     && valuevec == TREE_VALUE (t)
12981                     && chain == TREE_CHAIN (t))
12982                   return t;
12983
12984                 return tree_cons (purposevec, valuevec, chain);
12985               }
12986             
12987             /* Convert the argument vectors into a TREE_LIST */
12988             i = len;
12989             while (i > 0)
12990               {
12991                 /* Grab the Ith values.  */
12992                 i--;
12993                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
12994                                      : NULL_TREE;
12995                 value 
12996                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
12997                              : NULL_TREE;
12998
12999                 /* Build the list (backwards).  */
13000                 chain = tree_cons (purpose, value, chain);
13001               }
13002
13003             return chain;
13004           }
13005
13006         purpose = TREE_PURPOSE (t);
13007         if (purpose)
13008           purpose = RECUR (purpose);
13009         value = TREE_VALUE (t);
13010         if (value)
13011           value = RECUR (value);
13012         chain = TREE_CHAIN (t);
13013         if (chain && chain != void_type_node)
13014           chain = RECUR (chain);
13015         if (purpose == TREE_PURPOSE (t)
13016             && value == TREE_VALUE (t)
13017             && chain == TREE_CHAIN (t))
13018           return t;
13019         return tree_cons (purpose, value, chain);
13020       }
13021
13022     case COMPONENT_REF:
13023       {
13024         tree object;
13025         tree object_type;
13026         tree member;
13027
13028         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13029                                                      args, complain, in_decl);
13030         /* Remember that there was a reference to this entity.  */
13031         if (DECL_P (object))
13032           mark_used (object);
13033         object_type = TREE_TYPE (object);
13034
13035         member = TREE_OPERAND (t, 1);
13036         if (BASELINK_P (member))
13037           member = tsubst_baselink (member,
13038                                     non_reference (TREE_TYPE (object)),
13039                                     args, complain, in_decl);
13040         else
13041           member = tsubst_copy (member, args, complain, in_decl);
13042         if (member == error_mark_node)
13043           return error_mark_node;
13044
13045         if (object_type && !CLASS_TYPE_P (object_type))
13046           {
13047             if (SCALAR_TYPE_P (object_type))
13048               {
13049                 tree s = NULL_TREE;
13050                 tree dtor = member;
13051
13052                 if (TREE_CODE (dtor) == SCOPE_REF)
13053                   {
13054                     s = TREE_OPERAND (dtor, 0);
13055                     dtor = TREE_OPERAND (dtor, 1);
13056                   }
13057                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
13058                   {
13059                     dtor = TREE_OPERAND (dtor, 0);
13060                     if (TYPE_P (dtor))
13061                       return finish_pseudo_destructor_expr (object, s, dtor);
13062                   }
13063               }
13064           }
13065         else if (TREE_CODE (member) == SCOPE_REF
13066                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
13067           {
13068             tree tmpl;
13069             tree args;
13070
13071             /* Lookup the template functions now that we know what the
13072                scope is.  */
13073             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
13074             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
13075             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
13076                                             /*is_type_p=*/false,
13077                                             /*complain=*/false);
13078             if (BASELINK_P (member))
13079               {
13080                 BASELINK_FUNCTIONS (member)
13081                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
13082                               args);
13083                 member = (adjust_result_of_qualified_name_lookup
13084                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
13085                            object_type));
13086               }
13087             else
13088               {
13089                 qualified_name_lookup_error (object_type, tmpl, member,
13090                                              input_location);
13091                 return error_mark_node;
13092               }
13093           }
13094         else if (TREE_CODE (member) == SCOPE_REF
13095                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
13096                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
13097           {
13098             if (complain & tf_error)
13099               {
13100                 if (TYPE_P (TREE_OPERAND (member, 0)))
13101                   error ("%qT is not a class or namespace",
13102                          TREE_OPERAND (member, 0));
13103                 else
13104                   error ("%qD is not a class or namespace",
13105                          TREE_OPERAND (member, 0));
13106               }
13107             return error_mark_node;
13108           }
13109         else if (TREE_CODE (member) == FIELD_DECL)
13110           return finish_non_static_data_member (member, object, NULL_TREE);
13111
13112         return finish_class_member_access_expr (object, member,
13113                                                 /*template_p=*/false,
13114                                                 complain);
13115       }
13116
13117     case THROW_EXPR:
13118       return build_throw
13119         (RECUR (TREE_OPERAND (t, 0)));
13120
13121     case CONSTRUCTOR:
13122       {
13123         VEC(constructor_elt,gc) *n;
13124         constructor_elt *ce;
13125         unsigned HOST_WIDE_INT idx;
13126         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13127         bool process_index_p;
13128         int newlen;
13129         bool need_copy_p = false;
13130         tree r;
13131
13132         if (type == error_mark_node)
13133           return error_mark_node;
13134
13135         /* digest_init will do the wrong thing if we let it.  */
13136         if (type && TYPE_PTRMEMFUNC_P (type))
13137           return t;
13138
13139         /* We do not want to process the index of aggregate
13140            initializers as they are identifier nodes which will be
13141            looked up by digest_init.  */
13142         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
13143
13144         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
13145         newlen = VEC_length (constructor_elt, n);
13146         FOR_EACH_VEC_ELT (constructor_elt, n, idx, ce)
13147           {
13148             if (ce->index && process_index_p)
13149               ce->index = RECUR (ce->index);
13150
13151             if (PACK_EXPANSION_P (ce->value))
13152               {
13153                 /* Substitute into the pack expansion.  */
13154                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
13155                                                   in_decl);
13156
13157                 if (ce->value == error_mark_node)
13158                   ;
13159                 else if (TREE_VEC_LENGTH (ce->value) == 1)
13160                   /* Just move the argument into place.  */
13161                   ce->value = TREE_VEC_ELT (ce->value, 0);
13162                 else
13163                   {
13164                     /* Update the length of the final CONSTRUCTOR
13165                        arguments vector, and note that we will need to
13166                        copy.*/
13167                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
13168                     need_copy_p = true;
13169                   }
13170               }
13171             else
13172               ce->value = RECUR (ce->value);
13173           }
13174
13175         if (need_copy_p)
13176           {
13177             VEC(constructor_elt,gc) *old_n = n;
13178
13179             n = VEC_alloc (constructor_elt, gc, newlen);
13180             FOR_EACH_VEC_ELT (constructor_elt, old_n, idx, ce)
13181               {
13182                 if (TREE_CODE (ce->value) == TREE_VEC)
13183                   {
13184                     int i, len = TREE_VEC_LENGTH (ce->value);
13185                     for (i = 0; i < len; ++i)
13186                       CONSTRUCTOR_APPEND_ELT (n, 0,
13187                                               TREE_VEC_ELT (ce->value, i));
13188                   }
13189                 else
13190                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
13191               }
13192           }
13193
13194         r = build_constructor (init_list_type_node, n);
13195         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
13196
13197         if (TREE_HAS_CONSTRUCTOR (t))
13198           return finish_compound_literal (type, r);
13199
13200         return r;
13201       }
13202
13203     case TYPEID_EXPR:
13204       {
13205         tree operand_0 = TREE_OPERAND (t, 0);
13206         if (TYPE_P (operand_0))
13207           {
13208             operand_0 = tsubst (operand_0, args, complain, in_decl);
13209             return get_typeid (operand_0);
13210           }
13211         else
13212           {
13213             operand_0 = RECUR (operand_0);
13214             return build_typeid (operand_0);
13215           }
13216       }
13217
13218     case VAR_DECL:
13219       if (!args)
13220         return t;
13221       /* Fall through */
13222
13223     case PARM_DECL:
13224       {
13225         tree r = tsubst_copy (t, args, complain, in_decl);
13226
13227         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
13228           /* If the original type was a reference, we'll be wrapped in
13229              the appropriate INDIRECT_REF.  */
13230           r = convert_from_reference (r);
13231         return r;
13232       }
13233
13234     case VA_ARG_EXPR:
13235       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
13236                              tsubst_copy (TREE_TYPE (t), args, complain,
13237                                           in_decl));
13238
13239     case OFFSETOF_EXPR:
13240       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
13241
13242     case TRAIT_EXPR:
13243       {
13244         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
13245                                   complain, in_decl);
13246
13247         tree type2 = TRAIT_EXPR_TYPE2 (t);
13248         if (type2)
13249           type2 = tsubst_copy (type2, args, complain, in_decl);
13250         
13251         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
13252       }
13253
13254     case STMT_EXPR:
13255       {
13256         tree old_stmt_expr = cur_stmt_expr;
13257         tree stmt_expr = begin_stmt_expr ();
13258
13259         cur_stmt_expr = stmt_expr;
13260         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
13261                      integral_constant_expression_p);
13262         stmt_expr = finish_stmt_expr (stmt_expr, false);
13263         cur_stmt_expr = old_stmt_expr;
13264
13265         /* If the resulting list of expression statement is empty,
13266            fold it further into void_zero_node.  */
13267         if (empty_expr_stmt_p (stmt_expr))
13268           stmt_expr = void_zero_node;
13269
13270         return stmt_expr;
13271       }
13272
13273     case CONST_DECL:
13274       t = tsubst_copy (t, args, complain, in_decl);
13275       /* As in finish_id_expression, we resolve enumeration constants
13276          to their underlying values.  */
13277       if (TREE_CODE (t) == CONST_DECL)
13278         {
13279           used_types_insert (TREE_TYPE (t));
13280           return DECL_INITIAL (t);
13281         }
13282       return t;
13283
13284     case LAMBDA_EXPR:
13285       {
13286         tree r = build_lambda_expr ();
13287
13288         tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
13289         TREE_TYPE (r) = type;
13290         CLASSTYPE_LAMBDA_EXPR (type) = r;
13291
13292         LAMBDA_EXPR_LOCATION (r)
13293           = LAMBDA_EXPR_LOCATION (t);
13294         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
13295           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
13296         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
13297         LAMBDA_EXPR_DISCRIMINATOR (r)
13298           = (LAMBDA_EXPR_DISCRIMINATOR (t));
13299         LAMBDA_EXPR_CAPTURE_LIST (r)
13300           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
13301         LAMBDA_EXPR_THIS_CAPTURE (r)
13302           = RECUR (LAMBDA_EXPR_THIS_CAPTURE (t));
13303         LAMBDA_EXPR_EXTRA_SCOPE (r)
13304           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
13305
13306         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
13307         determine_visibility (TYPE_NAME (type));
13308         /* Now that we know visibility, instantiate the type so we have a
13309            declaration of the op() for later calls to lambda_function.  */
13310         complete_type (type);
13311
13312         type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
13313         if (type)
13314           apply_lambda_return_type (r, type);
13315
13316         return build_lambda_object (r);
13317       }
13318
13319     default:
13320       /* Handle Objective-C++ constructs, if appropriate.  */
13321       {
13322         tree subst
13323           = objcp_tsubst_copy_and_build (t, args, complain,
13324                                          in_decl, /*function_p=*/false);
13325         if (subst)
13326           return subst;
13327       }
13328       return tsubst_copy (t, args, complain, in_decl);
13329     }
13330
13331 #undef RECUR
13332 }
13333
13334 /* Verify that the instantiated ARGS are valid. For type arguments,
13335    make sure that the type's linkage is ok. For non-type arguments,
13336    make sure they are constants if they are integral or enumerations.
13337    Emit an error under control of COMPLAIN, and return TRUE on error.  */
13338
13339 static bool
13340 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
13341 {
13342   if (ARGUMENT_PACK_P (t))
13343     {
13344       tree vec = ARGUMENT_PACK_ARGS (t);
13345       int len = TREE_VEC_LENGTH (vec);
13346       bool result = false;
13347       int i;
13348
13349       for (i = 0; i < len; ++i)
13350         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
13351           result = true;
13352       return result;
13353     }
13354   else if (TYPE_P (t))
13355     {
13356       /* [basic.link]: A name with no linkage (notably, the name
13357          of a class or enumeration declared in a local scope)
13358          shall not be used to declare an entity with linkage.
13359          This implies that names with no linkage cannot be used as
13360          template arguments
13361
13362          DR 757 relaxes this restriction for C++0x.  */
13363       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
13364                  : no_linkage_check (t, /*relaxed_p=*/false));
13365
13366       if (nt)
13367         {
13368           /* DR 488 makes use of a type with no linkage cause
13369              type deduction to fail.  */
13370           if (complain & tf_error)
13371             {
13372               if (TYPE_ANONYMOUS_P (nt))
13373                 error ("%qT is/uses anonymous type", t);
13374               else
13375                 error ("template argument for %qD uses local type %qT",
13376                        tmpl, t);
13377             }
13378           return true;
13379         }
13380       /* In order to avoid all sorts of complications, we do not
13381          allow variably-modified types as template arguments.  */
13382       else if (variably_modified_type_p (t, NULL_TREE))
13383         {
13384           if (complain & tf_error)
13385             error ("%qT is a variably modified type", t);
13386           return true;
13387         }
13388     }
13389   /* A non-type argument of integral or enumerated type must be a
13390      constant.  */
13391   else if (TREE_TYPE (t)
13392            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
13393            && !TREE_CONSTANT (t))
13394     {
13395       if (complain & tf_error)
13396         error ("integral expression %qE is not constant", t);
13397       return true;
13398     }
13399   return false;
13400 }
13401
13402 static bool
13403 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
13404 {
13405   int ix, len = DECL_NTPARMS (tmpl);
13406   bool result = false;
13407
13408   for (ix = 0; ix != len; ix++)
13409     {
13410       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
13411         result = true;
13412     }
13413   if (result && (complain & tf_error))
13414     error ("  trying to instantiate %qD", tmpl);
13415   return result;
13416 }
13417
13418 /* Instantiate the indicated variable or function template TMPL with
13419    the template arguments in TARG_PTR.  */
13420
13421 tree
13422 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
13423 {
13424   tree targ_ptr = orig_args;
13425   tree fndecl;
13426   tree gen_tmpl;
13427   tree spec;
13428   HOST_WIDE_INT saved_processing_template_decl;
13429
13430   if (tmpl == error_mark_node)
13431     return error_mark_node;
13432
13433   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
13434
13435   /* If this function is a clone, handle it specially.  */
13436   if (DECL_CLONED_FUNCTION_P (tmpl))
13437     {
13438       tree spec;
13439       tree clone;
13440
13441       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
13442          DECL_CLONED_FUNCTION.  */
13443       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
13444                                    targ_ptr, complain);
13445       if (spec == error_mark_node)
13446         return error_mark_node;
13447
13448       /* Look for the clone.  */
13449       FOR_EACH_CLONE (clone, spec)
13450         if (DECL_NAME (clone) == DECL_NAME (tmpl))
13451           return clone;
13452       /* We should always have found the clone by now.  */
13453       gcc_unreachable ();
13454       return NULL_TREE;
13455     }
13456
13457   /* Check to see if we already have this specialization.  */
13458   gen_tmpl = most_general_template (tmpl);
13459   if (tmpl != gen_tmpl)
13460     /* The TMPL is a partial instantiation.  To get a full set of
13461        arguments we must add the arguments used to perform the
13462        partial instantiation.  */
13463     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
13464                                             targ_ptr);
13465
13466   /* It would be nice to avoid hashing here and then again in tsubst_decl,
13467      but it doesn't seem to be on the hot path.  */
13468   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
13469
13470   gcc_assert (tmpl == gen_tmpl
13471               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
13472                   == spec)
13473               || fndecl == NULL_TREE);
13474
13475   if (spec != NULL_TREE)
13476     return spec;
13477
13478   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
13479                                complain))
13480     return error_mark_node;
13481
13482   /* We are building a FUNCTION_DECL, during which the access of its
13483      parameters and return types have to be checked.  However this
13484      FUNCTION_DECL which is the desired context for access checking
13485      is not built yet.  We solve this chicken-and-egg problem by
13486      deferring all checks until we have the FUNCTION_DECL.  */
13487   push_deferring_access_checks (dk_deferred);
13488
13489   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
13490      (because, for example, we have encountered a non-dependent
13491      function call in the body of a template function and must now
13492      determine which of several overloaded functions will be called),
13493      within the instantiation itself we are not processing a
13494      template.  */  
13495   saved_processing_template_decl = processing_template_decl;
13496   processing_template_decl = 0;
13497   /* Substitute template parameters to obtain the specialization.  */
13498   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
13499                    targ_ptr, complain, gen_tmpl);
13500   processing_template_decl = saved_processing_template_decl;
13501   if (fndecl == error_mark_node)
13502     return error_mark_node;
13503
13504   /* Now we know the specialization, compute access previously
13505      deferred.  */
13506   push_access_scope (fndecl);
13507
13508   /* Some typedefs referenced from within the template code need to be access
13509      checked at template instantiation time, i.e now. These types were
13510      added to the template at parsing time. Let's get those and perfom
13511      the acces checks then.  */
13512   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
13513   perform_deferred_access_checks ();
13514   pop_access_scope (fndecl);
13515   pop_deferring_access_checks ();
13516
13517   /* The DECL_TI_TEMPLATE should always be the immediate parent
13518      template, not the most general template.  */
13519   DECL_TI_TEMPLATE (fndecl) = tmpl;
13520
13521   /* If we've just instantiated the main entry point for a function,
13522      instantiate all the alternate entry points as well.  We do this
13523      by cloning the instantiation of the main entry point, not by
13524      instantiating the template clones.  */
13525   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
13526     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
13527
13528   return fndecl;
13529 }
13530
13531 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
13532    NARGS elements of the arguments that are being used when calling
13533    it.  TARGS is a vector into which the deduced template arguments
13534    are placed.
13535
13536    Return zero for success, 2 for an incomplete match that doesn't resolve
13537    all the types, and 1 for complete failure.  An error message will be
13538    printed only for an incomplete match.
13539
13540    If FN is a conversion operator, or we are trying to produce a specific
13541    specialization, RETURN_TYPE is the return type desired.
13542
13543    The EXPLICIT_TARGS are explicit template arguments provided via a
13544    template-id.
13545
13546    The parameter STRICT is one of:
13547
13548    DEDUCE_CALL:
13549      We are deducing arguments for a function call, as in
13550      [temp.deduct.call].
13551
13552    DEDUCE_CONV:
13553      We are deducing arguments for a conversion function, as in
13554      [temp.deduct.conv].
13555
13556    DEDUCE_EXACT:
13557      We are deducing arguments when doing an explicit instantiation
13558      as in [temp.explicit], when determining an explicit specialization
13559      as in [temp.expl.spec], or when taking the address of a function
13560      template, as in [temp.deduct.funcaddr].  */
13561
13562 int
13563 fn_type_unification (tree fn,
13564                      tree explicit_targs,
13565                      tree targs,
13566                      const tree *args,
13567                      unsigned int nargs,
13568                      tree return_type,
13569                      unification_kind_t strict,
13570                      int flags)
13571 {
13572   tree parms;
13573   tree fntype;
13574   int result;
13575   bool incomplete_argument_packs_p = false;
13576
13577   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
13578
13579   fntype = TREE_TYPE (fn);
13580   if (explicit_targs)
13581     {
13582       /* [temp.deduct]
13583
13584          The specified template arguments must match the template
13585          parameters in kind (i.e., type, nontype, template), and there
13586          must not be more arguments than there are parameters;
13587          otherwise type deduction fails.
13588
13589          Nontype arguments must match the types of the corresponding
13590          nontype template parameters, or must be convertible to the
13591          types of the corresponding nontype parameters as specified in
13592          _temp.arg.nontype_, otherwise type deduction fails.
13593
13594          All references in the function type of the function template
13595          to the corresponding template parameters are replaced by the
13596          specified template argument values.  If a substitution in a
13597          template parameter or in the function type of the function
13598          template results in an invalid type, type deduction fails.  */
13599       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
13600       int i, len = TREE_VEC_LENGTH (tparms);
13601       tree converted_args;
13602       bool incomplete = false;
13603
13604       if (explicit_targs == error_mark_node)
13605         return 1;
13606
13607       converted_args
13608         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
13609                                   /*require_all_args=*/false,
13610                                   /*use_default_args=*/false));
13611       if (converted_args == error_mark_node)
13612         return 1;
13613
13614       /* Substitute the explicit args into the function type.  This is
13615          necessary so that, for instance, explicitly declared function
13616          arguments can match null pointed constants.  If we were given
13617          an incomplete set of explicit args, we must not do semantic
13618          processing during substitution as we could create partial
13619          instantiations.  */
13620       for (i = 0; i < len; i++)
13621         {
13622           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13623           bool parameter_pack = false;
13624
13625           /* Dig out the actual parm.  */
13626           if (TREE_CODE (parm) == TYPE_DECL
13627               || TREE_CODE (parm) == TEMPLATE_DECL)
13628             {
13629               parm = TREE_TYPE (parm);
13630               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
13631             }
13632           else if (TREE_CODE (parm) == PARM_DECL)
13633             {
13634               parm = DECL_INITIAL (parm);
13635               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
13636             }
13637
13638           if (parameter_pack)
13639             {
13640               int level, idx;
13641               tree targ;
13642               template_parm_level_and_index (parm, &level, &idx);
13643
13644               /* Mark the argument pack as "incomplete". We could
13645                  still deduce more arguments during unification.  */
13646               targ = TMPL_ARG (converted_args, level, idx);
13647               if (targ)
13648                 {
13649                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
13650                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
13651                     = ARGUMENT_PACK_ARGS (targ);
13652                 }
13653
13654               /* We have some incomplete argument packs.  */
13655               incomplete_argument_packs_p = true;
13656             }
13657         }
13658
13659       if (incomplete_argument_packs_p)
13660         /* Any substitution is guaranteed to be incomplete if there
13661            are incomplete argument packs, because we can still deduce
13662            more arguments.  */
13663         incomplete = 1;
13664       else
13665         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
13666
13667       processing_template_decl += incomplete;
13668       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
13669       processing_template_decl -= incomplete;
13670
13671       if (fntype == error_mark_node)
13672         return 1;
13673
13674       /* Place the explicitly specified arguments in TARGS.  */
13675       for (i = NUM_TMPL_ARGS (converted_args); i--;)
13676         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
13677     }
13678
13679   /* Never do unification on the 'this' parameter.  */
13680   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
13681
13682   if (return_type)
13683     {
13684       tree *new_args;
13685
13686       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
13687       new_args = XALLOCAVEC (tree, nargs + 1);
13688       new_args[0] = return_type;
13689       memcpy (new_args + 1, args, nargs * sizeof (tree));
13690       args = new_args;
13691       ++nargs;
13692     }
13693
13694   /* We allow incomplete unification without an error message here
13695      because the standard doesn't seem to explicitly prohibit it.  Our
13696      callers must be ready to deal with unification failures in any
13697      event.  */
13698   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
13699                                   targs, parms, args, nargs, /*subr=*/0,
13700                                   strict, flags);
13701
13702   if (result == 0 && incomplete_argument_packs_p)
13703     {
13704       int i, len = NUM_TMPL_ARGS (targs);
13705
13706       /* Clear the "incomplete" flags on all argument packs.  */
13707       for (i = 0; i < len; i++)
13708         {
13709           tree arg = TREE_VEC_ELT (targs, i);
13710           if (ARGUMENT_PACK_P (arg))
13711             {
13712               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
13713               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
13714             }
13715         }
13716     }
13717
13718   /* Now that we have bindings for all of the template arguments,
13719      ensure that the arguments deduced for the template template
13720      parameters have compatible template parameter lists.  We cannot
13721      check this property before we have deduced all template
13722      arguments, because the template parameter types of a template
13723      template parameter might depend on prior template parameters
13724      deduced after the template template parameter.  The following
13725      ill-formed example illustrates this issue:
13726
13727        template<typename T, template<T> class C> void f(C<5>, T);
13728
13729        template<int N> struct X {};
13730
13731        void g() {
13732          f(X<5>(), 5l); // error: template argument deduction fails
13733        }
13734
13735      The template parameter list of 'C' depends on the template type
13736      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
13737      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
13738      time that we deduce 'C'.  */
13739   if (result == 0
13740       && !template_template_parm_bindings_ok_p 
13741            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
13742     return 1;
13743
13744   if (result == 0)
13745     /* All is well so far.  Now, check:
13746
13747        [temp.deduct]
13748
13749        When all template arguments have been deduced, all uses of
13750        template parameters in nondeduced contexts are replaced with
13751        the corresponding deduced argument values.  If the
13752        substitution results in an invalid type, as described above,
13753        type deduction fails.  */
13754     {
13755       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
13756       if (substed == error_mark_node)
13757         return 1;
13758
13759       /* If we're looking for an exact match, check that what we got
13760          is indeed an exact match.  It might not be if some template
13761          parameters are used in non-deduced contexts.  */
13762       if (strict == DEDUCE_EXACT)
13763         {
13764           unsigned int i;
13765
13766           tree sarg
13767             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
13768           if (return_type)
13769             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
13770           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
13771             if (!same_type_p (args[i], TREE_VALUE (sarg)))
13772               return 1;
13773         }
13774     }
13775
13776   return result;
13777 }
13778
13779 /* Adjust types before performing type deduction, as described in
13780    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
13781    sections are symmetric.  PARM is the type of a function parameter
13782    or the return type of the conversion function.  ARG is the type of
13783    the argument passed to the call, or the type of the value
13784    initialized with the result of the conversion function.
13785    ARG_EXPR is the original argument expression, which may be null.  */
13786
13787 static int
13788 maybe_adjust_types_for_deduction (unification_kind_t strict,
13789                                   tree* parm,
13790                                   tree* arg,
13791                                   tree arg_expr)
13792 {
13793   int result = 0;
13794
13795   switch (strict)
13796     {
13797     case DEDUCE_CALL:
13798       break;
13799
13800     case DEDUCE_CONV:
13801       {
13802         /* Swap PARM and ARG throughout the remainder of this
13803            function; the handling is precisely symmetric since PARM
13804            will initialize ARG rather than vice versa.  */
13805         tree* temp = parm;
13806         parm = arg;
13807         arg = temp;
13808         break;
13809       }
13810
13811     case DEDUCE_EXACT:
13812       /* Core issue #873: Do the DR606 thing (see below) for these cases,
13813          too, but here handle it by stripping the reference from PARM
13814          rather than by adding it to ARG.  */
13815       if (TREE_CODE (*parm) == REFERENCE_TYPE
13816           && TYPE_REF_IS_RVALUE (*parm)
13817           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13818           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13819           && TREE_CODE (*arg) == REFERENCE_TYPE
13820           && !TYPE_REF_IS_RVALUE (*arg))
13821         *parm = TREE_TYPE (*parm);
13822       /* Nothing else to do in this case.  */
13823       return 0;
13824
13825     default:
13826       gcc_unreachable ();
13827     }
13828
13829   if (TREE_CODE (*parm) != REFERENCE_TYPE)
13830     {
13831       /* [temp.deduct.call]
13832
13833          If P is not a reference type:
13834
13835          --If A is an array type, the pointer type produced by the
13836          array-to-pointer standard conversion (_conv.array_) is
13837          used in place of A for type deduction; otherwise,
13838
13839          --If A is a function type, the pointer type produced by
13840          the function-to-pointer standard conversion
13841          (_conv.func_) is used in place of A for type deduction;
13842          otherwise,
13843
13844          --If A is a cv-qualified type, the top level
13845          cv-qualifiers of A's type are ignored for type
13846          deduction.  */
13847       if (TREE_CODE (*arg) == ARRAY_TYPE)
13848         *arg = build_pointer_type (TREE_TYPE (*arg));
13849       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
13850         *arg = build_pointer_type (*arg);
13851       else
13852         *arg = TYPE_MAIN_VARIANT (*arg);
13853     }
13854
13855   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
13856      of the form T&&, where T is a template parameter, and the argument
13857      is an lvalue, T is deduced as A& */
13858   if (TREE_CODE (*parm) == REFERENCE_TYPE
13859       && TYPE_REF_IS_RVALUE (*parm)
13860       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13861       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13862       && arg_expr && real_lvalue_p (arg_expr))
13863     *arg = build_reference_type (*arg);
13864
13865   /* [temp.deduct.call]
13866
13867      If P is a cv-qualified type, the top level cv-qualifiers
13868      of P's type are ignored for type deduction.  If P is a
13869      reference type, the type referred to by P is used for
13870      type deduction.  */
13871   *parm = TYPE_MAIN_VARIANT (*parm);
13872   if (TREE_CODE (*parm) == REFERENCE_TYPE)
13873     {
13874       *parm = TREE_TYPE (*parm);
13875       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13876     }
13877
13878   /* DR 322. For conversion deduction, remove a reference type on parm
13879      too (which has been swapped into ARG).  */
13880   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
13881     *arg = TREE_TYPE (*arg);
13882
13883   return result;
13884 }
13885
13886 /* Most parms like fn_type_unification.
13887
13888    If SUBR is 1, we're being called recursively (to unify the
13889    arguments of a function or method parameter of a function
13890    template). */
13891
13892 static int
13893 type_unification_real (tree tparms,
13894                        tree targs,
13895                        tree xparms,
13896                        const tree *xargs,
13897                        unsigned int xnargs,
13898                        int subr,
13899                        unification_kind_t strict,
13900                        int flags)
13901 {
13902   tree parm, arg, arg_expr;
13903   int i;
13904   int ntparms = TREE_VEC_LENGTH (tparms);
13905   int sub_strict;
13906   int saw_undeduced = 0;
13907   tree parms;
13908   const tree *args;
13909   unsigned int nargs;
13910   unsigned int ia;
13911
13912   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
13913   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
13914   gcc_assert (ntparms > 0);
13915
13916   /* Reset the number of non-defaulted template arguments contained
13917      in in TARGS.  */
13918   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
13919
13920   switch (strict)
13921     {
13922     case DEDUCE_CALL:
13923       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
13924                     | UNIFY_ALLOW_DERIVED);
13925       break;
13926
13927     case DEDUCE_CONV:
13928       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13929       break;
13930
13931     case DEDUCE_EXACT:
13932       sub_strict = UNIFY_ALLOW_NONE;
13933       break;
13934
13935     default:
13936       gcc_unreachable ();
13937     }
13938
13939  again:
13940   parms = xparms;
13941   args = xargs;
13942   nargs = xnargs;
13943
13944   ia = 0;
13945   while (parms && parms != void_list_node
13946          && ia < nargs)
13947     {
13948       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13949         break;
13950
13951       parm = TREE_VALUE (parms);
13952       parms = TREE_CHAIN (parms);
13953       arg = args[ia];
13954       ++ia;
13955       arg_expr = NULL;
13956
13957       if (arg == error_mark_node)
13958         return 1;
13959       if (arg == unknown_type_node)
13960         /* We can't deduce anything from this, but we might get all the
13961            template args from other function args.  */
13962         continue;
13963
13964       /* Conversions will be performed on a function argument that
13965          corresponds with a function parameter that contains only
13966          non-deducible template parameters and explicitly specified
13967          template parameters.  */
13968       if (!uses_template_parms (parm))
13969         {
13970           tree type;
13971
13972           if (!TYPE_P (arg))
13973             type = TREE_TYPE (arg);
13974           else
13975             type = arg;
13976
13977           if (same_type_p (parm, type))
13978             continue;
13979           if (strict != DEDUCE_EXACT
13980               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
13981                                   flags))
13982             continue;
13983
13984           return 1;
13985         }
13986
13987       if (!TYPE_P (arg))
13988         {
13989           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13990           if (type_unknown_p (arg))
13991             {
13992               /* [temp.deduct.type] 
13993
13994                  A template-argument can be deduced from a pointer to
13995                  function or pointer to member function argument if
13996                  the set of overloaded functions does not contain
13997                  function templates and at most one of a set of
13998                  overloaded functions provides a unique match.  */
13999               if (resolve_overloaded_unification
14000                   (tparms, targs, parm, arg, strict, sub_strict))
14001                 continue;
14002
14003               return 1;
14004             }
14005           arg_expr = arg;
14006           arg = unlowered_expr_type (arg);
14007           if (arg == error_mark_node)
14008             return 1;
14009         }
14010
14011       {
14012         int arg_strict = sub_strict;
14013
14014         if (!subr)
14015           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
14016                                                           arg_expr);
14017
14018         if (arg == init_list_type_node && arg_expr)
14019           arg = arg_expr;
14020         if (unify (tparms, targs, parm, arg, arg_strict))
14021           return 1;
14022       }
14023     }
14024
14025
14026   if (parms 
14027       && parms != void_list_node
14028       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
14029     {
14030       /* Unify the remaining arguments with the pack expansion type.  */
14031       tree argvec;
14032       tree parmvec = make_tree_vec (1);
14033
14034       /* Allocate a TREE_VEC and copy in all of the arguments */ 
14035       argvec = make_tree_vec (nargs - ia);
14036       for (i = 0; ia < nargs; ++ia, ++i)
14037         TREE_VEC_ELT (argvec, i) = args[ia];
14038
14039       /* Copy the parameter into parmvec.  */
14040       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
14041       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
14042                                 /*call_args_p=*/true, /*subr=*/subr))
14043         return 1;
14044
14045       /* Advance to the end of the list of parameters.  */
14046       parms = TREE_CHAIN (parms);
14047     }
14048
14049   /* Fail if we've reached the end of the parm list, and more args
14050      are present, and the parm list isn't variadic.  */
14051   if (ia < nargs && parms == void_list_node)
14052     return 1;
14053   /* Fail if parms are left and they don't have default values.  */
14054   if (parms && parms != void_list_node
14055       && TREE_PURPOSE (parms) == NULL_TREE)
14056     return 1;
14057
14058   if (!subr)
14059     for (i = 0; i < ntparms; i++)
14060       if (!TREE_VEC_ELT (targs, i))
14061         {
14062           tree tparm;
14063
14064           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
14065             continue;
14066
14067           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
14068
14069           /* If this is an undeduced nontype parameter that depends on
14070              a type parameter, try another pass; its type may have been
14071              deduced from a later argument than the one from which
14072              this parameter can be deduced.  */
14073           if (TREE_CODE (tparm) == PARM_DECL
14074               && uses_template_parms (TREE_TYPE (tparm))
14075               && !saw_undeduced++)
14076             goto again;
14077
14078           /* Core issue #226 (C++0x) [temp.deduct]:
14079
14080                If a template argument has not been deduced, its
14081                default template argument, if any, is used. 
14082
14083              When we are in C++98 mode, TREE_PURPOSE will either
14084              be NULL_TREE or ERROR_MARK_NODE, so we do not need
14085              to explicitly check cxx_dialect here.  */
14086           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
14087             {
14088               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
14089               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
14090               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
14091               arg = convert_template_argument (parm, arg, targs, tf_none,
14092                                                i, NULL_TREE);
14093               if (arg == error_mark_node)
14094                 return 1;
14095               else
14096                 {
14097                   TREE_VEC_ELT (targs, i) = arg;
14098                   /* The position of the first default template argument,
14099                      is also the number of non-defaulted arguments in TARGS.
14100                      Record that.  */
14101                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
14102                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
14103                   continue;
14104                 }
14105             }
14106
14107           /* If the type parameter is a parameter pack, then it will
14108              be deduced to an empty parameter pack.  */
14109           if (template_parameter_pack_p (tparm))
14110             {
14111               tree arg;
14112
14113               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
14114                 {
14115                   arg = make_node (NONTYPE_ARGUMENT_PACK);
14116                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
14117                   TREE_CONSTANT (arg) = 1;
14118                 }
14119               else
14120                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
14121
14122               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
14123
14124               TREE_VEC_ELT (targs, i) = arg;
14125               continue;
14126             }
14127
14128           return 2;
14129         }
14130 #ifdef ENABLE_CHECKING
14131   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
14132     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
14133 #endif
14134
14135   return 0;
14136 }
14137
14138 /* Subroutine of type_unification_real.  Args are like the variables
14139    at the call site.  ARG is an overloaded function (or template-id);
14140    we try deducing template args from each of the overloads, and if
14141    only one succeeds, we go with that.  Modifies TARGS and returns
14142    true on success.  */
14143
14144 static bool
14145 resolve_overloaded_unification (tree tparms,
14146                                 tree targs,
14147                                 tree parm,
14148                                 tree arg,
14149                                 unification_kind_t strict,
14150                                 int sub_strict)
14151 {
14152   tree tempargs = copy_node (targs);
14153   int good = 0;
14154   tree goodfn = NULL_TREE;
14155   bool addr_p;
14156
14157   if (TREE_CODE (arg) == ADDR_EXPR)
14158     {
14159       arg = TREE_OPERAND (arg, 0);
14160       addr_p = true;
14161     }
14162   else
14163     addr_p = false;
14164
14165   if (TREE_CODE (arg) == COMPONENT_REF)
14166     /* Handle `&x' where `x' is some static or non-static member
14167        function name.  */
14168     arg = TREE_OPERAND (arg, 1);
14169
14170   if (TREE_CODE (arg) == OFFSET_REF)
14171     arg = TREE_OPERAND (arg, 1);
14172
14173   /* Strip baselink information.  */
14174   if (BASELINK_P (arg))
14175     arg = BASELINK_FUNCTIONS (arg);
14176
14177   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
14178     {
14179       /* If we got some explicit template args, we need to plug them into
14180          the affected templates before we try to unify, in case the
14181          explicit args will completely resolve the templates in question.  */
14182
14183       tree expl_subargs = TREE_OPERAND (arg, 1);
14184       arg = TREE_OPERAND (arg, 0);
14185
14186       for (; arg; arg = OVL_NEXT (arg))
14187         {
14188           tree fn = OVL_CURRENT (arg);
14189           tree subargs, elem;
14190
14191           if (TREE_CODE (fn) != TEMPLATE_DECL)
14192             continue;
14193
14194           ++processing_template_decl;
14195           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
14196                                   expl_subargs, /*check_ret=*/false);
14197           if (subargs)
14198             {
14199               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
14200               if (try_one_overload (tparms, targs, tempargs, parm,
14201                                     elem, strict, sub_strict, addr_p)
14202                   && (!goodfn || !decls_match (goodfn, elem)))
14203                 {
14204                   goodfn = elem;
14205                   ++good;
14206                 }
14207             }
14208           --processing_template_decl;
14209         }
14210     }
14211   else if (TREE_CODE (arg) != OVERLOAD
14212            && TREE_CODE (arg) != FUNCTION_DECL)
14213     /* If ARG is, for example, "(0, &f)" then its type will be unknown
14214        -- but the deduction does not succeed because the expression is
14215        not just the function on its own.  */
14216     return false;
14217   else
14218     for (; arg; arg = OVL_NEXT (arg))
14219       if (try_one_overload (tparms, targs, tempargs, parm,
14220                             TREE_TYPE (OVL_CURRENT (arg)),
14221                             strict, sub_strict, addr_p)
14222           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
14223         {
14224           goodfn = OVL_CURRENT (arg);
14225           ++good;
14226         }
14227
14228   /* [temp.deduct.type] A template-argument can be deduced from a pointer
14229      to function or pointer to member function argument if the set of
14230      overloaded functions does not contain function templates and at most
14231      one of a set of overloaded functions provides a unique match.
14232
14233      So if we found multiple possibilities, we return success but don't
14234      deduce anything.  */
14235
14236   if (good == 1)
14237     {
14238       int i = TREE_VEC_LENGTH (targs);
14239       for (; i--; )
14240         if (TREE_VEC_ELT (tempargs, i))
14241           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
14242     }
14243   if (good)
14244     return true;
14245
14246   return false;
14247 }
14248
14249 /* Core DR 115: In contexts where deduction is done and fails, or in
14250    contexts where deduction is not done, if a template argument list is
14251    specified and it, along with any default template arguments, identifies
14252    a single function template specialization, then the template-id is an
14253    lvalue for the function template specialization.  */
14254
14255 tree
14256 resolve_nondeduced_context (tree orig_expr)
14257 {
14258   tree expr, offset, baselink;
14259   bool addr;
14260
14261   if (!type_unknown_p (orig_expr))
14262     return orig_expr;
14263
14264   expr = orig_expr;
14265   addr = false;
14266   offset = NULL_TREE;
14267   baselink = NULL_TREE;
14268
14269   if (TREE_CODE (expr) == ADDR_EXPR)
14270     {
14271       expr = TREE_OPERAND (expr, 0);
14272       addr = true;
14273     }
14274   if (TREE_CODE (expr) == OFFSET_REF)
14275     {
14276       offset = expr;
14277       expr = TREE_OPERAND (expr, 1);
14278     }
14279   if (TREE_CODE (expr) == BASELINK)
14280     {
14281       baselink = expr;
14282       expr = BASELINK_FUNCTIONS (expr);
14283     }
14284
14285   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
14286     {
14287       int good = 0;
14288       tree goodfn = NULL_TREE;
14289
14290       /* If we got some explicit template args, we need to plug them into
14291          the affected templates before we try to unify, in case the
14292          explicit args will completely resolve the templates in question.  */
14293
14294       tree expl_subargs = TREE_OPERAND (expr, 1);
14295       tree arg = TREE_OPERAND (expr, 0);
14296       tree badfn = NULL_TREE;
14297       tree badargs = NULL_TREE;
14298
14299       for (; arg; arg = OVL_NEXT (arg))
14300         {
14301           tree fn = OVL_CURRENT (arg);
14302           tree subargs, elem;
14303
14304           if (TREE_CODE (fn) != TEMPLATE_DECL)
14305             continue;
14306
14307           ++processing_template_decl;
14308           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
14309                                   expl_subargs, /*check_ret=*/false);
14310           if (subargs && !any_dependent_template_arguments_p (subargs))
14311             {
14312               elem = instantiate_template (fn, subargs, tf_none);
14313               if (elem == error_mark_node)
14314                 {
14315                   badfn = fn;
14316                   badargs = subargs;
14317                 }
14318               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
14319                 {
14320                   goodfn = elem;
14321                   ++good;
14322                 }
14323             }
14324           --processing_template_decl;
14325         }
14326       if (good == 1)
14327         {
14328           expr = goodfn;
14329           if (baselink)
14330             expr = build_baselink (BASELINK_BINFO (baselink),
14331                                    BASELINK_ACCESS_BINFO (baselink),
14332                                    expr, BASELINK_OPTYPE (baselink));
14333           if (offset)
14334             expr = build2 (OFFSET_REF, TREE_TYPE (expr),
14335                            TREE_OPERAND (offset, 0), expr);
14336           if (addr)
14337             expr = build_address (expr);
14338           return expr;
14339         }
14340       else if (good == 0 && badargs)
14341         /* There were no good options and at least one bad one, so let the
14342            user know what the problem is.  */
14343         instantiate_template (badfn, badargs, tf_warning_or_error);
14344     }
14345   return orig_expr;
14346 }
14347
14348 /* Subroutine of resolve_overloaded_unification; does deduction for a single
14349    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
14350    different overloads deduce different arguments for a given parm.
14351    ADDR_P is true if the expression for which deduction is being
14352    performed was of the form "& fn" rather than simply "fn".
14353
14354    Returns 1 on success.  */
14355
14356 static int
14357 try_one_overload (tree tparms,
14358                   tree orig_targs,
14359                   tree targs,
14360                   tree parm,
14361                   tree arg,
14362                   unification_kind_t strict,
14363                   int sub_strict,
14364                   bool addr_p)
14365 {
14366   int nargs;
14367   tree tempargs;
14368   int i;
14369
14370   /* [temp.deduct.type] A template-argument can be deduced from a pointer
14371      to function or pointer to member function argument if the set of
14372      overloaded functions does not contain function templates and at most
14373      one of a set of overloaded functions provides a unique match.
14374
14375      So if this is a template, just return success.  */
14376
14377   if (uses_template_parms (arg))
14378     return 1;
14379
14380   if (TREE_CODE (arg) == METHOD_TYPE)
14381     arg = build_ptrmemfunc_type (build_pointer_type (arg));
14382   else if (addr_p)
14383     arg = build_pointer_type (arg);
14384
14385   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
14386
14387   /* We don't copy orig_targs for this because if we have already deduced
14388      some template args from previous args, unify would complain when we
14389      try to deduce a template parameter for the same argument, even though
14390      there isn't really a conflict.  */
14391   nargs = TREE_VEC_LENGTH (targs);
14392   tempargs = make_tree_vec (nargs);
14393
14394   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
14395     return 0;
14396
14397   /* First make sure we didn't deduce anything that conflicts with
14398      explicitly specified args.  */
14399   for (i = nargs; i--; )
14400     {
14401       tree elt = TREE_VEC_ELT (tempargs, i);
14402       tree oldelt = TREE_VEC_ELT (orig_targs, i);
14403
14404       if (!elt)
14405         /*NOP*/;
14406       else if (uses_template_parms (elt))
14407         /* Since we're unifying against ourselves, we will fill in
14408            template args used in the function parm list with our own
14409            template parms.  Discard them.  */
14410         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
14411       else if (oldelt && !template_args_equal (oldelt, elt))
14412         return 0;
14413     }
14414
14415   for (i = nargs; i--; )
14416     {
14417       tree elt = TREE_VEC_ELT (tempargs, i);
14418
14419       if (elt)
14420         TREE_VEC_ELT (targs, i) = elt;
14421     }
14422
14423   return 1;
14424 }
14425
14426 /* PARM is a template class (perhaps with unbound template
14427    parameters).  ARG is a fully instantiated type.  If ARG can be
14428    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
14429    TARGS are as for unify.  */
14430
14431 static tree
14432 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
14433 {
14434   tree copy_of_targs;
14435
14436   if (!CLASSTYPE_TEMPLATE_INFO (arg)
14437       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
14438           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
14439     return NULL_TREE;
14440
14441   /* We need to make a new template argument vector for the call to
14442      unify.  If we used TARGS, we'd clutter it up with the result of
14443      the attempted unification, even if this class didn't work out.
14444      We also don't want to commit ourselves to all the unifications
14445      we've already done, since unification is supposed to be done on
14446      an argument-by-argument basis.  In other words, consider the
14447      following pathological case:
14448
14449        template <int I, int J, int K>
14450        struct S {};
14451
14452        template <int I, int J>
14453        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
14454
14455        template <int I, int J, int K>
14456        void f(S<I, J, K>, S<I, I, I>);
14457
14458        void g() {
14459          S<0, 0, 0> s0;
14460          S<0, 1, 2> s2;
14461
14462          f(s0, s2);
14463        }
14464
14465      Now, by the time we consider the unification involving `s2', we
14466      already know that we must have `f<0, 0, 0>'.  But, even though
14467      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
14468      because there are two ways to unify base classes of S<0, 1, 2>
14469      with S<I, I, I>.  If we kept the already deduced knowledge, we
14470      would reject the possibility I=1.  */
14471   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
14472
14473   /* If unification failed, we're done.  */
14474   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
14475              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
14476     return NULL_TREE;
14477
14478   return arg;
14479 }
14480
14481 /* Given a template type PARM and a class type ARG, find the unique
14482    base type in ARG that is an instance of PARM.  We do not examine
14483    ARG itself; only its base-classes.  If there is not exactly one
14484    appropriate base class, return NULL_TREE.  PARM may be the type of
14485    a partial specialization, as well as a plain template type.  Used
14486    by unify.  */
14487
14488 static tree
14489 get_template_base (tree tparms, tree targs, tree parm, tree arg)
14490 {
14491   tree rval = NULL_TREE;
14492   tree binfo;
14493
14494   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
14495
14496   binfo = TYPE_BINFO (complete_type (arg));
14497   if (!binfo)
14498     /* The type could not be completed.  */
14499     return NULL_TREE;
14500
14501   /* Walk in inheritance graph order.  The search order is not
14502      important, and this avoids multiple walks of virtual bases.  */
14503   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
14504     {
14505       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
14506
14507       if (r)
14508         {
14509           /* If there is more than one satisfactory baseclass, then:
14510
14511                [temp.deduct.call]
14512
14513               If they yield more than one possible deduced A, the type
14514               deduction fails.
14515
14516              applies.  */
14517           if (rval && !same_type_p (r, rval))
14518             return NULL_TREE;
14519
14520           rval = r;
14521         }
14522     }
14523
14524   return rval;
14525 }
14526
14527 /* Returns the level of DECL, which declares a template parameter.  */
14528
14529 static int
14530 template_decl_level (tree decl)
14531 {
14532   switch (TREE_CODE (decl))
14533     {
14534     case TYPE_DECL:
14535     case TEMPLATE_DECL:
14536       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
14537
14538     case PARM_DECL:
14539       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
14540
14541     default:
14542       gcc_unreachable ();
14543     }
14544   return 0;
14545 }
14546
14547 /* Decide whether ARG can be unified with PARM, considering only the
14548    cv-qualifiers of each type, given STRICT as documented for unify.
14549    Returns nonzero iff the unification is OK on that basis.  */
14550
14551 static int
14552 check_cv_quals_for_unify (int strict, tree arg, tree parm)
14553 {
14554   int arg_quals = cp_type_quals (arg);
14555   int parm_quals = cp_type_quals (parm);
14556
14557   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14558       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14559     {
14560       /*  Although a CVR qualifier is ignored when being applied to a
14561           substituted template parameter ([8.3.2]/1 for example), that
14562           does not allow us to unify "const T" with "int&" because both
14563           types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
14564           It is ok when we're allowing additional CV qualifiers
14565           at the outer level [14.8.2.1]/3,1st bullet.  */
14566       if ((TREE_CODE (arg) == REFERENCE_TYPE
14567            || TREE_CODE (arg) == FUNCTION_TYPE
14568            || TREE_CODE (arg) == METHOD_TYPE)
14569           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
14570         return 0;
14571
14572       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
14573           && (parm_quals & TYPE_QUAL_RESTRICT))
14574         return 0;
14575     }
14576
14577   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14578       && (arg_quals & parm_quals) != parm_quals)
14579     return 0;
14580
14581   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
14582       && (parm_quals & arg_quals) != arg_quals)
14583     return 0;
14584
14585   return 1;
14586 }
14587
14588 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
14589 void 
14590 template_parm_level_and_index (tree parm, int* level, int* index)
14591 {
14592   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14593       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14594       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14595     {
14596       *index = TEMPLATE_TYPE_IDX (parm);
14597       *level = TEMPLATE_TYPE_LEVEL (parm);
14598     }
14599   else
14600     {
14601       *index = TEMPLATE_PARM_IDX (parm);
14602       *level = TEMPLATE_PARM_LEVEL (parm);
14603     }
14604 }
14605
14606 /* Unifies the remaining arguments in PACKED_ARGS with the pack
14607    expansion at the end of PACKED_PARMS. Returns 0 if the type
14608    deduction succeeds, 1 otherwise. STRICT is the same as in
14609    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
14610    call argument list. We'll need to adjust the arguments to make them
14611    types. SUBR tells us if this is from a recursive call to
14612    type_unification_real.  */
14613 int
14614 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
14615                       tree packed_args, int strict, bool call_args_p,
14616                       bool subr)
14617 {
14618   tree parm 
14619     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
14620   tree pattern = PACK_EXPANSION_PATTERN (parm);
14621   tree pack, packs = NULL_TREE;
14622   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
14623   int len = TREE_VEC_LENGTH (packed_args);
14624
14625   /* Determine the parameter packs we will be deducing from the
14626      pattern, and record their current deductions.  */
14627   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
14628        pack; pack = TREE_CHAIN (pack))
14629     {
14630       tree parm_pack = TREE_VALUE (pack);
14631       int idx, level;
14632
14633       /* Determine the index and level of this parameter pack.  */
14634       template_parm_level_and_index (parm_pack, &level, &idx);
14635
14636       /* Keep track of the parameter packs and their corresponding
14637          argument packs.  */
14638       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
14639       TREE_TYPE (packs) = make_tree_vec (len - start);
14640     }
14641   
14642   /* Loop through all of the arguments that have not yet been
14643      unified and unify each with the pattern.  */
14644   for (i = start; i < len; i++)
14645     {
14646       tree parm = pattern;
14647
14648       /* For each parameter pack, clear out the deduced value so that
14649          we can deduce it again.  */
14650       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14651         {
14652           int idx, level;
14653           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14654
14655           TMPL_ARG (targs, level, idx) = NULL_TREE;
14656         }
14657
14658       /* Unify the pattern with the current argument.  */
14659       {
14660         tree arg = TREE_VEC_ELT (packed_args, i);
14661         tree arg_expr = NULL_TREE;
14662         int arg_strict = strict;
14663         bool skip_arg_p = false;
14664
14665         if (call_args_p)
14666           {
14667             int sub_strict;
14668
14669             /* This mirrors what we do in type_unification_real.  */
14670             switch (strict)
14671               {
14672               case DEDUCE_CALL:
14673                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
14674                               | UNIFY_ALLOW_MORE_CV_QUAL
14675                               | UNIFY_ALLOW_DERIVED);
14676                 break;
14677                 
14678               case DEDUCE_CONV:
14679                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14680                 break;
14681                 
14682               case DEDUCE_EXACT:
14683                 sub_strict = UNIFY_ALLOW_NONE;
14684                 break;
14685                 
14686               default:
14687                 gcc_unreachable ();
14688               }
14689
14690             if (!TYPE_P (arg))
14691               {
14692                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14693                 if (type_unknown_p (arg))
14694                   {
14695                     /* [temp.deduct.type] A template-argument can be
14696                        deduced from a pointer to function or pointer
14697                        to member function argument if the set of
14698                        overloaded functions does not contain function
14699                        templates and at most one of a set of
14700                        overloaded functions provides a unique
14701                        match.  */
14702
14703                     if (resolve_overloaded_unification
14704                         (tparms, targs, parm, arg,
14705                          (unification_kind_t) strict,
14706                          sub_strict)
14707                         != 0)
14708                       return 1;
14709                     skip_arg_p = true;
14710                   }
14711
14712                 if (!skip_arg_p)
14713                   {
14714                     arg_expr = arg;
14715                     arg = unlowered_expr_type (arg);
14716                     if (arg == error_mark_node)
14717                       return 1;
14718                   }
14719               }
14720       
14721             arg_strict = sub_strict;
14722
14723             if (!subr)
14724               arg_strict |= 
14725                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
14726                                                   &parm, &arg, arg_expr);
14727           }
14728
14729         if (!skip_arg_p)
14730           {
14731             /* For deduction from an init-list we need the actual list.  */
14732             if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
14733               arg = arg_expr;
14734             if (unify (tparms, targs, parm, arg, arg_strict))
14735               return 1;
14736           }
14737       }
14738
14739       /* For each parameter pack, collect the deduced value.  */
14740       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14741         {
14742           int idx, level;
14743           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14744
14745           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
14746             TMPL_ARG (targs, level, idx);
14747         }
14748     }
14749
14750   /* Verify that the results of unification with the parameter packs
14751      produce results consistent with what we've seen before, and make
14752      the deduced argument packs available.  */
14753   for (pack = packs; pack; pack = TREE_CHAIN (pack))
14754     {
14755       tree old_pack = TREE_VALUE (pack);
14756       tree new_args = TREE_TYPE (pack);
14757       int i, len = TREE_VEC_LENGTH (new_args);
14758       int idx, level;
14759       bool nondeduced_p = false;
14760
14761       /* By default keep the original deduced argument pack.
14762          If necessary, more specific code is going to update the
14763          resulting deduced argument later down in this function.  */
14764       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14765       TMPL_ARG (targs, level, idx) = old_pack;
14766
14767       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
14768          actually deduce anything.  */
14769       for (i = 0; i < len && !nondeduced_p; ++i)
14770         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
14771           nondeduced_p = true;
14772       if (nondeduced_p)
14773         continue;
14774
14775       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
14776         {
14777           /* Prepend the explicit arguments onto NEW_ARGS.  */
14778           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14779           tree old_args = new_args;
14780           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
14781           int len = explicit_len + TREE_VEC_LENGTH (old_args);
14782
14783           /* Copy the explicit arguments.  */
14784           new_args = make_tree_vec (len);
14785           for (i = 0; i < explicit_len; i++)
14786             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
14787
14788           /* Copy the deduced arguments.  */
14789           for (; i < len; i++)
14790             TREE_VEC_ELT (new_args, i) =
14791               TREE_VEC_ELT (old_args, i - explicit_len);
14792         }
14793
14794       if (!old_pack)
14795         {
14796           tree result;
14797           /* Build the deduced *_ARGUMENT_PACK.  */
14798           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
14799             {
14800               result = make_node (NONTYPE_ARGUMENT_PACK);
14801               TREE_TYPE (result) = 
14802                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
14803               TREE_CONSTANT (result) = 1;
14804             }
14805           else
14806             result = cxx_make_type (TYPE_ARGUMENT_PACK);
14807
14808           SET_ARGUMENT_PACK_ARGS (result, new_args);
14809
14810           /* Note the deduced argument packs for this parameter
14811              pack.  */
14812           TMPL_ARG (targs, level, idx) = result;
14813         }
14814       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
14815                && (ARGUMENT_PACK_ARGS (old_pack) 
14816                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
14817         {
14818           /* We only had the explicitly-provided arguments before, but
14819              now we have a complete set of arguments.  */
14820           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14821
14822           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
14823           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
14824           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
14825         }
14826       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
14827                                     new_args))
14828         /* Inconsistent unification of this parameter pack.  */
14829         return 1;
14830     }
14831
14832   return 0;
14833 }
14834
14835 /* Deduce the value of template parameters.  TPARMS is the (innermost)
14836    set of template parameters to a template.  TARGS is the bindings
14837    for those template parameters, as determined thus far; TARGS may
14838    include template arguments for outer levels of template parameters
14839    as well.  PARM is a parameter to a template function, or a
14840    subcomponent of that parameter; ARG is the corresponding argument.
14841    This function attempts to match PARM with ARG in a manner
14842    consistent with the existing assignments in TARGS.  If more values
14843    are deduced, then TARGS is updated.
14844
14845    Returns 0 if the type deduction succeeds, 1 otherwise.  The
14846    parameter STRICT is a bitwise or of the following flags:
14847
14848      UNIFY_ALLOW_NONE:
14849        Require an exact match between PARM and ARG.
14850      UNIFY_ALLOW_MORE_CV_QUAL:
14851        Allow the deduced ARG to be more cv-qualified (by qualification
14852        conversion) than ARG.
14853      UNIFY_ALLOW_LESS_CV_QUAL:
14854        Allow the deduced ARG to be less cv-qualified than ARG.
14855      UNIFY_ALLOW_DERIVED:
14856        Allow the deduced ARG to be a template base class of ARG,
14857        or a pointer to a template base class of the type pointed to by
14858        ARG.
14859      UNIFY_ALLOW_INTEGER:
14860        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
14861        case for more information.
14862      UNIFY_ALLOW_OUTER_LEVEL:
14863        This is the outermost level of a deduction. Used to determine validity
14864        of qualification conversions. A valid qualification conversion must
14865        have const qualified pointers leading up to the inner type which
14866        requires additional CV quals, except at the outer level, where const
14867        is not required [conv.qual]. It would be normal to set this flag in
14868        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
14869      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
14870        This is the outermost level of a deduction, and PARM can be more CV
14871        qualified at this point.
14872      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
14873        This is the outermost level of a deduction, and PARM can be less CV
14874        qualified at this point.  */
14875
14876 static int
14877 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
14878 {
14879   int idx;
14880   tree targ;
14881   tree tparm;
14882   int strict_in = strict;
14883
14884   /* I don't think this will do the right thing with respect to types.
14885      But the only case I've seen it in so far has been array bounds, where
14886      signedness is the only information lost, and I think that will be
14887      okay.  */
14888   while (TREE_CODE (parm) == NOP_EXPR)
14889     parm = TREE_OPERAND (parm, 0);
14890
14891   if (arg == error_mark_node)
14892     return 1;
14893   if (arg == unknown_type_node
14894       || arg == init_list_type_node)
14895     /* We can't deduce anything from this, but we might get all the
14896        template args from other function args.  */
14897     return 0;
14898
14899   /* If PARM uses template parameters, then we can't bail out here,
14900      even if ARG == PARM, since we won't record unifications for the
14901      template parameters.  We might need them if we're trying to
14902      figure out which of two things is more specialized.  */
14903   if (arg == parm && !uses_template_parms (parm))
14904     return 0;
14905
14906   /* Handle init lists early, so the rest of the function can assume
14907      we're dealing with a type. */
14908   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
14909     {
14910       tree elt, elttype;
14911       unsigned i;
14912       tree orig_parm = parm;
14913
14914       /* Replace T with std::initializer_list<T> for deduction.  */
14915       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14916           && flag_deduce_init_list)
14917         parm = listify (parm);
14918
14919       if (!is_std_init_list (parm))
14920         /* We can only deduce from an initializer list argument if the
14921            parameter is std::initializer_list; otherwise this is a
14922            non-deduced context. */
14923         return 0;
14924
14925       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
14926
14927       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
14928         {
14929           int elt_strict = strict;
14930
14931           if (elt == error_mark_node)
14932             return 1;
14933
14934           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
14935             {
14936               tree type = TREE_TYPE (elt);
14937               /* It should only be possible to get here for a call.  */
14938               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
14939               elt_strict |= maybe_adjust_types_for_deduction
14940                 (DEDUCE_CALL, &elttype, &type, elt);
14941               elt = type;
14942             }
14943
14944           if (unify (tparms, targs, elttype, elt, elt_strict))
14945             return 1;
14946         }
14947
14948       /* If the std::initializer_list<T> deduction worked, replace the
14949          deduced A with std::initializer_list<A>.  */
14950       if (orig_parm != parm)
14951         {
14952           idx = TEMPLATE_TYPE_IDX (orig_parm);
14953           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14954           targ = listify (targ);
14955           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
14956         }
14957       return 0;
14958     }
14959
14960   /* Immediately reject some pairs that won't unify because of
14961      cv-qualification mismatches.  */
14962   if (TREE_CODE (arg) == TREE_CODE (parm)
14963       && TYPE_P (arg)
14964       /* It is the elements of the array which hold the cv quals of an array
14965          type, and the elements might be template type parms. We'll check
14966          when we recurse.  */
14967       && TREE_CODE (arg) != ARRAY_TYPE
14968       /* We check the cv-qualifiers when unifying with template type
14969          parameters below.  We want to allow ARG `const T' to unify with
14970          PARM `T' for example, when computing which of two templates
14971          is more specialized, for example.  */
14972       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
14973       && !check_cv_quals_for_unify (strict_in, arg, parm))
14974     return 1;
14975
14976   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
14977       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
14978     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
14979   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
14980   strict &= ~UNIFY_ALLOW_DERIVED;
14981   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14982   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
14983
14984   switch (TREE_CODE (parm))
14985     {
14986     case TYPENAME_TYPE:
14987     case SCOPE_REF:
14988     case UNBOUND_CLASS_TEMPLATE:
14989       /* In a type which contains a nested-name-specifier, template
14990          argument values cannot be deduced for template parameters used
14991          within the nested-name-specifier.  */
14992       return 0;
14993
14994     case TEMPLATE_TYPE_PARM:
14995     case TEMPLATE_TEMPLATE_PARM:
14996     case BOUND_TEMPLATE_TEMPLATE_PARM:
14997       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14998       if (tparm == error_mark_node)
14999         return 1;
15000
15001       if (TEMPLATE_TYPE_LEVEL (parm)
15002           != template_decl_level (tparm))
15003         /* The PARM is not one we're trying to unify.  Just check
15004            to see if it matches ARG.  */
15005         return (TREE_CODE (arg) == TREE_CODE (parm)
15006                 && same_type_p (parm, arg)) ? 0 : 1;
15007       idx = TEMPLATE_TYPE_IDX (parm);
15008       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15009       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
15010
15011       /* Check for mixed types and values.  */
15012       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15013            && TREE_CODE (tparm) != TYPE_DECL)
15014           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15015               && TREE_CODE (tparm) != TEMPLATE_DECL))
15016         return 1;
15017
15018       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15019         {
15020           /* ARG must be constructed from a template class or a template
15021              template parameter.  */
15022           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
15023               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
15024             return 1;
15025
15026           {
15027             tree parmvec = TYPE_TI_ARGS (parm);
15028             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
15029             tree full_argvec = add_to_template_args (targs, argvec);
15030             tree parm_parms 
15031               = DECL_INNERMOST_TEMPLATE_PARMS
15032                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
15033             int i, len;
15034             int parm_variadic_p = 0;
15035
15036             /* The resolution to DR150 makes clear that default
15037                arguments for an N-argument may not be used to bind T
15038                to a template template parameter with fewer than N
15039                parameters.  It is not safe to permit the binding of
15040                default arguments as an extension, as that may change
15041                the meaning of a conforming program.  Consider:
15042
15043                   struct Dense { static const unsigned int dim = 1; };
15044
15045                   template <template <typename> class View,
15046                             typename Block>
15047                   void operator+(float, View<Block> const&);
15048
15049                   template <typename Block,
15050                             unsigned int Dim = Block::dim>
15051                   struct Lvalue_proxy { operator float() const; };
15052
15053                   void
15054                   test_1d (void) {
15055                     Lvalue_proxy<Dense> p;
15056                     float b;
15057                     b + p;
15058                   }
15059
15060               Here, if Lvalue_proxy is permitted to bind to View, then
15061               the global operator+ will be used; if they are not, the
15062               Lvalue_proxy will be converted to float.  */
15063             if (coerce_template_parms (parm_parms,
15064                                        full_argvec,
15065                                        TYPE_TI_TEMPLATE (parm),
15066                                        tf_none,
15067                                        /*require_all_args=*/true,
15068                                        /*use_default_args=*/false)
15069                 == error_mark_node)
15070               return 1;
15071
15072             /* Deduce arguments T, i from TT<T> or TT<i>.
15073                We check each element of PARMVEC and ARGVEC individually
15074                rather than the whole TREE_VEC since they can have
15075                different number of elements.  */
15076
15077             parmvec = expand_template_argument_pack (parmvec);
15078             argvec = expand_template_argument_pack (argvec);
15079
15080             len = TREE_VEC_LENGTH (parmvec);
15081
15082             /* Check if the parameters end in a pack, making them
15083                variadic.  */
15084             if (len > 0
15085                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
15086               parm_variadic_p = 1;
15087             
15088             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
15089               return 1;
15090
15091              for (i = 0; i < len - parm_variadic_p; ++i)
15092               {
15093                 if (unify (tparms, targs,
15094                            TREE_VEC_ELT (parmvec, i),
15095                            TREE_VEC_ELT (argvec, i),
15096                            UNIFY_ALLOW_NONE))
15097                   return 1;
15098               }
15099
15100             if (parm_variadic_p
15101                 && unify_pack_expansion (tparms, targs,
15102                                          parmvec, argvec,
15103                                          UNIFY_ALLOW_NONE,
15104                                          /*call_args_p=*/false,
15105                                          /*subr=*/false))
15106               return 1;
15107           }
15108           arg = TYPE_TI_TEMPLATE (arg);
15109
15110           /* Fall through to deduce template name.  */
15111         }
15112
15113       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15114           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15115         {
15116           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
15117
15118           /* Simple cases: Value already set, does match or doesn't.  */
15119           if (targ != NULL_TREE && template_args_equal (targ, arg))
15120             return 0;
15121           else if (targ)
15122             return 1;
15123         }
15124       else
15125         {
15126           /* If PARM is `const T' and ARG is only `int', we don't have
15127              a match unless we are allowing additional qualification.
15128              If ARG is `const int' and PARM is just `T' that's OK;
15129              that binds `const int' to `T'.  */
15130           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
15131                                          arg, parm))
15132             return 1;
15133
15134           /* Consider the case where ARG is `const volatile int' and
15135              PARM is `const T'.  Then, T should be `volatile int'.  */
15136           arg = cp_build_qualified_type_real
15137             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
15138           if (arg == error_mark_node)
15139             return 1;
15140
15141           /* Simple cases: Value already set, does match or doesn't.  */
15142           if (targ != NULL_TREE && same_type_p (targ, arg))
15143             return 0;
15144           else if (targ)
15145             return 1;
15146
15147           /* Make sure that ARG is not a variable-sized array.  (Note
15148              that were talking about variable-sized arrays (like
15149              `int[n]'), rather than arrays of unknown size (like
15150              `int[]').)  We'll get very confused by such a type since
15151              the bound of the array will not be computable in an
15152              instantiation.  Besides, such types are not allowed in
15153              ISO C++, so we can do as we please here.  */
15154           if (variably_modified_type_p (arg, NULL_TREE))
15155             return 1;
15156
15157           /* Strip typedefs as in convert_template_argument.  */
15158           arg = strip_typedefs (arg);
15159         }
15160
15161       /* If ARG is a parameter pack or an expansion, we cannot unify
15162          against it unless PARM is also a parameter pack.  */
15163       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
15164           && !template_parameter_pack_p (parm))
15165         return 1;
15166
15167       /* If the argument deduction results is a METHOD_TYPE,
15168          then there is a problem.
15169          METHOD_TYPE doesn't map to any real C++ type the result of
15170          the deduction can not be of that type.  */
15171       if (TREE_CODE (arg) == METHOD_TYPE)
15172         return 1;
15173
15174       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
15175       return 0;
15176
15177     case TEMPLATE_PARM_INDEX:
15178       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
15179       if (tparm == error_mark_node)
15180         return 1;
15181
15182       if (TEMPLATE_PARM_LEVEL (parm)
15183           != template_decl_level (tparm))
15184         /* The PARM is not one we're trying to unify.  Just check
15185            to see if it matches ARG.  */
15186         return !(TREE_CODE (arg) == TREE_CODE (parm)
15187                  && cp_tree_equal (parm, arg));
15188
15189       idx = TEMPLATE_PARM_IDX (parm);
15190       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15191
15192       if (targ)
15193         return !cp_tree_equal (targ, arg);
15194
15195       /* [temp.deduct.type] If, in the declaration of a function template
15196          with a non-type template-parameter, the non-type
15197          template-parameter is used in an expression in the function
15198          parameter-list and, if the corresponding template-argument is
15199          deduced, the template-argument type shall match the type of the
15200          template-parameter exactly, except that a template-argument
15201          deduced from an array bound may be of any integral type.
15202          The non-type parameter might use already deduced type parameters.  */
15203       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
15204       if (!TREE_TYPE (arg))
15205         /* Template-parameter dependent expression.  Just accept it for now.
15206            It will later be processed in convert_template_argument.  */
15207         ;
15208       else if (same_type_p (TREE_TYPE (arg), tparm))
15209         /* OK */;
15210       else if ((strict & UNIFY_ALLOW_INTEGER)
15211                && (TREE_CODE (tparm) == INTEGER_TYPE
15212                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
15213         /* Convert the ARG to the type of PARM; the deduced non-type
15214            template argument must exactly match the types of the
15215            corresponding parameter.  */
15216         arg = fold (build_nop (tparm, arg));
15217       else if (uses_template_parms (tparm))
15218         /* We haven't deduced the type of this parameter yet.  Try again
15219            later.  */
15220         return 0;
15221       else
15222         return 1;
15223
15224       /* If ARG is a parameter pack or an expansion, we cannot unify
15225          against it unless PARM is also a parameter pack.  */
15226       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
15227           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
15228         return 1;
15229
15230       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
15231       return 0;
15232
15233     case PTRMEM_CST:
15234      {
15235         /* A pointer-to-member constant can be unified only with
15236          another constant.  */
15237       if (TREE_CODE (arg) != PTRMEM_CST)
15238         return 1;
15239
15240       /* Just unify the class member. It would be useless (and possibly
15241          wrong, depending on the strict flags) to unify also
15242          PTRMEM_CST_CLASS, because we want to be sure that both parm and
15243          arg refer to the same variable, even if through different
15244          classes. For instance:
15245
15246          struct A { int x; };
15247          struct B : A { };
15248
15249          Unification of &A::x and &B::x must succeed.  */
15250       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
15251                     PTRMEM_CST_MEMBER (arg), strict);
15252      }
15253
15254     case POINTER_TYPE:
15255       {
15256         if (TREE_CODE (arg) != POINTER_TYPE)
15257           return 1;
15258
15259         /* [temp.deduct.call]
15260
15261            A can be another pointer or pointer to member type that can
15262            be converted to the deduced A via a qualification
15263            conversion (_conv.qual_).
15264
15265            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
15266            This will allow for additional cv-qualification of the
15267            pointed-to types if appropriate.  */
15268
15269         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
15270           /* The derived-to-base conversion only persists through one
15271              level of pointers.  */
15272           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
15273
15274         return unify (tparms, targs, TREE_TYPE (parm),
15275                       TREE_TYPE (arg), strict);
15276       }
15277
15278     case REFERENCE_TYPE:
15279       if (TREE_CODE (arg) != REFERENCE_TYPE)
15280         return 1;
15281       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15282                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
15283
15284     case ARRAY_TYPE:
15285       if (TREE_CODE (arg) != ARRAY_TYPE)
15286         return 1;
15287       if ((TYPE_DOMAIN (parm) == NULL_TREE)
15288           != (TYPE_DOMAIN (arg) == NULL_TREE))
15289         return 1;
15290       if (TYPE_DOMAIN (parm) != NULL_TREE)
15291         {
15292           tree parm_max;
15293           tree arg_max;
15294           bool parm_cst;
15295           bool arg_cst;
15296
15297           /* Our representation of array types uses "N - 1" as the
15298              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
15299              not an integer constant.  We cannot unify arbitrarily
15300              complex expressions, so we eliminate the MINUS_EXPRs
15301              here.  */
15302           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
15303           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
15304           if (!parm_cst)
15305             {
15306               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
15307               parm_max = TREE_OPERAND (parm_max, 0);
15308             }
15309           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
15310           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
15311           if (!arg_cst)
15312             {
15313               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
15314                  trying to unify the type of a variable with the type
15315                  of a template parameter.  For example:
15316
15317                    template <unsigned int N>
15318                    void f (char (&) [N]);
15319                    int g(); 
15320                    void h(int i) {
15321                      char a[g(i)];
15322                      f(a); 
15323                    }
15324
15325                 Here, the type of the ARG will be "int [g(i)]", and
15326                 may be a SAVE_EXPR, etc.  */
15327               if (TREE_CODE (arg_max) != MINUS_EXPR)
15328                 return 1;
15329               arg_max = TREE_OPERAND (arg_max, 0);
15330             }
15331
15332           /* If only one of the bounds used a MINUS_EXPR, compensate
15333              by adding one to the other bound.  */
15334           if (parm_cst && !arg_cst)
15335             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
15336                                     integer_type_node,
15337                                     parm_max,
15338                                     integer_one_node);
15339           else if (arg_cst && !parm_cst)
15340             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
15341                                    integer_type_node,
15342                                    arg_max,
15343                                    integer_one_node);
15344
15345           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
15346             return 1;
15347         }
15348       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15349                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
15350
15351     case REAL_TYPE:
15352     case COMPLEX_TYPE:
15353     case VECTOR_TYPE:
15354     case INTEGER_TYPE:
15355     case BOOLEAN_TYPE:
15356     case ENUMERAL_TYPE:
15357     case VOID_TYPE:
15358       if (TREE_CODE (arg) != TREE_CODE (parm))
15359         return 1;
15360
15361       /* We have already checked cv-qualification at the top of the
15362          function.  */
15363       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
15364         return 1;
15365
15366       /* As far as unification is concerned, this wins.  Later checks
15367          will invalidate it if necessary.  */
15368       return 0;
15369
15370       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
15371       /* Type INTEGER_CST can come from ordinary constant template args.  */
15372     case INTEGER_CST:
15373       while (TREE_CODE (arg) == NOP_EXPR)
15374         arg = TREE_OPERAND (arg, 0);
15375
15376       if (TREE_CODE (arg) != INTEGER_CST)
15377         return 1;
15378       return !tree_int_cst_equal (parm, arg);
15379
15380     case TREE_VEC:
15381       {
15382         int i;
15383         if (TREE_CODE (arg) != TREE_VEC)
15384           return 1;
15385         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
15386           return 1;
15387         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
15388           if (unify (tparms, targs,
15389                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
15390                      UNIFY_ALLOW_NONE))
15391             return 1;
15392         return 0;
15393       }
15394
15395     case RECORD_TYPE:
15396     case UNION_TYPE:
15397       if (TREE_CODE (arg) != TREE_CODE (parm))
15398         return 1;
15399
15400       if (TYPE_PTRMEMFUNC_P (parm))
15401         {
15402           if (!TYPE_PTRMEMFUNC_P (arg))
15403             return 1;
15404
15405           return unify (tparms, targs,
15406                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
15407                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
15408                         strict);
15409         }
15410
15411       if (CLASSTYPE_TEMPLATE_INFO (parm))
15412         {
15413           tree t = NULL_TREE;
15414
15415           if (strict_in & UNIFY_ALLOW_DERIVED)
15416             {
15417               /* First, we try to unify the PARM and ARG directly.  */
15418               t = try_class_unification (tparms, targs,
15419                                          parm, arg);
15420
15421               if (!t)
15422                 {
15423                   /* Fallback to the special case allowed in
15424                      [temp.deduct.call]:
15425
15426                        If P is a class, and P has the form
15427                        template-id, then A can be a derived class of
15428                        the deduced A.  Likewise, if P is a pointer to
15429                        a class of the form template-id, A can be a
15430                        pointer to a derived class pointed to by the
15431                        deduced A.  */
15432                   t = get_template_base (tparms, targs, parm, arg);
15433
15434                   if (!t)
15435                     return 1;
15436                 }
15437             }
15438           else if (CLASSTYPE_TEMPLATE_INFO (arg)
15439                    && (CLASSTYPE_TI_TEMPLATE (parm)
15440                        == CLASSTYPE_TI_TEMPLATE (arg)))
15441             /* Perhaps PARM is something like S<U> and ARG is S<int>.
15442                Then, we should unify `int' and `U'.  */
15443             t = arg;
15444           else
15445             /* There's no chance of unification succeeding.  */
15446             return 1;
15447
15448           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
15449                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
15450         }
15451       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
15452         return 1;
15453       return 0;
15454
15455     case METHOD_TYPE:
15456     case FUNCTION_TYPE:
15457       {
15458         unsigned int nargs;
15459         tree *args;
15460         tree a;
15461         unsigned int i;
15462
15463         if (TREE_CODE (arg) != TREE_CODE (parm))
15464           return 1;
15465
15466         /* CV qualifications for methods can never be deduced, they must
15467            match exactly.  We need to check them explicitly here,
15468            because type_unification_real treats them as any other
15469            cv-qualified parameter.  */
15470         if (TREE_CODE (parm) == METHOD_TYPE
15471             && (!check_cv_quals_for_unify
15472                 (UNIFY_ALLOW_NONE,
15473                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
15474                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
15475           return 1;
15476
15477         if (unify (tparms, targs, TREE_TYPE (parm),
15478                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
15479           return 1;
15480
15481         nargs = list_length (TYPE_ARG_TYPES (arg));
15482         args = XALLOCAVEC (tree, nargs);
15483         for (a = TYPE_ARG_TYPES (arg), i = 0;
15484              a != NULL_TREE && a != void_list_node;
15485              a = TREE_CHAIN (a), ++i)
15486           args[i] = TREE_VALUE (a);
15487         nargs = i;
15488
15489         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
15490                                       args, nargs, 1, DEDUCE_EXACT,
15491                                       LOOKUP_NORMAL);
15492       }
15493
15494     case OFFSET_TYPE:
15495       /* Unify a pointer to member with a pointer to member function, which
15496          deduces the type of the member as a function type. */
15497       if (TYPE_PTRMEMFUNC_P (arg))
15498         {
15499           tree method_type;
15500           tree fntype;
15501
15502           /* Check top-level cv qualifiers */
15503           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
15504             return 1;
15505
15506           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15507                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
15508             return 1;
15509
15510           /* Determine the type of the function we are unifying against. */
15511           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
15512           fntype =
15513             build_function_type (TREE_TYPE (method_type),
15514                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
15515
15516           /* Extract the cv-qualifiers of the member function from the
15517              implicit object parameter and place them on the function
15518              type to be restored later. */
15519           fntype = apply_memfn_quals (fntype, type_memfn_quals (method_type));
15520           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
15521         }
15522
15523       if (TREE_CODE (arg) != OFFSET_TYPE)
15524         return 1;
15525       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15526                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
15527         return 1;
15528       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15529                     strict);
15530
15531     case CONST_DECL:
15532       if (DECL_TEMPLATE_PARM_P (parm))
15533         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
15534       if (arg != integral_constant_value (parm))
15535         return 1;
15536       return 0;
15537
15538     case FIELD_DECL:
15539     case TEMPLATE_DECL:
15540       /* Matched cases are handled by the ARG == PARM test above.  */
15541       return 1;
15542
15543     case VAR_DECL:
15544       /* A non-type template parameter that is a variable should be a
15545          an integral constant, in which case, it whould have been
15546          folded into its (constant) value. So we should not be getting
15547          a variable here.  */
15548       gcc_unreachable ();
15549
15550     case TYPE_ARGUMENT_PACK:
15551     case NONTYPE_ARGUMENT_PACK:
15552       {
15553         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
15554         tree packed_args = ARGUMENT_PACK_ARGS (arg);
15555         int i, len = TREE_VEC_LENGTH (packed_parms);
15556         int argslen = TREE_VEC_LENGTH (packed_args);
15557         int parm_variadic_p = 0;
15558
15559         for (i = 0; i < len; ++i)
15560           {
15561             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
15562               {
15563                 if (i == len - 1)
15564                   /* We can unify against something with a trailing
15565                      parameter pack.  */
15566                   parm_variadic_p = 1;
15567                 else
15568                   /* Since there is something following the pack
15569                      expansion, we cannot unify this template argument
15570                      list.  */
15571                   return 0;
15572               }
15573           }
15574           
15575
15576         /* If we don't have enough arguments to satisfy the parameters
15577            (not counting the pack expression at the end), or we have
15578            too many arguments for a parameter list that doesn't end in
15579            a pack expression, we can't unify.  */
15580         if (argslen < (len - parm_variadic_p)
15581             || (argslen > len && !parm_variadic_p))
15582           return 1;
15583
15584         /* Unify all of the parameters that precede the (optional)
15585            pack expression.  */
15586         for (i = 0; i < len - parm_variadic_p; ++i)
15587           {
15588             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
15589                        TREE_VEC_ELT (packed_args, i), strict))
15590               return 1;
15591           }
15592
15593         if (parm_variadic_p)
15594           return unify_pack_expansion (tparms, targs, 
15595                                        packed_parms, packed_args,
15596                                        strict, /*call_args_p=*/false,
15597                                        /*subr=*/false);
15598         return 0;
15599       }
15600
15601       break;
15602
15603     case TYPEOF_TYPE:
15604     case DECLTYPE_TYPE:
15605       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
15606          nodes.  */
15607       return 0;
15608
15609     case ERROR_MARK:
15610       /* Unification fails if we hit an error node.  */
15611       return 1;
15612
15613     default:
15614       gcc_assert (EXPR_P (parm));
15615
15616       /* We must be looking at an expression.  This can happen with
15617          something like:
15618
15619            template <int I>
15620            void foo(S<I>, S<I + 2>);
15621
15622          This is a "nondeduced context":
15623
15624            [deduct.type]
15625
15626            The nondeduced contexts are:
15627
15628            --A type that is a template-id in which one or more of
15629              the template-arguments is an expression that references
15630              a template-parameter.
15631
15632          In these cases, we assume deduction succeeded, but don't
15633          actually infer any unifications.  */
15634
15635       if (!uses_template_parms (parm)
15636           && !template_args_equal (parm, arg))
15637         return 1;
15638       else
15639         return 0;
15640     }
15641 }
15642 \f
15643 /* Note that DECL can be defined in this translation unit, if
15644    required.  */
15645
15646 static void
15647 mark_definable (tree decl)
15648 {
15649   tree clone;
15650   DECL_NOT_REALLY_EXTERN (decl) = 1;
15651   FOR_EACH_CLONE (clone, decl)
15652     DECL_NOT_REALLY_EXTERN (clone) = 1;
15653 }
15654
15655 /* Called if RESULT is explicitly instantiated, or is a member of an
15656    explicitly instantiated class.  */
15657
15658 void
15659 mark_decl_instantiated (tree result, int extern_p)
15660 {
15661   SET_DECL_EXPLICIT_INSTANTIATION (result);
15662
15663   /* If this entity has already been written out, it's too late to
15664      make any modifications.  */
15665   if (TREE_ASM_WRITTEN (result))
15666     return;
15667
15668   if (TREE_CODE (result) != FUNCTION_DECL)
15669     /* The TREE_PUBLIC flag for function declarations will have been
15670        set correctly by tsubst.  */
15671     TREE_PUBLIC (result) = 1;
15672
15673   /* This might have been set by an earlier implicit instantiation.  */
15674   DECL_COMDAT (result) = 0;
15675
15676   if (extern_p)
15677     DECL_NOT_REALLY_EXTERN (result) = 0;
15678   else
15679     {
15680       mark_definable (result);
15681       /* Always make artificials weak.  */
15682       if (DECL_ARTIFICIAL (result) && flag_weak)
15683         comdat_linkage (result);
15684       /* For WIN32 we also want to put explicit instantiations in
15685          linkonce sections.  */
15686       else if (TREE_PUBLIC (result))
15687         maybe_make_one_only (result);
15688     }
15689
15690   /* If EXTERN_P, then this function will not be emitted -- unless
15691      followed by an explicit instantiation, at which point its linkage
15692      will be adjusted.  If !EXTERN_P, then this function will be
15693      emitted here.  In neither circumstance do we want
15694      import_export_decl to adjust the linkage.  */
15695   DECL_INTERFACE_KNOWN (result) = 1;
15696 }
15697
15698 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
15699    important template arguments.  If any are missing, we check whether
15700    they're important by using error_mark_node for substituting into any
15701    args that were used for partial ordering (the ones between ARGS and END)
15702    and seeing if it bubbles up.  */
15703
15704 static bool
15705 check_undeduced_parms (tree targs, tree args, tree end)
15706 {
15707   bool found = false;
15708   int i;
15709   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
15710     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
15711       {
15712         found = true;
15713         TREE_VEC_ELT (targs, i) = error_mark_node;
15714       }
15715   if (found)
15716     {
15717       for (; args != end; args = TREE_CHAIN (args))
15718         {
15719           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
15720           if (substed == error_mark_node)
15721             return true;
15722         }
15723     }
15724   return false;
15725 }
15726
15727 /* Given two function templates PAT1 and PAT2, return:
15728
15729    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
15730    -1 if PAT2 is more specialized than PAT1.
15731    0 if neither is more specialized.
15732
15733    LEN indicates the number of parameters we should consider
15734    (defaulted parameters should not be considered).
15735
15736    The 1998 std underspecified function template partial ordering, and
15737    DR214 addresses the issue.  We take pairs of arguments, one from
15738    each of the templates, and deduce them against each other.  One of
15739    the templates will be more specialized if all the *other*
15740    template's arguments deduce against its arguments and at least one
15741    of its arguments *does* *not* deduce against the other template's
15742    corresponding argument.  Deduction is done as for class templates.
15743    The arguments used in deduction have reference and top level cv
15744    qualifiers removed.  Iff both arguments were originally reference
15745    types *and* deduction succeeds in both directions, the template
15746    with the more cv-qualified argument wins for that pairing (if
15747    neither is more cv-qualified, they both are equal).  Unlike regular
15748    deduction, after all the arguments have been deduced in this way,
15749    we do *not* verify the deduced template argument values can be
15750    substituted into non-deduced contexts.
15751
15752    The logic can be a bit confusing here, because we look at deduce1 and
15753    targs1 to see if pat2 is at least as specialized, and vice versa; if we
15754    can find template arguments for pat1 to make arg1 look like arg2, that
15755    means that arg2 is at least as specialized as arg1.  */
15756
15757 int
15758 more_specialized_fn (tree pat1, tree pat2, int len)
15759 {
15760   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
15761   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
15762   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
15763   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
15764   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
15765   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
15766   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
15767   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
15768   tree origs1, origs2;
15769   bool lose1 = false;
15770   bool lose2 = false;
15771
15772   /* Remove the this parameter from non-static member functions.  If
15773      one is a non-static member function and the other is not a static
15774      member function, remove the first parameter from that function
15775      also.  This situation occurs for operator functions where we
15776      locate both a member function (with this pointer) and non-member
15777      operator (with explicit first operand).  */
15778   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
15779     {
15780       len--; /* LEN is the number of significant arguments for DECL1 */
15781       args1 = TREE_CHAIN (args1);
15782       if (!DECL_STATIC_FUNCTION_P (decl2))
15783         args2 = TREE_CHAIN (args2);
15784     }
15785   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
15786     {
15787       args2 = TREE_CHAIN (args2);
15788       if (!DECL_STATIC_FUNCTION_P (decl1))
15789         {
15790           len--;
15791           args1 = TREE_CHAIN (args1);
15792         }
15793     }
15794
15795   /* If only one is a conversion operator, they are unordered.  */
15796   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
15797     return 0;
15798
15799   /* Consider the return type for a conversion function */
15800   if (DECL_CONV_FN_P (decl1))
15801     {
15802       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
15803       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
15804       len++;
15805     }
15806
15807   processing_template_decl++;
15808
15809   origs1 = args1;
15810   origs2 = args2;
15811
15812   while (len--
15813          /* Stop when an ellipsis is seen.  */
15814          && args1 != NULL_TREE && args2 != NULL_TREE)
15815     {
15816       tree arg1 = TREE_VALUE (args1);
15817       tree arg2 = TREE_VALUE (args2);
15818       int deduce1, deduce2;
15819       int quals1 = -1;
15820       int quals2 = -1;
15821
15822       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15823           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15824         {
15825           /* When both arguments are pack expansions, we need only
15826              unify the patterns themselves.  */
15827           arg1 = PACK_EXPANSION_PATTERN (arg1);
15828           arg2 = PACK_EXPANSION_PATTERN (arg2);
15829
15830           /* This is the last comparison we need to do.  */
15831           len = 0;
15832         }
15833
15834       if (TREE_CODE (arg1) == REFERENCE_TYPE)
15835         {
15836           arg1 = TREE_TYPE (arg1);
15837           quals1 = cp_type_quals (arg1);
15838         }
15839
15840       if (TREE_CODE (arg2) == REFERENCE_TYPE)
15841         {
15842           arg2 = TREE_TYPE (arg2);
15843           quals2 = cp_type_quals (arg2);
15844         }
15845
15846       if ((quals1 < 0) != (quals2 < 0))
15847         {
15848           /* Only of the args is a reference, see if we should apply
15849              array/function pointer decay to it.  This is not part of
15850              DR214, but is, IMHO, consistent with the deduction rules
15851              for the function call itself, and with our earlier
15852              implementation of the underspecified partial ordering
15853              rules.  (nathan).  */
15854           if (quals1 >= 0)
15855             {
15856               switch (TREE_CODE (arg1))
15857                 {
15858                 case ARRAY_TYPE:
15859                   arg1 = TREE_TYPE (arg1);
15860                   /* FALLTHROUGH. */
15861                 case FUNCTION_TYPE:
15862                   arg1 = build_pointer_type (arg1);
15863                   break;
15864
15865                 default:
15866                   break;
15867                 }
15868             }
15869           else
15870             {
15871               switch (TREE_CODE (arg2))
15872                 {
15873                 case ARRAY_TYPE:
15874                   arg2 = TREE_TYPE (arg2);
15875                   /* FALLTHROUGH. */
15876                 case FUNCTION_TYPE:
15877                   arg2 = build_pointer_type (arg2);
15878                   break;
15879
15880                 default:
15881                   break;
15882                 }
15883             }
15884         }
15885
15886       arg1 = TYPE_MAIN_VARIANT (arg1);
15887       arg2 = TYPE_MAIN_VARIANT (arg2);
15888
15889       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
15890         {
15891           int i, len2 = list_length (args2);
15892           tree parmvec = make_tree_vec (1);
15893           tree argvec = make_tree_vec (len2);
15894           tree ta = args2;
15895
15896           /* Setup the parameter vector, which contains only ARG1.  */
15897           TREE_VEC_ELT (parmvec, 0) = arg1;
15898
15899           /* Setup the argument vector, which contains the remaining
15900              arguments.  */
15901           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
15902             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15903
15904           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
15905                                            argvec, UNIFY_ALLOW_NONE, 
15906                                            /*call_args_p=*/false, 
15907                                            /*subr=*/0);
15908
15909           /* We cannot deduce in the other direction, because ARG1 is
15910              a pack expansion but ARG2 is not.  */
15911           deduce2 = 0;
15912         }
15913       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15914         {
15915           int i, len1 = list_length (args1);
15916           tree parmvec = make_tree_vec (1);
15917           tree argvec = make_tree_vec (len1);
15918           tree ta = args1;
15919
15920           /* Setup the parameter vector, which contains only ARG1.  */
15921           TREE_VEC_ELT (parmvec, 0) = arg2;
15922
15923           /* Setup the argument vector, which contains the remaining
15924              arguments.  */
15925           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
15926             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15927
15928           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
15929                                            argvec, UNIFY_ALLOW_NONE, 
15930                                            /*call_args_p=*/false, 
15931                                            /*subr=*/0);
15932
15933           /* We cannot deduce in the other direction, because ARG2 is
15934              a pack expansion but ARG1 is not.*/
15935           deduce1 = 0;
15936         }
15937
15938       else
15939         {
15940           /* The normal case, where neither argument is a pack
15941              expansion.  */
15942           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
15943           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
15944         }
15945
15946       /* If we couldn't deduce arguments for tparms1 to make arg1 match
15947          arg2, then arg2 is not as specialized as arg1.  */
15948       if (!deduce1)
15949         lose2 = true;
15950       if (!deduce2)
15951         lose1 = true;
15952
15953       /* "If, for a given type, deduction succeeds in both directions
15954          (i.e., the types are identical after the transformations above)
15955          and if the type from the argument template is more cv-qualified
15956          than the type from the parameter template (as described above)
15957          that type is considered to be more specialized than the other. If
15958          neither type is more cv-qualified than the other then neither type
15959          is more specialized than the other."  */
15960
15961       if (deduce1 && deduce2
15962           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
15963         {
15964           if ((quals1 & quals2) == quals2)
15965             lose2 = true;
15966           if ((quals1 & quals2) == quals1)
15967             lose1 = true;
15968         }
15969
15970       if (lose1 && lose2)
15971         /* We've failed to deduce something in either direction.
15972            These must be unordered.  */
15973         break;
15974
15975       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15976           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15977         /* We have already processed all of the arguments in our
15978            handing of the pack expansion type.  */
15979         len = 0;
15980
15981       args1 = TREE_CHAIN (args1);
15982       args2 = TREE_CHAIN (args2);
15983     }
15984
15985   /* "In most cases, all template parameters must have values in order for
15986      deduction to succeed, but for partial ordering purposes a template
15987      parameter may remain without a value provided it is not used in the
15988      types being used for partial ordering."
15989
15990      Thus, if we are missing any of the targs1 we need to substitute into
15991      origs1, then pat2 is not as specialized as pat1.  This can happen when
15992      there is a nondeduced context.  */
15993   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
15994     lose2 = true;
15995   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
15996     lose1 = true;
15997
15998   processing_template_decl--;
15999
16000   /* All things being equal, if the next argument is a pack expansion
16001      for one function but not for the other, prefer the
16002      non-variadic function.  FIXME this is bogus; see c++/41958.  */
16003   if (lose1 == lose2
16004       && args1 && TREE_VALUE (args1)
16005       && args2 && TREE_VALUE (args2))
16006     {
16007       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
16008       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
16009     }
16010
16011   if (lose1 == lose2)
16012     return 0;
16013   else if (!lose1)
16014     return 1;
16015   else
16016     return -1;
16017 }
16018
16019 /* Determine which of two partial specializations is more specialized.
16020
16021    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
16022    to the first partial specialization.  The TREE_VALUE is the
16023    innermost set of template parameters for the partial
16024    specialization.  PAT2 is similar, but for the second template.
16025
16026    Return 1 if the first partial specialization is more specialized;
16027    -1 if the second is more specialized; 0 if neither is more
16028    specialized.
16029
16030    See [temp.class.order] for information about determining which of
16031    two templates is more specialized.  */
16032
16033 static int
16034 more_specialized_class (tree pat1, tree pat2)
16035 {
16036   tree targs;
16037   tree tmpl1, tmpl2;
16038   int winner = 0;
16039   bool any_deductions = false;
16040
16041   tmpl1 = TREE_TYPE (pat1);
16042   tmpl2 = TREE_TYPE (pat2);
16043
16044   /* Just like what happens for functions, if we are ordering between
16045      different class template specializations, we may encounter dependent
16046      types in the arguments, and we need our dependency check functions
16047      to behave correctly.  */
16048   ++processing_template_decl;
16049   targs = get_class_bindings (TREE_VALUE (pat1),
16050                               CLASSTYPE_TI_ARGS (tmpl1),
16051                               CLASSTYPE_TI_ARGS (tmpl2));
16052   if (targs)
16053     {
16054       --winner;
16055       any_deductions = true;
16056     }
16057
16058   targs = get_class_bindings (TREE_VALUE (pat2),
16059                               CLASSTYPE_TI_ARGS (tmpl2),
16060                               CLASSTYPE_TI_ARGS (tmpl1));
16061   if (targs)
16062     {
16063       ++winner;
16064       any_deductions = true;
16065     }
16066   --processing_template_decl;
16067
16068   /* In the case of a tie where at least one of the class templates
16069      has a parameter pack at the end, the template with the most
16070      non-packed parameters wins.  */
16071   if (winner == 0
16072       && any_deductions
16073       && (template_args_variadic_p (TREE_PURPOSE (pat1))
16074           || template_args_variadic_p (TREE_PURPOSE (pat2))))
16075     {
16076       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
16077       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
16078       int len1 = TREE_VEC_LENGTH (args1);
16079       int len2 = TREE_VEC_LENGTH (args2);
16080
16081       /* We don't count the pack expansion at the end.  */
16082       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
16083         --len1;
16084       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
16085         --len2;
16086
16087       if (len1 > len2)
16088         return 1;
16089       else if (len1 < len2)
16090         return -1;
16091     }
16092
16093   return winner;
16094 }
16095
16096 /* Return the template arguments that will produce the function signature
16097    DECL from the function template FN, with the explicit template
16098    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
16099    also match.  Return NULL_TREE if no satisfactory arguments could be
16100    found.  */
16101
16102 static tree
16103 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
16104 {
16105   int ntparms = DECL_NTPARMS (fn);
16106   tree targs = make_tree_vec (ntparms);
16107   tree decl_type;
16108   tree decl_arg_types;
16109   tree *args;
16110   unsigned int nargs, ix;
16111   tree arg;
16112
16113   /* Substitute the explicit template arguments into the type of DECL.
16114      The call to fn_type_unification will handle substitution into the
16115      FN.  */
16116   decl_type = TREE_TYPE (decl);
16117   if (explicit_args && uses_template_parms (decl_type))
16118     {
16119       tree tmpl;
16120       tree converted_args;
16121
16122       if (DECL_TEMPLATE_INFO (decl))
16123         tmpl = DECL_TI_TEMPLATE (decl);
16124       else
16125         /* We can get here for some invalid specializations.  */
16126         return NULL_TREE;
16127
16128       converted_args
16129         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
16130                                  explicit_args, NULL_TREE,
16131                                  tf_none,
16132                                  /*require_all_args=*/false,
16133                                  /*use_default_args=*/false);
16134       if (converted_args == error_mark_node)
16135         return NULL_TREE;
16136
16137       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
16138       if (decl_type == error_mark_node)
16139         return NULL_TREE;
16140     }
16141
16142   /* Never do unification on the 'this' parameter.  */
16143   decl_arg_types = skip_artificial_parms_for (decl, 
16144                                               TYPE_ARG_TYPES (decl_type));
16145
16146   nargs = list_length (decl_arg_types);
16147   args = XALLOCAVEC (tree, nargs);
16148   for (arg = decl_arg_types, ix = 0;
16149        arg != NULL_TREE && arg != void_list_node;
16150        arg = TREE_CHAIN (arg), ++ix)
16151     args[ix] = TREE_VALUE (arg);
16152
16153   if (fn_type_unification (fn, explicit_args, targs,
16154                            args, ix,
16155                            (check_rettype || DECL_CONV_FN_P (fn)
16156                             ? TREE_TYPE (decl_type) : NULL_TREE),
16157                            DEDUCE_EXACT, LOOKUP_NORMAL))
16158     return NULL_TREE;
16159
16160   return targs;
16161 }
16162
16163 /* Return the innermost template arguments that, when applied to a
16164    template specialization whose innermost template parameters are
16165    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
16166    ARGS.
16167
16168    For example, suppose we have:
16169
16170      template <class T, class U> struct S {};
16171      template <class T> struct S<T*, int> {};
16172
16173    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
16174    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
16175    int}.  The resulting vector will be {double}, indicating that `T'
16176    is bound to `double'.  */
16177
16178 static tree
16179 get_class_bindings (tree tparms, tree spec_args, tree args)
16180 {
16181   int i, ntparms = TREE_VEC_LENGTH (tparms);
16182   tree deduced_args;
16183   tree innermost_deduced_args;
16184
16185   innermost_deduced_args = make_tree_vec (ntparms);
16186   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
16187     {
16188       deduced_args = copy_node (args);
16189       SET_TMPL_ARGS_LEVEL (deduced_args,
16190                            TMPL_ARGS_DEPTH (deduced_args),
16191                            innermost_deduced_args);
16192     }
16193   else
16194     deduced_args = innermost_deduced_args;
16195
16196   if (unify (tparms, deduced_args,
16197              INNERMOST_TEMPLATE_ARGS (spec_args),
16198              INNERMOST_TEMPLATE_ARGS (args),
16199              UNIFY_ALLOW_NONE))
16200     return NULL_TREE;
16201
16202   for (i =  0; i < ntparms; ++i)
16203     if (! TREE_VEC_ELT (innermost_deduced_args, i))
16204       return NULL_TREE;
16205
16206   /* Verify that nondeduced template arguments agree with the type
16207      obtained from argument deduction.
16208
16209      For example:
16210
16211        struct A { typedef int X; };
16212        template <class T, class U> struct C {};
16213        template <class T> struct C<T, typename T::X> {};
16214
16215      Then with the instantiation `C<A, int>', we can deduce that
16216      `T' is `A' but unify () does not check whether `typename T::X'
16217      is `int'.  */
16218   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
16219   if (spec_args == error_mark_node
16220       /* We only need to check the innermost arguments; the other
16221          arguments will always agree.  */
16222       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
16223                               INNERMOST_TEMPLATE_ARGS (args)))
16224     return NULL_TREE;
16225
16226   /* Now that we have bindings for all of the template arguments,
16227      ensure that the arguments deduced for the template template
16228      parameters have compatible template parameter lists.  See the use
16229      of template_template_parm_bindings_ok_p in fn_type_unification
16230      for more information.  */
16231   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
16232     return NULL_TREE;
16233
16234   return deduced_args;
16235 }
16236
16237 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
16238    Return the TREE_LIST node with the most specialized template, if
16239    any.  If there is no most specialized template, the error_mark_node
16240    is returned.
16241
16242    Note that this function does not look at, or modify, the
16243    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
16244    returned is one of the elements of INSTANTIATIONS, callers may
16245    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
16246    and retrieve it from the value returned.  */
16247
16248 tree
16249 most_specialized_instantiation (tree templates)
16250 {
16251   tree fn, champ;
16252
16253   ++processing_template_decl;
16254
16255   champ = templates;
16256   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
16257     {
16258       int fate = 0;
16259
16260       if (get_bindings (TREE_VALUE (champ),
16261                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
16262                         NULL_TREE, /*check_ret=*/false))
16263         fate--;
16264
16265       if (get_bindings (TREE_VALUE (fn),
16266                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
16267                         NULL_TREE, /*check_ret=*/false))
16268         fate++;
16269
16270       if (fate == -1)
16271         champ = fn;
16272       else if (!fate)
16273         {
16274           /* Equally specialized, move to next function.  If there
16275              is no next function, nothing's most specialized.  */
16276           fn = TREE_CHAIN (fn);
16277           champ = fn;
16278           if (!fn)
16279             break;
16280         }
16281     }
16282
16283   if (champ)
16284     /* Now verify that champ is better than everything earlier in the
16285        instantiation list.  */
16286     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
16287       if (get_bindings (TREE_VALUE (champ),
16288                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
16289                         NULL_TREE, /*check_ret=*/false)
16290           || !get_bindings (TREE_VALUE (fn),
16291                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
16292                             NULL_TREE, /*check_ret=*/false))
16293         {
16294           champ = NULL_TREE;
16295           break;
16296         }
16297
16298   processing_template_decl--;
16299
16300   if (!champ)
16301     return error_mark_node;
16302
16303   return champ;
16304 }
16305
16306 /* If DECL is a specialization of some template, return the most
16307    general such template.  Otherwise, returns NULL_TREE.
16308
16309    For example, given:
16310
16311      template <class T> struct S { template <class U> void f(U); };
16312
16313    if TMPL is `template <class U> void S<int>::f(U)' this will return
16314    the full template.  This function will not trace past partial
16315    specializations, however.  For example, given in addition:
16316
16317      template <class T> struct S<T*> { template <class U> void f(U); };
16318
16319    if TMPL is `template <class U> void S<int*>::f(U)' this will return
16320    `template <class T> template <class U> S<T*>::f(U)'.  */
16321
16322 tree
16323 most_general_template (tree decl)
16324 {
16325   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
16326      an immediate specialization.  */
16327   if (TREE_CODE (decl) == FUNCTION_DECL)
16328     {
16329       if (DECL_TEMPLATE_INFO (decl)) {
16330         decl = DECL_TI_TEMPLATE (decl);
16331
16332         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
16333            template friend.  */
16334         if (TREE_CODE (decl) != TEMPLATE_DECL)
16335           return NULL_TREE;
16336       } else
16337         return NULL_TREE;
16338     }
16339
16340   /* Look for more and more general templates.  */
16341   while (DECL_TEMPLATE_INFO (decl))
16342     {
16343       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
16344          (See cp-tree.h for details.)  */
16345       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
16346         break;
16347
16348       if (CLASS_TYPE_P (TREE_TYPE (decl))
16349           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
16350         break;
16351
16352       /* Stop if we run into an explicitly specialized class template.  */
16353       if (!DECL_NAMESPACE_SCOPE_P (decl)
16354           && DECL_CONTEXT (decl)
16355           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
16356         break;
16357
16358       decl = DECL_TI_TEMPLATE (decl);
16359     }
16360
16361   return decl;
16362 }
16363
16364 /* Return the most specialized of the class template partial
16365    specializations of TMPL which can produce TYPE, a specialization of
16366    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
16367    a _TYPE node corresponding to the partial specialization, while the
16368    TREE_PURPOSE is the set of template arguments that must be
16369    substituted into the TREE_TYPE in order to generate TYPE.
16370
16371    If the choice of partial specialization is ambiguous, a diagnostic
16372    is issued, and the error_mark_node is returned.  If there are no
16373    partial specializations of TMPL matching TYPE, then NULL_TREE is
16374    returned.  */
16375
16376 static tree
16377 most_specialized_class (tree type, tree tmpl, tsubst_flags_t complain)
16378 {
16379   tree list = NULL_TREE;
16380   tree t;
16381   tree champ;
16382   int fate;
16383   bool ambiguous_p;
16384   tree args;
16385   tree outer_args = NULL_TREE;
16386
16387   tmpl = most_general_template (tmpl);
16388   args = CLASSTYPE_TI_ARGS (type);
16389
16390   /* For determining which partial specialization to use, only the
16391      innermost args are interesting.  */
16392   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
16393     {
16394       outer_args = strip_innermost_template_args (args, 1);
16395       args = INNERMOST_TEMPLATE_ARGS (args);
16396     }
16397
16398   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
16399     {
16400       tree partial_spec_args;
16401       tree spec_args;
16402       tree parms = TREE_VALUE (t);
16403
16404       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
16405
16406       ++processing_template_decl;
16407
16408       if (outer_args)
16409         {
16410           int i;
16411
16412           /* Discard the outer levels of args, and then substitute in the
16413              template args from the enclosing class.  */
16414           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
16415           partial_spec_args = tsubst_template_args
16416             (partial_spec_args, outer_args, tf_none, NULL_TREE);
16417
16418           /* PARMS already refers to just the innermost parms, but the
16419              template parms in partial_spec_args had their levels lowered
16420              by tsubst, so we need to do the same for the parm list.  We
16421              can't just tsubst the TREE_VEC itself, as tsubst wants to
16422              treat a TREE_VEC as an argument vector.  */
16423           parms = copy_node (parms);
16424           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
16425             TREE_VEC_ELT (parms, i) =
16426               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
16427
16428         }
16429
16430       partial_spec_args =
16431           coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
16432                                  add_to_template_args (outer_args,
16433                                                        partial_spec_args),
16434                                  tmpl, tf_none,
16435                                  /*require_all_args=*/true,
16436                                  /*use_default_args=*/true);
16437
16438       --processing_template_decl;
16439
16440       if (partial_spec_args == error_mark_node)
16441         return error_mark_node;
16442
16443       spec_args = get_class_bindings (parms,
16444                                       partial_spec_args,
16445                                       args);
16446       if (spec_args)
16447         {
16448           if (outer_args)
16449             spec_args = add_to_template_args (outer_args, spec_args);
16450           list = tree_cons (spec_args, TREE_VALUE (t), list);
16451           TREE_TYPE (list) = TREE_TYPE (t);
16452         }
16453     }
16454
16455   if (! list)
16456     return NULL_TREE;
16457
16458   ambiguous_p = false;
16459   t = list;
16460   champ = t;
16461   t = TREE_CHAIN (t);
16462   for (; t; t = TREE_CHAIN (t))
16463     {
16464       fate = more_specialized_class (champ, t);
16465       if (fate == 1)
16466         ;
16467       else
16468         {
16469           if (fate == 0)
16470             {
16471               t = TREE_CHAIN (t);
16472               if (! t)
16473                 {
16474                   ambiguous_p = true;
16475                   break;
16476                 }
16477             }
16478           champ = t;
16479         }
16480     }
16481
16482   if (!ambiguous_p)
16483     for (t = list; t && t != champ; t = TREE_CHAIN (t))
16484       {
16485         fate = more_specialized_class (champ, t);
16486         if (fate != 1)
16487           {
16488             ambiguous_p = true;
16489             break;
16490           }
16491       }
16492
16493   if (ambiguous_p)
16494     {
16495       const char *str;
16496       char *spaces = NULL;
16497       if (!(complain & tf_error))
16498         return error_mark_node;
16499       error ("ambiguous class template instantiation for %q#T", type);
16500       str = TREE_CHAIN (list) ? _("candidates are:") : _("candidate is:");
16501       for (t = list; t; t = TREE_CHAIN (t))
16502         {
16503           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
16504           spaces = spaces ? spaces : get_spaces (str);
16505         }
16506       free (spaces);
16507       return error_mark_node;
16508     }
16509
16510   return champ;
16511 }
16512
16513 /* Explicitly instantiate DECL.  */
16514
16515 void
16516 do_decl_instantiation (tree decl, tree storage)
16517 {
16518   tree result = NULL_TREE;
16519   int extern_p = 0;
16520
16521   if (!decl || decl == error_mark_node)
16522     /* An error occurred, for which grokdeclarator has already issued
16523        an appropriate message.  */
16524     return;
16525   else if (! DECL_LANG_SPECIFIC (decl))
16526     {
16527       error ("explicit instantiation of non-template %q#D", decl);
16528       return;
16529     }
16530   else if (TREE_CODE (decl) == VAR_DECL)
16531     {
16532       /* There is an asymmetry here in the way VAR_DECLs and
16533          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
16534          the latter, the DECL we get back will be marked as a
16535          template instantiation, and the appropriate
16536          DECL_TEMPLATE_INFO will be set up.  This does not happen for
16537          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
16538          should handle VAR_DECLs as it currently handles
16539          FUNCTION_DECLs.  */
16540       if (!DECL_CLASS_SCOPE_P (decl))
16541         {
16542           error ("%qD is not a static data member of a class template", decl);
16543           return;
16544         }
16545       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
16546       if (!result || TREE_CODE (result) != VAR_DECL)
16547         {
16548           error ("no matching template for %qD found", decl);
16549           return;
16550         }
16551       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
16552         {
16553           error ("type %qT for explicit instantiation %qD does not match "
16554                  "declared type %qT", TREE_TYPE (result), decl,
16555                  TREE_TYPE (decl));
16556           return;
16557         }
16558     }
16559   else if (TREE_CODE (decl) != FUNCTION_DECL)
16560     {
16561       error ("explicit instantiation of %q#D", decl);
16562       return;
16563     }
16564   else
16565     result = decl;
16566
16567   /* Check for various error cases.  Note that if the explicit
16568      instantiation is valid the RESULT will currently be marked as an
16569      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
16570      until we get here.  */
16571
16572   if (DECL_TEMPLATE_SPECIALIZATION (result))
16573     {
16574       /* DR 259 [temp.spec].
16575
16576          Both an explicit instantiation and a declaration of an explicit
16577          specialization shall not appear in a program unless the explicit
16578          instantiation follows a declaration of the explicit specialization.
16579
16580          For a given set of template parameters, if an explicit
16581          instantiation of a template appears after a declaration of an
16582          explicit specialization for that template, the explicit
16583          instantiation has no effect.  */
16584       return;
16585     }
16586   else if (DECL_EXPLICIT_INSTANTIATION (result))
16587     {
16588       /* [temp.spec]
16589
16590          No program shall explicitly instantiate any template more
16591          than once.
16592
16593          We check DECL_NOT_REALLY_EXTERN so as not to complain when
16594          the first instantiation was `extern' and the second is not,
16595          and EXTERN_P for the opposite case.  */
16596       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
16597         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
16598       /* If an "extern" explicit instantiation follows an ordinary
16599          explicit instantiation, the template is instantiated.  */
16600       if (extern_p)
16601         return;
16602     }
16603   else if (!DECL_IMPLICIT_INSTANTIATION (result))
16604     {
16605       error ("no matching template for %qD found", result);
16606       return;
16607     }
16608   else if (!DECL_TEMPLATE_INFO (result))
16609     {
16610       permerror (input_location, "explicit instantiation of non-template %q#D", result);
16611       return;
16612     }
16613
16614   if (storage == NULL_TREE)
16615     ;
16616   else if (storage == ridpointers[(int) RID_EXTERN])
16617     {
16618       if (!in_system_header && (cxx_dialect == cxx98))
16619         pedwarn (input_location, OPT_pedantic, 
16620                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
16621                  "instantiations");
16622       extern_p = 1;
16623     }
16624   else
16625     error ("storage class %qD applied to template instantiation", storage);
16626
16627   check_explicit_instantiation_namespace (result);
16628   mark_decl_instantiated (result, extern_p);
16629   if (! extern_p)
16630     instantiate_decl (result, /*defer_ok=*/1,
16631                       /*expl_inst_class_mem_p=*/false);
16632 }
16633
16634 static void
16635 mark_class_instantiated (tree t, int extern_p)
16636 {
16637   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
16638   SET_CLASSTYPE_INTERFACE_KNOWN (t);
16639   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
16640   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
16641   if (! extern_p)
16642     {
16643       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
16644       rest_of_type_compilation (t, 1);
16645     }
16646 }
16647
16648 /* Called from do_type_instantiation through binding_table_foreach to
16649    do recursive instantiation for the type bound in ENTRY.  */
16650 static void
16651 bt_instantiate_type_proc (binding_entry entry, void *data)
16652 {
16653   tree storage = *(tree *) data;
16654
16655   if (MAYBE_CLASS_TYPE_P (entry->type)
16656       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
16657     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
16658 }
16659
16660 /* Called from do_type_instantiation to instantiate a member
16661    (a member function or a static member variable) of an
16662    explicitly instantiated class template.  */
16663 static void
16664 instantiate_class_member (tree decl, int extern_p)
16665 {
16666   mark_decl_instantiated (decl, extern_p);
16667   if (! extern_p)
16668     instantiate_decl (decl, /*defer_ok=*/1,
16669                       /*expl_inst_class_mem_p=*/true);
16670 }
16671
16672 /* Perform an explicit instantiation of template class T.  STORAGE, if
16673    non-null, is the RID for extern, inline or static.  COMPLAIN is
16674    nonzero if this is called from the parser, zero if called recursively,
16675    since the standard is unclear (as detailed below).  */
16676
16677 void
16678 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
16679 {
16680   int extern_p = 0;
16681   int nomem_p = 0;
16682   int static_p = 0;
16683   int previous_instantiation_extern_p = 0;
16684
16685   if (TREE_CODE (t) == TYPE_DECL)
16686     t = TREE_TYPE (t);
16687
16688   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
16689     {
16690       error ("explicit instantiation of non-template type %qT", t);
16691       return;
16692     }
16693
16694   complete_type (t);
16695
16696   if (!COMPLETE_TYPE_P (t))
16697     {
16698       if (complain & tf_error)
16699         error ("explicit instantiation of %q#T before definition of template",
16700                t);
16701       return;
16702     }
16703
16704   if (storage != NULL_TREE)
16705     {
16706       if (!in_system_header)
16707         {
16708           if (storage == ridpointers[(int) RID_EXTERN])
16709             {
16710               if (cxx_dialect == cxx98)
16711                 pedwarn (input_location, OPT_pedantic, 
16712                          "ISO C++ 1998 forbids the use of %<extern%> on "
16713                          "explicit instantiations");
16714             }
16715           else
16716             pedwarn (input_location, OPT_pedantic, 
16717                      "ISO C++ forbids the use of %qE"
16718                      " on explicit instantiations", storage);
16719         }
16720
16721       if (storage == ridpointers[(int) RID_INLINE])
16722         nomem_p = 1;
16723       else if (storage == ridpointers[(int) RID_EXTERN])
16724         extern_p = 1;
16725       else if (storage == ridpointers[(int) RID_STATIC])
16726         static_p = 1;
16727       else
16728         {
16729           error ("storage class %qD applied to template instantiation",
16730                  storage);
16731           extern_p = 0;
16732         }
16733     }
16734
16735   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
16736     {
16737       /* DR 259 [temp.spec].
16738
16739          Both an explicit instantiation and a declaration of an explicit
16740          specialization shall not appear in a program unless the explicit
16741          instantiation follows a declaration of the explicit specialization.
16742
16743          For a given set of template parameters, if an explicit
16744          instantiation of a template appears after a declaration of an
16745          explicit specialization for that template, the explicit
16746          instantiation has no effect.  */
16747       return;
16748     }
16749   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
16750     {
16751       /* [temp.spec]
16752
16753          No program shall explicitly instantiate any template more
16754          than once.
16755
16756          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
16757          instantiation was `extern'.  If EXTERN_P then the second is.
16758          These cases are OK.  */
16759       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
16760
16761       if (!previous_instantiation_extern_p && !extern_p
16762           && (complain & tf_error))
16763         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
16764
16765       /* If we've already instantiated the template, just return now.  */
16766       if (!CLASSTYPE_INTERFACE_ONLY (t))
16767         return;
16768     }
16769
16770   check_explicit_instantiation_namespace (TYPE_NAME (t));
16771   mark_class_instantiated (t, extern_p);
16772
16773   if (nomem_p)
16774     return;
16775
16776   {
16777     tree tmp;
16778
16779     /* In contrast to implicit instantiation, where only the
16780        declarations, and not the definitions, of members are
16781        instantiated, we have here:
16782
16783          [temp.explicit]
16784
16785          The explicit instantiation of a class template specialization
16786          implies the instantiation of all of its members not
16787          previously explicitly specialized in the translation unit
16788          containing the explicit instantiation.
16789
16790        Of course, we can't instantiate member template classes, since
16791        we don't have any arguments for them.  Note that the standard
16792        is unclear on whether the instantiation of the members are
16793        *explicit* instantiations or not.  However, the most natural
16794        interpretation is that it should be an explicit instantiation.  */
16795
16796     if (! static_p)
16797       for (tmp = TYPE_METHODS (t); tmp; tmp = DECL_CHAIN (tmp))
16798         if (TREE_CODE (tmp) == FUNCTION_DECL
16799             && DECL_TEMPLATE_INSTANTIATION (tmp))
16800           instantiate_class_member (tmp, extern_p);
16801
16802     for (tmp = TYPE_FIELDS (t); tmp; tmp = DECL_CHAIN (tmp))
16803       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
16804         instantiate_class_member (tmp, extern_p);
16805
16806     if (CLASSTYPE_NESTED_UTDS (t))
16807       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
16808                              bt_instantiate_type_proc, &storage);
16809   }
16810 }
16811
16812 /* Given a function DECL, which is a specialization of TMPL, modify
16813    DECL to be a re-instantiation of TMPL with the same template
16814    arguments.  TMPL should be the template into which tsubst'ing
16815    should occur for DECL, not the most general template.
16816
16817    One reason for doing this is a scenario like this:
16818
16819      template <class T>
16820      void f(const T&, int i);
16821
16822      void g() { f(3, 7); }
16823
16824      template <class T>
16825      void f(const T& t, const int i) { }
16826
16827    Note that when the template is first instantiated, with
16828    instantiate_template, the resulting DECL will have no name for the
16829    first parameter, and the wrong type for the second.  So, when we go
16830    to instantiate the DECL, we regenerate it.  */
16831
16832 static void
16833 regenerate_decl_from_template (tree decl, tree tmpl)
16834 {
16835   /* The arguments used to instantiate DECL, from the most general
16836      template.  */
16837   tree args;
16838   tree code_pattern;
16839
16840   args = DECL_TI_ARGS (decl);
16841   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
16842
16843   /* Make sure that we can see identifiers, and compute access
16844      correctly.  */
16845   push_access_scope (decl);
16846
16847   if (TREE_CODE (decl) == FUNCTION_DECL)
16848     {
16849       tree decl_parm;
16850       tree pattern_parm;
16851       tree specs;
16852       int args_depth;
16853       int parms_depth;
16854
16855       args_depth = TMPL_ARGS_DEPTH (args);
16856       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
16857       if (args_depth > parms_depth)
16858         args = get_innermost_template_args (args, parms_depth);
16859
16860       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
16861                                               args, tf_error, NULL_TREE);
16862       if (specs)
16863         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
16864                                                     specs);
16865
16866       /* Merge parameter declarations.  */
16867       decl_parm = skip_artificial_parms_for (decl,
16868                                              DECL_ARGUMENTS (decl));
16869       pattern_parm
16870         = skip_artificial_parms_for (code_pattern,
16871                                      DECL_ARGUMENTS (code_pattern));
16872       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
16873         {
16874           tree parm_type;
16875           tree attributes;
16876           
16877           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16878             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
16879           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
16880                               NULL_TREE);
16881           parm_type = type_decays_to (parm_type);
16882           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16883             TREE_TYPE (decl_parm) = parm_type;
16884           attributes = DECL_ATTRIBUTES (pattern_parm);
16885           if (DECL_ATTRIBUTES (decl_parm) != attributes)
16886             {
16887               DECL_ATTRIBUTES (decl_parm) = attributes;
16888               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16889             }
16890           decl_parm = DECL_CHAIN (decl_parm);
16891           pattern_parm = DECL_CHAIN (pattern_parm);
16892         }
16893       /* Merge any parameters that match with the function parameter
16894          pack.  */
16895       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
16896         {
16897           int i, len;
16898           tree expanded_types;
16899           /* Expand the TYPE_PACK_EXPANSION that provides the types for
16900              the parameters in this function parameter pack.  */
16901           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
16902                                                  args, tf_error, NULL_TREE);
16903           len = TREE_VEC_LENGTH (expanded_types);
16904           for (i = 0; i < len; i++)
16905             {
16906               tree parm_type;
16907               tree attributes;
16908           
16909               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16910                 /* Rename the parameter to include the index.  */
16911                 DECL_NAME (decl_parm) = 
16912                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
16913               parm_type = TREE_VEC_ELT (expanded_types, i);
16914               parm_type = type_decays_to (parm_type);
16915               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16916                 TREE_TYPE (decl_parm) = parm_type;
16917               attributes = DECL_ATTRIBUTES (pattern_parm);
16918               if (DECL_ATTRIBUTES (decl_parm) != attributes)
16919                 {
16920                   DECL_ATTRIBUTES (decl_parm) = attributes;
16921                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16922                 }
16923               decl_parm = DECL_CHAIN (decl_parm);
16924             }
16925         }
16926       /* Merge additional specifiers from the CODE_PATTERN.  */
16927       if (DECL_DECLARED_INLINE_P (code_pattern)
16928           && !DECL_DECLARED_INLINE_P (decl))
16929         DECL_DECLARED_INLINE_P (decl) = 1;
16930     }
16931   else if (TREE_CODE (decl) == VAR_DECL)
16932     {
16933       DECL_INITIAL (decl) =
16934         tsubst_expr (DECL_INITIAL (code_pattern), args,
16935                      tf_error, DECL_TI_TEMPLATE (decl),
16936                      /*integral_constant_expression_p=*/false);
16937       if (VAR_HAD_UNKNOWN_BOUND (decl))
16938         TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
16939                                    tf_error, DECL_TI_TEMPLATE (decl));
16940     }
16941   else
16942     gcc_unreachable ();
16943
16944   pop_access_scope (decl);
16945 }
16946
16947 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
16948    substituted to get DECL.  */
16949
16950 tree
16951 template_for_substitution (tree decl)
16952 {
16953   tree tmpl = DECL_TI_TEMPLATE (decl);
16954
16955   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
16956      for the instantiation.  This is not always the most general
16957      template.  Consider, for example:
16958
16959         template <class T>
16960         struct S { template <class U> void f();
16961                    template <> void f<int>(); };
16962
16963      and an instantiation of S<double>::f<int>.  We want TD to be the
16964      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
16965   while (/* An instantiation cannot have a definition, so we need a
16966             more general template.  */
16967          DECL_TEMPLATE_INSTANTIATION (tmpl)
16968            /* We must also deal with friend templates.  Given:
16969
16970                 template <class T> struct S {
16971                   template <class U> friend void f() {};
16972                 };
16973
16974               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
16975               so far as the language is concerned, but that's still
16976               where we get the pattern for the instantiation from.  On
16977               other hand, if the definition comes outside the class, say:
16978
16979                 template <class T> struct S {
16980                   template <class U> friend void f();
16981                 };
16982                 template <class U> friend void f() {}
16983
16984               we don't need to look any further.  That's what the check for
16985               DECL_INITIAL is for.  */
16986           || (TREE_CODE (decl) == FUNCTION_DECL
16987               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
16988               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
16989     {
16990       /* The present template, TD, should not be a definition.  If it
16991          were a definition, we should be using it!  Note that we
16992          cannot restructure the loop to just keep going until we find
16993          a template with a definition, since that might go too far if
16994          a specialization was declared, but not defined.  */
16995       gcc_assert (TREE_CODE (decl) != VAR_DECL
16996                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
16997
16998       /* Fetch the more general template.  */
16999       tmpl = DECL_TI_TEMPLATE (tmpl);
17000     }
17001
17002   return tmpl;
17003 }
17004
17005 /* Returns true if we need to instantiate this template instance even if we
17006    know we aren't going to emit it..  */
17007
17008 bool
17009 always_instantiate_p (tree decl)
17010 {
17011   /* We always instantiate inline functions so that we can inline them.  An
17012      explicit instantiation declaration prohibits implicit instantiation of
17013      non-inline functions.  With high levels of optimization, we would
17014      normally inline non-inline functions -- but we're not allowed to do
17015      that for "extern template" functions.  Therefore, we check
17016      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
17017   return ((TREE_CODE (decl) == FUNCTION_DECL
17018            && DECL_DECLARED_INLINE_P (decl))
17019           /* And we need to instantiate static data members so that
17020              their initializers are available in integral constant
17021              expressions.  */
17022           || (TREE_CODE (decl) == VAR_DECL
17023               && decl_maybe_constant_var_p (decl)));
17024 }
17025
17026 /* Produce the definition of D, a _DECL generated from a template.  If
17027    DEFER_OK is nonzero, then we don't have to actually do the
17028    instantiation now; we just have to do it sometime.  Normally it is
17029    an error if this is an explicit instantiation but D is undefined.
17030    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
17031    explicitly instantiated class template.  */
17032
17033 tree
17034 instantiate_decl (tree d, int defer_ok,
17035                   bool expl_inst_class_mem_p)
17036 {
17037   tree tmpl = DECL_TI_TEMPLATE (d);
17038   tree gen_args;
17039   tree args;
17040   tree td;
17041   tree code_pattern;
17042   tree spec;
17043   tree gen_tmpl;
17044   bool pattern_defined;
17045   int need_push;
17046   location_t saved_loc = input_location;
17047   bool external_p;
17048
17049   /* This function should only be used to instantiate templates for
17050      functions and static member variables.  */
17051   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
17052               || TREE_CODE (d) == VAR_DECL);
17053
17054   /* Variables are never deferred; if instantiation is required, they
17055      are instantiated right away.  That allows for better code in the
17056      case that an expression refers to the value of the variable --
17057      if the variable has a constant value the referring expression can
17058      take advantage of that fact.  */
17059   if (TREE_CODE (d) == VAR_DECL
17060       || DECL_DECLARED_CONSTEXPR_P (d))
17061     defer_ok = 0;
17062
17063   /* Don't instantiate cloned functions.  Instead, instantiate the
17064      functions they cloned.  */
17065   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
17066     d = DECL_CLONED_FUNCTION (d);
17067
17068   if (DECL_TEMPLATE_INSTANTIATED (d)
17069       || DECL_TEMPLATE_SPECIALIZATION (d))
17070     /* D has already been instantiated or explicitly specialized, so
17071        there's nothing for us to do here.
17072
17073        It might seem reasonable to check whether or not D is an explicit
17074        instantiation, and, if so, stop here.  But when an explicit
17075        instantiation is deferred until the end of the compilation,
17076        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
17077        the instantiation.  */
17078     return d;
17079
17080   /* Check to see whether we know that this template will be
17081      instantiated in some other file, as with "extern template"
17082      extension.  */
17083   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
17084
17085   /* In general, we do not instantiate such templates.  */
17086   if (external_p && !always_instantiate_p (d))
17087     return d;
17088
17089   gen_tmpl = most_general_template (tmpl);
17090   gen_args = DECL_TI_ARGS (d);
17091
17092   if (tmpl != gen_tmpl)
17093     /* We should already have the extra args.  */
17094     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
17095                 == TMPL_ARGS_DEPTH (gen_args));
17096   /* And what's in the hash table should match D.  */
17097   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
17098               || spec == NULL_TREE);
17099
17100   /* This needs to happen before any tsubsting.  */
17101   if (! push_tinst_level (d))
17102     return d;
17103
17104   timevar_push (TV_PARSE);
17105
17106   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
17107      for the instantiation.  */
17108   td = template_for_substitution (d);
17109   code_pattern = DECL_TEMPLATE_RESULT (td);
17110
17111   /* We should never be trying to instantiate a member of a class
17112      template or partial specialization.  */
17113   gcc_assert (d != code_pattern);
17114
17115   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
17116       || DECL_TEMPLATE_SPECIALIZATION (td))
17117     /* In the case of a friend template whose definition is provided
17118        outside the class, we may have too many arguments.  Drop the
17119        ones we don't need.  The same is true for specializations.  */
17120     args = get_innermost_template_args
17121       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
17122   else
17123     args = gen_args;
17124
17125   if (TREE_CODE (d) == FUNCTION_DECL)
17126     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
17127   else
17128     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
17129
17130   /* We may be in the middle of deferred access check.  Disable it now.  */
17131   push_deferring_access_checks (dk_no_deferred);
17132
17133   /* Unless an explicit instantiation directive has already determined
17134      the linkage of D, remember that a definition is available for
17135      this entity.  */
17136   if (pattern_defined
17137       && !DECL_INTERFACE_KNOWN (d)
17138       && !DECL_NOT_REALLY_EXTERN (d))
17139     mark_definable (d);
17140
17141   input_location = DECL_SOURCE_LOCATION (d);
17142
17143   /* If D is a member of an explicitly instantiated class template,
17144      and no definition is available, treat it like an implicit
17145      instantiation.  */
17146   if (!pattern_defined && expl_inst_class_mem_p
17147       && DECL_EXPLICIT_INSTANTIATION (d))
17148     {
17149       DECL_NOT_REALLY_EXTERN (d) = 0;
17150       DECL_INTERFACE_KNOWN (d) = 0;
17151       SET_DECL_IMPLICIT_INSTANTIATION (d);
17152     }
17153
17154   /* Recheck the substitutions to obtain any warning messages
17155      about ignoring cv qualifiers.  Don't do this for artificial decls,
17156      as it breaks the context-sensitive substitution for lambda op(). */
17157   if (!defer_ok && !DECL_ARTIFICIAL (d))
17158     {
17159       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
17160       tree type = TREE_TYPE (gen);
17161
17162       /* Make sure that we can see identifiers, and compute access
17163          correctly.  D is already the target FUNCTION_DECL with the
17164          right context.  */
17165       push_access_scope (d);
17166
17167       if (TREE_CODE (gen) == FUNCTION_DECL)
17168         {
17169           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
17170           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
17171                                           d);
17172           /* Don't simply tsubst the function type, as that will give
17173              duplicate warnings about poor parameter qualifications.
17174              The function arguments are the same as the decl_arguments
17175              without the top level cv qualifiers.  */
17176           type = TREE_TYPE (type);
17177         }
17178       tsubst (type, gen_args, tf_warning_or_error, d);
17179
17180       pop_access_scope (d);
17181     }
17182
17183   /* Defer all other templates, unless we have been explicitly
17184      forbidden from doing so.  */
17185   if (/* If there is no definition, we cannot instantiate the
17186          template.  */
17187       ! pattern_defined
17188       /* If it's OK to postpone instantiation, do so.  */
17189       || defer_ok
17190       /* If this is a static data member that will be defined
17191          elsewhere, we don't want to instantiate the entire data
17192          member, but we do want to instantiate the initializer so that
17193          we can substitute that elsewhere.  */
17194       || (external_p && TREE_CODE (d) == VAR_DECL))
17195     {
17196       /* The definition of the static data member is now required so
17197          we must substitute the initializer.  */
17198       if (TREE_CODE (d) == VAR_DECL
17199           && !DECL_INITIAL (d)
17200           && DECL_INITIAL (code_pattern))
17201         {
17202           tree ns;
17203           tree init;
17204           bool const_init = false;
17205
17206           ns = decl_namespace_context (d);
17207           push_nested_namespace (ns);
17208           push_nested_class (DECL_CONTEXT (d));
17209           init = tsubst_expr (DECL_INITIAL (code_pattern),
17210                               args,
17211                               tf_warning_or_error, NULL_TREE,
17212                               /*integral_constant_expression_p=*/false);
17213           /* Make sure the initializer is still constant, in case of
17214              circular dependency (template/instantiate6.C). */
17215           const_init
17216             = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
17217           cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
17218                           /*asmspec_tree=*/NULL_TREE,
17219                           LOOKUP_ONLYCONVERTING);
17220           pop_nested_class ();
17221           pop_nested_namespace (ns);
17222         }
17223
17224       /* We restore the source position here because it's used by
17225          add_pending_template.  */
17226       input_location = saved_loc;
17227
17228       if (at_eof && !pattern_defined
17229           && DECL_EXPLICIT_INSTANTIATION (d)
17230           && DECL_NOT_REALLY_EXTERN (d))
17231         /* [temp.explicit]
17232
17233            The definition of a non-exported function template, a
17234            non-exported member function template, or a non-exported
17235            member function or static data member of a class template
17236            shall be present in every translation unit in which it is
17237            explicitly instantiated.  */
17238         permerror (input_location,  "explicit instantiation of %qD "
17239                    "but no definition available", d);
17240
17241       /* If we're in unevaluated context, we just wanted to get the
17242          constant value; this isn't an odr use, so don't queue
17243          a full instantiation.  */
17244       if (cp_unevaluated_operand != 0)
17245         goto out;
17246       /* ??? Historically, we have instantiated inline functions, even
17247          when marked as "extern template".  */
17248       if (!(external_p && TREE_CODE (d) == VAR_DECL))
17249         add_pending_template (d);
17250       goto out;
17251     }
17252   /* Tell the repository that D is available in this translation unit
17253      -- and see if it is supposed to be instantiated here.  */
17254   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
17255     {
17256       /* In a PCH file, despite the fact that the repository hasn't
17257          requested instantiation in the PCH it is still possible that
17258          an instantiation will be required in a file that includes the
17259          PCH.  */
17260       if (pch_file)
17261         add_pending_template (d);
17262       /* Instantiate inline functions so that the inliner can do its
17263          job, even though we'll not be emitting a copy of this
17264          function.  */
17265       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
17266         goto out;
17267     }
17268
17269   need_push = !cfun || !global_bindings_p ();
17270   if (need_push)
17271     push_to_top_level ();
17272
17273   /* Mark D as instantiated so that recursive calls to
17274      instantiate_decl do not try to instantiate it again.  */
17275   DECL_TEMPLATE_INSTANTIATED (d) = 1;
17276
17277   /* Regenerate the declaration in case the template has been modified
17278      by a subsequent redeclaration.  */
17279   regenerate_decl_from_template (d, td);
17280
17281   /* We already set the file and line above.  Reset them now in case
17282      they changed as a result of calling regenerate_decl_from_template.  */
17283   input_location = DECL_SOURCE_LOCATION (d);
17284
17285   if (TREE_CODE (d) == VAR_DECL)
17286     {
17287       tree init;
17288       bool const_init = false;
17289
17290       /* Clear out DECL_RTL; whatever was there before may not be right
17291          since we've reset the type of the declaration.  */
17292       SET_DECL_RTL (d, NULL);
17293       DECL_IN_AGGR_P (d) = 0;
17294
17295       /* The initializer is placed in DECL_INITIAL by
17296          regenerate_decl_from_template so we don't need to
17297          push/pop_access_scope again here.  Pull it out so that
17298          cp_finish_decl can process it.  */
17299       init = DECL_INITIAL (d);
17300       DECL_INITIAL (d) = NULL_TREE;
17301       DECL_INITIALIZED_P (d) = 0;
17302
17303       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
17304          initializer.  That function will defer actual emission until
17305          we have a chance to determine linkage.  */
17306       DECL_EXTERNAL (d) = 0;
17307
17308       /* Enter the scope of D so that access-checking works correctly.  */
17309       push_nested_class (DECL_CONTEXT (d));
17310       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
17311       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
17312       pop_nested_class ();
17313     }
17314   else if (TREE_CODE (d) == FUNCTION_DECL)
17315     {
17316       htab_t saved_local_specializations;
17317       tree subst_decl;
17318       tree tmpl_parm;
17319       tree spec_parm;
17320
17321       /* Save away the current list, in case we are instantiating one
17322          template from within the body of another.  */
17323       saved_local_specializations = local_specializations;
17324
17325       /* Set up the list of local specializations.  */
17326       local_specializations = htab_create (37,
17327                                            hash_local_specialization,
17328                                            eq_local_specializations,
17329                                            NULL);
17330
17331       /* Set up context.  */
17332       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
17333
17334       /* Create substitution entries for the parameters.  */
17335       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
17336       tmpl_parm = DECL_ARGUMENTS (subst_decl);
17337       spec_parm = DECL_ARGUMENTS (d);
17338       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
17339         {
17340           register_local_specialization (spec_parm, tmpl_parm);
17341           spec_parm = skip_artificial_parms_for (d, spec_parm);
17342           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
17343         }
17344       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
17345         {
17346           register_local_specialization (spec_parm, tmpl_parm);
17347           tmpl_parm = DECL_CHAIN (tmpl_parm);
17348           spec_parm = DECL_CHAIN (spec_parm);
17349         }
17350       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
17351         {
17352           /* Register the (value) argument pack as a specialization of
17353              TMPL_PARM, then move on.  */
17354           tree argpack = make_fnparm_pack (spec_parm);
17355           register_local_specialization (argpack, tmpl_parm);
17356           tmpl_parm = DECL_CHAIN (tmpl_parm);
17357           spec_parm = NULL_TREE;
17358         }
17359       gcc_assert (!spec_parm);
17360
17361       /* Substitute into the body of the function.  */
17362       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
17363                    tf_warning_or_error, tmpl,
17364                    /*integral_constant_expression_p=*/false);
17365
17366       /* Set the current input_location to the end of the function
17367          so that finish_function knows where we are.  */
17368       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
17369
17370       /* We don't need the local specializations any more.  */
17371       htab_delete (local_specializations);
17372       local_specializations = saved_local_specializations;
17373
17374       /* Finish the function.  */
17375       d = finish_function (0);
17376       expand_or_defer_fn (d);
17377     }
17378
17379   /* We're not deferring instantiation any more.  */
17380   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
17381
17382   if (need_push)
17383     pop_from_top_level ();
17384
17385 out:
17386   input_location = saved_loc;
17387   pop_deferring_access_checks ();
17388   pop_tinst_level ();
17389
17390   timevar_pop (TV_PARSE);
17391
17392   return d;
17393 }
17394
17395 /* Run through the list of templates that we wish we could
17396    instantiate, and instantiate any we can.  RETRIES is the
17397    number of times we retry pending template instantiation.  */
17398
17399 void
17400 instantiate_pending_templates (int retries)
17401 {
17402   int reconsider;
17403   location_t saved_loc = input_location;
17404
17405   /* Instantiating templates may trigger vtable generation.  This in turn
17406      may require further template instantiations.  We place a limit here
17407      to avoid infinite loop.  */
17408   if (pending_templates && retries >= max_tinst_depth)
17409     {
17410       tree decl = pending_templates->tinst->decl;
17411
17412       error ("template instantiation depth exceeds maximum of %d"
17413              " instantiating %q+D, possibly from virtual table generation"
17414              " (use -ftemplate-depth= to increase the maximum)",
17415              max_tinst_depth, decl);
17416       if (TREE_CODE (decl) == FUNCTION_DECL)
17417         /* Pretend that we defined it.  */
17418         DECL_INITIAL (decl) = error_mark_node;
17419       return;
17420     }
17421
17422   do
17423     {
17424       struct pending_template **t = &pending_templates;
17425       struct pending_template *last = NULL;
17426       reconsider = 0;
17427       while (*t)
17428         {
17429           tree instantiation = reopen_tinst_level ((*t)->tinst);
17430           bool complete = false;
17431
17432           if (TYPE_P (instantiation))
17433             {
17434               tree fn;
17435
17436               if (!COMPLETE_TYPE_P (instantiation))
17437                 {
17438                   instantiate_class_template (instantiation);
17439                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
17440                     for (fn = TYPE_METHODS (instantiation);
17441                          fn;
17442                          fn = TREE_CHAIN (fn))
17443                       if (! DECL_ARTIFICIAL (fn))
17444                         instantiate_decl (fn,
17445                                           /*defer_ok=*/0,
17446                                           /*expl_inst_class_mem_p=*/false);
17447                   if (COMPLETE_TYPE_P (instantiation))
17448                     reconsider = 1;
17449                 }
17450
17451               complete = COMPLETE_TYPE_P (instantiation);
17452             }
17453           else
17454             {
17455               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
17456                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
17457                 {
17458                   instantiation
17459                     = instantiate_decl (instantiation,
17460                                         /*defer_ok=*/0,
17461                                         /*expl_inst_class_mem_p=*/false);
17462                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
17463                     reconsider = 1;
17464                 }
17465
17466               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
17467                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
17468             }
17469
17470           if (complete)
17471             /* If INSTANTIATION has been instantiated, then we don't
17472                need to consider it again in the future.  */
17473             *t = (*t)->next;
17474           else
17475             {
17476               last = *t;
17477               t = &(*t)->next;
17478             }
17479           tinst_depth = 0;
17480           current_tinst_level = NULL;
17481         }
17482       last_pending_template = last;
17483     }
17484   while (reconsider);
17485
17486   input_location = saved_loc;
17487 }
17488
17489 /* Substitute ARGVEC into T, which is a list of initializers for
17490    either base class or a non-static data member.  The TREE_PURPOSEs
17491    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
17492    instantiate_decl.  */
17493
17494 static tree
17495 tsubst_initializer_list (tree t, tree argvec)
17496 {
17497   tree inits = NULL_TREE;
17498
17499   for (; t; t = TREE_CHAIN (t))
17500     {
17501       tree decl;
17502       tree init;
17503       tree expanded_bases = NULL_TREE;
17504       tree expanded_arguments = NULL_TREE;
17505       int i, len = 1;
17506
17507       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
17508         {
17509           tree expr;
17510           tree arg;
17511
17512           /* Expand the base class expansion type into separate base
17513              classes.  */
17514           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
17515                                                  tf_warning_or_error,
17516                                                  NULL_TREE);
17517           if (expanded_bases == error_mark_node)
17518             continue;
17519           
17520           /* We'll be building separate TREE_LISTs of arguments for
17521              each base.  */
17522           len = TREE_VEC_LENGTH (expanded_bases);
17523           expanded_arguments = make_tree_vec (len);
17524           for (i = 0; i < len; i++)
17525             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
17526
17527           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
17528              expand each argument in the TREE_VALUE of t.  */
17529           expr = make_node (EXPR_PACK_EXPANSION);
17530           PACK_EXPANSION_PARAMETER_PACKS (expr) =
17531             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
17532
17533           if (TREE_VALUE (t) == void_type_node)
17534             /* VOID_TYPE_NODE is used to indicate
17535                value-initialization.  */
17536             {
17537               for (i = 0; i < len; i++)
17538                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
17539             }
17540           else
17541             {
17542               /* Substitute parameter packs into each argument in the
17543                  TREE_LIST.  */
17544               in_base_initializer = 1;
17545               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
17546                 {
17547                   tree expanded_exprs;
17548
17549                   /* Expand the argument.  */
17550                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
17551                   expanded_exprs 
17552                     = tsubst_pack_expansion (expr, argvec,
17553                                              tf_warning_or_error,
17554                                              NULL_TREE);
17555                   if (expanded_exprs == error_mark_node)
17556                     continue;
17557
17558                   /* Prepend each of the expanded expressions to the
17559                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
17560                   for (i = 0; i < len; i++)
17561                     {
17562                       TREE_VEC_ELT (expanded_arguments, i) = 
17563                         tree_cons (NULL_TREE, 
17564                                    TREE_VEC_ELT (expanded_exprs, i),
17565                                    TREE_VEC_ELT (expanded_arguments, i));
17566                     }
17567                 }
17568               in_base_initializer = 0;
17569
17570               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
17571                  since we built them backwards.  */
17572               for (i = 0; i < len; i++)
17573                 {
17574                   TREE_VEC_ELT (expanded_arguments, i) = 
17575                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
17576                 }
17577             }
17578         }
17579
17580       for (i = 0; i < len; ++i)
17581         {
17582           if (expanded_bases)
17583             {
17584               decl = TREE_VEC_ELT (expanded_bases, i);
17585               decl = expand_member_init (decl);
17586               init = TREE_VEC_ELT (expanded_arguments, i);
17587             }
17588           else
17589             {
17590               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
17591                                   tf_warning_or_error, NULL_TREE);
17592
17593               decl = expand_member_init (decl);
17594               if (decl && !DECL_P (decl))
17595                 in_base_initializer = 1;
17596
17597               init = TREE_VALUE (t);
17598               if (init != void_type_node)
17599                 init = tsubst_expr (init, argvec,
17600                                     tf_warning_or_error, NULL_TREE,
17601                                     /*integral_constant_expression_p=*/false);
17602               in_base_initializer = 0;
17603             }
17604
17605           if (decl)
17606             {
17607               init = build_tree_list (decl, init);
17608               TREE_CHAIN (init) = inits;
17609               inits = init;
17610             }
17611         }
17612     }
17613   return inits;
17614 }
17615
17616 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
17617
17618 static void
17619 set_current_access_from_decl (tree decl)
17620 {
17621   if (TREE_PRIVATE (decl))
17622     current_access_specifier = access_private_node;
17623   else if (TREE_PROTECTED (decl))
17624     current_access_specifier = access_protected_node;
17625   else
17626     current_access_specifier = access_public_node;
17627 }
17628
17629 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
17630    is the instantiation (which should have been created with
17631    start_enum) and ARGS are the template arguments to use.  */
17632
17633 static void
17634 tsubst_enum (tree tag, tree newtag, tree args)
17635 {
17636   tree e;
17637
17638   if (SCOPED_ENUM_P (newtag))
17639     begin_scope (sk_scoped_enum, newtag);
17640
17641   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
17642     {
17643       tree value;
17644       tree decl;
17645
17646       decl = TREE_VALUE (e);
17647       /* Note that in a template enum, the TREE_VALUE is the
17648          CONST_DECL, not the corresponding INTEGER_CST.  */
17649       value = tsubst_expr (DECL_INITIAL (decl),
17650                            args, tf_warning_or_error, NULL_TREE,
17651                            /*integral_constant_expression_p=*/true);
17652
17653       /* Give this enumeration constant the correct access.  */
17654       set_current_access_from_decl (decl);
17655
17656       /* Actually build the enumerator itself.  */
17657       build_enumerator
17658         (DECL_NAME (decl), value, newtag, DECL_SOURCE_LOCATION (decl));
17659     }
17660
17661   if (SCOPED_ENUM_P (newtag))
17662     finish_scope ();
17663
17664   finish_enum_value_list (newtag);
17665   finish_enum (newtag);
17666
17667   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
17668     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
17669 }
17670
17671 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
17672    its type -- but without substituting the innermost set of template
17673    arguments.  So, innermost set of template parameters will appear in
17674    the type.  */
17675
17676 tree
17677 get_mostly_instantiated_function_type (tree decl)
17678 {
17679   tree fn_type;
17680   tree tmpl;
17681   tree targs;
17682   tree tparms;
17683   int parm_depth;
17684
17685   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
17686   targs = DECL_TI_ARGS (decl);
17687   tparms = DECL_TEMPLATE_PARMS (tmpl);
17688   parm_depth = TMPL_PARMS_DEPTH (tparms);
17689
17690   /* There should be as many levels of arguments as there are levels
17691      of parameters.  */
17692   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
17693
17694   fn_type = TREE_TYPE (tmpl);
17695
17696   if (parm_depth == 1)
17697     /* No substitution is necessary.  */
17698     ;
17699   else
17700     {
17701       int i, save_access_control;
17702       tree partial_args;
17703
17704       /* Replace the innermost level of the TARGS with NULL_TREEs to
17705          let tsubst know not to substitute for those parameters.  */
17706       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
17707       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
17708         SET_TMPL_ARGS_LEVEL (partial_args, i,
17709                              TMPL_ARGS_LEVEL (targs, i));
17710       SET_TMPL_ARGS_LEVEL (partial_args,
17711                            TMPL_ARGS_DEPTH (targs),
17712                            make_tree_vec (DECL_NTPARMS (tmpl)));
17713
17714       /* Disable access control as this function is used only during
17715          name-mangling.  */
17716       save_access_control = flag_access_control;
17717       flag_access_control = 0;
17718
17719       ++processing_template_decl;
17720       /* Now, do the (partial) substitution to figure out the
17721          appropriate function type.  */
17722       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
17723       --processing_template_decl;
17724
17725       /* Substitute into the template parameters to obtain the real
17726          innermost set of parameters.  This step is important if the
17727          innermost set of template parameters contains value
17728          parameters whose types depend on outer template parameters.  */
17729       TREE_VEC_LENGTH (partial_args)--;
17730       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
17731
17732       flag_access_control = save_access_control;
17733     }
17734
17735   return fn_type;
17736 }
17737
17738 /* Return truthvalue if we're processing a template different from
17739    the last one involved in diagnostics.  */
17740 int
17741 problematic_instantiation_changed (void)
17742 {
17743   return last_template_error_tick != tinst_level_tick;
17744 }
17745
17746 /* Remember current template involved in diagnostics.  */
17747 void
17748 record_last_problematic_instantiation (void)
17749 {
17750   last_template_error_tick = tinst_level_tick;
17751 }
17752
17753 struct tinst_level *
17754 current_instantiation (void)
17755 {
17756   return current_tinst_level;
17757 }
17758
17759 /* [temp.param] Check that template non-type parm TYPE is of an allowable
17760    type. Return zero for ok, nonzero for disallowed. Issue error and
17761    warning messages under control of COMPLAIN.  */
17762
17763 static int
17764 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
17765 {
17766   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
17767     return 0;
17768   else if (POINTER_TYPE_P (type))
17769     return 0;
17770   else if (TYPE_PTR_TO_MEMBER_P (type))
17771     return 0;
17772   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
17773     return 0;
17774   else if (TREE_CODE (type) == TYPENAME_TYPE)
17775     return 0;
17776
17777   if (complain & tf_error)
17778     error ("%q#T is not a valid type for a template constant parameter", type);
17779   return 1;
17780 }
17781
17782 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
17783    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
17784
17785 static bool
17786 dependent_type_p_r (tree type)
17787 {
17788   tree scope;
17789
17790   /* [temp.dep.type]
17791
17792      A type is dependent if it is:
17793
17794      -- a template parameter. Template template parameters are types
17795         for us (since TYPE_P holds true for them) so we handle
17796         them here.  */
17797   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17798       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
17799     return true;
17800   /* -- a qualified-id with a nested-name-specifier which contains a
17801         class-name that names a dependent type or whose unqualified-id
17802         names a dependent type.  */
17803   if (TREE_CODE (type) == TYPENAME_TYPE)
17804     return true;
17805   /* -- a cv-qualified type where the cv-unqualified type is
17806         dependent.  */
17807   type = TYPE_MAIN_VARIANT (type);
17808   /* -- a compound type constructed from any dependent type.  */
17809   if (TYPE_PTR_TO_MEMBER_P (type))
17810     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
17811             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
17812                                            (type)));
17813   else if (TREE_CODE (type) == POINTER_TYPE
17814            || TREE_CODE (type) == REFERENCE_TYPE)
17815     return dependent_type_p (TREE_TYPE (type));
17816   else if (TREE_CODE (type) == FUNCTION_TYPE
17817            || TREE_CODE (type) == METHOD_TYPE)
17818     {
17819       tree arg_type;
17820
17821       if (dependent_type_p (TREE_TYPE (type)))
17822         return true;
17823       for (arg_type = TYPE_ARG_TYPES (type);
17824            arg_type;
17825            arg_type = TREE_CHAIN (arg_type))
17826         if (dependent_type_p (TREE_VALUE (arg_type)))
17827           return true;
17828       return false;
17829     }
17830   /* -- an array type constructed from any dependent type or whose
17831         size is specified by a constant expression that is
17832         value-dependent.
17833
17834         We checked for type- and value-dependence of the bounds in
17835         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
17836   if (TREE_CODE (type) == ARRAY_TYPE)
17837     {
17838       if (TYPE_DOMAIN (type)
17839           && dependent_type_p (TYPE_DOMAIN (type)))
17840         return true;
17841       return dependent_type_p (TREE_TYPE (type));
17842     }
17843
17844   /* -- a template-id in which either the template name is a template
17845      parameter ...  */
17846   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
17847     return true;
17848   /* ... or any of the template arguments is a dependent type or
17849         an expression that is type-dependent or value-dependent.  */
17850   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
17851            && (any_dependent_template_arguments_p
17852                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
17853     return true;
17854
17855   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
17856      argument of the `typeof' expression is not type-dependent, then
17857      it should already been have resolved.  */
17858   if (TREE_CODE (type) == TYPEOF_TYPE
17859       || TREE_CODE (type) == DECLTYPE_TYPE)
17860     return true;
17861
17862   /* A template argument pack is dependent if any of its packed
17863      arguments are.  */
17864   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
17865     {
17866       tree args = ARGUMENT_PACK_ARGS (type);
17867       int i, len = TREE_VEC_LENGTH (args);
17868       for (i = 0; i < len; ++i)
17869         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17870           return true;
17871     }
17872
17873   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
17874      be template parameters.  */
17875   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
17876     return true;
17877
17878   /* The standard does not specifically mention types that are local
17879      to template functions or local classes, but they should be
17880      considered dependent too.  For example:
17881
17882        template <int I> void f() {
17883          enum E { a = I };
17884          S<sizeof (E)> s;
17885        }
17886
17887      The size of `E' cannot be known until the value of `I' has been
17888      determined.  Therefore, `E' must be considered dependent.  */
17889   scope = TYPE_CONTEXT (type);
17890   if (scope && TYPE_P (scope))
17891     return dependent_type_p (scope);
17892   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
17893     return type_dependent_expression_p (scope);
17894
17895   /* Other types are non-dependent.  */
17896   return false;
17897 }
17898
17899 /* Returns TRUE if TYPE is dependent, in the sense of
17900    [temp.dep.type].  */
17901
17902 bool
17903 dependent_type_p (tree type)
17904 {
17905   /* If there are no template parameters in scope, then there can't be
17906      any dependent types.  */
17907   if (!processing_template_decl)
17908     {
17909       /* If we are not processing a template, then nobody should be
17910          providing us with a dependent type.  */
17911       gcc_assert (type);
17912       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
17913       return false;
17914     }
17915
17916   /* If the type is NULL, we have not computed a type for the entity
17917      in question; in that case, the type is dependent.  */
17918   if (!type)
17919     return true;
17920
17921   /* Erroneous types can be considered non-dependent.  */
17922   if (type == error_mark_node)
17923     return false;
17924
17925   /* If we have not already computed the appropriate value for TYPE,
17926      do so now.  */
17927   if (!TYPE_DEPENDENT_P_VALID (type))
17928     {
17929       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
17930       TYPE_DEPENDENT_P_VALID (type) = 1;
17931     }
17932
17933   return TYPE_DEPENDENT_P (type);
17934 }
17935
17936 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
17937    lookup.  In other words, a dependent type that is not the current
17938    instantiation.  */
17939
17940 bool
17941 dependent_scope_p (tree scope)
17942 {
17943   return (scope && TYPE_P (scope) && dependent_type_p (scope)
17944           && !currently_open_class (scope));
17945 }
17946
17947 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
17948    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
17949    expression.  */
17950
17951 /* FIXME this predicate is not appropriate for general expressions; the
17952    predicates we want instead are "valid constant expression, value
17953    dependent or not?", "really constant expression, not value dependent?"
17954    and "instantiation-dependent?".  Try to integrate with
17955    potential_constant_expression?
17956
17957    fold_non_dependent_expr: fold if constant and not type-dependent and not value-dependent.
17958      (what about instantiation-dependent constant-expressions?)
17959    is_late_template_attribute: defer if instantiation-dependent.
17960    compute_array_index_type: proceed if constant and not t- or v-dependent
17961      if instantiation-dependent, need to remember full expression
17962    uses_template_parms: FIXME - need to audit callers
17963    tsubst_decl [function_decl]: Why is this using value_dependent_expression_p?
17964    dependent_type_p [array_type]: dependent if index type is dependent
17965      (or non-constant?)
17966    static_assert - instantiation-dependent */
17967
17968 bool
17969 value_dependent_expression_p (tree expression)
17970 {
17971   if (!processing_template_decl)
17972     return false;
17973
17974   /* A name declared with a dependent type.  */
17975   if (DECL_P (expression) && type_dependent_expression_p (expression))
17976     return true;
17977
17978   switch (TREE_CODE (expression))
17979     {
17980     case IDENTIFIER_NODE:
17981       /* A name that has not been looked up -- must be dependent.  */
17982       return true;
17983
17984     case TEMPLATE_PARM_INDEX:
17985       /* A non-type template parm.  */
17986       return true;
17987
17988     case CONST_DECL:
17989       /* A non-type template parm.  */
17990       if (DECL_TEMPLATE_PARM_P (expression))
17991         return true;
17992       return value_dependent_expression_p (DECL_INITIAL (expression));
17993
17994     case VAR_DECL:
17995        /* A constant with integral or enumeration type and is initialized
17996           with an expression that is value-dependent.  */
17997       if (DECL_INITIAL (expression)
17998           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
17999           && value_dependent_expression_p (DECL_INITIAL (expression)))
18000         return true;
18001       return false;
18002
18003     case DYNAMIC_CAST_EXPR:
18004     case STATIC_CAST_EXPR:
18005     case CONST_CAST_EXPR:
18006     case REINTERPRET_CAST_EXPR:
18007     case CAST_EXPR:
18008       /* These expressions are value-dependent if the type to which
18009          the cast occurs is dependent or the expression being casted
18010          is value-dependent.  */
18011       {
18012         tree type = TREE_TYPE (expression);
18013
18014         if (dependent_type_p (type))
18015           return true;
18016
18017         /* A functional cast has a list of operands.  */
18018         expression = TREE_OPERAND (expression, 0);
18019         if (!expression)
18020           {
18021             /* If there are no operands, it must be an expression such
18022                as "int()". This should not happen for aggregate types
18023                because it would form non-constant expressions.  */
18024             gcc_assert (cxx_dialect >= cxx0x
18025                         || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
18026
18027             return false;
18028           }
18029
18030         if (TREE_CODE (expression) == TREE_LIST)
18031           return any_value_dependent_elements_p (expression);
18032
18033         return value_dependent_expression_p (expression);
18034       }
18035
18036     case SIZEOF_EXPR:
18037     case ALIGNOF_EXPR:
18038       /* A `sizeof' expression is value-dependent if the operand is
18039          type-dependent or is a pack expansion.  */
18040       expression = TREE_OPERAND (expression, 0);
18041       if (PACK_EXPANSION_P (expression))
18042         return true;
18043       else if (TYPE_P (expression))
18044         return dependent_type_p (expression);
18045       return type_dependent_expression_p (expression);
18046
18047     case AT_ENCODE_EXPR:
18048       /* An 'encode' expression is value-dependent if the operand is
18049          type-dependent.  */
18050       expression = TREE_OPERAND (expression, 0);
18051       return dependent_type_p (expression);
18052
18053     case NOEXCEPT_EXPR:
18054       expression = TREE_OPERAND (expression, 0);
18055       /* FIXME why check value-dependency?  */
18056       return (type_dependent_expression_p (expression)
18057               || value_dependent_expression_p (expression));
18058
18059     case SCOPE_REF:
18060       {
18061         tree name = TREE_OPERAND (expression, 1);
18062         return value_dependent_expression_p (name);
18063       }
18064
18065     case COMPONENT_REF:
18066       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
18067               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
18068
18069     case NONTYPE_ARGUMENT_PACK:
18070       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
18071          is value-dependent.  */
18072       {
18073         tree values = ARGUMENT_PACK_ARGS (expression);
18074         int i, len = TREE_VEC_LENGTH (values);
18075         
18076         for (i = 0; i < len; ++i)
18077           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
18078             return true;
18079         
18080         return false;
18081       }
18082
18083     case TRAIT_EXPR:
18084       {
18085         tree type2 = TRAIT_EXPR_TYPE2 (expression);
18086         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
18087                 || (type2 ? dependent_type_p (type2) : false));
18088       }
18089
18090     case MODOP_EXPR:
18091       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
18092               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
18093
18094     case ADDR_EXPR:
18095       {
18096         tree op = TREE_OPERAND (expression, 0);
18097         return (value_dependent_expression_p (op)
18098                 || has_value_dependent_address (op));
18099       }
18100
18101     case CALL_EXPR:
18102       {
18103         tree fn = get_callee_fndecl (expression);
18104         int i, nargs;
18105         if (!fn && value_dependent_expression_p (CALL_EXPR_FN (expression)))
18106           return true;
18107         nargs = call_expr_nargs (expression);
18108         for (i = 0; i < nargs; ++i)
18109           {
18110             tree op = CALL_EXPR_ARG (expression, i);
18111             /* In a call to a constexpr member function, look through the
18112                implicit ADDR_EXPR on the object argument so that it doesn't
18113                cause the call to be considered value-dependent.  We also
18114                look through it in potential_constant_expression.  */
18115             if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
18116                 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
18117                 && TREE_CODE (op) == ADDR_EXPR)
18118               op = TREE_OPERAND (op, 0);
18119             if (value_dependent_expression_p (op))
18120               return true;
18121           }
18122         return false;
18123       }
18124
18125     default:
18126       /* A constant expression is value-dependent if any subexpression is
18127          value-dependent.  */
18128       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
18129         {
18130         case tcc_reference:
18131         case tcc_unary:
18132           return (value_dependent_expression_p
18133                   (TREE_OPERAND (expression, 0)));
18134
18135         case tcc_comparison:
18136         case tcc_binary:
18137           return ((value_dependent_expression_p
18138                    (TREE_OPERAND (expression, 0)))
18139                   || (value_dependent_expression_p
18140                       (TREE_OPERAND (expression, 1))));
18141
18142         case tcc_expression:
18143         case tcc_vl_exp:
18144           {
18145             int i;
18146             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
18147               /* In some cases, some of the operands may be missing.
18148                  (For example, in the case of PREDECREMENT_EXPR, the
18149                  amount to increment by may be missing.)  That doesn't
18150                  make the expression dependent.  */
18151               if (TREE_OPERAND (expression, i)
18152                   && (value_dependent_expression_p
18153                       (TREE_OPERAND (expression, i))))
18154                 return true;
18155             return false;
18156           }
18157
18158         default:
18159           break;
18160         }
18161     }
18162
18163   /* The expression is not value-dependent.  */
18164   return false;
18165 }
18166
18167 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
18168    [temp.dep.expr].  */
18169
18170 bool
18171 type_dependent_expression_p (tree expression)
18172 {
18173   if (!processing_template_decl)
18174     return false;
18175
18176   if (expression == error_mark_node)
18177     return false;
18178
18179   /* An unresolved name is always dependent.  */
18180   if (TREE_CODE (expression) == IDENTIFIER_NODE
18181       || TREE_CODE (expression) == USING_DECL)
18182     return true;
18183
18184   /* Some expression forms are never type-dependent.  */
18185   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
18186       || TREE_CODE (expression) == SIZEOF_EXPR
18187       || TREE_CODE (expression) == ALIGNOF_EXPR
18188       || TREE_CODE (expression) == AT_ENCODE_EXPR
18189       || TREE_CODE (expression) == NOEXCEPT_EXPR
18190       || TREE_CODE (expression) == TRAIT_EXPR
18191       || TREE_CODE (expression) == TYPEID_EXPR
18192       || TREE_CODE (expression) == DELETE_EXPR
18193       || TREE_CODE (expression) == VEC_DELETE_EXPR
18194       || TREE_CODE (expression) == THROW_EXPR)
18195     return false;
18196
18197   /* The types of these expressions depends only on the type to which
18198      the cast occurs.  */
18199   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
18200       || TREE_CODE (expression) == STATIC_CAST_EXPR
18201       || TREE_CODE (expression) == CONST_CAST_EXPR
18202       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
18203       || TREE_CODE (expression) == CAST_EXPR)
18204     return dependent_type_p (TREE_TYPE (expression));
18205
18206   /* The types of these expressions depends only on the type created
18207      by the expression.  */
18208   if (TREE_CODE (expression) == NEW_EXPR
18209       || TREE_CODE (expression) == VEC_NEW_EXPR)
18210     {
18211       /* For NEW_EXPR tree nodes created inside a template, either
18212          the object type itself or a TREE_LIST may appear as the
18213          operand 1.  */
18214       tree type = TREE_OPERAND (expression, 1);
18215       if (TREE_CODE (type) == TREE_LIST)
18216         /* This is an array type.  We need to check array dimensions
18217            as well.  */
18218         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
18219                || value_dependent_expression_p
18220                     (TREE_OPERAND (TREE_VALUE (type), 1));
18221       else
18222         return dependent_type_p (type);
18223     }
18224
18225   if (TREE_CODE (expression) == SCOPE_REF)
18226     {
18227       tree scope = TREE_OPERAND (expression, 0);
18228       tree name = TREE_OPERAND (expression, 1);
18229
18230       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
18231          contains an identifier associated by name lookup with one or more
18232          declarations declared with a dependent type, or...a
18233          nested-name-specifier or qualified-id that names a member of an
18234          unknown specialization.  */
18235       return (type_dependent_expression_p (name)
18236               || dependent_scope_p (scope));
18237     }
18238
18239   if (TREE_CODE (expression) == FUNCTION_DECL
18240       && DECL_LANG_SPECIFIC (expression)
18241       && DECL_TEMPLATE_INFO (expression)
18242       && (any_dependent_template_arguments_p
18243           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
18244     return true;
18245
18246   if (TREE_CODE (expression) == TEMPLATE_DECL
18247       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
18248     return false;
18249
18250   if (TREE_CODE (expression) == STMT_EXPR)
18251     expression = stmt_expr_value_expr (expression);
18252
18253   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
18254     {
18255       tree elt;
18256       unsigned i;
18257
18258       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
18259         {
18260           if (type_dependent_expression_p (elt))
18261             return true;
18262         }
18263       return false;
18264     }
18265
18266   /* A static data member of the current instantiation with incomplete
18267      array type is type-dependent, as the definition and specializations
18268      can have different bounds.  */
18269   if (TREE_CODE (expression) == VAR_DECL
18270       && DECL_CLASS_SCOPE_P (expression)
18271       && dependent_type_p (DECL_CONTEXT (expression))
18272       && VAR_HAD_UNKNOWN_BOUND (expression))
18273     return true;
18274
18275   if (TREE_TYPE (expression) == unknown_type_node)
18276     {
18277       if (TREE_CODE (expression) == ADDR_EXPR)
18278         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
18279       if (TREE_CODE (expression) == COMPONENT_REF
18280           || TREE_CODE (expression) == OFFSET_REF)
18281         {
18282           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
18283             return true;
18284           expression = TREE_OPERAND (expression, 1);
18285           if (TREE_CODE (expression) == IDENTIFIER_NODE)
18286             return false;
18287         }
18288       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
18289       if (TREE_CODE (expression) == SCOPE_REF)
18290         return false;
18291
18292       if (TREE_CODE (expression) == BASELINK)
18293         expression = BASELINK_FUNCTIONS (expression);
18294
18295       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
18296         {
18297           if (any_dependent_template_arguments_p
18298               (TREE_OPERAND (expression, 1)))
18299             return true;
18300           expression = TREE_OPERAND (expression, 0);
18301         }
18302       gcc_assert (TREE_CODE (expression) == OVERLOAD
18303                   || TREE_CODE (expression) == FUNCTION_DECL);
18304
18305       while (expression)
18306         {
18307           if (type_dependent_expression_p (OVL_CURRENT (expression)))
18308             return true;
18309           expression = OVL_NEXT (expression);
18310         }
18311       return false;
18312     }
18313
18314   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
18315
18316   return (dependent_type_p (TREE_TYPE (expression)));
18317 }
18318
18319 /* Like type_dependent_expression_p, but it also works while not processing
18320    a template definition, i.e. during substitution or mangling.  */
18321
18322 bool
18323 type_dependent_expression_p_push (tree expr)
18324 {
18325   bool b;
18326   ++processing_template_decl;
18327   b = type_dependent_expression_p (expr);
18328   --processing_template_decl;
18329   return b;
18330 }
18331
18332 /* Returns TRUE if ARGS contains a type-dependent expression.  */
18333
18334 bool
18335 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
18336 {
18337   unsigned int i;
18338   tree arg;
18339
18340   FOR_EACH_VEC_ELT (tree, args, i, arg)
18341     {
18342       if (type_dependent_expression_p (arg))
18343         return true;
18344     }
18345   return false;
18346 }
18347
18348 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
18349    expressions) contains any value-dependent expressions.  */
18350
18351 bool
18352 any_value_dependent_elements_p (const_tree list)
18353 {
18354   for (; list; list = TREE_CHAIN (list))
18355     if (value_dependent_expression_p (TREE_VALUE (list)))
18356       return true;
18357
18358   return false;
18359 }
18360
18361 /* Returns TRUE if the ARG (a template argument) is dependent.  */
18362
18363 bool
18364 dependent_template_arg_p (tree arg)
18365 {
18366   if (!processing_template_decl)
18367     return false;
18368
18369   /* Assume a template argument that was wrongly written by the user
18370      is dependent. This is consistent with what
18371      any_dependent_template_arguments_p [that calls this function]
18372      does.  */
18373   if (arg == error_mark_node)
18374     return true;
18375
18376   if (TREE_CODE (arg) == TEMPLATE_DECL
18377       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
18378     return dependent_template_p (arg);
18379   else if (ARGUMENT_PACK_P (arg))
18380     {
18381       tree args = ARGUMENT_PACK_ARGS (arg);
18382       int i, len = TREE_VEC_LENGTH (args);
18383       for (i = 0; i < len; ++i)
18384         {
18385           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
18386             return true;
18387         }
18388
18389       return false;
18390     }
18391   else if (TYPE_P (arg))
18392     return dependent_type_p (arg);
18393   else
18394     return (type_dependent_expression_p (arg)
18395             || value_dependent_expression_p (arg));
18396 }
18397
18398 /* Returns true if ARGS (a collection of template arguments) contains
18399    any types that require structural equality testing.  */
18400
18401 bool
18402 any_template_arguments_need_structural_equality_p (tree args)
18403 {
18404   int i;
18405   int j;
18406
18407   if (!args)
18408     return false;
18409   if (args == error_mark_node)
18410     return true;
18411
18412   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
18413     {
18414       tree level = TMPL_ARGS_LEVEL (args, i + 1);
18415       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
18416         {
18417           tree arg = TREE_VEC_ELT (level, j);
18418           tree packed_args = NULL_TREE;
18419           int k, len = 1;
18420
18421           if (ARGUMENT_PACK_P (arg))
18422             {
18423               /* Look inside the argument pack.  */
18424               packed_args = ARGUMENT_PACK_ARGS (arg);
18425               len = TREE_VEC_LENGTH (packed_args);
18426             }
18427
18428           for (k = 0; k < len; ++k)
18429             {
18430               if (packed_args)
18431                 arg = TREE_VEC_ELT (packed_args, k);
18432
18433               if (error_operand_p (arg))
18434                 return true;
18435               else if (TREE_CODE (arg) == TEMPLATE_DECL
18436                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
18437                 continue;
18438               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
18439                 return true;
18440               else if (!TYPE_P (arg) && TREE_TYPE (arg)
18441                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
18442                 return true;
18443             }
18444         }
18445     }
18446
18447   return false;
18448 }
18449
18450 /* Returns true if ARGS (a collection of template arguments) contains
18451    any dependent arguments.  */
18452
18453 bool
18454 any_dependent_template_arguments_p (const_tree args)
18455 {
18456   int i;
18457   int j;
18458
18459   if (!args)
18460     return false;
18461   if (args == error_mark_node)
18462     return true;
18463
18464   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
18465     {
18466       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
18467       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
18468         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
18469           return true;
18470     }
18471
18472   return false;
18473 }
18474
18475 /* Returns TRUE if the template TMPL is dependent.  */
18476
18477 bool
18478 dependent_template_p (tree tmpl)
18479 {
18480   if (TREE_CODE (tmpl) == OVERLOAD)
18481     {
18482       while (tmpl)
18483         {
18484           if (dependent_template_p (OVL_FUNCTION (tmpl)))
18485             return true;
18486           tmpl = OVL_CHAIN (tmpl);
18487         }
18488       return false;
18489     }
18490
18491   /* Template template parameters are dependent.  */
18492   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
18493       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
18494     return true;
18495   /* So are names that have not been looked up.  */
18496   if (TREE_CODE (tmpl) == SCOPE_REF
18497       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
18498     return true;
18499   /* So are member templates of dependent classes.  */
18500   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
18501     return dependent_type_p (DECL_CONTEXT (tmpl));
18502   return false;
18503 }
18504
18505 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
18506
18507 bool
18508 dependent_template_id_p (tree tmpl, tree args)
18509 {
18510   return (dependent_template_p (tmpl)
18511           || any_dependent_template_arguments_p (args));
18512 }
18513
18514 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
18515    is dependent.  */
18516
18517 bool
18518 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
18519 {
18520   int i;
18521
18522   if (!processing_template_decl)
18523     return false;
18524
18525   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
18526     {
18527       tree decl = TREE_VEC_ELT (declv, i);
18528       tree init = TREE_VEC_ELT (initv, i);
18529       tree cond = TREE_VEC_ELT (condv, i);
18530       tree incr = TREE_VEC_ELT (incrv, i);
18531
18532       if (type_dependent_expression_p (decl))
18533         return true;
18534
18535       if (init && type_dependent_expression_p (init))
18536         return true;
18537
18538       if (type_dependent_expression_p (cond))
18539         return true;
18540
18541       if (COMPARISON_CLASS_P (cond)
18542           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
18543               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
18544         return true;
18545
18546       if (TREE_CODE (incr) == MODOP_EXPR)
18547         {
18548           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
18549               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
18550             return true;
18551         }
18552       else if (type_dependent_expression_p (incr))
18553         return true;
18554       else if (TREE_CODE (incr) == MODIFY_EXPR)
18555         {
18556           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
18557             return true;
18558           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
18559             {
18560               tree t = TREE_OPERAND (incr, 1);
18561               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
18562                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
18563                 return true;
18564             }
18565         }
18566     }
18567
18568   return false;
18569 }
18570
18571 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
18572    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
18573    no such TYPE can be found.  Note that this function peers inside
18574    uninstantiated templates and therefore should be used only in
18575    extremely limited situations.  ONLY_CURRENT_P restricts this
18576    peering to the currently open classes hierarchy (which is required
18577    when comparing types).  */
18578
18579 tree
18580 resolve_typename_type (tree type, bool only_current_p)
18581 {
18582   tree scope;
18583   tree name;
18584   tree decl;
18585   int quals;
18586   tree pushed_scope;
18587   tree result;
18588
18589   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
18590
18591   scope = TYPE_CONTEXT (type);
18592   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
18593      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
18594      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
18595      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
18596      identifier  of the TYPENAME_TYPE anymore.
18597      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
18598      TYPENAME_TYPE instead, we avoid messing up with a possible
18599      typedef variant case.  */
18600   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
18601
18602   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
18603      it first before we can figure out what NAME refers to.  */
18604   if (TREE_CODE (scope) == TYPENAME_TYPE)
18605     scope = resolve_typename_type (scope, only_current_p);
18606   /* If we don't know what SCOPE refers to, then we cannot resolve the
18607      TYPENAME_TYPE.  */
18608   if (TREE_CODE (scope) == TYPENAME_TYPE)
18609     return type;
18610   /* If the SCOPE is a template type parameter, we have no way of
18611      resolving the name.  */
18612   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
18613     return type;
18614   /* If the SCOPE is not the current instantiation, there's no reason
18615      to look inside it.  */
18616   if (only_current_p && !currently_open_class (scope))
18617     return type;
18618   /* If this is a typedef, we don't want to look inside (c++/11987).  */
18619   if (typedef_variant_p (type))
18620     return type;
18621   /* If SCOPE isn't the template itself, it will not have a valid
18622      TYPE_FIELDS list.  */
18623   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
18624     /* scope is either the template itself or a compatible instantiation
18625        like X<T>, so look up the name in the original template.  */
18626     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
18627   else
18628     /* scope is a partial instantiation, so we can't do the lookup or we
18629        will lose the template arguments.  */
18630     return type;
18631   /* Enter the SCOPE so that name lookup will be resolved as if we
18632      were in the class definition.  In particular, SCOPE will no
18633      longer be considered a dependent type.  */
18634   pushed_scope = push_scope (scope);
18635   /* Look up the declaration.  */
18636   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
18637
18638   result = NULL_TREE;
18639   
18640   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
18641      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
18642   if (!decl)
18643     /*nop*/;
18644   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
18645            && TREE_CODE (decl) == TYPE_DECL)
18646     {
18647       result = TREE_TYPE (decl);
18648       if (result == error_mark_node)
18649         result = NULL_TREE;
18650     }
18651   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
18652            && DECL_CLASS_TEMPLATE_P (decl))
18653     {
18654       tree tmpl;
18655       tree args;
18656       /* Obtain the template and the arguments.  */
18657       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
18658       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
18659       /* Instantiate the template.  */
18660       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
18661                                       /*entering_scope=*/0,
18662                                       tf_error | tf_user);
18663       if (result == error_mark_node)
18664         result = NULL_TREE;
18665     }
18666   
18667   /* Leave the SCOPE.  */
18668   if (pushed_scope)
18669     pop_scope (pushed_scope);
18670
18671   /* If we failed to resolve it, return the original typename.  */
18672   if (!result)
18673     return type;
18674   
18675   /* If lookup found a typename type, resolve that too.  */
18676   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
18677     {
18678       /* Ill-formed programs can cause infinite recursion here, so we
18679          must catch that.  */
18680       TYPENAME_IS_RESOLVING_P (type) = 1;
18681       result = resolve_typename_type (result, only_current_p);
18682       TYPENAME_IS_RESOLVING_P (type) = 0;
18683     }
18684   
18685   /* Qualify the resulting type.  */
18686   quals = cp_type_quals (type);
18687   if (quals)
18688     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
18689
18690   return result;
18691 }
18692
18693 /* EXPR is an expression which is not type-dependent.  Return a proxy
18694    for EXPR that can be used to compute the types of larger
18695    expressions containing EXPR.  */
18696
18697 tree
18698 build_non_dependent_expr (tree expr)
18699 {
18700   tree inner_expr;
18701
18702   /* Preserve null pointer constants so that the type of things like
18703      "p == 0" where "p" is a pointer can be determined.  */
18704   if (null_ptr_cst_p (expr))
18705     return expr;
18706   /* Preserve OVERLOADs; the functions must be available to resolve
18707      types.  */
18708   inner_expr = expr;
18709   if (TREE_CODE (inner_expr) == STMT_EXPR)
18710     inner_expr = stmt_expr_value_expr (inner_expr);
18711   if (TREE_CODE (inner_expr) == ADDR_EXPR)
18712     inner_expr = TREE_OPERAND (inner_expr, 0);
18713   if (TREE_CODE (inner_expr) == COMPONENT_REF)
18714     inner_expr = TREE_OPERAND (inner_expr, 1);
18715   if (is_overloaded_fn (inner_expr)
18716       || TREE_CODE (inner_expr) == OFFSET_REF)
18717     return expr;
18718   /* There is no need to return a proxy for a variable.  */
18719   if (TREE_CODE (expr) == VAR_DECL)
18720     return expr;
18721   /* Preserve string constants; conversions from string constants to
18722      "char *" are allowed, even though normally a "const char *"
18723      cannot be used to initialize a "char *".  */
18724   if (TREE_CODE (expr) == STRING_CST)
18725     return expr;
18726   /* Preserve arithmetic constants, as an optimization -- there is no
18727      reason to create a new node.  */
18728   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
18729     return expr;
18730   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
18731      There is at least one place where we want to know that a
18732      particular expression is a throw-expression: when checking a ?:
18733      expression, there are special rules if the second or third
18734      argument is a throw-expression.  */
18735   if (TREE_CODE (expr) == THROW_EXPR)
18736     return expr;
18737
18738   if (TREE_CODE (expr) == COND_EXPR)
18739     return build3 (COND_EXPR,
18740                    TREE_TYPE (expr),
18741                    TREE_OPERAND (expr, 0),
18742                    (TREE_OPERAND (expr, 1)
18743                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
18744                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
18745                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
18746   if (TREE_CODE (expr) == COMPOUND_EXPR
18747       && !COMPOUND_EXPR_OVERLOADED (expr))
18748     return build2 (COMPOUND_EXPR,
18749                    TREE_TYPE (expr),
18750                    TREE_OPERAND (expr, 0),
18751                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
18752
18753   /* If the type is unknown, it can't really be non-dependent */
18754   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
18755
18756   /* Otherwise, build a NON_DEPENDENT_EXPR.
18757
18758      REFERENCE_TYPEs are not stripped for expressions in templates
18759      because doing so would play havoc with mangling.  Consider, for
18760      example:
18761
18762        template <typename T> void f<T& g>() { g(); }
18763
18764      In the body of "f", the expression for "g" will have
18765      REFERENCE_TYPE, even though the standard says that it should
18766      not.  The reason is that we must preserve the syntactic form of
18767      the expression so that mangling (say) "f<g>" inside the body of
18768      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
18769      stripped here.  */
18770   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
18771 }
18772
18773 /* ARGS is a vector of expressions as arguments to a function call.
18774    Replace the arguments with equivalent non-dependent expressions.
18775    This modifies ARGS in place.  */
18776
18777 void
18778 make_args_non_dependent (VEC(tree,gc) *args)
18779 {
18780   unsigned int ix;
18781   tree arg;
18782
18783   FOR_EACH_VEC_ELT (tree, args, ix, arg)
18784     {
18785       tree newarg = build_non_dependent_expr (arg);
18786       if (newarg != arg)
18787         VEC_replace (tree, args, ix, newarg);
18788     }
18789 }
18790
18791 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
18792    with a level one deeper than the actual template parms.  */
18793
18794 tree
18795 make_auto (void)
18796 {
18797   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
18798   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
18799                                TYPE_DECL, get_identifier ("auto"), au);
18800   TYPE_STUB_DECL (au) = TYPE_NAME (au);
18801   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
18802     (0, processing_template_decl + 1, processing_template_decl + 1,
18803      0, TYPE_NAME (au), NULL_TREE);
18804   TYPE_CANONICAL (au) = canonical_type_parameter (au);
18805   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
18806   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
18807
18808   return au;
18809 }
18810
18811 /* Given type ARG, return std::initializer_list<ARG>.  */
18812
18813 static tree
18814 listify (tree arg)
18815 {
18816   tree std_init_list = namespace_binding
18817     (get_identifier ("initializer_list"), std_node);
18818   tree argvec;
18819   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
18820     {    
18821       error ("deducing from brace-enclosed initializer list requires "
18822              "#include <initializer_list>");
18823       return error_mark_node;
18824     }
18825   argvec = make_tree_vec (1);
18826   TREE_VEC_ELT (argvec, 0) = arg;
18827   return lookup_template_class (std_init_list, argvec, NULL_TREE,
18828                                 NULL_TREE, 0, tf_warning_or_error);
18829 }
18830
18831 /* Replace auto in TYPE with std::initializer_list<auto>.  */
18832
18833 static tree
18834 listify_autos (tree type, tree auto_node)
18835 {
18836   tree init_auto = listify (auto_node);
18837   tree argvec = make_tree_vec (1);
18838   TREE_VEC_ELT (argvec, 0) = init_auto;
18839   if (processing_template_decl)
18840     argvec = add_to_template_args (current_template_args (), argvec);
18841   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18842 }
18843
18844 /* walk_tree helper for do_auto_deduction.  */
18845
18846 static tree
18847 contains_auto_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
18848                  void *type)
18849 {
18850   /* Is this a variable with the type we're looking for?  */
18851   if (DECL_P (*tp)
18852       && TREE_TYPE (*tp) == type)
18853     return *tp;
18854   else
18855     return NULL_TREE;
18856 }
18857
18858 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
18859    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
18860
18861 tree
18862 do_auto_deduction (tree type, tree init, tree auto_node)
18863 {
18864   tree parms, tparms, targs;
18865   tree args[1];
18866   tree decl;
18867   int val;
18868
18869   /* The name of the object being declared shall not appear in the
18870      initializer expression.  */
18871   decl = cp_walk_tree_without_duplicates (&init, contains_auto_r, type);
18872   if (decl)
18873     {
18874       error ("variable %q#D with %<auto%> type used in its own "
18875              "initializer", decl);
18876       return error_mark_node;
18877     }
18878
18879   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
18880      with either a new invented type template parameter U or, if the
18881      initializer is a braced-init-list (8.5.4), with
18882      std::initializer_list<U>.  */
18883   if (BRACE_ENCLOSED_INITIALIZER_P (init))
18884     type = listify_autos (type, auto_node);
18885
18886   parms = build_tree_list (NULL_TREE, type);
18887   args[0] = init;
18888   tparms = make_tree_vec (1);
18889   targs = make_tree_vec (1);
18890   TREE_VEC_ELT (tparms, 0)
18891     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
18892   val = type_unification_real (tparms, targs, parms, args, 1, 0,
18893                                DEDUCE_CALL, LOOKUP_NORMAL);
18894   if (val > 0)
18895     {
18896       error ("unable to deduce %qT from %qE", type, init);
18897       return error_mark_node;
18898     }
18899
18900   /* If the list of declarators contains more than one declarator, the type
18901      of each declared variable is determined as described above. If the
18902      type deduced for the template parameter U is not the same in each
18903      deduction, the program is ill-formed.  */
18904   if (TREE_TYPE (auto_node)
18905       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
18906     {
18907       error ("inconsistent deduction for %qT: %qT and then %qT",
18908              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
18909       return error_mark_node;
18910     }
18911   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
18912
18913   if (processing_template_decl)
18914     targs = add_to_template_args (current_template_args (), targs);
18915   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
18916 }
18917
18918 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
18919    result.  */
18920
18921 tree
18922 splice_late_return_type (tree type, tree late_return_type)
18923 {
18924   tree argvec;
18925
18926   if (late_return_type == NULL_TREE)
18927     return type;
18928   argvec = make_tree_vec (1);
18929   TREE_VEC_ELT (argvec, 0) = late_return_type;
18930   if (processing_template_decl)
18931     argvec = add_to_template_args (current_template_args (), argvec);
18932   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18933 }
18934
18935 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
18936
18937 bool
18938 is_auto (const_tree type)
18939 {
18940   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18941       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
18942     return true;
18943   else
18944     return false;
18945 }
18946
18947 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
18948    appear as a type-specifier for the declaration in question, we don't
18949    have to look through the whole type.  */
18950
18951 tree
18952 type_uses_auto (tree type)
18953 {
18954   enum tree_code code;
18955   if (is_auto (type))
18956     return type;
18957
18958   code = TREE_CODE (type);
18959
18960   if (code == POINTER_TYPE || code == REFERENCE_TYPE
18961       || code == OFFSET_TYPE || code == FUNCTION_TYPE
18962       || code == METHOD_TYPE || code == ARRAY_TYPE)
18963     return type_uses_auto (TREE_TYPE (type));
18964
18965   if (TYPE_PTRMEMFUNC_P (type))
18966     return type_uses_auto (TREE_TYPE (TREE_TYPE
18967                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
18968
18969   return NULL_TREE;
18970 }
18971
18972 /* For a given template T, return the vector of typedefs referenced
18973    in T for which access check is needed at T instantiation time.
18974    T is either  a FUNCTION_DECL or a RECORD_TYPE.
18975    Those typedefs were added to T by the function
18976    append_type_to_template_for_access_check.  */
18977
18978 VEC(qualified_typedef_usage_t,gc)*
18979 get_types_needing_access_check (tree t)
18980 {
18981   tree ti;
18982   VEC(qualified_typedef_usage_t,gc) *result = NULL;
18983
18984   if (!t || t == error_mark_node)
18985     return NULL;
18986
18987   if (!(ti = get_template_info (t)))
18988     return NULL;
18989
18990   if (CLASS_TYPE_P (t)
18991       || TREE_CODE (t) == FUNCTION_DECL)
18992     {
18993       if (!TI_TEMPLATE (ti))
18994         return NULL;
18995
18996       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
18997     }
18998
18999   return result;
19000 }
19001
19002 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
19003    tied to T. That list of typedefs will be access checked at
19004    T instantiation time.
19005    T is either a FUNCTION_DECL or a RECORD_TYPE.
19006    TYPE_DECL is a TYPE_DECL node representing a typedef.
19007    SCOPE is the scope through which TYPE_DECL is accessed.
19008    LOCATION is the location of the usage point of TYPE_DECL.
19009
19010    This function is a subroutine of
19011    append_type_to_template_for_access_check.  */
19012
19013 static void
19014 append_type_to_template_for_access_check_1 (tree t,
19015                                             tree type_decl,
19016                                             tree scope,
19017                                             location_t location)
19018 {
19019   qualified_typedef_usage_t typedef_usage;
19020   tree ti;
19021
19022   if (!t || t == error_mark_node)
19023     return;
19024
19025   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
19026                || CLASS_TYPE_P (t))
19027               && type_decl
19028               && TREE_CODE (type_decl) == TYPE_DECL
19029               && scope);
19030
19031   if (!(ti = get_template_info (t)))
19032     return;
19033
19034   gcc_assert (TI_TEMPLATE (ti));
19035
19036   typedef_usage.typedef_decl = type_decl;
19037   typedef_usage.context = scope;
19038   typedef_usage.locus = location;
19039
19040   VEC_safe_push (qualified_typedef_usage_t, gc,
19041                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
19042                  &typedef_usage);
19043 }
19044
19045 /* Append TYPE_DECL to the template TEMPL.
19046    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
19047    At TEMPL instanciation time, TYPE_DECL will be checked to see
19048    if it can be accessed through SCOPE.
19049    LOCATION is the location of the usage point of TYPE_DECL.
19050
19051    e.g. consider the following code snippet:
19052
19053      class C
19054      {
19055        typedef int myint;
19056      };
19057
19058      template<class U> struct S
19059      {
19060        C::myint mi; // <-- usage point of the typedef C::myint
19061      };
19062
19063      S<char> s;
19064
19065    At S<char> instantiation time, we need to check the access of C::myint
19066    In other words, we need to check the access of the myint typedef through
19067    the C scope. For that purpose, this function will add the myint typedef
19068    and the scope C through which its being accessed to a list of typedefs
19069    tied to the template S. That list will be walked at template instantiation
19070    time and access check performed on each typedefs it contains.
19071    Note that this particular code snippet should yield an error because
19072    myint is private to C.  */
19073
19074 void
19075 append_type_to_template_for_access_check (tree templ,
19076                                           tree type_decl,
19077                                           tree scope,
19078                                           location_t location)
19079 {
19080   qualified_typedef_usage_t *iter;
19081   int i;
19082
19083   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
19084
19085   /* Make sure we don't append the type to the template twice.  */
19086   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
19087                     get_types_needing_access_check (templ),
19088                     i, iter)
19089     if (iter->typedef_decl == type_decl && scope == iter->context)
19090       return;
19091
19092   append_type_to_template_for_access_check_1 (templ, type_decl,
19093                                               scope, location);
19094 }
19095
19096 /* Set up the hash tables for template instantiations.  */
19097
19098 void
19099 init_template_processing (void)
19100 {
19101   decl_specializations = htab_create_ggc (37,
19102                                           hash_specialization,
19103                                           eq_specializations,
19104                                           ggc_free);
19105   type_specializations = htab_create_ggc (37,
19106                                           hash_specialization,
19107                                           eq_specializations,
19108                                           ggc_free);
19109 }
19110
19111 /* Print stats about the template hash tables for -fstats.  */
19112
19113 void
19114 print_template_statistics (void)
19115 {
19116   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
19117            "%f collisions\n", (long) htab_size (decl_specializations),
19118            (long) htab_elements (decl_specializations),
19119            htab_collisions (decl_specializations));
19120   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
19121            "%f collisions\n", (long) htab_size (type_specializations),
19122            (long) htab_elements (type_specializations),
19123            htab_collisions (type_specializations));
19124 }
19125
19126 #include "gt-cp-pt.h"