OSDN Git Service

gcc/
[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
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 "obstack.h"
34 #include "tree.h"
35 #include "intl.h"
36 #include "pointer-set.h"
37 #include "flags.h"
38 #include "c-common.h"
39 #include "cp-tree.h"
40 #include "cp-objcp-common.h"
41 #include "tree-inline.h"
42 #include "decl.h"
43 #include "output.h"
44 #include "except.h"
45 #include "toplev.h"
46 #include "rtl.h"
47 #include "timevar.h"
48 #include "tree-iterator.h"
49 #include "vecprim.h"
50
51 /* The type of functions taking a tree, and some additional data, and
52    returning an int.  */
53 typedef int (*tree_fn_t) (tree, void*);
54
55 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
56    instantiations have been deferred, either because their definitions
57    were not yet available, or because we were putting off doing the work.  */
58 struct GTY (()) pending_template {
59   struct pending_template *next;
60   struct tinst_level *tinst;
61 };
62
63 static GTY(()) struct pending_template *pending_templates;
64 static GTY(()) struct pending_template *last_pending_template;
65
66 int processing_template_parmlist;
67 static int template_header_count;
68
69 static GTY(()) tree saved_trees;
70 static VEC(int,heap) *inline_parm_levels;
71
72 static GTY(()) struct tinst_level *current_tinst_level;
73
74 static GTY(()) tree saved_access_scope;
75
76 /* Live only within one (recursive) call to tsubst_expr.  We use
77    this to pass the statement expression node from the STMT_EXPR
78    to the EXPR_STMT that is its result.  */
79 static tree cur_stmt_expr;
80
81 /* A map from local variable declarations in the body of the template
82    presently being instantiated to the corresponding instantiated
83    local variables.  */
84 static htab_t local_specializations;
85
86 typedef struct GTY(()) spec_entry
87 {
88   tree tmpl;
89   tree args;
90   tree spec;
91 } spec_entry;
92
93 static GTY ((param_is (spec_entry)))
94   htab_t decl_specializations;
95
96 static GTY ((param_is (spec_entry)))
97   htab_t type_specializations;
98
99 /* Contains canonical template parameter types. The vector is indexed by
100    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
101    TREE_LIST, whose TREE_VALUEs contain the canonical template
102    parameters of various types and levels.  */
103 static GTY(()) VEC(tree,gc) *canonical_template_parms;
104
105 #define UNIFY_ALLOW_NONE 0
106 #define UNIFY_ALLOW_MORE_CV_QUAL 1
107 #define UNIFY_ALLOW_LESS_CV_QUAL 2
108 #define UNIFY_ALLOW_DERIVED 4
109 #define UNIFY_ALLOW_INTEGER 8
110 #define UNIFY_ALLOW_OUTER_LEVEL 16
111 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
112 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
113
114 static void push_access_scope (tree);
115 static void pop_access_scope (tree);
116 static bool resolve_overloaded_unification (tree, tree, tree, tree,
117                                             unification_kind_t, int);
118 static int try_one_overload (tree, tree, tree, tree, tree,
119                              unification_kind_t, int, bool);
120 static int unify (tree, tree, tree, tree, int);
121 static void add_pending_template (tree);
122 static tree reopen_tinst_level (struct tinst_level *);
123 static tree tsubst_initializer_list (tree, tree);
124 static tree get_class_bindings (tree, tree, tree);
125 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
126                                    bool, bool);
127 static void tsubst_enum (tree, tree, tree);
128 static tree add_to_template_args (tree, tree);
129 static tree add_outermost_template_args (tree, tree);
130 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
131 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
132                                              tree);
133 static int type_unification_real (tree, tree, tree, const tree *,
134                                   unsigned int, int, unification_kind_t, int);
135 static void note_template_header (int);
136 static tree convert_nontype_argument_function (tree, tree);
137 static tree convert_nontype_argument (tree, tree);
138 static tree convert_template_argument (tree, tree, tree,
139                                        tsubst_flags_t, int, tree);
140 static int for_each_template_parm (tree, tree_fn_t, void*,
141                                    struct pointer_set_t*, bool);
142 static tree expand_template_argument_pack (tree);
143 static tree build_template_parm_index (int, int, int, tree, tree);
144 static bool inline_needs_template_parms (tree);
145 static void push_inline_template_parms_recursive (tree, int);
146 static tree retrieve_local_specialization (tree);
147 static void register_local_specialization (tree, tree);
148 static hashval_t hash_specialization (const void *p);
149 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
150 static int mark_template_parm (tree, void *);
151 static int template_parm_this_level_p (tree, void *);
152 static tree tsubst_friend_function (tree, tree);
153 static tree tsubst_friend_class (tree, tree);
154 static int can_complete_type_without_circularity (tree);
155 static tree get_bindings (tree, tree, tree, bool);
156 static int template_decl_level (tree);
157 static int check_cv_quals_for_unify (int, tree, tree);
158 static void template_parm_level_and_index (tree, int*, int*);
159 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
160 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
161 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
162 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
163 static void regenerate_decl_from_template (tree, tree);
164 static tree most_specialized_class (tree, tree);
165 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
166 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
167 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
168 static bool check_specialization_scope (void);
169 static tree process_partial_specialization (tree);
170 static void set_current_access_from_decl (tree);
171 static tree get_template_base (tree, tree, tree, tree);
172 static tree try_class_unification (tree, tree, tree, tree);
173 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
174                                            tree, tree);
175 static bool template_template_parm_bindings_ok_p (tree, tree);
176 static int template_args_equal (tree, tree);
177 static void tsubst_default_arguments (tree);
178 static tree for_each_template_parm_r (tree *, int *, void *);
179 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
180 static void copy_default_args_to_explicit_spec (tree);
181 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
182 static int eq_local_specializations (const void *, const void *);
183 static bool dependent_template_arg_p (tree);
184 static bool any_template_arguments_need_structural_equality_p (tree);
185 static bool dependent_type_p_r (tree);
186 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
187 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
188 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
189 static tree tsubst_decl (tree, tree, tsubst_flags_t);
190 static void perform_typedefs_access_check (tree tmpl, tree targs);
191 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
192                                                         location_t);
193 static hashval_t iterative_hash_template_arg (tree arg, hashval_t val);
194 static tree listify (tree);
195 static tree listify_autos (tree, tree);
196
197 /* Make the current scope suitable for access checking when we are
198    processing T.  T can be FUNCTION_DECL for instantiated function
199    template, or VAR_DECL for static member variable (need by
200    instantiate_decl).  */
201
202 static void
203 push_access_scope (tree t)
204 {
205   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
206               || TREE_CODE (t) == VAR_DECL);
207
208   if (DECL_FRIEND_CONTEXT (t))
209     push_nested_class (DECL_FRIEND_CONTEXT (t));
210   else if (DECL_CLASS_SCOPE_P (t))
211     push_nested_class (DECL_CONTEXT (t));
212   else
213     push_to_top_level ();
214
215   if (TREE_CODE (t) == FUNCTION_DECL)
216     {
217       saved_access_scope = tree_cons
218         (NULL_TREE, current_function_decl, saved_access_scope);
219       current_function_decl = t;
220     }
221 }
222
223 /* Restore the scope set up by push_access_scope.  T is the node we
224    are processing.  */
225
226 static void
227 pop_access_scope (tree t)
228 {
229   if (TREE_CODE (t) == FUNCTION_DECL)
230     {
231       current_function_decl = TREE_VALUE (saved_access_scope);
232       saved_access_scope = TREE_CHAIN (saved_access_scope);
233     }
234
235   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
236     pop_nested_class ();
237   else
238     pop_from_top_level ();
239 }
240
241 /* Do any processing required when DECL (a member template
242    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
243    to DECL, unless it is a specialization, in which case the DECL
244    itself is returned.  */
245
246 tree
247 finish_member_template_decl (tree decl)
248 {
249   if (decl == error_mark_node)
250     return error_mark_node;
251
252   gcc_assert (DECL_P (decl));
253
254   if (TREE_CODE (decl) == TYPE_DECL)
255     {
256       tree type;
257
258       type = TREE_TYPE (decl);
259       if (type == error_mark_node)
260         return error_mark_node;
261       if (MAYBE_CLASS_TYPE_P (type)
262           && CLASSTYPE_TEMPLATE_INFO (type)
263           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
264         {
265           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
266           check_member_template (tmpl);
267           return tmpl;
268         }
269       return NULL_TREE;
270     }
271   else if (TREE_CODE (decl) == FIELD_DECL)
272     error ("data member %qD cannot be a member template", decl);
273   else if (DECL_TEMPLATE_INFO (decl))
274     {
275       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
276         {
277           check_member_template (DECL_TI_TEMPLATE (decl));
278           return DECL_TI_TEMPLATE (decl);
279         }
280       else
281         return decl;
282     }
283   else
284     error ("invalid member template declaration %qD", decl);
285
286   return error_mark_node;
287 }
288
289 /* Create a template info node.  */
290
291 tree
292 build_template_info (tree template_decl, tree template_args)
293 {
294   tree result = make_node (TEMPLATE_INFO);
295   TI_TEMPLATE (result) = template_decl;
296   TI_ARGS (result) = template_args;
297   return result;
298 }
299
300 /* Return the template info node corresponding to T, whatever T is.  */
301
302 tree
303 get_template_info (const_tree t)
304 {
305   tree tinfo = NULL_TREE;
306
307   if (!t || t == error_mark_node)
308     return NULL;
309
310   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
311     tinfo = DECL_TEMPLATE_INFO (t);
312
313   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
314     t = TREE_TYPE (t);
315
316   if (TAGGED_TYPE_P (t))
317     tinfo = TYPE_TEMPLATE_INFO (t);
318   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
319     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
320
321   return tinfo;
322 }
323
324 /* Returns the template nesting level of the indicated class TYPE.
325
326    For example, in:
327      template <class T>
328      struct A
329      {
330        template <class U>
331        struct B {};
332      };
333
334    A<T>::B<U> has depth two, while A<T> has depth one.
335    Both A<T>::B<int> and A<int>::B<U> have depth one, if
336    they are instantiations, not specializations.
337
338    This function is guaranteed to return 0 if passed NULL_TREE so
339    that, for example, `template_class_depth (current_class_type)' is
340    always safe.  */
341
342 int
343 template_class_depth (tree type)
344 {
345   int depth;
346
347   for (depth = 0;
348        type && TREE_CODE (type) != NAMESPACE_DECL;
349        type = (TREE_CODE (type) == FUNCTION_DECL)
350          ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
351     {
352       tree tinfo = get_template_info (type);
353
354       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
355           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
356         ++depth;
357     }
358
359   return depth;
360 }
361
362 /* Subroutine of maybe_begin_member_template_processing.
363    Returns true if processing DECL needs us to push template parms.  */
364
365 static bool
366 inline_needs_template_parms (tree decl)
367 {
368   if (! DECL_TEMPLATE_INFO (decl))
369     return false;
370
371   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
372           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
373 }
374
375 /* Subroutine of maybe_begin_member_template_processing.
376    Push the template parms in PARMS, starting from LEVELS steps into the
377    chain, and ending at the beginning, since template parms are listed
378    innermost first.  */
379
380 static void
381 push_inline_template_parms_recursive (tree parmlist, int levels)
382 {
383   tree parms = TREE_VALUE (parmlist);
384   int i;
385
386   if (levels > 1)
387     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
388
389   ++processing_template_decl;
390   current_template_parms
391     = tree_cons (size_int (processing_template_decl),
392                  parms, current_template_parms);
393   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
394
395   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
396                NULL);
397   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
398     {
399       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
400
401       if (parm == error_mark_node)
402         continue;
403
404       gcc_assert (DECL_P (parm));
405
406       switch (TREE_CODE (parm))
407         {
408         case TYPE_DECL:
409         case TEMPLATE_DECL:
410           pushdecl (parm);
411           break;
412
413         case PARM_DECL:
414           {
415             /* Make a CONST_DECL as is done in process_template_parm.
416                It is ugly that we recreate this here; the original
417                version built in process_template_parm is no longer
418                available.  */
419             tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
420                                     CONST_DECL, DECL_NAME (parm),
421                                     TREE_TYPE (parm));
422             DECL_ARTIFICIAL (decl) = 1;
423             TREE_CONSTANT (decl) = 1;
424             TREE_READONLY (decl) = 1;
425             DECL_INITIAL (decl) = DECL_INITIAL (parm);
426             SET_DECL_TEMPLATE_PARM_P (decl);
427             pushdecl (decl);
428           }
429           break;
430
431         default:
432           gcc_unreachable ();
433         }
434     }
435 }
436
437 /* Restore the template parameter context for a member template or
438    a friend template defined in a class definition.  */
439
440 void
441 maybe_begin_member_template_processing (tree decl)
442 {
443   tree parms;
444   int levels = 0;
445
446   if (inline_needs_template_parms (decl))
447     {
448       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
449       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
450
451       if (DECL_TEMPLATE_SPECIALIZATION (decl))
452         {
453           --levels;
454           parms = TREE_CHAIN (parms);
455         }
456
457       push_inline_template_parms_recursive (parms, levels);
458     }
459
460   /* Remember how many levels of template parameters we pushed so that
461      we can pop them later.  */
462   VEC_safe_push (int, heap, inline_parm_levels, levels);
463 }
464
465 /* Undo the effects of maybe_begin_member_template_processing.  */
466
467 void
468 maybe_end_member_template_processing (void)
469 {
470   int i;
471   int last;
472
473   if (VEC_length (int, inline_parm_levels) == 0)
474     return;
475
476   last = VEC_pop (int, inline_parm_levels);
477   for (i = 0; i < last; ++i)
478     {
479       --processing_template_decl;
480       current_template_parms = TREE_CHAIN (current_template_parms);
481       poplevel (0, 0, 0);
482     }
483 }
484
485 /* Return a new template argument vector which contains all of ARGS,
486    but has as its innermost set of arguments the EXTRA_ARGS.  */
487
488 static tree
489 add_to_template_args (tree args, tree extra_args)
490 {
491   tree new_args;
492   int extra_depth;
493   int i;
494   int j;
495
496   extra_depth = TMPL_ARGS_DEPTH (extra_args);
497   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
498
499   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
500     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
501
502   for (j = 1; j <= extra_depth; ++j, ++i)
503     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
504
505   return new_args;
506 }
507
508 /* Like add_to_template_args, but only the outermost ARGS are added to
509    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
510    (EXTRA_ARGS) levels are added.  This function is used to combine
511    the template arguments from a partial instantiation with the
512    template arguments used to attain the full instantiation from the
513    partial instantiation.  */
514
515 static tree
516 add_outermost_template_args (tree args, tree extra_args)
517 {
518   tree new_args;
519
520   /* If there are more levels of EXTRA_ARGS than there are ARGS,
521      something very fishy is going on.  */
522   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
523
524   /* If *all* the new arguments will be the EXTRA_ARGS, just return
525      them.  */
526   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
527     return extra_args;
528
529   /* For the moment, we make ARGS look like it contains fewer levels.  */
530   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
531
532   new_args = add_to_template_args (args, extra_args);
533
534   /* Now, we restore ARGS to its full dimensions.  */
535   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
536
537   return new_args;
538 }
539
540 /* Return the N levels of innermost template arguments from the ARGS.  */
541
542 tree
543 get_innermost_template_args (tree args, int n)
544 {
545   tree new_args;
546   int extra_levels;
547   int i;
548
549   gcc_assert (n >= 0);
550
551   /* If N is 1, just return the innermost set of template arguments.  */
552   if (n == 1)
553     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
554
555   /* If we're not removing anything, just return the arguments we were
556      given.  */
557   extra_levels = TMPL_ARGS_DEPTH (args) - n;
558   gcc_assert (extra_levels >= 0);
559   if (extra_levels == 0)
560     return args;
561
562   /* Make a new set of arguments, not containing the outer arguments.  */
563   new_args = make_tree_vec (n);
564   for (i = 1; i <= n; ++i)
565     SET_TMPL_ARGS_LEVEL (new_args, i,
566                          TMPL_ARGS_LEVEL (args, i + extra_levels));
567
568   return new_args;
569 }
570
571 /* The inverse of get_innermost_template_args: Return all but the innermost
572    EXTRA_LEVELS levels of template arguments from the ARGS.  */
573
574 static tree
575 strip_innermost_template_args (tree args, int extra_levels)
576 {
577   tree new_args;
578   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
579   int i;
580
581   gcc_assert (n >= 0);
582
583   /* If N is 1, just return the outermost set of template arguments.  */
584   if (n == 1)
585     return TMPL_ARGS_LEVEL (args, 1);
586
587   /* If we're not removing anything, just return the arguments we were
588      given.  */
589   gcc_assert (extra_levels >= 0);
590   if (extra_levels == 0)
591     return args;
592
593   /* Make a new set of arguments, not containing the inner arguments.  */
594   new_args = make_tree_vec (n);
595   for (i = 1; i <= n; ++i)
596     SET_TMPL_ARGS_LEVEL (new_args, i,
597                          TMPL_ARGS_LEVEL (args, i));
598
599   return new_args;
600 }
601
602 /* We've got a template header coming up; push to a new level for storing
603    the parms.  */
604
605 void
606 begin_template_parm_list (void)
607 {
608   /* We use a non-tag-transparent scope here, which causes pushtag to
609      put tags in this scope, rather than in the enclosing class or
610      namespace scope.  This is the right thing, since we want
611      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
612      global template class, push_template_decl handles putting the
613      TEMPLATE_DECL into top-level scope.  For a nested template class,
614      e.g.:
615
616        template <class T> struct S1 {
617          template <class T> struct S2 {};
618        };
619
620      pushtag contains special code to call pushdecl_with_scope on the
621      TEMPLATE_DECL for S2.  */
622   begin_scope (sk_template_parms, NULL);
623   ++processing_template_decl;
624   ++processing_template_parmlist;
625   note_template_header (0);
626 }
627
628 /* This routine is called when a specialization is declared.  If it is
629    invalid to declare a specialization here, an error is reported and
630    false is returned, otherwise this routine will return true.  */
631
632 static bool
633 check_specialization_scope (void)
634 {
635   tree scope = current_scope ();
636
637   /* [temp.expl.spec]
638
639      An explicit specialization shall be declared in the namespace of
640      which the template is a member, or, for member templates, in the
641      namespace of which the enclosing class or enclosing class
642      template is a member.  An explicit specialization of a member
643      function, member class or static data member of a class template
644      shall be declared in the namespace of which the class template
645      is a member.  */
646   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
647     {
648       error ("explicit specialization in non-namespace scope %qD", scope);
649       return false;
650     }
651
652   /* [temp.expl.spec]
653
654      In an explicit specialization declaration for a member of a class
655      template or a member template that appears in namespace scope,
656      the member template and some of its enclosing class templates may
657      remain unspecialized, except that the declaration shall not
658      explicitly specialize a class member template if its enclosing
659      class templates are not explicitly specialized as well.  */
660   if (current_template_parms)
661     {
662       error ("enclosing class templates are not explicitly specialized");
663       return false;
664     }
665
666   return true;
667 }
668
669 /* We've just seen template <>.  */
670
671 bool
672 begin_specialization (void)
673 {
674   begin_scope (sk_template_spec, NULL);
675   note_template_header (1);
676   return check_specialization_scope ();
677 }
678
679 /* Called at then end of processing a declaration preceded by
680    template<>.  */
681
682 void
683 end_specialization (void)
684 {
685   finish_scope ();
686   reset_specialization ();
687 }
688
689 /* Any template <>'s that we have seen thus far are not referring to a
690    function specialization.  */
691
692 void
693 reset_specialization (void)
694 {
695   processing_specialization = 0;
696   template_header_count = 0;
697 }
698
699 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
700    it was of the form template <>.  */
701
702 static void
703 note_template_header (int specialization)
704 {
705   processing_specialization = specialization;
706   template_header_count++;
707 }
708
709 /* We're beginning an explicit instantiation.  */
710
711 void
712 begin_explicit_instantiation (void)
713 {
714   gcc_assert (!processing_explicit_instantiation);
715   processing_explicit_instantiation = true;
716 }
717
718
719 void
720 end_explicit_instantiation (void)
721 {
722   gcc_assert (processing_explicit_instantiation);
723   processing_explicit_instantiation = false;
724 }
725
726 /* An explicit specialization or partial specialization TMPL is being
727    declared.  Check that the namespace in which the specialization is
728    occurring is permissible.  Returns false iff it is invalid to
729    specialize TMPL in the current namespace.  */
730
731 static bool
732 check_specialization_namespace (tree tmpl)
733 {
734   tree tpl_ns = decl_namespace_context (tmpl);
735
736   /* [tmpl.expl.spec]
737
738      An explicit specialization shall be declared in the namespace of
739      which the template is a member, or, for member templates, in the
740      namespace of which the enclosing class or enclosing class
741      template is a member.  An explicit specialization of a member
742      function, member class or static data member of a class template
743      shall be declared in the namespace of which the class template is
744      a member.  */
745   if (current_scope() != DECL_CONTEXT (tmpl)
746       && !at_namespace_scope_p ())
747     {
748       error ("specialization of %qD must appear at namespace scope", tmpl);
749       return false;
750     }
751   if (is_associated_namespace (current_namespace, tpl_ns))
752     /* Same or super-using namespace.  */
753     return true;
754   else
755     {
756       permerror (input_location, "specialization of %qD in different namespace", tmpl);
757       permerror (input_location, "  from definition of %q+#D", tmpl);
758       return false;
759     }
760 }
761
762 /* SPEC is an explicit instantiation.  Check that it is valid to
763    perform this explicit instantiation in the current namespace.  */
764
765 static void
766 check_explicit_instantiation_namespace (tree spec)
767 {
768   tree ns;
769
770   /* DR 275: An explicit instantiation shall appear in an enclosing
771      namespace of its template.  */
772   ns = decl_namespace_context (spec);
773   if (!is_ancestor (current_namespace, ns))
774     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
775                "(which does not enclose namespace %qD)",
776                spec, current_namespace, ns);
777 }
778
779 /* The TYPE is being declared.  If it is a template type, that means it
780    is a partial specialization.  Do appropriate error-checking.  */
781
782 tree
783 maybe_process_partial_specialization (tree type)
784 {
785   tree context;
786
787   if (type == error_mark_node)
788     return error_mark_node;
789
790   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
791     {
792       error ("name of class shadows template template parameter %qD",
793              TYPE_NAME (type));
794       return error_mark_node;
795     }
796
797   context = TYPE_CONTEXT (type);
798
799   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
800     {
801       /* This is for ordinary explicit specialization and partial
802          specialization of a template class such as:
803
804            template <> class C<int>;
805
806          or:
807
808            template <class T> class C<T*>;
809
810          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
811
812       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
813           && !COMPLETE_TYPE_P (type))
814         {
815           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
816           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
817           if (processing_template_decl)
818             {
819               if (push_template_decl (TYPE_MAIN_DECL (type))
820                   == error_mark_node)
821                 return error_mark_node;
822             }
823         }
824       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
825         error ("specialization of %qT after instantiation", type);
826     }
827   else if (CLASS_TYPE_P (type)
828            && !CLASSTYPE_USE_TEMPLATE (type)
829            && CLASSTYPE_TEMPLATE_INFO (type)
830            && context && CLASS_TYPE_P (context)
831            && CLASSTYPE_TEMPLATE_INFO (context))
832     {
833       /* This is for an explicit specialization of member class
834          template according to [temp.expl.spec/18]:
835
836            template <> template <class U> class C<int>::D;
837
838          The context `C<int>' must be an implicit instantiation.
839          Otherwise this is just a member class template declared
840          earlier like:
841
842            template <> class C<int> { template <class U> class D; };
843            template <> template <class U> class C<int>::D;
844
845          In the first case, `C<int>::D' is a specialization of `C<T>::D'
846          while in the second case, `C<int>::D' is a primary template
847          and `C<T>::D' may not exist.  */
848
849       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
850           && !COMPLETE_TYPE_P (type))
851         {
852           tree t;
853           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
854
855           if (current_namespace
856               != decl_namespace_context (tmpl))
857             {
858               permerror (input_location, "specializing %q#T in different namespace", type);
859               permerror (input_location, "  from definition of %q+#D", tmpl);
860             }
861
862           /* Check for invalid specialization after instantiation:
863
864                template <> template <> class C<int>::D<int>;
865                template <> template <class U> class C<int>::D;  */
866
867           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
868                t; t = TREE_CHAIN (t))
869             {
870               tree inst = TREE_VALUE (t);
871               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst))
872                 {
873                   /* We already have a full specialization of this partial
874                      instantiation.  Reassign it to the new member
875                      specialization template.  */
876                   spec_entry elt;
877                   spec_entry **slot;
878
879                   elt.tmpl = most_general_template (tmpl);
880                   elt.args = CLASSTYPE_TI_ARGS (inst);
881                   elt.spec = inst;
882
883                   htab_remove_elt (type_specializations, &elt);
884
885                   elt.tmpl = tmpl;
886                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
887
888                   slot = (spec_entry **)
889                     htab_find_slot (type_specializations, &elt, INSERT);
890                   *slot = GGC_NEW (spec_entry);
891                   **slot = elt;
892                 }
893               else if (COMPLETE_TYPE_P (inst) || TYPE_BEING_DEFINED (inst))
894                 /* But if we've had an implicit instantiation, that's a
895                    problem ([temp.expl.spec]/6).  */
896                 error ("specialization %qT after instantiation %qT",
897                        type, inst);
898             }
899
900           /* Mark TYPE as a specialization.  And as a result, we only
901              have one level of template argument for the innermost
902              class template.  */
903           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
904           CLASSTYPE_TI_ARGS (type)
905             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
906         }
907     }
908   else if (processing_specialization)
909     {
910       error ("explicit specialization of non-template %qT", type);
911       return error_mark_node;
912     }
913
914   return type;
915 }
916
917 /* Returns nonzero if we can optimize the retrieval of specializations
918    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
919    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
920
921 static inline bool
922 optimize_specialization_lookup_p (tree tmpl)
923 {
924   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
925           && DECL_CLASS_SCOPE_P (tmpl)
926           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
927              parameter.  */
928           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
929           /* The optimized lookup depends on the fact that the
930              template arguments for the member function template apply
931              purely to the containing class, which is not true if the
932              containing class is an explicit or partial
933              specialization.  */
934           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
935           && !DECL_MEMBER_TEMPLATE_P (tmpl)
936           && !DECL_CONV_FN_P (tmpl)
937           /* It is possible to have a template that is not a member
938              template and is not a member of a template class:
939
940              template <typename T>
941              struct S { friend A::f(); };
942
943              Here, the friend function is a template, but the context does
944              not have template information.  The optimized lookup relies
945              on having ARGS be the template arguments for both the class
946              and the function template.  */
947           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
948 }
949
950 /* Retrieve the specialization (in the sense of [temp.spec] - a
951    specialization is either an instantiation or an explicit
952    specialization) of TMPL for the given template ARGS.  If there is
953    no such specialization, return NULL_TREE.  The ARGS are a vector of
954    arguments, or a vector of vectors of arguments, in the case of
955    templates with more than one level of parameters.
956
957    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
958    then we search for a partial specialization matching ARGS.  This
959    parameter is ignored if TMPL is not a class template.  */
960
961 static tree
962 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
963 {
964   if (args == error_mark_node)
965     return NULL_TREE;
966
967   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
968
969   /* There should be as many levels of arguments as there are
970      levels of parameters.  */
971   gcc_assert (TMPL_ARGS_DEPTH (args)
972               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
973
974   if (optimize_specialization_lookup_p (tmpl))
975     {
976       tree class_template;
977       tree class_specialization;
978       VEC(tree,gc) *methods;
979       tree fns;
980       int idx;
981
982       /* The template arguments actually apply to the containing
983          class.  Find the class specialization with those
984          arguments.  */
985       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
986       class_specialization
987         = retrieve_specialization (class_template, args, 0);
988       if (!class_specialization)
989         return NULL_TREE;
990       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
991          for the specialization.  */
992       idx = class_method_index_for_fn (class_specialization, tmpl);
993       if (idx == -1)
994         return NULL_TREE;
995       /* Iterate through the methods with the indicated name, looking
996          for the one that has an instance of TMPL.  */
997       methods = CLASSTYPE_METHOD_VEC (class_specialization);
998       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
999         {
1000           tree fn = OVL_CURRENT (fns);
1001           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1002               /* using-declarations can add base methods to the method vec,
1003                  and we don't want those here.  */
1004               && DECL_CONTEXT (fn) == class_specialization)
1005             return fn;
1006         }
1007       return NULL_TREE;
1008     }
1009   else
1010     {
1011       spec_entry *found;
1012       spec_entry elt;
1013       htab_t specializations;
1014
1015       elt.tmpl = tmpl;
1016       elt.args = args;
1017       elt.spec = NULL_TREE;
1018
1019       if (DECL_CLASS_TEMPLATE_P (tmpl))
1020         specializations = type_specializations;
1021       else
1022         specializations = decl_specializations;
1023
1024       if (hash == 0)
1025         hash = hash_specialization (&elt);
1026       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1027       if (found)
1028         return found->spec;
1029     }
1030
1031   return NULL_TREE;
1032 }
1033
1034 /* Like retrieve_specialization, but for local declarations.  */
1035
1036 static tree
1037 retrieve_local_specialization (tree tmpl)
1038 {
1039   tree spec;
1040
1041   if (local_specializations == NULL)
1042     return NULL_TREE;
1043
1044   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1045                                      htab_hash_pointer (tmpl));
1046   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1047 }
1048
1049 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1050
1051 int
1052 is_specialization_of (tree decl, tree tmpl)
1053 {
1054   tree t;
1055
1056   if (TREE_CODE (decl) == FUNCTION_DECL)
1057     {
1058       for (t = decl;
1059            t != NULL_TREE;
1060            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1061         if (t == tmpl)
1062           return 1;
1063     }
1064   else
1065     {
1066       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1067
1068       for (t = TREE_TYPE (decl);
1069            t != NULL_TREE;
1070            t = CLASSTYPE_USE_TEMPLATE (t)
1071              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1072         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1073           return 1;
1074     }
1075
1076   return 0;
1077 }
1078
1079 /* Returns nonzero iff DECL is a specialization of friend declaration
1080    FRIEND_DECL according to [temp.friend].  */
1081
1082 bool
1083 is_specialization_of_friend (tree decl, tree friend_decl)
1084 {
1085   bool need_template = true;
1086   int template_depth;
1087
1088   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1089               || TREE_CODE (decl) == TYPE_DECL);
1090
1091   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1092      of a template class, we want to check if DECL is a specialization
1093      if this.  */
1094   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1095       && DECL_TEMPLATE_INFO (friend_decl)
1096       && !DECL_USE_TEMPLATE (friend_decl))
1097     {
1098       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1099       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1100       need_template = false;
1101     }
1102   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1103            && !PRIMARY_TEMPLATE_P (friend_decl))
1104     need_template = false;
1105
1106   /* There is nothing to do if this is not a template friend.  */
1107   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1108     return false;
1109
1110   if (is_specialization_of (decl, friend_decl))
1111     return true;
1112
1113   /* [temp.friend/6]
1114      A member of a class template may be declared to be a friend of a
1115      non-template class.  In this case, the corresponding member of
1116      every specialization of the class template is a friend of the
1117      class granting friendship.
1118
1119      For example, given a template friend declaration
1120
1121        template <class T> friend void A<T>::f();
1122
1123      the member function below is considered a friend
1124
1125        template <> struct A<int> {
1126          void f();
1127        };
1128
1129      For this type of template friend, TEMPLATE_DEPTH below will be
1130      nonzero.  To determine if DECL is a friend of FRIEND, we first
1131      check if the enclosing class is a specialization of another.  */
1132
1133   template_depth = template_class_depth (DECL_CONTEXT (friend_decl));
1134   if (template_depth
1135       && DECL_CLASS_SCOPE_P (decl)
1136       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1137                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1138     {
1139       /* Next, we check the members themselves.  In order to handle
1140          a few tricky cases, such as when FRIEND_DECL's are
1141
1142            template <class T> friend void A<T>::g(T t);
1143            template <class T> template <T t> friend void A<T>::h();
1144
1145          and DECL's are
1146
1147            void A<int>::g(int);
1148            template <int> void A<int>::h();
1149
1150          we need to figure out ARGS, the template arguments from
1151          the context of DECL.  This is required for template substitution
1152          of `T' in the function parameter of `g' and template parameter
1153          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1154
1155       tree context = DECL_CONTEXT (decl);
1156       tree args = NULL_TREE;
1157       int current_depth = 0;
1158
1159       while (current_depth < template_depth)
1160         {
1161           if (CLASSTYPE_TEMPLATE_INFO (context))
1162             {
1163               if (current_depth == 0)
1164                 args = TYPE_TI_ARGS (context);
1165               else
1166                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1167               current_depth++;
1168             }
1169           context = TYPE_CONTEXT (context);
1170         }
1171
1172       if (TREE_CODE (decl) == FUNCTION_DECL)
1173         {
1174           bool is_template;
1175           tree friend_type;
1176           tree decl_type;
1177           tree friend_args_type;
1178           tree decl_args_type;
1179
1180           /* Make sure that both DECL and FRIEND_DECL are templates or
1181              non-templates.  */
1182           is_template = DECL_TEMPLATE_INFO (decl)
1183                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1184           if (need_template ^ is_template)
1185             return false;
1186           else if (is_template)
1187             {
1188               /* If both are templates, check template parameter list.  */
1189               tree friend_parms
1190                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1191                                          args, tf_none);
1192               if (!comp_template_parms
1193                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1194                       friend_parms))
1195                 return false;
1196
1197               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1198             }
1199           else
1200             decl_type = TREE_TYPE (decl);
1201
1202           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1203                                               tf_none, NULL_TREE);
1204           if (friend_type == error_mark_node)
1205             return false;
1206
1207           /* Check if return types match.  */
1208           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1209             return false;
1210
1211           /* Check if function parameter types match, ignoring the
1212              `this' parameter.  */
1213           friend_args_type = TYPE_ARG_TYPES (friend_type);
1214           decl_args_type = TYPE_ARG_TYPES (decl_type);
1215           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1216             friend_args_type = TREE_CHAIN (friend_args_type);
1217           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1218             decl_args_type = TREE_CHAIN (decl_args_type);
1219
1220           return compparms (decl_args_type, friend_args_type);
1221         }
1222       else
1223         {
1224           /* DECL is a TYPE_DECL */
1225           bool is_template;
1226           tree decl_type = TREE_TYPE (decl);
1227
1228           /* Make sure that both DECL and FRIEND_DECL are templates or
1229              non-templates.  */
1230           is_template
1231             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1232               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1233
1234           if (need_template ^ is_template)
1235             return false;
1236           else if (is_template)
1237             {
1238               tree friend_parms;
1239               /* If both are templates, check the name of the two
1240                  TEMPLATE_DECL's first because is_friend didn't.  */
1241               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1242                   != DECL_NAME (friend_decl))
1243                 return false;
1244
1245               /* Now check template parameter list.  */
1246               friend_parms
1247                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1248                                          args, tf_none);
1249               return comp_template_parms
1250                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1251                  friend_parms);
1252             }
1253           else
1254             return (DECL_NAME (decl)
1255                     == DECL_NAME (friend_decl));
1256         }
1257     }
1258   return false;
1259 }
1260
1261 /* Register the specialization SPEC as a specialization of TMPL with
1262    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1263    is actually just a friend declaration.  Returns SPEC, or an
1264    equivalent prior declaration, if available.  */
1265
1266 static tree
1267 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1268                          hashval_t hash)
1269 {
1270   tree fn;
1271   spec_entry **slot = NULL;
1272   spec_entry elt;
1273
1274   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1275
1276   if (TREE_CODE (spec) == FUNCTION_DECL
1277       && uses_template_parms (DECL_TI_ARGS (spec)))
1278     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1279        register it; we want the corresponding TEMPLATE_DECL instead.
1280        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1281        the more obvious `uses_template_parms (spec)' to avoid problems
1282        with default function arguments.  In particular, given
1283        something like this:
1284
1285           template <class T> void f(T t1, T t = T())
1286
1287        the default argument expression is not substituted for in an
1288        instantiation unless and until it is actually needed.  */
1289     return spec;
1290
1291   if (optimize_specialization_lookup_p (tmpl))
1292     /* We don't put these specializations in the hash table, but we might
1293        want to give an error about a mismatch.  */
1294     fn = retrieve_specialization (tmpl, args, 0);
1295   else
1296     {
1297       elt.tmpl = tmpl;
1298       elt.args = args;
1299       elt.spec = spec;
1300
1301       if (hash == 0)
1302         hash = hash_specialization (&elt);
1303
1304       slot = (spec_entry **)
1305         htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1306       if (*slot)
1307         fn = (*slot)->spec;
1308       else
1309         fn = NULL_TREE;
1310     }
1311
1312   /* We can sometimes try to re-register a specialization that we've
1313      already got.  In particular, regenerate_decl_from_template calls
1314      duplicate_decls which will update the specialization list.  But,
1315      we'll still get called again here anyhow.  It's more convenient
1316      to simply allow this than to try to prevent it.  */
1317   if (fn == spec)
1318     return spec;
1319   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1320     {
1321       if (DECL_TEMPLATE_INSTANTIATION (fn))
1322         {
1323           if (DECL_ODR_USED (fn)
1324               || DECL_EXPLICIT_INSTANTIATION (fn))
1325             {
1326               error ("specialization of %qD after instantiation",
1327                      fn);
1328               return error_mark_node;
1329             }
1330           else
1331             {
1332               tree clone;
1333               /* This situation should occur only if the first
1334                  specialization is an implicit instantiation, the
1335                  second is an explicit specialization, and the
1336                  implicit instantiation has not yet been used.  That
1337                  situation can occur if we have implicitly
1338                  instantiated a member function and then specialized
1339                  it later.
1340
1341                  We can also wind up here if a friend declaration that
1342                  looked like an instantiation turns out to be a
1343                  specialization:
1344
1345                    template <class T> void foo(T);
1346                    class S { friend void foo<>(int) };
1347                    template <> void foo(int);
1348
1349                  We transform the existing DECL in place so that any
1350                  pointers to it become pointers to the updated
1351                  declaration.
1352
1353                  If there was a definition for the template, but not
1354                  for the specialization, we want this to look as if
1355                  there were no definition, and vice versa.  */
1356               DECL_INITIAL (fn) = NULL_TREE;
1357               duplicate_decls (spec, fn, is_friend);
1358               /* The call to duplicate_decls will have applied
1359                  [temp.expl.spec]:
1360
1361                    An explicit specialization of a function template
1362                    is inline only if it is explicitly declared to be,
1363                    and independently of whether its function template
1364                    is.
1365
1366                 to the primary function; now copy the inline bits to
1367                 the various clones.  */
1368               FOR_EACH_CLONE (clone, fn)
1369                 {
1370                   DECL_DECLARED_INLINE_P (clone)
1371                     = DECL_DECLARED_INLINE_P (fn);
1372                   DECL_SOURCE_LOCATION (clone)
1373                     = DECL_SOURCE_LOCATION (fn);
1374                 }
1375               check_specialization_namespace (fn);
1376
1377               return fn;
1378             }
1379         }
1380       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1381         {
1382           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1383             /* Dup decl failed, but this is a new definition. Set the
1384                line number so any errors match this new
1385                definition.  */
1386             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1387
1388           return fn;
1389         }
1390     }
1391   else if (fn)
1392     return duplicate_decls (spec, fn, is_friend);
1393
1394   /* A specialization must be declared in the same namespace as the
1395      template it is specializing.  */
1396   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1397       && !check_specialization_namespace (tmpl))
1398     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1399
1400   if (!optimize_specialization_lookup_p (tmpl))
1401     {
1402       gcc_assert (tmpl && args && spec);
1403       *slot = GGC_NEW (spec_entry);
1404       **slot = elt;
1405       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1406           && PRIMARY_TEMPLATE_P (tmpl)
1407           && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1408         /* TMPL is a forward declaration of a template function; keep a list
1409            of all specializations in case we need to reassign them to a friend
1410            template later in tsubst_friend_function.  */
1411         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1412           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1413     }
1414
1415   return spec;
1416 }
1417
1418 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1419    TMPL and ARGS members, ignores SPEC.  */
1420
1421 static int
1422 eq_specializations (const void *p1, const void *p2)
1423 {
1424   const spec_entry *e1 = (const spec_entry *)p1;
1425   const spec_entry *e2 = (const spec_entry *)p2;
1426
1427   return (e1->tmpl == e2->tmpl
1428           && comp_template_args (e1->args, e2->args));
1429 }
1430
1431 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1432
1433 static hashval_t
1434 hash_tmpl_and_args (tree tmpl, tree args)
1435 {
1436   hashval_t val = DECL_UID (tmpl);
1437   return iterative_hash_template_arg (args, val);
1438 }
1439
1440 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1441    ignoring SPEC.  */
1442
1443 static hashval_t
1444 hash_specialization (const void *p)
1445 {
1446   const spec_entry *e = (const spec_entry *)p;
1447   return hash_tmpl_and_args (e->tmpl, e->args);
1448 }
1449
1450 /* Recursively calculate a hash value for a template argument ARG, for use
1451    in the hash tables of template specializations.  */
1452
1453 static hashval_t
1454 iterative_hash_template_arg (tree arg, hashval_t val)
1455 {
1456   unsigned HOST_WIDE_INT i;
1457   enum tree_code code;
1458   char tclass;
1459
1460   if (arg == NULL_TREE)
1461     return iterative_hash_object (arg, val);
1462
1463   if (!TYPE_P (arg))
1464     STRIP_NOPS (arg);
1465
1466   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1467     /* We can get one of these when re-hashing a previous entry in the middle
1468        of substituting into a pack expansion.  Just look through it.  */
1469     arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1470
1471   code = TREE_CODE (arg);
1472   tclass = TREE_CODE_CLASS (code);
1473
1474   val = iterative_hash_object (code, val);
1475
1476   switch (code)
1477     {
1478     case ERROR_MARK:
1479       return val;
1480
1481     case IDENTIFIER_NODE:
1482       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1483
1484     case TREE_VEC:
1485       {
1486         int i, len = TREE_VEC_LENGTH (arg);
1487         for (i = 0; i < len; ++i)
1488           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1489         return val;
1490       }
1491
1492     case TYPE_PACK_EXPANSION:
1493     case EXPR_PACK_EXPANSION:
1494       return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1495
1496     case TYPE_ARGUMENT_PACK:
1497     case NONTYPE_ARGUMENT_PACK:
1498       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1499
1500     case TREE_LIST:
1501       for (; arg; arg = TREE_CHAIN (arg))
1502         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1503       return val;
1504
1505     case OVERLOAD:
1506       for (; arg; arg = OVL_CHAIN (arg))
1507         val = iterative_hash_template_arg (OVL_FUNCTION (arg), val);
1508       return val;
1509
1510     case CONSTRUCTOR:
1511       {
1512         tree field, value;
1513         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1514           {
1515             val = iterative_hash_template_arg (field, val);
1516             val = iterative_hash_template_arg (value, val);
1517           }
1518         return val;
1519       }
1520
1521     case PARM_DECL:
1522       if (!DECL_ARTIFICIAL (arg))
1523         val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1524       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1525
1526     case TARGET_EXPR:
1527       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1528
1529     case PTRMEM_CST:
1530       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1531       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1532
1533     case TEMPLATE_PARM_INDEX:
1534       val = iterative_hash_template_arg
1535         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1536       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1537       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1538
1539     case TRAIT_EXPR:
1540       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1541       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1542       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1543
1544     case BASELINK:
1545       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1546                                          val);
1547       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1548                                           val);
1549
1550     case MODOP_EXPR:
1551       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1552       code = TREE_CODE (TREE_OPERAND (arg, 1));
1553       val = iterative_hash_object (code, val);
1554       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1555
1556     case ARRAY_TYPE:
1557       /* layout_type sets structural equality for arrays of
1558          incomplete type, so we can't rely on the canonical type
1559          for hashing.  */
1560       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1561       return iterative_hash_template_arg (TYPE_DOMAIN (arg), val);
1562
1563     default:
1564       switch (tclass)
1565         {
1566         case tcc_type:
1567           if (TYPE_CANONICAL (arg))
1568             return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1569                                           val);
1570           else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1571             return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1572           /* Otherwise just compare the types during lookup.  */
1573           return val;
1574
1575         case tcc_declaration:
1576         case tcc_constant:
1577           return iterative_hash_expr (arg, val);
1578
1579         default:
1580           gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1581           {
1582             unsigned n = TREE_OPERAND_LENGTH (arg);
1583             for (i = 0; i < n; ++i)
1584               val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1585             return val;
1586           }
1587         }
1588     }
1589   gcc_unreachable ();
1590   return 0;
1591 }
1592
1593 /* Unregister the specialization SPEC as a specialization of TMPL.
1594    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1595    if the SPEC was listed as a specialization of TMPL.
1596
1597    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1598
1599 bool
1600 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1601 {
1602   spec_entry **slot;
1603   spec_entry elt;
1604
1605   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1606   elt.args = TI_ARGS (tinfo);
1607   elt.spec = NULL_TREE;
1608
1609   slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1610   if (*slot)
1611     {
1612       gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1613       gcc_assert (new_spec != NULL_TREE);
1614       (*slot)->spec = new_spec;
1615       return 1;
1616     }
1617
1618   return 0;
1619 }
1620
1621 /* Compare an entry in the local specializations hash table P1 (which
1622    is really a pointer to a TREE_LIST) with P2 (which is really a
1623    DECL).  */
1624
1625 static int
1626 eq_local_specializations (const void *p1, const void *p2)
1627 {
1628   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1629 }
1630
1631 /* Hash P1, an entry in the local specializations table.  */
1632
1633 static hashval_t
1634 hash_local_specialization (const void* p1)
1635 {
1636   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1637 }
1638
1639 /* Like register_specialization, but for local declarations.  We are
1640    registering SPEC, an instantiation of TMPL.  */
1641
1642 static void
1643 register_local_specialization (tree spec, tree tmpl)
1644 {
1645   void **slot;
1646
1647   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1648                                    htab_hash_pointer (tmpl), INSERT);
1649   *slot = build_tree_list (spec, tmpl);
1650 }
1651
1652 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1653    specialized class.  */
1654
1655 bool
1656 explicit_class_specialization_p (tree type)
1657 {
1658   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1659     return false;
1660   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1661 }
1662
1663 /* Print the list of functions at FNS, going through all the overloads
1664    for each element of the list.  Alternatively, FNS can not be a
1665    TREE_LIST, in which case it will be printed together with all the
1666    overloads.
1667
1668    MORE and *STR should respectively be FALSE and NULL when the function
1669    is called from the outside.  They are used internally on recursive
1670    calls.  print_candidates manages the two parameters and leaves NULL
1671    in *STR when it ends.  */
1672
1673 static void
1674 print_candidates_1 (tree fns, bool more, const char **str)
1675 {
1676   tree fn, fn2;
1677   char *spaces = NULL;
1678
1679   for (fn = fns; fn; fn = OVL_NEXT (fn))
1680     if (TREE_CODE (fn) == TREE_LIST)
1681       {
1682         gcc_assert (!OVL_NEXT (fn) && !is_overloaded_fn (fn));
1683         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1684           print_candidates_1 (TREE_VALUE (fn2),
1685                               TREE_CHAIN (fn2) || more, str);
1686       }
1687     else
1688       {
1689         if (!*str)
1690           {
1691             /* Pick the prefix string.  */
1692             if (!more && !OVL_NEXT (fns))
1693               {
1694                 error ("candidate is: %+#D", OVL_CURRENT (fn));
1695                 continue;
1696               }
1697
1698             *str = _("candidates are:");
1699             spaces = get_spaces (*str);
1700           }
1701         error ("%s %+#D", *str, OVL_CURRENT (fn));
1702         *str = spaces ? spaces : *str;
1703       }
1704
1705   if (!more)
1706     {
1707       free (spaces);
1708       *str = NULL;
1709     }
1710 }
1711
1712 /* Print the list of candidate FNS in an error message.  */
1713
1714 void
1715 print_candidates (tree fns)
1716 {
1717   const char *str = NULL;
1718   print_candidates_1 (fns, false, &str);
1719   gcc_assert (str == NULL);
1720 }
1721
1722 /* Returns the template (one of the functions given by TEMPLATE_ID)
1723    which can be specialized to match the indicated DECL with the
1724    explicit template args given in TEMPLATE_ID.  The DECL may be
1725    NULL_TREE if none is available.  In that case, the functions in
1726    TEMPLATE_ID are non-members.
1727
1728    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1729    specialization of a member template.
1730
1731    The TEMPLATE_COUNT is the number of references to qualifying
1732    template classes that appeared in the name of the function. See
1733    check_explicit_specialization for a more accurate description.
1734
1735    TSK indicates what kind of template declaration (if any) is being
1736    declared.  TSK_TEMPLATE indicates that the declaration given by
1737    DECL, though a FUNCTION_DECL, has template parameters, and is
1738    therefore a template function.
1739
1740    The template args (those explicitly specified and those deduced)
1741    are output in a newly created vector *TARGS_OUT.
1742
1743    If it is impossible to determine the result, an error message is
1744    issued.  The error_mark_node is returned to indicate failure.  */
1745
1746 static tree
1747 determine_specialization (tree template_id,
1748                           tree decl,
1749                           tree* targs_out,
1750                           int need_member_template,
1751                           int template_count,
1752                           tmpl_spec_kind tsk)
1753 {
1754   tree fns;
1755   tree targs;
1756   tree explicit_targs;
1757   tree candidates = NULL_TREE;
1758   /* A TREE_LIST of templates of which DECL may be a specialization.
1759      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1760      corresponding TREE_PURPOSE is the set of template arguments that,
1761      when used to instantiate the template, would produce a function
1762      with the signature of DECL.  */
1763   tree templates = NULL_TREE;
1764   int header_count;
1765   struct cp_binding_level *b;
1766
1767   *targs_out = NULL_TREE;
1768
1769   if (template_id == error_mark_node || decl == error_mark_node)
1770     return error_mark_node;
1771
1772   fns = TREE_OPERAND (template_id, 0);
1773   explicit_targs = TREE_OPERAND (template_id, 1);
1774
1775   if (fns == error_mark_node)
1776     return error_mark_node;
1777
1778   /* Check for baselinks.  */
1779   if (BASELINK_P (fns))
1780     fns = BASELINK_FUNCTIONS (fns);
1781
1782   if (!is_overloaded_fn (fns))
1783     {
1784       error ("%qD is not a function template", fns);
1785       return error_mark_node;
1786     }
1787
1788   /* Count the number of template headers specified for this
1789      specialization.  */
1790   header_count = 0;
1791   for (b = current_binding_level;
1792        b->kind == sk_template_parms;
1793        b = b->level_chain)
1794     ++header_count;
1795
1796   for (; fns; fns = OVL_NEXT (fns))
1797     {
1798       tree fn = OVL_CURRENT (fns);
1799
1800       if (TREE_CODE (fn) == TEMPLATE_DECL)
1801         {
1802           tree decl_arg_types;
1803           tree fn_arg_types;
1804
1805           /* In case of explicit specialization, we need to check if
1806              the number of template headers appearing in the specialization
1807              is correct. This is usually done in check_explicit_specialization,
1808              but the check done there cannot be exhaustive when specializing
1809              member functions. Consider the following code:
1810
1811              template <> void A<int>::f(int);
1812              template <> template <> void A<int>::f(int);
1813
1814              Assuming that A<int> is not itself an explicit specialization
1815              already, the first line specializes "f" which is a non-template
1816              member function, whilst the second line specializes "f" which
1817              is a template member function. So both lines are syntactically
1818              correct, and check_explicit_specialization does not reject
1819              them.
1820
1821              Here, we can do better, as we are matching the specialization
1822              against the declarations. We count the number of template
1823              headers, and we check if they match TEMPLATE_COUNT + 1
1824              (TEMPLATE_COUNT is the number of qualifying template classes,
1825              plus there must be another header for the member template
1826              itself).
1827
1828              Notice that if header_count is zero, this is not a
1829              specialization but rather a template instantiation, so there
1830              is no check we can perform here.  */
1831           if (header_count && header_count != template_count + 1)
1832             continue;
1833
1834           /* Check that the number of template arguments at the
1835              innermost level for DECL is the same as for FN.  */
1836           if (current_binding_level->kind == sk_template_parms
1837               && !current_binding_level->explicit_spec_p
1838               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1839                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1840                                       (current_template_parms))))
1841             continue;
1842
1843           /* DECL might be a specialization of FN.  */
1844           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1845           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1846
1847           /* For a non-static member function, we need to make sure
1848              that the const qualification is the same.  Since
1849              get_bindings does not try to merge the "this" parameter,
1850              we must do the comparison explicitly.  */
1851           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1852               && !same_type_p (TREE_VALUE (fn_arg_types),
1853                                TREE_VALUE (decl_arg_types)))
1854             continue;
1855
1856           /* Skip the "this" parameter and, for constructors of
1857              classes with virtual bases, the VTT parameter.  A
1858              full specialization of a constructor will have a VTT
1859              parameter, but a template never will.  */ 
1860           decl_arg_types 
1861             = skip_artificial_parms_for (decl, decl_arg_types);
1862           fn_arg_types 
1863             = skip_artificial_parms_for (fn, fn_arg_types);
1864
1865           /* Check that the number of function parameters matches.
1866              For example,
1867                template <class T> void f(int i = 0);
1868                template <> void f<int>();
1869              The specialization f<int> is invalid but is not caught
1870              by get_bindings below.  */
1871           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1872             continue;
1873
1874           /* Function templates cannot be specializations; there are
1875              no partial specializations of functions.  Therefore, if
1876              the type of DECL does not match FN, there is no
1877              match.  */
1878           if (tsk == tsk_template)
1879             {
1880               if (compparms (fn_arg_types, decl_arg_types))
1881                 candidates = tree_cons (NULL_TREE, fn, candidates);
1882               continue;
1883             }
1884
1885           /* See whether this function might be a specialization of this
1886              template.  */
1887           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1888
1889           if (!targs)
1890             /* We cannot deduce template arguments that when used to
1891                specialize TMPL will produce DECL.  */
1892             continue;
1893
1894           /* Save this template, and the arguments deduced.  */
1895           templates = tree_cons (targs, fn, templates);
1896         }
1897       else if (need_member_template)
1898         /* FN is an ordinary member function, and we need a
1899            specialization of a member template.  */
1900         ;
1901       else if (TREE_CODE (fn) != FUNCTION_DECL)
1902         /* We can get IDENTIFIER_NODEs here in certain erroneous
1903            cases.  */
1904         ;
1905       else if (!DECL_FUNCTION_MEMBER_P (fn))
1906         /* This is just an ordinary non-member function.  Nothing can
1907            be a specialization of that.  */
1908         ;
1909       else if (DECL_ARTIFICIAL (fn))
1910         /* Cannot specialize functions that are created implicitly.  */
1911         ;
1912       else
1913         {
1914           tree decl_arg_types;
1915
1916           /* This is an ordinary member function.  However, since
1917              we're here, we can assume it's enclosing class is a
1918              template class.  For example,
1919
1920                template <typename T> struct S { void f(); };
1921                template <> void S<int>::f() {}
1922
1923              Here, S<int>::f is a non-template, but S<int> is a
1924              template class.  If FN has the same type as DECL, we
1925              might be in business.  */
1926
1927           if (!DECL_TEMPLATE_INFO (fn))
1928             /* Its enclosing class is an explicit specialization
1929                of a template class.  This is not a candidate.  */
1930             continue;
1931
1932           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1933                             TREE_TYPE (TREE_TYPE (fn))))
1934             /* The return types differ.  */
1935             continue;
1936
1937           /* Adjust the type of DECL in case FN is a static member.  */
1938           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1939           if (DECL_STATIC_FUNCTION_P (fn)
1940               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1941             decl_arg_types = TREE_CHAIN (decl_arg_types);
1942
1943           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1944                          decl_arg_types))
1945             /* They match!  */
1946             candidates = tree_cons (NULL_TREE, fn, candidates);
1947         }
1948     }
1949
1950   if (templates && TREE_CHAIN (templates))
1951     {
1952       /* We have:
1953
1954            [temp.expl.spec]
1955
1956            It is possible for a specialization with a given function
1957            signature to be instantiated from more than one function
1958            template.  In such cases, explicit specification of the
1959            template arguments must be used to uniquely identify the
1960            function template specialization being specialized.
1961
1962          Note that here, there's no suggestion that we're supposed to
1963          determine which of the candidate templates is most
1964          specialized.  However, we, also have:
1965
1966            [temp.func.order]
1967
1968            Partial ordering of overloaded function template
1969            declarations is used in the following contexts to select
1970            the function template to which a function template
1971            specialization refers:
1972
1973            -- when an explicit specialization refers to a function
1974               template.
1975
1976          So, we do use the partial ordering rules, at least for now.
1977          This extension can only serve to make invalid programs valid,
1978          so it's safe.  And, there is strong anecdotal evidence that
1979          the committee intended the partial ordering rules to apply;
1980          the EDG front end has that behavior, and John Spicer claims
1981          that the committee simply forgot to delete the wording in
1982          [temp.expl.spec].  */
1983       tree tmpl = most_specialized_instantiation (templates);
1984       if (tmpl != error_mark_node)
1985         {
1986           templates = tmpl;
1987           TREE_CHAIN (templates) = NULL_TREE;
1988         }
1989     }
1990
1991   if (templates == NULL_TREE && candidates == NULL_TREE)
1992     {
1993       error ("template-id %qD for %q+D does not match any template "
1994              "declaration", template_id, decl);
1995       if (header_count && header_count != template_count + 1)
1996         inform (input_location, "saw %d %<template<>%>, need %d for "
1997                 "specializing a member function template",
1998                 header_count, template_count + 1);
1999       return error_mark_node;
2000     }
2001   else if ((templates && TREE_CHAIN (templates))
2002            || (candidates && TREE_CHAIN (candidates))
2003            || (templates && candidates))
2004     {
2005       error ("ambiguous template specialization %qD for %q+D",
2006              template_id, decl);
2007       candidates = chainon (candidates, templates);
2008       print_candidates (candidates);
2009       return error_mark_node;
2010     }
2011
2012   /* We have one, and exactly one, match.  */
2013   if (candidates)
2014     {
2015       tree fn = TREE_VALUE (candidates);
2016       *targs_out = copy_node (DECL_TI_ARGS (fn));
2017       /* DECL is a re-declaration or partial instantiation of a template
2018          function.  */
2019       if (TREE_CODE (fn) == TEMPLATE_DECL)
2020         return fn;
2021       /* It was a specialization of an ordinary member function in a
2022          template class.  */
2023       return DECL_TI_TEMPLATE (fn);
2024     }
2025
2026   /* It was a specialization of a template.  */
2027   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2028   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2029     {
2030       *targs_out = copy_node (targs);
2031       SET_TMPL_ARGS_LEVEL (*targs_out,
2032                            TMPL_ARGS_DEPTH (*targs_out),
2033                            TREE_PURPOSE (templates));
2034     }
2035   else
2036     *targs_out = TREE_PURPOSE (templates);
2037   return TREE_VALUE (templates);
2038 }
2039
2040 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2041    but with the default argument values filled in from those in the
2042    TMPL_TYPES.  */
2043
2044 static tree
2045 copy_default_args_to_explicit_spec_1 (tree spec_types,
2046                                       tree tmpl_types)
2047 {
2048   tree new_spec_types;
2049
2050   if (!spec_types)
2051     return NULL_TREE;
2052
2053   if (spec_types == void_list_node)
2054     return void_list_node;
2055
2056   /* Substitute into the rest of the list.  */
2057   new_spec_types =
2058     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2059                                           TREE_CHAIN (tmpl_types));
2060
2061   /* Add the default argument for this parameter.  */
2062   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2063                          TREE_VALUE (spec_types),
2064                          new_spec_types);
2065 }
2066
2067 /* DECL is an explicit specialization.  Replicate default arguments
2068    from the template it specializes.  (That way, code like:
2069
2070      template <class T> void f(T = 3);
2071      template <> void f(double);
2072      void g () { f (); }
2073
2074    works, as required.)  An alternative approach would be to look up
2075    the correct default arguments at the call-site, but this approach
2076    is consistent with how implicit instantiations are handled.  */
2077
2078 static void
2079 copy_default_args_to_explicit_spec (tree decl)
2080 {
2081   tree tmpl;
2082   tree spec_types;
2083   tree tmpl_types;
2084   tree new_spec_types;
2085   tree old_type;
2086   tree new_type;
2087   tree t;
2088   tree object_type = NULL_TREE;
2089   tree in_charge = NULL_TREE;
2090   tree vtt = NULL_TREE;
2091
2092   /* See if there's anything we need to do.  */
2093   tmpl = DECL_TI_TEMPLATE (decl);
2094   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2095   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2096     if (TREE_PURPOSE (t))
2097       break;
2098   if (!t)
2099     return;
2100
2101   old_type = TREE_TYPE (decl);
2102   spec_types = TYPE_ARG_TYPES (old_type);
2103
2104   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2105     {
2106       /* Remove the this pointer, but remember the object's type for
2107          CV quals.  */
2108       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2109       spec_types = TREE_CHAIN (spec_types);
2110       tmpl_types = TREE_CHAIN (tmpl_types);
2111
2112       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2113         {
2114           /* DECL may contain more parameters than TMPL due to the extra
2115              in-charge parameter in constructors and destructors.  */
2116           in_charge = spec_types;
2117           spec_types = TREE_CHAIN (spec_types);
2118         }
2119       if (DECL_HAS_VTT_PARM_P (decl))
2120         {
2121           vtt = spec_types;
2122           spec_types = TREE_CHAIN (spec_types);
2123         }
2124     }
2125
2126   /* Compute the merged default arguments.  */
2127   new_spec_types =
2128     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2129
2130   /* Compute the new FUNCTION_TYPE.  */
2131   if (object_type)
2132     {
2133       if (vtt)
2134         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2135                                          TREE_VALUE (vtt),
2136                                          new_spec_types);
2137
2138       if (in_charge)
2139         /* Put the in-charge parameter back.  */
2140         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2141                                          TREE_VALUE (in_charge),
2142                                          new_spec_types);
2143
2144       new_type = build_method_type_directly (object_type,
2145                                              TREE_TYPE (old_type),
2146                                              new_spec_types);
2147     }
2148   else
2149     new_type = build_function_type (TREE_TYPE (old_type),
2150                                     new_spec_types);
2151   new_type = cp_build_type_attribute_variant (new_type,
2152                                               TYPE_ATTRIBUTES (old_type));
2153   new_type = build_exception_variant (new_type,
2154                                       TYPE_RAISES_EXCEPTIONS (old_type));
2155   TREE_TYPE (decl) = new_type;
2156 }
2157
2158 /* Check to see if the function just declared, as indicated in
2159    DECLARATOR, and in DECL, is a specialization of a function
2160    template.  We may also discover that the declaration is an explicit
2161    instantiation at this point.
2162
2163    Returns DECL, or an equivalent declaration that should be used
2164    instead if all goes well.  Issues an error message if something is
2165    amiss.  Returns error_mark_node if the error is not easily
2166    recoverable.
2167
2168    FLAGS is a bitmask consisting of the following flags:
2169
2170    2: The function has a definition.
2171    4: The function is a friend.
2172
2173    The TEMPLATE_COUNT is the number of references to qualifying
2174    template classes that appeared in the name of the function.  For
2175    example, in
2176
2177      template <class T> struct S { void f(); };
2178      void S<int>::f();
2179
2180    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2181    classes are not counted in the TEMPLATE_COUNT, so that in
2182
2183      template <class T> struct S {};
2184      template <> struct S<int> { void f(); }
2185      template <> void S<int>::f();
2186
2187    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2188    invalid; there should be no template <>.)
2189
2190    If the function is a specialization, it is marked as such via
2191    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2192    is set up correctly, and it is added to the list of specializations
2193    for that template.  */
2194
2195 tree
2196 check_explicit_specialization (tree declarator,
2197                                tree decl,
2198                                int template_count,
2199                                int flags)
2200 {
2201   int have_def = flags & 2;
2202   int is_friend = flags & 4;
2203   int specialization = 0;
2204   int explicit_instantiation = 0;
2205   int member_specialization = 0;
2206   tree ctype = DECL_CLASS_CONTEXT (decl);
2207   tree dname = DECL_NAME (decl);
2208   tmpl_spec_kind tsk;
2209
2210   if (is_friend)
2211     {
2212       if (!processing_specialization)
2213         tsk = tsk_none;
2214       else
2215         tsk = tsk_excessive_parms;
2216     }
2217   else
2218     tsk = current_tmpl_spec_kind (template_count);
2219
2220   switch (tsk)
2221     {
2222     case tsk_none:
2223       if (processing_specialization)
2224         {
2225           specialization = 1;
2226           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2227         }
2228       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2229         {
2230           if (is_friend)
2231             /* This could be something like:
2232
2233                template <class T> void f(T);
2234                class S { friend void f<>(int); }  */
2235             specialization = 1;
2236           else
2237             {
2238               /* This case handles bogus declarations like template <>
2239                  template <class T> void f<int>(); */
2240
2241               error ("template-id %qD in declaration of primary template",
2242                      declarator);
2243               return decl;
2244             }
2245         }
2246       break;
2247
2248     case tsk_invalid_member_spec:
2249       /* The error has already been reported in
2250          check_specialization_scope.  */
2251       return error_mark_node;
2252
2253     case tsk_invalid_expl_inst:
2254       error ("template parameter list used in explicit instantiation");
2255
2256       /* Fall through.  */
2257
2258     case tsk_expl_inst:
2259       if (have_def)
2260         error ("definition provided for explicit instantiation");
2261
2262       explicit_instantiation = 1;
2263       break;
2264
2265     case tsk_excessive_parms:
2266     case tsk_insufficient_parms:
2267       if (tsk == tsk_excessive_parms)
2268         error ("too many template parameter lists in declaration of %qD",
2269                decl);
2270       else if (template_header_count)
2271         error("too few template parameter lists in declaration of %qD", decl);
2272       else
2273         error("explicit specialization of %qD must be introduced by "
2274               "%<template <>%>", decl);
2275
2276       /* Fall through.  */
2277     case tsk_expl_spec:
2278       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2279       if (ctype)
2280         member_specialization = 1;
2281       else
2282         specialization = 1;
2283       break;
2284
2285     case tsk_template:
2286       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2287         {
2288           /* This case handles bogus declarations like template <>
2289              template <class T> void f<int>(); */
2290
2291           if (uses_template_parms (declarator))
2292             error ("function template partial specialization %qD "
2293                    "is not allowed", declarator);
2294           else
2295             error ("template-id %qD in declaration of primary template",
2296                    declarator);
2297           return decl;
2298         }
2299
2300       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2301         /* This is a specialization of a member template, without
2302            specialization the containing class.  Something like:
2303
2304              template <class T> struct S {
2305                template <class U> void f (U);
2306              };
2307              template <> template <class U> void S<int>::f(U) {}
2308
2309            That's a specialization -- but of the entire template.  */
2310         specialization = 1;
2311       break;
2312
2313     default:
2314       gcc_unreachable ();
2315     }
2316
2317   if (specialization || member_specialization)
2318     {
2319       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2320       for (; t; t = TREE_CHAIN (t))
2321         if (TREE_PURPOSE (t))
2322           {
2323             permerror (input_location, 
2324                        "default argument specified in explicit specialization");
2325             break;
2326           }
2327     }
2328
2329   if (specialization || member_specialization || explicit_instantiation)
2330     {
2331       tree tmpl = NULL_TREE;
2332       tree targs = NULL_TREE;
2333
2334       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2335       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2336         {
2337           tree fns;
2338
2339           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2340           if (ctype)
2341             fns = dname;
2342           else
2343             {
2344               /* If there is no class context, the explicit instantiation
2345                  must be at namespace scope.  */
2346               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2347
2348               /* Find the namespace binding, using the declaration
2349                  context.  */
2350               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2351                                            false, true);
2352               if (fns == error_mark_node || !is_overloaded_fn (fns))
2353                 {
2354                   error ("%qD is not a template function", dname);
2355                   fns = error_mark_node;
2356                 }
2357               else
2358                 {
2359                   tree fn = OVL_CURRENT (fns);
2360                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2361                                                 CP_DECL_CONTEXT (fn)))
2362                     error ("%qD is not declared in %qD",
2363                            decl, current_namespace);
2364                 }
2365             }
2366
2367           declarator = lookup_template_function (fns, NULL_TREE);
2368         }
2369
2370       if (declarator == error_mark_node)
2371         return error_mark_node;
2372
2373       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2374         {
2375           if (!explicit_instantiation)
2376             /* A specialization in class scope.  This is invalid,
2377                but the error will already have been flagged by
2378                check_specialization_scope.  */
2379             return error_mark_node;
2380           else
2381             {
2382               /* It's not valid to write an explicit instantiation in
2383                  class scope, e.g.:
2384
2385                    class C { template void f(); }
2386
2387                    This case is caught by the parser.  However, on
2388                    something like:
2389
2390                    template class C { void f(); };
2391
2392                    (which is invalid) we can get here.  The error will be
2393                    issued later.  */
2394               ;
2395             }
2396
2397           return decl;
2398         }
2399       else if (ctype != NULL_TREE
2400                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2401                    IDENTIFIER_NODE))
2402         {
2403           /* Find the list of functions in ctype that have the same
2404              name as the declared function.  */
2405           tree name = TREE_OPERAND (declarator, 0);
2406           tree fns = NULL_TREE;
2407           int idx;
2408
2409           if (constructor_name_p (name, ctype))
2410             {
2411               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2412
2413               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2414                   : !CLASSTYPE_DESTRUCTORS (ctype))
2415                 {
2416                   /* From [temp.expl.spec]:
2417
2418                      If such an explicit specialization for the member
2419                      of a class template names an implicitly-declared
2420                      special member function (clause _special_), the
2421                      program is ill-formed.
2422
2423                      Similar language is found in [temp.explicit].  */
2424                   error ("specialization of implicitly-declared special member function");
2425                   return error_mark_node;
2426                 }
2427
2428               name = is_constructor ? ctor_identifier : dtor_identifier;
2429             }
2430
2431           if (!DECL_CONV_FN_P (decl))
2432             {
2433               idx = lookup_fnfields_1 (ctype, name);
2434               if (idx >= 0)
2435                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2436             }
2437           else
2438             {
2439               VEC(tree,gc) *methods;
2440               tree ovl;
2441
2442               /* For a type-conversion operator, we cannot do a
2443                  name-based lookup.  We might be looking for `operator
2444                  int' which will be a specialization of `operator T'.
2445                  So, we find *all* the conversion operators, and then
2446                  select from them.  */
2447               fns = NULL_TREE;
2448
2449               methods = CLASSTYPE_METHOD_VEC (ctype);
2450               if (methods)
2451                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2452                      VEC_iterate (tree, methods, idx, ovl);
2453                      ++idx)
2454                   {
2455                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2456                       /* There are no more conversion functions.  */
2457                       break;
2458
2459                     /* Glue all these conversion functions together
2460                        with those we already have.  */
2461                     for (; ovl; ovl = OVL_NEXT (ovl))
2462                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2463                   }
2464             }
2465
2466           if (fns == NULL_TREE)
2467             {
2468               error ("no member function %qD declared in %qT", name, ctype);
2469               return error_mark_node;
2470             }
2471           else
2472             TREE_OPERAND (declarator, 0) = fns;
2473         }
2474
2475       /* Figure out what exactly is being specialized at this point.
2476          Note that for an explicit instantiation, even one for a
2477          member function, we cannot tell apriori whether the
2478          instantiation is for a member template, or just a member
2479          function of a template class.  Even if a member template is
2480          being instantiated, the member template arguments may be
2481          elided if they can be deduced from the rest of the
2482          declaration.  */
2483       tmpl = determine_specialization (declarator, decl,
2484                                        &targs,
2485                                        member_specialization,
2486                                        template_count,
2487                                        tsk);
2488
2489       if (!tmpl || tmpl == error_mark_node)
2490         /* We couldn't figure out what this declaration was
2491            specializing.  */
2492         return error_mark_node;
2493       else
2494         {
2495           tree gen_tmpl = most_general_template (tmpl);
2496
2497           if (explicit_instantiation)
2498             {
2499               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2500                  is done by do_decl_instantiation later.  */
2501
2502               int arg_depth = TMPL_ARGS_DEPTH (targs);
2503               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2504
2505               if (arg_depth > parm_depth)
2506                 {
2507                   /* If TMPL is not the most general template (for
2508                      example, if TMPL is a friend template that is
2509                      injected into namespace scope), then there will
2510                      be too many levels of TARGS.  Remove some of them
2511                      here.  */
2512                   int i;
2513                   tree new_targs;
2514
2515                   new_targs = make_tree_vec (parm_depth);
2516                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2517                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2518                       = TREE_VEC_ELT (targs, i);
2519                   targs = new_targs;
2520                 }
2521
2522               return instantiate_template (tmpl, targs, tf_error);
2523             }
2524
2525           /* If we thought that the DECL was a member function, but it
2526              turns out to be specializing a static member function,
2527              make DECL a static member function as well.  */
2528           if (DECL_STATIC_FUNCTION_P (tmpl)
2529               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2530             revert_static_member_fn (decl);
2531
2532           /* If this is a specialization of a member template of a
2533              template class, we want to return the TEMPLATE_DECL, not
2534              the specialization of it.  */
2535           if (tsk == tsk_template)
2536             {
2537               tree result = DECL_TEMPLATE_RESULT (tmpl);
2538               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2539               DECL_INITIAL (result) = NULL_TREE;
2540               if (have_def)
2541                 {
2542                   tree parm;
2543                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2544                   DECL_SOURCE_LOCATION (result)
2545                     = DECL_SOURCE_LOCATION (decl);
2546                   /* We want to use the argument list specified in the
2547                      definition, not in the original declaration.  */
2548                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2549                   for (parm = DECL_ARGUMENTS (result); parm;
2550                        parm = TREE_CHAIN (parm))
2551                     DECL_CONTEXT (parm) = result;
2552                 }
2553               return register_specialization (tmpl, gen_tmpl, targs,
2554                                               is_friend, 0);
2555             }
2556
2557           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2558           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2559
2560           /* Inherit default function arguments from the template
2561              DECL is specializing.  */
2562           copy_default_args_to_explicit_spec (decl);
2563
2564           /* This specialization has the same protection as the
2565              template it specializes.  */
2566           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2567           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2568
2569           /* 7.1.1-1 [dcl.stc]
2570
2571              A storage-class-specifier shall not be specified in an
2572              explicit specialization...
2573
2574              The parser rejects these, so unless action is taken here,
2575              explicit function specializations will always appear with
2576              global linkage.
2577
2578              The action recommended by the C++ CWG in response to C++
2579              defect report 605 is to make the storage class and linkage
2580              of the explicit specialization match the templated function:
2581
2582              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2583            */
2584           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2585             {
2586               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2587               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2588
2589               /* This specialization has the same linkage and visibility as
2590                  the function template it specializes.  */
2591               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2592               if (! TREE_PUBLIC (decl))
2593                 {
2594                   DECL_INTERFACE_KNOWN (decl) = 1;
2595                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2596                 }
2597               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2598               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2599                 {
2600                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2601                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2602                 }
2603             }
2604
2605           /* If DECL is a friend declaration, declared using an
2606              unqualified name, the namespace associated with DECL may
2607              have been set incorrectly.  For example, in:
2608
2609                template <typename T> void f(T);
2610                namespace N {
2611                  struct S { friend void f<int>(int); }
2612                }
2613
2614              we will have set the DECL_CONTEXT for the friend
2615              declaration to N, rather than to the global namespace.  */
2616           if (DECL_NAMESPACE_SCOPE_P (decl))
2617             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2618
2619           if (is_friend && !have_def)
2620             /* This is not really a declaration of a specialization.
2621                It's just the name of an instantiation.  But, it's not
2622                a request for an instantiation, either.  */
2623             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2624           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2625             /* This is indeed a specialization.  In case of constructors
2626                and destructors, we need in-charge and not-in-charge
2627                versions in V3 ABI.  */
2628             clone_function_decl (decl, /*update_method_vec_p=*/0);
2629
2630           /* Register this specialization so that we can find it
2631              again.  */
2632           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2633         }
2634     }
2635
2636   return decl;
2637 }
2638
2639 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2640    parameters.  These are represented in the same format used for
2641    DECL_TEMPLATE_PARMS.  */
2642
2643 int
2644 comp_template_parms (const_tree parms1, const_tree parms2)
2645 {
2646   const_tree p1;
2647   const_tree p2;
2648
2649   if (parms1 == parms2)
2650     return 1;
2651
2652   for (p1 = parms1, p2 = parms2;
2653        p1 != NULL_TREE && p2 != NULL_TREE;
2654        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2655     {
2656       tree t1 = TREE_VALUE (p1);
2657       tree t2 = TREE_VALUE (p2);
2658       int i;
2659
2660       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2661       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2662
2663       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2664         return 0;
2665
2666       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2667         {
2668           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2669           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2670
2671           /* If either of the template parameters are invalid, assume
2672              they match for the sake of error recovery. */
2673           if (parm1 == error_mark_node || parm2 == error_mark_node)
2674             return 1;
2675
2676           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2677             return 0;
2678
2679           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2680               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2681                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2682             continue;
2683           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2684             return 0;
2685         }
2686     }
2687
2688   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2689     /* One set of parameters has more parameters lists than the
2690        other.  */
2691     return 0;
2692
2693   return 1;
2694 }
2695
2696 /* Determine whether PARM is a parameter pack.  */
2697
2698 bool 
2699 template_parameter_pack_p (const_tree parm)
2700 {
2701   /* Determine if we have a non-type template parameter pack.  */
2702   if (TREE_CODE (parm) == PARM_DECL)
2703     return (DECL_TEMPLATE_PARM_P (parm) 
2704             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2705
2706   /* If this is a list of template parameters, we could get a
2707      TYPE_DECL or a TEMPLATE_DECL.  */ 
2708   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2709     parm = TREE_TYPE (parm);
2710
2711   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2712            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2713           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2714 }
2715
2716 /* Determine if T is a function parameter pack.  */
2717
2718 bool
2719 function_parameter_pack_p (const_tree t)
2720 {
2721   if (t && TREE_CODE (t) == PARM_DECL)
2722     return FUNCTION_PARAMETER_PACK_P (t);
2723   return false;
2724 }
2725
2726 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2727    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2728
2729 tree
2730 get_function_template_decl (const_tree primary_func_tmpl_inst)
2731 {
2732   if (! primary_func_tmpl_inst
2733       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2734       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2735     return NULL;
2736
2737   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2738 }
2739
2740 /* Return true iff the function parameter PARAM_DECL was expanded
2741    from the function parameter pack PACK.  */
2742
2743 bool
2744 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2745 {
2746   if (DECL_ARTIFICIAL (param_decl)
2747       || !function_parameter_pack_p (pack))
2748     return false;
2749
2750   /* The parameter pack and its pack arguments have the same
2751      DECL_PARM_INDEX.  */
2752   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2753 }
2754
2755 /* Determine whether ARGS describes a variadic template args list,
2756    i.e., one that is terminated by a template argument pack.  */
2757
2758 static bool 
2759 template_args_variadic_p (tree args)
2760 {
2761   int nargs;
2762   tree last_parm;
2763
2764   if (args == NULL_TREE)
2765     return false;
2766
2767   args = INNERMOST_TEMPLATE_ARGS (args);
2768   nargs = TREE_VEC_LENGTH (args);
2769
2770   if (nargs == 0)
2771     return false;
2772
2773   last_parm = TREE_VEC_ELT (args, nargs - 1);
2774
2775   return ARGUMENT_PACK_P (last_parm);
2776 }
2777
2778 /* Generate a new name for the parameter pack name NAME (an
2779    IDENTIFIER_NODE) that incorporates its */
2780
2781 static tree
2782 make_ith_pack_parameter_name (tree name, int i)
2783 {
2784   /* Munge the name to include the parameter index.  */
2785 #define NUMBUF_LEN 128
2786   char numbuf[NUMBUF_LEN];
2787   char* newname;
2788   int newname_len;
2789
2790   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2791   newname_len = IDENTIFIER_LENGTH (name)
2792                 + strlen (numbuf) + 2;
2793   newname = (char*)alloca (newname_len);
2794   snprintf (newname, newname_len,
2795             "%s#%i", IDENTIFIER_POINTER (name), i);
2796   return get_identifier (newname);
2797 }
2798
2799 /* Return true if T is a primary function
2800    or class template instantiation.  */
2801
2802 bool
2803 primary_template_instantiation_p (const_tree t)
2804 {
2805   if (!t)
2806     return false;
2807
2808   if (TREE_CODE (t) == FUNCTION_DECL)
2809     return DECL_LANG_SPECIFIC (t)
2810            && DECL_TEMPLATE_INSTANTIATION (t)
2811            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2812   else if (CLASS_TYPE_P (t))
2813     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2814            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2815   return false;
2816 }
2817
2818 /* Return true if PARM is a template template parameter.  */
2819
2820 bool
2821 template_template_parameter_p (const_tree parm)
2822 {
2823   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2824 }
2825
2826 /* Return the template parameters of T if T is a
2827    primary template instantiation, NULL otherwise.  */
2828
2829 tree
2830 get_primary_template_innermost_parameters (const_tree t)
2831 {
2832   tree parms = NULL, template_info = NULL;
2833
2834   if ((template_info = get_template_info (t))
2835       && primary_template_instantiation_p (t))
2836     parms = INNERMOST_TEMPLATE_PARMS
2837         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2838
2839   return parms;
2840 }
2841
2842 /* Returns the template arguments of T if T is a template instantiation,
2843    NULL otherwise.  */
2844
2845 tree
2846 get_template_innermost_arguments (const_tree t)
2847 {
2848   tree args = NULL, template_info = NULL;
2849
2850   if ((template_info = get_template_info (t))
2851       && TI_ARGS (template_info))
2852     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2853
2854   return args;
2855 }
2856
2857 /* Return the argument pack elements of T if T is a template argument pack,
2858    NULL otherwise.  */
2859
2860 tree
2861 get_template_argument_pack_elems (const_tree t)
2862 {
2863   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2864       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2865     return NULL;
2866
2867   return ARGUMENT_PACK_ARGS (t);
2868 }
2869
2870 /* Structure used to track the progress of find_parameter_packs_r.  */
2871 struct find_parameter_pack_data 
2872 {
2873   /* TREE_LIST that will contain all of the parameter packs found by
2874      the traversal.  */
2875   tree* parameter_packs;
2876
2877   /* Set of AST nodes that have been visited by the traversal.  */
2878   struct pointer_set_t *visited;
2879 };
2880
2881 /* Identifies all of the argument packs that occur in a template
2882    argument and appends them to the TREE_LIST inside DATA, which is a
2883    find_parameter_pack_data structure. This is a subroutine of
2884    make_pack_expansion and uses_parameter_packs.  */
2885 static tree
2886 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2887 {
2888   tree t = *tp;
2889   struct find_parameter_pack_data* ppd = 
2890     (struct find_parameter_pack_data*)data;
2891   bool parameter_pack_p = false;
2892
2893   /* Identify whether this is a parameter pack or not.  */
2894   switch (TREE_CODE (t))
2895     {
2896     case TEMPLATE_PARM_INDEX:
2897       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2898         parameter_pack_p = true;
2899       break;
2900
2901     case TEMPLATE_TYPE_PARM:
2902     case TEMPLATE_TEMPLATE_PARM:
2903       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2904         parameter_pack_p = true;
2905       break;
2906
2907     case PARM_DECL:
2908       if (FUNCTION_PARAMETER_PACK_P (t))
2909         {
2910           /* We don't want to walk into the type of a PARM_DECL,
2911              because we don't want to see the type parameter pack.  */
2912           *walk_subtrees = 0;
2913           parameter_pack_p = true;
2914         }
2915       break;
2916
2917     default:
2918       /* Not a parameter pack.  */
2919       break;
2920     }
2921
2922   if (parameter_pack_p)
2923     {
2924       /* Add this parameter pack to the list.  */
2925       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2926     }
2927
2928   if (TYPE_P (t))
2929     cp_walk_tree (&TYPE_CONTEXT (t), 
2930                   &find_parameter_packs_r, ppd, ppd->visited);
2931
2932   /* This switch statement will return immediately if we don't find a
2933      parameter pack.  */
2934   switch (TREE_CODE (t)) 
2935     {
2936     case TEMPLATE_PARM_INDEX:
2937       return NULL_TREE;
2938
2939     case BOUND_TEMPLATE_TEMPLATE_PARM:
2940       /* Check the template itself.  */
2941       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2942                     &find_parameter_packs_r, ppd, ppd->visited);
2943       /* Check the template arguments.  */
2944       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2945                     ppd->visited);
2946       *walk_subtrees = 0;
2947       return NULL_TREE;
2948
2949     case TEMPLATE_TYPE_PARM:
2950     case TEMPLATE_TEMPLATE_PARM:
2951       return NULL_TREE;
2952
2953     case PARM_DECL:
2954       return NULL_TREE;
2955
2956     case RECORD_TYPE:
2957       if (TYPE_PTRMEMFUNC_P (t))
2958         return NULL_TREE;
2959       /* Fall through.  */
2960
2961     case UNION_TYPE:
2962     case ENUMERAL_TYPE:
2963       if (TYPE_TEMPLATE_INFO (t))
2964         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
2965                       &find_parameter_packs_r, ppd, ppd->visited);
2966
2967       *walk_subtrees = 0;
2968       return NULL_TREE;
2969
2970     case TEMPLATE_DECL:
2971       cp_walk_tree (&TREE_TYPE (t),
2972                     &find_parameter_packs_r, ppd, ppd->visited);
2973       return NULL_TREE;
2974  
2975     case TYPENAME_TYPE:
2976       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
2977                    ppd, ppd->visited);
2978       *walk_subtrees = 0;
2979       return NULL_TREE;
2980       
2981     case TYPE_PACK_EXPANSION:
2982     case EXPR_PACK_EXPANSION:
2983       *walk_subtrees = 0;
2984       return NULL_TREE;
2985
2986     case INTEGER_TYPE:
2987       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
2988                     ppd, ppd->visited);
2989       *walk_subtrees = 0;
2990       return NULL_TREE;
2991
2992     case IDENTIFIER_NODE:
2993       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
2994                     ppd->visited);
2995       *walk_subtrees = 0;
2996       return NULL_TREE;
2997
2998     default:
2999       return NULL_TREE;
3000     }
3001
3002   return NULL_TREE;
3003 }
3004
3005 /* Determines if the expression or type T uses any parameter packs.  */
3006 bool
3007 uses_parameter_packs (tree t)
3008 {
3009   tree parameter_packs = NULL_TREE;
3010   struct find_parameter_pack_data ppd;
3011   ppd.parameter_packs = &parameter_packs;
3012   ppd.visited = pointer_set_create ();
3013   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3014   pointer_set_destroy (ppd.visited);
3015   return parameter_packs != NULL_TREE;
3016 }
3017
3018 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3019    representation a base-class initializer into a parameter pack
3020    expansion. If all goes well, the resulting node will be an
3021    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3022    respectively.  */
3023 tree 
3024 make_pack_expansion (tree arg)
3025 {
3026   tree result;
3027   tree parameter_packs = NULL_TREE;
3028   bool for_types = false;
3029   struct find_parameter_pack_data ppd;
3030
3031   if (!arg || arg == error_mark_node)
3032     return arg;
3033
3034   if (TREE_CODE (arg) == TREE_LIST)
3035     {
3036       /* The only time we will see a TREE_LIST here is for a base
3037          class initializer.  In this case, the TREE_PURPOSE will be a
3038          _TYPE node (representing the base class expansion we're
3039          initializing) and the TREE_VALUE will be a TREE_LIST
3040          containing the initialization arguments. 
3041
3042          The resulting expansion looks somewhat different from most
3043          expansions. Rather than returning just one _EXPANSION, we
3044          return a TREE_LIST whose TREE_PURPOSE is a
3045          TYPE_PACK_EXPANSION containing the bases that will be
3046          initialized.  The TREE_VALUE will be identical to the
3047          original TREE_VALUE, which is a list of arguments that will
3048          be passed to each base.  We do not introduce any new pack
3049          expansion nodes into the TREE_VALUE (although it is possible
3050          that some already exist), because the TREE_PURPOSE and
3051          TREE_VALUE all need to be expanded together with the same
3052          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3053          resulting TREE_PURPOSE will mention the parameter packs in
3054          both the bases and the arguments to the bases.  */
3055       tree purpose;
3056       tree value;
3057       tree parameter_packs = NULL_TREE;
3058
3059       /* Determine which parameter packs will be used by the base
3060          class expansion.  */
3061       ppd.visited = pointer_set_create ();
3062       ppd.parameter_packs = &parameter_packs;
3063       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3064                     &ppd, ppd.visited);
3065
3066       if (parameter_packs == NULL_TREE)
3067         {
3068           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3069           pointer_set_destroy (ppd.visited);
3070           return error_mark_node;
3071         }
3072
3073       if (TREE_VALUE (arg) != void_type_node)
3074         {
3075           /* Collect the sets of parameter packs used in each of the
3076              initialization arguments.  */
3077           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3078             {
3079               /* Determine which parameter packs will be expanded in this
3080                  argument.  */
3081               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3082                             &ppd, ppd.visited);
3083             }
3084         }
3085
3086       pointer_set_destroy (ppd.visited);
3087
3088       /* Create the pack expansion type for the base type.  */
3089       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3090       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3091       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3092
3093       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3094          they will rarely be compared to anything.  */
3095       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3096
3097       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3098     }
3099
3100   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3101     for_types = true;
3102
3103   /* Build the PACK_EXPANSION_* node.  */
3104   result = for_types
3105      ? cxx_make_type (TYPE_PACK_EXPANSION)
3106      : make_node (EXPR_PACK_EXPANSION);
3107   SET_PACK_EXPANSION_PATTERN (result, arg);
3108   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3109     {
3110       /* Propagate type and const-expression information.  */
3111       TREE_TYPE (result) = TREE_TYPE (arg);
3112       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3113     }
3114   else
3115     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3116        they will rarely be compared to anything.  */
3117     SET_TYPE_STRUCTURAL_EQUALITY (result);
3118
3119   /* Determine which parameter packs will be expanded.  */
3120   ppd.parameter_packs = &parameter_packs;
3121   ppd.visited = pointer_set_create ();
3122   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3123   pointer_set_destroy (ppd.visited);
3124
3125   /* Make sure we found some parameter packs.  */
3126   if (parameter_packs == NULL_TREE)
3127     {
3128       if (TYPE_P (arg))
3129         error ("expansion pattern %<%T%> contains no argument packs", arg);
3130       else
3131         error ("expansion pattern %<%E%> contains no argument packs", arg);
3132       return error_mark_node;
3133     }
3134   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3135
3136   return result;
3137 }
3138
3139 /* Checks T for any "bare" parameter packs, which have not yet been
3140    expanded, and issues an error if any are found. This operation can
3141    only be done on full expressions or types (e.g., an expression
3142    statement, "if" condition, etc.), because we could have expressions like:
3143
3144      foo(f(g(h(args)))...)
3145
3146    where "args" is a parameter pack. check_for_bare_parameter_packs
3147    should not be called for the subexpressions args, h(args),
3148    g(h(args)), or f(g(h(args))), because we would produce erroneous
3149    error messages. 
3150
3151    Returns TRUE and emits an error if there were bare parameter packs,
3152    returns FALSE otherwise.  */
3153 bool 
3154 check_for_bare_parameter_packs (tree t)
3155 {
3156   tree parameter_packs = NULL_TREE;
3157   struct find_parameter_pack_data ppd;
3158
3159   if (!processing_template_decl || !t || t == error_mark_node)
3160     return false;
3161
3162   if (TREE_CODE (t) == TYPE_DECL)
3163     t = TREE_TYPE (t);
3164
3165   ppd.parameter_packs = &parameter_packs;
3166   ppd.visited = pointer_set_create ();
3167   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3168   pointer_set_destroy (ppd.visited);
3169
3170   if (parameter_packs) 
3171     {
3172       error ("parameter packs not expanded with %<...%>:");
3173       while (parameter_packs)
3174         {
3175           tree pack = TREE_VALUE (parameter_packs);
3176           tree name = NULL_TREE;
3177
3178           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3179               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3180             name = TYPE_NAME (pack);
3181           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3182             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3183           else
3184             name = DECL_NAME (pack);
3185
3186           if (name)
3187             inform (input_location, "        %qD", name);
3188           else
3189             inform (input_location, "        <anonymous>");
3190
3191           parameter_packs = TREE_CHAIN (parameter_packs);
3192         }
3193
3194       return true;
3195     }
3196
3197   return false;
3198 }
3199
3200 /* Expand any parameter packs that occur in the template arguments in
3201    ARGS.  */
3202 tree
3203 expand_template_argument_pack (tree args)
3204 {
3205   tree result_args = NULL_TREE;
3206   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3207   int num_result_args = -1;
3208   int non_default_args_count = -1;
3209
3210   /* First, determine if we need to expand anything, and the number of
3211      slots we'll need.  */
3212   for (in_arg = 0; in_arg < nargs; ++in_arg)
3213     {
3214       tree arg = TREE_VEC_ELT (args, in_arg);
3215       if (arg == NULL_TREE)
3216         return args;
3217       if (ARGUMENT_PACK_P (arg))
3218         {
3219           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3220           if (num_result_args < 0)
3221             num_result_args = in_arg + num_packed;
3222           else
3223             num_result_args += num_packed;
3224         }
3225       else
3226         {
3227           if (num_result_args >= 0)
3228             num_result_args++;
3229         }
3230     }
3231
3232   /* If no expansion is necessary, we're done.  */
3233   if (num_result_args < 0)
3234     return args;
3235
3236   /* Expand arguments.  */
3237   result_args = make_tree_vec (num_result_args);
3238   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3239     non_default_args_count =
3240       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3241   for (in_arg = 0; in_arg < nargs; ++in_arg)
3242     {
3243       tree arg = TREE_VEC_ELT (args, in_arg);
3244       if (ARGUMENT_PACK_P (arg))
3245         {
3246           tree packed = ARGUMENT_PACK_ARGS (arg);
3247           int i, num_packed = TREE_VEC_LENGTH (packed);
3248           for (i = 0; i < num_packed; ++i, ++out_arg)
3249             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3250           if (non_default_args_count > 0)
3251             non_default_args_count += num_packed;
3252         }
3253       else
3254         {
3255           TREE_VEC_ELT (result_args, out_arg) = arg;
3256           ++out_arg;
3257         }
3258     }
3259   if (non_default_args_count >= 0)
3260     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3261   return result_args;
3262 }
3263
3264 /* Checks if DECL shadows a template parameter.
3265
3266    [temp.local]: A template-parameter shall not be redeclared within its
3267    scope (including nested scopes).
3268
3269    Emits an error and returns TRUE if the DECL shadows a parameter,
3270    returns FALSE otherwise.  */
3271
3272 bool
3273 check_template_shadow (tree decl)
3274 {
3275   tree olddecl;
3276
3277   /* If we're not in a template, we can't possibly shadow a template
3278      parameter.  */
3279   if (!current_template_parms)
3280     return true;
3281
3282   /* Figure out what we're shadowing.  */
3283   if (TREE_CODE (decl) == OVERLOAD)
3284     decl = OVL_CURRENT (decl);
3285   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3286
3287   /* If there's no previous binding for this name, we're not shadowing
3288      anything, let alone a template parameter.  */
3289   if (!olddecl)
3290     return true;
3291
3292   /* If we're not shadowing a template parameter, we're done.  Note
3293      that OLDDECL might be an OVERLOAD (or perhaps even an
3294      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3295      node.  */
3296   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3297     return true;
3298
3299   /* We check for decl != olddecl to avoid bogus errors for using a
3300      name inside a class.  We check TPFI to avoid duplicate errors for
3301      inline member templates.  */
3302   if (decl == olddecl
3303       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3304     return true;
3305
3306   error ("declaration of %q+#D", decl);
3307   error (" shadows template parm %q+#D", olddecl);
3308   return false;
3309 }
3310
3311 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3312    ORIG_LEVEL, DECL, and TYPE.  */
3313
3314 static tree
3315 build_template_parm_index (int index,
3316                            int level,
3317                            int orig_level,
3318                            tree decl,
3319                            tree type)
3320 {
3321   tree t = make_node (TEMPLATE_PARM_INDEX);
3322   TEMPLATE_PARM_IDX (t) = index;
3323   TEMPLATE_PARM_LEVEL (t) = level;
3324   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3325   TEMPLATE_PARM_DECL (t) = decl;
3326   TREE_TYPE (t) = type;
3327   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3328   TREE_READONLY (t) = TREE_READONLY (decl);
3329
3330   return t;
3331 }
3332
3333 /* Find the canonical type parameter for the given template type
3334    parameter.  Returns the canonical type parameter, which may be TYPE
3335    if no such parameter existed.  */
3336 static tree
3337 canonical_type_parameter (tree type)
3338 {
3339   tree list;
3340   int idx = TEMPLATE_TYPE_IDX (type);
3341   if (!canonical_template_parms)
3342     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3343
3344   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3345     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3346
3347   list = VEC_index (tree, canonical_template_parms, idx);
3348   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3349     list = TREE_CHAIN (list);
3350
3351   if (list)
3352     return TREE_VALUE (list);
3353   else
3354     {
3355       VEC_replace(tree, canonical_template_parms, idx,
3356                   tree_cons (NULL_TREE, type, 
3357                              VEC_index (tree, canonical_template_parms, idx)));
3358       return type;
3359     }
3360 }
3361
3362 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3363    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3364    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3365    new one is created.  */
3366
3367 static tree
3368 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3369                             tsubst_flags_t complain)
3370 {
3371   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3372       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3373           != TEMPLATE_PARM_LEVEL (index) - levels)
3374       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3375     {
3376       tree orig_decl = TEMPLATE_PARM_DECL (index);
3377       tree decl, t;
3378
3379       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3380                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3381       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3382       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3383       DECL_ARTIFICIAL (decl) = 1;
3384       SET_DECL_TEMPLATE_PARM_P (decl);
3385
3386       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3387                                      TEMPLATE_PARM_LEVEL (index) - levels,
3388                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3389                                      decl, type);
3390       TEMPLATE_PARM_DESCENDANTS (index) = t;
3391       TEMPLATE_PARM_PARAMETER_PACK (t) 
3392         = TEMPLATE_PARM_PARAMETER_PACK (index);
3393
3394         /* Template template parameters need this.  */
3395       if (TREE_CODE (decl) == TEMPLATE_DECL)
3396         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3397           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3398            args, complain);
3399     }
3400
3401   return TEMPLATE_PARM_DESCENDANTS (index);
3402 }
3403
3404 /* Process information from new template parameter PARM and append it to the
3405    LIST being built.  This new parameter is a non-type parameter iff
3406    IS_NON_TYPE is true. This new parameter is a parameter
3407    pack iff IS_PARAMETER_PACK is true.  The location of PARM is in 
3408    PARM_LOC.  */
3409
3410 tree
3411 process_template_parm (tree list, location_t parm_loc, tree parm, bool is_non_type, 
3412                        bool is_parameter_pack)
3413 {
3414   tree decl = 0;
3415   tree defval;
3416   tree err_parm_list;
3417   int idx = 0;
3418
3419   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3420   defval = TREE_PURPOSE (parm);
3421
3422   if (list)
3423     {
3424       tree p = tree_last (list);
3425
3426       if (p && TREE_VALUE (p) != error_mark_node)
3427         {
3428           p = TREE_VALUE (p);
3429           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3430             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3431           else
3432             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3433         }
3434
3435       ++idx;
3436     }
3437   else
3438     idx = 0;
3439
3440   if (is_non_type)
3441     {
3442       parm = TREE_VALUE (parm);
3443
3444       SET_DECL_TEMPLATE_PARM_P (parm);
3445
3446       if (TREE_TYPE (parm) == error_mark_node)
3447         {
3448           err_parm_list = build_tree_list (defval, parm);
3449           TREE_VALUE (err_parm_list) = error_mark_node;
3450            return chainon (list, err_parm_list);
3451         }
3452       else
3453       {
3454         /* [temp.param]
3455
3456            The top-level cv-qualifiers on the template-parameter are
3457            ignored when determining its type.  */
3458         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3459         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3460           {
3461             err_parm_list = build_tree_list (defval, parm);
3462             TREE_VALUE (err_parm_list) = error_mark_node;
3463              return chainon (list, err_parm_list);
3464           }
3465
3466         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3467           {
3468             /* This template parameter is not a parameter pack, but it
3469                should be. Complain about "bare" parameter packs.  */
3470             check_for_bare_parameter_packs (TREE_TYPE (parm));
3471             
3472             /* Recover by calling this a parameter pack.  */
3473             is_parameter_pack = true;
3474           }
3475       }
3476
3477       /* A template parameter is not modifiable.  */
3478       TREE_CONSTANT (parm) = 1;
3479       TREE_READONLY (parm) = 1;
3480       decl = build_decl (parm_loc,
3481                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3482       TREE_CONSTANT (decl) = 1;
3483       TREE_READONLY (decl) = 1;
3484       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3485         = build_template_parm_index (idx, processing_template_decl,
3486                                      processing_template_decl,
3487                                      decl, TREE_TYPE (parm));
3488
3489       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3490         = is_parameter_pack;
3491     }
3492   else
3493     {
3494       tree t;
3495       parm = TREE_VALUE (TREE_VALUE (parm));
3496
3497       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3498         {
3499           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3500           /* This is for distinguishing between real templates and template
3501              template parameters */
3502           TREE_TYPE (parm) = t;
3503           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3504           decl = parm;
3505         }
3506       else
3507         {
3508           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3509           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3510           decl = build_decl (parm_loc,
3511                              TYPE_DECL, parm, t);
3512         }
3513
3514       TYPE_NAME (t) = decl;
3515       TYPE_STUB_DECL (t) = decl;
3516       parm = decl;
3517       TEMPLATE_TYPE_PARM_INDEX (t)
3518         = build_template_parm_index (idx, processing_template_decl,
3519                                      processing_template_decl,
3520                                      decl, TREE_TYPE (parm));
3521       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3522       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3523     }
3524   DECL_ARTIFICIAL (decl) = 1;
3525   SET_DECL_TEMPLATE_PARM_P (decl);
3526   pushdecl (decl);
3527   parm = build_tree_list (defval, parm);
3528   return chainon (list, parm);
3529 }
3530
3531 /* The end of a template parameter list has been reached.  Process the
3532    tree list into a parameter vector, converting each parameter into a more
3533    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3534    as PARM_DECLs.  */
3535
3536 tree
3537 end_template_parm_list (tree parms)
3538 {
3539   int nparms;
3540   tree parm, next;
3541   tree saved_parmlist = make_tree_vec (list_length (parms));
3542
3543   current_template_parms
3544     = tree_cons (size_int (processing_template_decl),
3545                  saved_parmlist, current_template_parms);
3546
3547   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3548     {
3549       next = TREE_CHAIN (parm);
3550       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3551       TREE_CHAIN (parm) = NULL_TREE;
3552     }
3553
3554   --processing_template_parmlist;
3555
3556   return saved_parmlist;
3557 }
3558
3559 /* end_template_decl is called after a template declaration is seen.  */
3560
3561 void
3562 end_template_decl (void)
3563 {
3564   reset_specialization ();
3565
3566   if (! processing_template_decl)
3567     return;
3568
3569   /* This matches the pushlevel in begin_template_parm_list.  */
3570   finish_scope ();
3571
3572   --processing_template_decl;
3573   current_template_parms = TREE_CHAIN (current_template_parms);
3574 }
3575
3576 /* Within the declaration of a template, return all levels of template
3577    parameters that apply.  The template parameters are represented as
3578    a TREE_VEC, in the form documented in cp-tree.h for template
3579    arguments.  */
3580
3581 static tree
3582 current_template_args (void)
3583 {
3584   tree header;
3585   tree args = NULL_TREE;
3586   int length = TMPL_PARMS_DEPTH (current_template_parms);
3587   int l = length;
3588
3589   /* If there is only one level of template parameters, we do not
3590      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3591      TREE_VEC containing the arguments.  */
3592   if (length > 1)
3593     args = make_tree_vec (length);
3594
3595   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3596     {
3597       tree a = copy_node (TREE_VALUE (header));
3598       int i;
3599
3600       TREE_TYPE (a) = NULL_TREE;
3601       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3602         {
3603           tree t = TREE_VEC_ELT (a, i);
3604
3605           /* T will be a list if we are called from within a
3606              begin/end_template_parm_list pair, but a vector directly
3607              if within a begin/end_member_template_processing pair.  */
3608           if (TREE_CODE (t) == TREE_LIST)
3609             {
3610               t = TREE_VALUE (t);
3611
3612               if (!error_operand_p (t))
3613                 {
3614                   if (TREE_CODE (t) == TYPE_DECL
3615                       || TREE_CODE (t) == TEMPLATE_DECL)
3616                     {
3617                       t = TREE_TYPE (t);
3618                       
3619                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3620                         {
3621                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3622                              with a single element, which expands T.  */
3623                           tree vec = make_tree_vec (1);
3624 #ifdef ENABLE_CHECKING
3625                           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3626                                 (vec, TREE_VEC_LENGTH (vec));
3627 #endif
3628                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3629                           
3630                           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3631                           SET_ARGUMENT_PACK_ARGS (t, vec);
3632                         }
3633                     }
3634                   else
3635                     {
3636                       t = DECL_INITIAL (t);
3637                       
3638                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3639                         {
3640                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3641                              with a single element, which expands T.  */
3642                           tree vec = make_tree_vec (1);
3643                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3644 #ifdef ENABLE_CHECKING
3645                           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3646                                 (vec, TREE_VEC_LENGTH (vec));
3647 #endif
3648                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3649                           
3650                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3651                           SET_ARGUMENT_PACK_ARGS (t, vec);
3652                           TREE_TYPE (t) = type;
3653                         }
3654                     }
3655                   TREE_VEC_ELT (a, i) = t;
3656                 }
3657             }
3658         }
3659
3660 #ifdef ENABLE_CHECKING
3661       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
3662 #endif
3663
3664       if (length > 1)
3665         TREE_VEC_ELT (args, --l) = a;
3666       else
3667         args = a;
3668     }
3669
3670   return args;
3671 }
3672
3673 /* Update the declared TYPE by doing any lookups which were thought to be
3674    dependent, but are not now that we know the SCOPE of the declarator.  */
3675
3676 tree
3677 maybe_update_decl_type (tree orig_type, tree scope)
3678 {
3679   tree type = orig_type;
3680
3681   if (type == NULL_TREE)
3682     return type;
3683
3684   if (TREE_CODE (orig_type) == TYPE_DECL)
3685     type = TREE_TYPE (type);
3686
3687   if (scope && TYPE_P (scope) && dependent_type_p (scope)
3688       && dependent_type_p (type)
3689       /* Don't bother building up the args in this case.  */
3690       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
3691     {
3692       /* tsubst in the args corresponding to the template parameters,
3693          including auto if present.  Most things will be unchanged, but
3694          make_typename_type and tsubst_qualified_id will resolve
3695          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
3696       tree args = current_template_args ();
3697       tree auto_node = type_uses_auto (type);
3698       if (auto_node)
3699         {
3700           tree auto_vec = make_tree_vec (1);
3701           TREE_VEC_ELT (auto_vec, 0) = auto_node;
3702           args = add_to_template_args (args, auto_vec);
3703         }
3704       push_scope (scope);
3705       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
3706       pop_scope (scope);
3707     }
3708
3709   if (type == error_mark_node)
3710     return orig_type;
3711
3712   if (TREE_CODE (orig_type) == TYPE_DECL)
3713     {
3714       if (same_type_p (type, TREE_TYPE (orig_type)))
3715         type = orig_type;
3716       else
3717         type = TYPE_NAME (type);
3718     }
3719   return type;
3720 }
3721
3722 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3723    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3724    a member template.  Used by push_template_decl below.  */
3725
3726 static tree
3727 build_template_decl (tree decl, tree parms, bool member_template_p)
3728 {
3729   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3730   DECL_TEMPLATE_PARMS (tmpl) = parms;
3731   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3732   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3733
3734   return tmpl;
3735 }
3736
3737 struct template_parm_data
3738 {
3739   /* The level of the template parameters we are currently
3740      processing.  */
3741   int level;
3742
3743   /* The index of the specialization argument we are currently
3744      processing.  */
3745   int current_arg;
3746
3747   /* An array whose size is the number of template parameters.  The
3748      elements are nonzero if the parameter has been used in any one
3749      of the arguments processed so far.  */
3750   int* parms;
3751
3752   /* An array whose size is the number of template arguments.  The
3753      elements are nonzero if the argument makes use of template
3754      parameters of this level.  */
3755   int* arg_uses_template_parms;
3756 };
3757
3758 /* Subroutine of push_template_decl used to see if each template
3759    parameter in a partial specialization is used in the explicit
3760    argument list.  If T is of the LEVEL given in DATA (which is
3761    treated as a template_parm_data*), then DATA->PARMS is marked
3762    appropriately.  */
3763
3764 static int
3765 mark_template_parm (tree t, void* data)
3766 {
3767   int level;
3768   int idx;
3769   struct template_parm_data* tpd = (struct template_parm_data*) data;
3770
3771   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3772     {
3773       level = TEMPLATE_PARM_LEVEL (t);
3774       idx = TEMPLATE_PARM_IDX (t);
3775     }
3776   else
3777     {
3778       level = TEMPLATE_TYPE_LEVEL (t);
3779       idx = TEMPLATE_TYPE_IDX (t);
3780     }
3781
3782   if (level == tpd->level)
3783     {
3784       tpd->parms[idx] = 1;
3785       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3786     }
3787
3788   /* Return zero so that for_each_template_parm will continue the
3789      traversal of the tree; we want to mark *every* template parm.  */
3790   return 0;
3791 }
3792
3793 /* Process the partial specialization DECL.  */
3794
3795 static tree
3796 process_partial_specialization (tree decl)
3797 {
3798   tree type = TREE_TYPE (decl);
3799   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3800   tree specargs = CLASSTYPE_TI_ARGS (type);
3801   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3802   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3803   tree inner_parms;
3804   int nargs = TREE_VEC_LENGTH (inner_args);
3805   int ntparms;
3806   int  i;
3807   int did_error_intro = 0;
3808   struct template_parm_data tpd;
3809   struct template_parm_data tpd2;
3810
3811   gcc_assert (current_template_parms);
3812
3813   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3814   ntparms = TREE_VEC_LENGTH (inner_parms);
3815
3816   /* We check that each of the template parameters given in the
3817      partial specialization is used in the argument list to the
3818      specialization.  For example:
3819
3820        template <class T> struct S;
3821        template <class T> struct S<T*>;
3822
3823      The second declaration is OK because `T*' uses the template
3824      parameter T, whereas
3825
3826        template <class T> struct S<int>;
3827
3828      is no good.  Even trickier is:
3829
3830        template <class T>
3831        struct S1
3832        {
3833           template <class U>
3834           struct S2;
3835           template <class U>
3836           struct S2<T>;
3837        };
3838
3839      The S2<T> declaration is actually invalid; it is a
3840      full-specialization.  Of course,
3841
3842           template <class U>
3843           struct S2<T (*)(U)>;
3844
3845      or some such would have been OK.  */
3846   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3847   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3848   memset (tpd.parms, 0, sizeof (int) * ntparms);
3849
3850   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3851   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3852   for (i = 0; i < nargs; ++i)
3853     {
3854       tpd.current_arg = i;
3855       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3856                               &mark_template_parm,
3857                               &tpd,
3858                               NULL,
3859                               /*include_nondeduced_p=*/false);
3860     }
3861   for (i = 0; i < ntparms; ++i)
3862     if (tpd.parms[i] == 0)
3863       {
3864         /* One of the template parms was not used in the
3865            specialization.  */
3866         if (!did_error_intro)
3867           {
3868             error ("template parameters not used in partial specialization:");
3869             did_error_intro = 1;
3870           }
3871
3872         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3873       }
3874
3875   /* [temp.class.spec]
3876
3877      The argument list of the specialization shall not be identical to
3878      the implicit argument list of the primary template.  */
3879   if (comp_template_args
3880       (inner_args,
3881        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3882                                                    (maintmpl)))))
3883     error ("partial specialization %qT does not specialize any template arguments", type);
3884
3885   /* [temp.class.spec]
3886
3887      A partially specialized non-type argument expression shall not
3888      involve template parameters of the partial specialization except
3889      when the argument expression is a simple identifier.
3890
3891      The type of a template parameter corresponding to a specialized
3892      non-type argument shall not be dependent on a parameter of the
3893      specialization. 
3894
3895      Also, we verify that pack expansions only occur at the
3896      end of the argument list.  */
3897   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3898   tpd2.parms = 0;
3899   for (i = 0; i < nargs; ++i)
3900     {
3901       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3902       tree arg = TREE_VEC_ELT (inner_args, i);
3903       tree packed_args = NULL_TREE;
3904       int j, len = 1;
3905
3906       if (ARGUMENT_PACK_P (arg))
3907         {
3908           /* Extract the arguments from the argument pack. We'll be
3909              iterating over these in the following loop.  */
3910           packed_args = ARGUMENT_PACK_ARGS (arg);
3911           len = TREE_VEC_LENGTH (packed_args);
3912         }
3913
3914       for (j = 0; j < len; j++)
3915         {
3916           if (packed_args)
3917             /* Get the Jth argument in the parameter pack.  */
3918             arg = TREE_VEC_ELT (packed_args, j);
3919
3920           if (PACK_EXPANSION_P (arg))
3921             {
3922               /* Pack expansions must come at the end of the
3923                  argument list.  */
3924               if ((packed_args && j < len - 1)
3925                   || (!packed_args && i < nargs - 1))
3926                 {
3927                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3928                     error ("parameter pack argument %qE must be at the "
3929                            "end of the template argument list", arg);
3930                   else
3931                     error ("parameter pack argument %qT must be at the "
3932                            "end of the template argument list", arg);
3933                 }
3934             }
3935
3936           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3937             /* We only care about the pattern.  */
3938             arg = PACK_EXPANSION_PATTERN (arg);
3939
3940           if (/* These first two lines are the `non-type' bit.  */
3941               !TYPE_P (arg)
3942               && TREE_CODE (arg) != TEMPLATE_DECL
3943               /* This next line is the `argument expression is not just a
3944                  simple identifier' condition and also the `specialized
3945                  non-type argument' bit.  */
3946               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3947             {
3948               if ((!packed_args && tpd.arg_uses_template_parms[i])
3949                   || (packed_args && uses_template_parms (arg)))
3950                 error ("template argument %qE involves template parameter(s)",
3951                        arg);
3952               else 
3953                 {
3954                   /* Look at the corresponding template parameter,
3955                      marking which template parameters its type depends
3956                      upon.  */
3957                   tree type = TREE_TYPE (parm);
3958
3959                   if (!tpd2.parms)
3960                     {
3961                       /* We haven't yet initialized TPD2.  Do so now.  */
3962                       tpd2.arg_uses_template_parms 
3963                         = (int *) alloca (sizeof (int) * nargs);
3964                       /* The number of parameters here is the number in the
3965                          main template, which, as checked in the assertion
3966                          above, is NARGS.  */
3967                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3968                       tpd2.level = 
3969                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3970                     }
3971
3972                   /* Mark the template parameters.  But this time, we're
3973                      looking for the template parameters of the main
3974                      template, not in the specialization.  */
3975                   tpd2.current_arg = i;
3976                   tpd2.arg_uses_template_parms[i] = 0;
3977                   memset (tpd2.parms, 0, sizeof (int) * nargs);
3978                   for_each_template_parm (type,
3979                                           &mark_template_parm,
3980                                           &tpd2,
3981                                           NULL,
3982                                           /*include_nondeduced_p=*/false);
3983
3984                   if (tpd2.arg_uses_template_parms [i])
3985                     {
3986                       /* The type depended on some template parameters.
3987                          If they are fully specialized in the
3988                          specialization, that's OK.  */
3989                       int j;
3990                       for (j = 0; j < nargs; ++j)
3991                         if (tpd2.parms[j] != 0
3992                             && tpd.arg_uses_template_parms [j])
3993                           {
3994                             error ("type %qT of template argument %qE depends "
3995                                    "on template parameter(s)", 
3996                                    type,
3997                                    arg);
3998                             break;
3999                           }
4000                     }
4001                 }
4002             }
4003         }
4004     }
4005
4006   /* We should only get here once.  */
4007   gcc_assert (!COMPLETE_TYPE_P (type));
4008
4009   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4010     = tree_cons (specargs, inner_parms,
4011                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4012   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4013   return decl;
4014 }
4015
4016 /* Check that a template declaration's use of default arguments and
4017    parameter packs is not invalid.  Here, PARMS are the template
4018    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
4019    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
4020    specialization.
4021    
4022
4023    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4024    declaration (but not a definition); 1 indicates a declaration, 2
4025    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4026    emitted for extraneous default arguments.
4027
4028    Returns TRUE if there were no errors found, FALSE otherwise. */
4029
4030 bool
4031 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
4032                          int is_partial, int is_friend_decl)
4033 {
4034   const char *msg;
4035   int last_level_to_check;
4036   tree parm_level;
4037   bool no_errors = true;
4038
4039   /* [temp.param]
4040
4041      A default template-argument shall not be specified in a
4042      function template declaration or a function template definition, nor
4043      in the template-parameter-list of the definition of a member of a
4044      class template.  */
4045
4046   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
4047     /* You can't have a function template declaration in a local
4048        scope, nor you can you define a member of a class template in a
4049        local scope.  */
4050     return true;
4051
4052   if (current_class_type
4053       && !TYPE_BEING_DEFINED (current_class_type)
4054       && DECL_LANG_SPECIFIC (decl)
4055       && DECL_DECLARES_FUNCTION_P (decl)
4056       /* If this is either a friend defined in the scope of the class
4057          or a member function.  */
4058       && (DECL_FUNCTION_MEMBER_P (decl)
4059           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4060           : DECL_FRIEND_CONTEXT (decl)
4061           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4062           : false)
4063       /* And, if it was a member function, it really was defined in
4064          the scope of the class.  */
4065       && (!DECL_FUNCTION_MEMBER_P (decl)
4066           || DECL_INITIALIZED_IN_CLASS_P (decl)))
4067     /* We already checked these parameters when the template was
4068        declared, so there's no need to do it again now.  This function
4069        was defined in class scope, but we're processing it's body now
4070        that the class is complete.  */
4071     return true;
4072
4073   /* Core issue 226 (C++0x only): the following only applies to class
4074      templates.  */
4075   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
4076     {
4077       /* [temp.param]
4078
4079          If a template-parameter has a default template-argument, all
4080          subsequent template-parameters shall have a default
4081          template-argument supplied.  */
4082       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4083         {
4084           tree inner_parms = TREE_VALUE (parm_level);
4085           int ntparms = TREE_VEC_LENGTH (inner_parms);
4086           int seen_def_arg_p = 0;
4087           int i;
4088
4089           for (i = 0; i < ntparms; ++i)
4090             {
4091               tree parm = TREE_VEC_ELT (inner_parms, i);
4092
4093               if (parm == error_mark_node)
4094                 continue;
4095
4096               if (TREE_PURPOSE (parm))
4097                 seen_def_arg_p = 1;
4098               else if (seen_def_arg_p
4099                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4100                 {
4101                   error ("no default argument for %qD", TREE_VALUE (parm));
4102                   /* For better subsequent error-recovery, we indicate that
4103                      there should have been a default argument.  */
4104                   TREE_PURPOSE (parm) = error_mark_node;
4105                   no_errors = false;
4106                 }
4107               else if (is_primary
4108                        && !is_partial
4109                        && !is_friend_decl
4110                        /* Don't complain about an enclosing partial
4111                           specialization.  */
4112                        && parm_level == parms
4113                        && TREE_CODE (decl) == TYPE_DECL
4114                        && i < ntparms - 1
4115                        && template_parameter_pack_p (TREE_VALUE (parm)))
4116                 {
4117                   /* A primary class template can only have one
4118                      parameter pack, at the end of the template
4119                      parameter list.  */
4120
4121                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4122                     error ("parameter pack %qE must be at the end of the"
4123                            " template parameter list", TREE_VALUE (parm));
4124                   else
4125                     error ("parameter pack %qT must be at the end of the"
4126                            " template parameter list", 
4127                            TREE_TYPE (TREE_VALUE (parm)));
4128
4129                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4130                     = error_mark_node;
4131                   no_errors = false;
4132                 }
4133             }
4134         }
4135     }
4136
4137   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4138       || is_partial 
4139       || !is_primary
4140       || is_friend_decl)
4141     /* For an ordinary class template, default template arguments are
4142        allowed at the innermost level, e.g.:
4143          template <class T = int>
4144          struct S {};
4145        but, in a partial specialization, they're not allowed even
4146        there, as we have in [temp.class.spec]:
4147
4148          The template parameter list of a specialization shall not
4149          contain default template argument values.
4150
4151        So, for a partial specialization, or for a function template
4152        (in C++98/C++03), we look at all of them.  */
4153     ;
4154   else
4155     /* But, for a primary class template that is not a partial
4156        specialization we look at all template parameters except the
4157        innermost ones.  */
4158     parms = TREE_CHAIN (parms);
4159
4160   /* Figure out what error message to issue.  */
4161   if (is_friend_decl == 2)
4162     msg = G_("default template arguments may not be used in function template "
4163              "friend re-declaration");
4164   else if (is_friend_decl)
4165     msg = G_("default template arguments may not be used in function template "
4166              "friend declarations");
4167   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4168     msg = G_("default template arguments may not be used in function templates "
4169              "without -std=c++0x or -std=gnu++0x");
4170   else if (is_partial)
4171     msg = G_("default template arguments may not be used in "
4172              "partial specializations");
4173   else
4174     msg = G_("default argument for template parameter for class enclosing %qD");
4175
4176   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4177     /* If we're inside a class definition, there's no need to
4178        examine the parameters to the class itself.  On the one
4179        hand, they will be checked when the class is defined, and,
4180        on the other, default arguments are valid in things like:
4181          template <class T = double>
4182          struct S { template <class U> void f(U); };
4183        Here the default argument for `S' has no bearing on the
4184        declaration of `f'.  */
4185     last_level_to_check = template_class_depth (current_class_type) + 1;
4186   else
4187     /* Check everything.  */
4188     last_level_to_check = 0;
4189
4190   for (parm_level = parms;
4191        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4192        parm_level = TREE_CHAIN (parm_level))
4193     {
4194       tree inner_parms = TREE_VALUE (parm_level);
4195       int i;
4196       int ntparms;
4197
4198       ntparms = TREE_VEC_LENGTH (inner_parms);
4199       for (i = 0; i < ntparms; ++i)
4200         {
4201           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4202             continue;
4203
4204           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4205             {
4206               if (msg)
4207                 {
4208                   no_errors = false;
4209                   if (is_friend_decl == 2)
4210                     return no_errors;
4211
4212                   error (msg, decl);
4213                   msg = 0;
4214                 }
4215
4216               /* Clear out the default argument so that we are not
4217                  confused later.  */
4218               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4219             }
4220         }
4221
4222       /* At this point, if we're still interested in issuing messages,
4223          they must apply to classes surrounding the object declared.  */
4224       if (msg)
4225         msg = G_("default argument for template parameter for class "
4226                  "enclosing %qD");
4227     }
4228
4229   return no_errors;
4230 }
4231
4232 /* Worker for push_template_decl_real, called via
4233    for_each_template_parm.  DATA is really an int, indicating the
4234    level of the parameters we are interested in.  If T is a template
4235    parameter of that level, return nonzero.  */
4236
4237 static int
4238 template_parm_this_level_p (tree t, void* data)
4239 {
4240   int this_level = *(int *)data;
4241   int level;
4242
4243   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4244     level = TEMPLATE_PARM_LEVEL (t);
4245   else
4246     level = TEMPLATE_TYPE_LEVEL (t);
4247   return level == this_level;
4248 }
4249
4250 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4251    parameters given by current_template_args, or reuses a
4252    previously existing one, if appropriate.  Returns the DECL, or an
4253    equivalent one, if it is replaced via a call to duplicate_decls.
4254
4255    If IS_FRIEND is true, DECL is a friend declaration.  */
4256
4257 tree
4258 push_template_decl_real (tree decl, bool is_friend)
4259 {
4260   tree tmpl;
4261   tree args;
4262   tree info;
4263   tree ctx;
4264   int primary;
4265   int is_partial;
4266   int new_template_p = 0;
4267   /* True if the template is a member template, in the sense of
4268      [temp.mem].  */
4269   bool member_template_p = false;
4270
4271   if (decl == error_mark_node || !current_template_parms)
4272     return error_mark_node;
4273
4274   /* See if this is a partial specialization.  */
4275   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4276                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4277                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4278
4279   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4280     is_friend = true;
4281
4282   if (is_friend)
4283     /* For a friend, we want the context of the friend function, not
4284        the type of which it is a friend.  */
4285     ctx = DECL_CONTEXT (decl);
4286   else if (CP_DECL_CONTEXT (decl)
4287            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4288     /* In the case of a virtual function, we want the class in which
4289        it is defined.  */
4290     ctx = CP_DECL_CONTEXT (decl);
4291   else
4292     /* Otherwise, if we're currently defining some class, the DECL
4293        is assumed to be a member of the class.  */
4294     ctx = current_scope ();
4295
4296   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4297     ctx = NULL_TREE;
4298
4299   if (!DECL_CONTEXT (decl))
4300     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4301
4302   /* See if this is a primary template.  */
4303   if (is_friend && ctx)
4304     /* A friend template that specifies a class context, i.e.
4305          template <typename T> friend void A<T>::f();
4306        is not primary.  */
4307     primary = 0;
4308   else
4309     primary = template_parm_scope_p ();
4310
4311   if (primary)
4312     {
4313       if (DECL_CLASS_SCOPE_P (decl))
4314         member_template_p = true;
4315       if (TREE_CODE (decl) == TYPE_DECL
4316           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4317         {
4318           error ("template class without a name");
4319           return error_mark_node;
4320         }
4321       else if (TREE_CODE (decl) == FUNCTION_DECL)
4322         {
4323           if (DECL_DESTRUCTOR_P (decl))
4324             {
4325               /* [temp.mem]
4326
4327                  A destructor shall not be a member template.  */
4328               error ("destructor %qD declared as member template", decl);
4329               return error_mark_node;
4330             }
4331           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4332               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
4333                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4334                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4335                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4336                       == void_list_node)))
4337             {
4338               /* [basic.stc.dynamic.allocation]
4339
4340                  An allocation function can be a function
4341                  template. ... Template allocation functions shall
4342                  have two or more parameters.  */
4343               error ("invalid template declaration of %qD", decl);
4344               return error_mark_node;
4345             }
4346         }
4347       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4348                && CLASS_TYPE_P (TREE_TYPE (decl)))
4349         /* OK */;
4350       else
4351         {
4352           error ("template declaration of %q#D", decl);
4353           return error_mark_node;
4354         }
4355     }
4356
4357   /* Check to see that the rules regarding the use of default
4358      arguments are not being violated.  */
4359   check_default_tmpl_args (decl, current_template_parms,
4360                            primary, is_partial, /*is_friend_decl=*/0);
4361
4362   /* Ensure that there are no parameter packs in the type of this
4363      declaration that have not been expanded.  */
4364   if (TREE_CODE (decl) == FUNCTION_DECL)
4365     {
4366       /* Check each of the arguments individually to see if there are
4367          any bare parameter packs.  */
4368       tree type = TREE_TYPE (decl);
4369       tree arg = DECL_ARGUMENTS (decl);
4370       tree argtype = TYPE_ARG_TYPES (type);
4371
4372       while (arg && argtype)
4373         {
4374           if (!FUNCTION_PARAMETER_PACK_P (arg)
4375               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4376             {
4377             /* This is a PARM_DECL that contains unexpanded parameter
4378                packs. We have already complained about this in the
4379                check_for_bare_parameter_packs call, so just replace
4380                these types with ERROR_MARK_NODE.  */
4381               TREE_TYPE (arg) = error_mark_node;
4382               TREE_VALUE (argtype) = error_mark_node;
4383             }
4384
4385           arg = TREE_CHAIN (arg);
4386           argtype = TREE_CHAIN (argtype);
4387         }
4388
4389       /* Check for bare parameter packs in the return type and the
4390          exception specifiers.  */
4391       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4392         /* Errors were already issued, set return type to int
4393            as the frontend doesn't expect error_mark_node as
4394            the return type.  */
4395         TREE_TYPE (type) = integer_type_node;
4396       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4397         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4398     }
4399   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4400     {
4401       TREE_TYPE (decl) = error_mark_node;
4402       return error_mark_node;
4403     }
4404
4405   if (is_partial)
4406     return process_partial_specialization (decl);
4407
4408   args = current_template_args ();
4409
4410   if (!ctx
4411       || TREE_CODE (ctx) == FUNCTION_DECL
4412       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4413       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4414     {
4415       if (DECL_LANG_SPECIFIC (decl)
4416           && DECL_TEMPLATE_INFO (decl)
4417           && DECL_TI_TEMPLATE (decl))
4418         tmpl = DECL_TI_TEMPLATE (decl);
4419       /* If DECL is a TYPE_DECL for a class-template, then there won't
4420          be DECL_LANG_SPECIFIC.  The information equivalent to
4421          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4422       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4423                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4424                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4425         {
4426           /* Since a template declaration already existed for this
4427              class-type, we must be redeclaring it here.  Make sure
4428              that the redeclaration is valid.  */
4429           redeclare_class_template (TREE_TYPE (decl),
4430                                     current_template_parms);
4431           /* We don't need to create a new TEMPLATE_DECL; just use the
4432              one we already had.  */
4433           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4434         }
4435       else
4436         {
4437           tmpl = build_template_decl (decl, current_template_parms,
4438                                       member_template_p);
4439           new_template_p = 1;
4440
4441           if (DECL_LANG_SPECIFIC (decl)
4442               && DECL_TEMPLATE_SPECIALIZATION (decl))
4443             {
4444               /* A specialization of a member template of a template
4445                  class.  */
4446               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4447               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4448               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4449             }
4450         }
4451     }
4452   else
4453     {
4454       tree a, t, current, parms;
4455       int i;
4456       tree tinfo = get_template_info (decl);
4457
4458       if (!tinfo)
4459         {
4460           error ("template definition of non-template %q#D", decl);
4461           return error_mark_node;
4462         }
4463
4464       tmpl = TI_TEMPLATE (tinfo);
4465
4466       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4467           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4468           && DECL_TEMPLATE_SPECIALIZATION (decl)
4469           && DECL_MEMBER_TEMPLATE_P (tmpl))
4470         {
4471           tree new_tmpl;
4472
4473           /* The declaration is a specialization of a member
4474              template, declared outside the class.  Therefore, the
4475              innermost template arguments will be NULL, so we
4476              replace them with the arguments determined by the
4477              earlier call to check_explicit_specialization.  */
4478           args = DECL_TI_ARGS (decl);
4479
4480           new_tmpl
4481             = build_template_decl (decl, current_template_parms,
4482                                    member_template_p);
4483           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4484           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4485           DECL_TI_TEMPLATE (decl) = new_tmpl;
4486           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4487           DECL_TEMPLATE_INFO (new_tmpl)
4488             = build_template_info (tmpl, args);
4489
4490           register_specialization (new_tmpl,
4491                                    most_general_template (tmpl),
4492                                    args,
4493                                    is_friend, 0);
4494           return decl;
4495         }
4496
4497       /* Make sure the template headers we got make sense.  */
4498
4499       parms = DECL_TEMPLATE_PARMS (tmpl);
4500       i = TMPL_PARMS_DEPTH (parms);
4501       if (TMPL_ARGS_DEPTH (args) != i)
4502         {
4503           error ("expected %d levels of template parms for %q#D, got %d",
4504                  i, decl, TMPL_ARGS_DEPTH (args));
4505         }
4506       else
4507         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4508           {
4509             a = TMPL_ARGS_LEVEL (args, i);
4510             t = INNERMOST_TEMPLATE_PARMS (parms);
4511
4512             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4513               {
4514                 if (current == decl)
4515                   error ("got %d template parameters for %q#D",
4516                          TREE_VEC_LENGTH (a), decl);
4517                 else
4518                   error ("got %d template parameters for %q#T",
4519                          TREE_VEC_LENGTH (a), current);
4520                 error ("  but %d required", TREE_VEC_LENGTH (t));
4521                 return error_mark_node;
4522               }
4523
4524             if (current == decl)
4525               current = ctx;
4526             else
4527               current = (TYPE_P (current)
4528                          ? TYPE_CONTEXT (current)
4529                          : DECL_CONTEXT (current));
4530           }
4531
4532       /* Check that the parms are used in the appropriate qualifying scopes
4533          in the declarator.  */
4534       if (!comp_template_args
4535           (TI_ARGS (tinfo),
4536            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4537         {
4538           error ("\
4539 template arguments to %qD do not match original template %qD",
4540                  decl, DECL_TEMPLATE_RESULT (tmpl));
4541           if (!uses_template_parms (TI_ARGS (tinfo)))
4542             inform (input_location, "use template<> for an explicit specialization");
4543           /* Avoid crash in import_export_decl.  */
4544           DECL_INTERFACE_KNOWN (decl) = 1;
4545           return error_mark_node;
4546         }
4547     }
4548
4549   DECL_TEMPLATE_RESULT (tmpl) = decl;
4550   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4551
4552   /* Push template declarations for global functions and types.  Note
4553      that we do not try to push a global template friend declared in a
4554      template class; such a thing may well depend on the template
4555      parameters of the class.  */
4556   if (new_template_p && !ctx
4557       && !(is_friend && template_class_depth (current_class_type) > 0))
4558     {
4559       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4560       if (tmpl == error_mark_node)
4561         return error_mark_node;
4562
4563       /* Hide template friend classes that haven't been declared yet.  */
4564       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4565         {
4566           DECL_ANTICIPATED (tmpl) = 1;
4567           DECL_FRIEND_P (tmpl) = 1;
4568         }
4569     }
4570
4571   if (primary)
4572     {
4573       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4574       int i;
4575
4576       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4577       if (DECL_CONV_FN_P (tmpl))
4578         {
4579           int depth = TMPL_PARMS_DEPTH (parms);
4580
4581           /* It is a conversion operator. See if the type converted to
4582              depends on innermost template operands.  */
4583
4584           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4585                                          depth))
4586             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4587         }
4588
4589       /* Give template template parms a DECL_CONTEXT of the template
4590          for which they are a parameter.  */
4591       parms = INNERMOST_TEMPLATE_PARMS (parms);
4592       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4593         {
4594           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4595           if (TREE_CODE (parm) == TEMPLATE_DECL)
4596             DECL_CONTEXT (parm) = tmpl;
4597
4598           if (TREE_CODE (TREE_TYPE (parm)) == TEMPLATE_TYPE_PARM)
4599             DECL_CONTEXT (TYPE_NAME (TREE_TYPE (parm))) = tmpl;
4600         }
4601     }
4602
4603   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4604      back to its most general template.  If TMPL is a specialization,
4605      ARGS may only have the innermost set of arguments.  Add the missing
4606      argument levels if necessary.  */
4607   if (DECL_TEMPLATE_INFO (tmpl))
4608     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4609
4610   info = build_template_info (tmpl, args);
4611
4612   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4613     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4614   else if (DECL_LANG_SPECIFIC (decl))
4615     DECL_TEMPLATE_INFO (decl) = info;
4616
4617   return DECL_TEMPLATE_RESULT (tmpl);
4618 }
4619
4620 tree
4621 push_template_decl (tree decl)
4622 {
4623   return push_template_decl_real (decl, false);
4624 }
4625
4626 /* Called when a class template TYPE is redeclared with the indicated
4627    template PARMS, e.g.:
4628
4629      template <class T> struct S;
4630      template <class T> struct S {};  */
4631
4632 bool
4633 redeclare_class_template (tree type, tree parms)
4634 {
4635   tree tmpl;
4636   tree tmpl_parms;
4637   int i;
4638
4639   if (!TYPE_TEMPLATE_INFO (type))
4640     {
4641       error ("%qT is not a template type", type);
4642       return false;
4643     }
4644
4645   tmpl = TYPE_TI_TEMPLATE (type);
4646   if (!PRIMARY_TEMPLATE_P (tmpl))
4647     /* The type is nested in some template class.  Nothing to worry
4648        about here; there are no new template parameters for the nested
4649        type.  */
4650     return true;
4651
4652   if (!parms)
4653     {
4654       error ("template specifiers not specified in declaration of %qD",
4655              tmpl);
4656       return false;
4657     }
4658
4659   parms = INNERMOST_TEMPLATE_PARMS (parms);
4660   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4661
4662   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4663     {
4664       error_n (input_location, TREE_VEC_LENGTH (parms),
4665                "redeclared with %d template parameter",
4666                "redeclared with %d template parameters",
4667                TREE_VEC_LENGTH (parms));
4668       inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
4669                 "previous declaration %q+D used %d template parameter",
4670                 "previous declaration %q+D used %d template parameters",
4671                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
4672       return false;
4673     }
4674
4675   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4676     {
4677       tree tmpl_parm;
4678       tree parm;
4679       tree tmpl_default;
4680       tree parm_default;
4681
4682       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4683           || TREE_VEC_ELT (parms, i) == error_mark_node)
4684         continue;
4685
4686       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4687       if (tmpl_parm == error_mark_node)
4688         return false;
4689
4690       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4691       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4692       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4693
4694       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4695          TEMPLATE_DECL.  */
4696       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4697           || (TREE_CODE (tmpl_parm) != TYPE_DECL
4698               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4699           || (TREE_CODE (tmpl_parm) != PARM_DECL
4700               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4701                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4702           || (TREE_CODE (tmpl_parm) == PARM_DECL
4703               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4704                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
4705         {
4706           error ("template parameter %q+#D", tmpl_parm);
4707           error ("redeclared here as %q#D", parm);
4708           return false;
4709         }
4710
4711       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4712         {
4713           /* We have in [temp.param]:
4714
4715              A template-parameter may not be given default arguments
4716              by two different declarations in the same scope.  */
4717           error_at (input_location, "redefinition of default argument for %q#D", parm);
4718           inform (DECL_SOURCE_LOCATION (tmpl_parm),
4719                   "original definition appeared here");
4720           return false;
4721         }
4722
4723       if (parm_default != NULL_TREE)
4724         /* Update the previous template parameters (which are the ones
4725            that will really count) with the new default value.  */
4726         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4727       else if (tmpl_default != NULL_TREE)
4728         /* Update the new parameters, too; they'll be used as the
4729            parameters for any members.  */
4730         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4731     }
4732
4733     return true;
4734 }
4735
4736 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4737    (possibly simplified) expression.  */
4738
4739 tree
4740 fold_non_dependent_expr (tree expr)
4741 {
4742   if (expr == NULL_TREE)
4743     return NULL_TREE;
4744
4745   /* If we're in a template, but EXPR isn't value dependent, simplify
4746      it.  We're supposed to treat:
4747
4748        template <typename T> void f(T[1 + 1]);
4749        template <typename T> void f(T[2]);
4750
4751      as two declarations of the same function, for example.  */
4752   if (processing_template_decl
4753       && !type_dependent_expression_p (expr)
4754       && !value_dependent_expression_p (expr))
4755     {
4756       HOST_WIDE_INT saved_processing_template_decl;
4757
4758       saved_processing_template_decl = processing_template_decl;
4759       processing_template_decl = 0;
4760       expr = tsubst_copy_and_build (expr,
4761                                     /*args=*/NULL_TREE,
4762                                     tf_error,
4763                                     /*in_decl=*/NULL_TREE,
4764                                     /*function_p=*/false,
4765                                     /*integral_constant_expression_p=*/true);
4766       processing_template_decl = saved_processing_template_decl;
4767     }
4768   return expr;
4769 }
4770
4771 /* EXPR is an expression which is used in a constant-expression context.
4772    For instance, it could be a VAR_DECL with a constant initializer.
4773    Extract the innermost constant expression.
4774
4775    This is basically a more powerful version of
4776    integral_constant_value, which can be used also in templates where
4777    initializers can maintain a syntactic rather than semantic form
4778    (even if they are non-dependent, for access-checking purposes).  */
4779
4780 static tree
4781 fold_decl_constant_value (tree expr)
4782 {
4783   tree const_expr = expr;
4784   do
4785     {
4786       expr = fold_non_dependent_expr (const_expr);
4787       const_expr = integral_constant_value (expr);
4788     }
4789   while (expr != const_expr);
4790
4791   return expr;
4792 }
4793
4794 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4795    must be a function or a pointer-to-function type, as specified
4796    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4797    and check that the resulting function has external linkage.  */
4798
4799 static tree
4800 convert_nontype_argument_function (tree type, tree expr)
4801 {
4802   tree fns = expr;
4803   tree fn, fn_no_ptr;
4804
4805   fn = instantiate_type (type, fns, tf_none);
4806   if (fn == error_mark_node)
4807     return error_mark_node;
4808
4809   fn_no_ptr = fn;
4810   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4811     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4812   if (TREE_CODE (fn_no_ptr) == BASELINK)
4813     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4814  
4815   /* [temp.arg.nontype]/1
4816
4817      A template-argument for a non-type, non-template template-parameter
4818      shall be one of:
4819      [...]
4820      -- the address of an object or function with external linkage.  */
4821   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4822     {
4823       error ("%qE is not a valid template argument for type %qT "
4824              "because function %qD has not external linkage",
4825              expr, type, fn_no_ptr);
4826       return NULL_TREE;
4827     }
4828
4829   return fn;
4830 }
4831
4832 /* Subroutine of convert_nontype_argument.
4833    Check if EXPR of type TYPE is a valid pointer-to-member constant.
4834    Emit an error otherwise.  */
4835
4836 static bool
4837 check_valid_ptrmem_cst_expr (tree type, tree expr)
4838 {
4839   STRIP_NOPS (expr);
4840   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
4841     return true;
4842   error ("%qE is not a valid template argument for type %qT",
4843          expr, type);
4844   error ("it must be a pointer-to-member of the form `&X::Y'");
4845   return false;
4846 }
4847
4848 /* Attempt to convert the non-type template parameter EXPR to the
4849    indicated TYPE.  If the conversion is successful, return the
4850    converted value.  If the conversion is unsuccessful, return
4851    NULL_TREE if we issued an error message, or error_mark_node if we
4852    did not.  We issue error messages for out-and-out bad template
4853    parameters, but not simply because the conversion failed, since we
4854    might be just trying to do argument deduction.  Both TYPE and EXPR
4855    must be non-dependent.
4856
4857    The conversion follows the special rules described in
4858    [temp.arg.nontype], and it is much more strict than an implicit
4859    conversion.
4860
4861    This function is called twice for each template argument (see
4862    lookup_template_class for a more accurate description of this
4863    problem). This means that we need to handle expressions which
4864    are not valid in a C++ source, but can be created from the
4865    first call (for instance, casts to perform conversions). These
4866    hacks can go away after we fix the double coercion problem.  */
4867
4868 static tree
4869 convert_nontype_argument (tree type, tree expr)
4870 {
4871   tree expr_type;
4872
4873   /* Detect immediately string literals as invalid non-type argument.
4874      This special-case is not needed for correctness (we would easily
4875      catch this later), but only to provide better diagnostic for this
4876      common user mistake. As suggested by DR 100, we do not mention
4877      linkage issues in the diagnostic as this is not the point.  */
4878   if (TREE_CODE (expr) == STRING_CST)
4879     {
4880       error ("%qE is not a valid template argument for type %qT "
4881              "because string literals can never be used in this context",
4882              expr, type);
4883       return NULL_TREE;
4884     }
4885
4886   /* If we are in a template, EXPR may be non-dependent, but still
4887      have a syntactic, rather than semantic, form.  For example, EXPR
4888      might be a SCOPE_REF, rather than the VAR_DECL to which the
4889      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4890      so that access checking can be performed when the template is
4891      instantiated -- but here we need the resolved form so that we can
4892      convert the argument.  */
4893   expr = fold_non_dependent_expr (expr);
4894   if (error_operand_p (expr))
4895     return error_mark_node;
4896   expr_type = TREE_TYPE (expr);
4897
4898   /* HACK: Due to double coercion, we can get a
4899      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4900      which is the tree that we built on the first call (see
4901      below when coercing to reference to object or to reference to
4902      function). We just strip everything and get to the arg.
4903      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4904      for examples.  */
4905   if (TREE_CODE (expr) == NOP_EXPR)
4906     {
4907       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4908         {
4909           /* ??? Maybe we could use convert_from_reference here, but we
4910              would need to relax its constraints because the NOP_EXPR
4911              could actually change the type to something more cv-qualified,
4912              and this is not folded by convert_from_reference.  */
4913           tree addr = TREE_OPERAND (expr, 0);
4914           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4915           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4916           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4917           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4918                       (TREE_TYPE (expr_type),
4919                        TREE_TYPE (TREE_TYPE (addr))));
4920
4921           expr = TREE_OPERAND (addr, 0);
4922           expr_type = TREE_TYPE (expr);
4923         }
4924
4925       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4926          parameter is a pointer to object, through decay and
4927          qualification conversion. Let's strip everything.  */
4928       else if (TYPE_PTROBV_P (type))
4929         {
4930           STRIP_NOPS (expr);
4931           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4932           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4933           /* Skip the ADDR_EXPR only if it is part of the decay for
4934              an array. Otherwise, it is part of the original argument
4935              in the source code.  */
4936           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4937             expr = TREE_OPERAND (expr, 0);
4938           expr_type = TREE_TYPE (expr);
4939         }
4940     }
4941
4942   /* [temp.arg.nontype]/5, bullet 1
4943
4944      For a non-type template-parameter of integral or enumeration type,
4945      integral promotions (_conv.prom_) and integral conversions
4946      (_conv.integral_) are applied.  */
4947   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4948     {
4949       if (!INTEGRAL_OR_ENUMERATION_TYPE_P (expr_type))
4950         return error_mark_node;
4951
4952       expr = fold_decl_constant_value (expr);
4953       /* Notice that there are constant expressions like '4 % 0' which
4954          do not fold into integer constants.  */
4955       if (TREE_CODE (expr) != INTEGER_CST)
4956         {
4957           error ("%qE is not a valid template argument for type %qT "
4958                  "because it is a non-constant expression", expr, type);
4959           return NULL_TREE;
4960         }
4961
4962       /* At this point, an implicit conversion does what we want,
4963          because we already know that the expression is of integral
4964          type.  */
4965       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4966       if (expr == error_mark_node)
4967         return error_mark_node;
4968
4969       /* Conversion was allowed: fold it to a bare integer constant.  */
4970       expr = fold (expr);
4971     }
4972   /* [temp.arg.nontype]/5, bullet 2
4973
4974      For a non-type template-parameter of type pointer to object,
4975      qualification conversions (_conv.qual_) and the array-to-pointer
4976      conversion (_conv.array_) are applied.  */
4977   else if (TYPE_PTROBV_P (type))
4978     {
4979       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
4980
4981          A template-argument for a non-type, non-template template-parameter
4982          shall be one of: [...]
4983
4984          -- the name of a non-type template-parameter;
4985          -- the address of an object or function with external linkage, [...]
4986             expressed as "& id-expression" where the & is optional if the name
4987             refers to a function or array, or if the corresponding
4988             template-parameter is a reference.
4989
4990         Here, we do not care about functions, as they are invalid anyway
4991         for a parameter of type pointer-to-object.  */
4992
4993       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
4994         /* Non-type template parameters are OK.  */
4995         ;
4996       else if (TREE_CODE (expr) != ADDR_EXPR
4997                && TREE_CODE (expr_type) != ARRAY_TYPE)
4998         {
4999           if (TREE_CODE (expr) == VAR_DECL)
5000             {
5001               error ("%qD is not a valid template argument "
5002                      "because %qD is a variable, not the address of "
5003                      "a variable",
5004                      expr, expr);
5005               return NULL_TREE;
5006             }
5007           /* Other values, like integer constants, might be valid
5008              non-type arguments of some other type.  */
5009           return error_mark_node;
5010         }
5011       else
5012         {
5013           tree decl;
5014
5015           decl = ((TREE_CODE (expr) == ADDR_EXPR)
5016                   ? TREE_OPERAND (expr, 0) : expr);
5017           if (TREE_CODE (decl) != VAR_DECL)
5018             {
5019               error ("%qE is not a valid template argument of type %qT "
5020                      "because %qE is not a variable",
5021                      expr, type, decl);
5022               return NULL_TREE;
5023             }
5024           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
5025             {
5026               error ("%qE is not a valid template argument of type %qT "
5027                      "because %qD does not have external linkage",
5028                      expr, type, decl);
5029               return NULL_TREE;
5030             }
5031         }
5032
5033       expr = decay_conversion (expr);
5034       if (expr == error_mark_node)
5035         return error_mark_node;
5036
5037       expr = perform_qualification_conversions (type, expr);
5038       if (expr == error_mark_node)
5039         return error_mark_node;
5040     }
5041   /* [temp.arg.nontype]/5, bullet 3
5042
5043      For a non-type template-parameter of type reference to object, no
5044      conversions apply. The type referred to by the reference may be more
5045      cv-qualified than the (otherwise identical) type of the
5046      template-argument. The template-parameter is bound directly to the
5047      template-argument, which must be an lvalue.  */
5048   else if (TYPE_REF_OBJ_P (type))
5049     {
5050       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5051                                                       expr_type))
5052         return error_mark_node;
5053
5054       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5055         {
5056           error ("%qE is not a valid template argument for type %qT "
5057                  "because of conflicts in cv-qualification", expr, type);
5058           return NULL_TREE;
5059         }
5060
5061       if (!real_lvalue_p (expr))
5062         {
5063           error ("%qE is not a valid template argument for type %qT "
5064                  "because it is not an lvalue", expr, type);
5065           return NULL_TREE;
5066         }
5067
5068       /* [temp.arg.nontype]/1
5069
5070          A template-argument for a non-type, non-template template-parameter
5071          shall be one of: [...]
5072
5073          -- the address of an object or function with external linkage.  */
5074       if (TREE_CODE (expr) == INDIRECT_REF
5075           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5076         {
5077           expr = TREE_OPERAND (expr, 0);
5078           if (DECL_P (expr))
5079             {
5080               error ("%q#D is not a valid template argument for type %qT "
5081                      "because a reference variable does not have a constant "
5082                      "address", expr, type);
5083               return NULL_TREE;
5084             }
5085         }
5086
5087       if (!DECL_P (expr))
5088         {
5089           error ("%qE is not a valid template argument for type %qT "
5090                  "because it is not an object with external linkage",
5091                  expr, type);
5092           return NULL_TREE;
5093         }
5094
5095       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5096         {
5097           error ("%qE is not a valid template argument for type %qT "
5098                  "because object %qD has not external linkage",
5099                  expr, type, expr);
5100           return NULL_TREE;
5101         }
5102
5103       expr = build_nop (type, build_address (expr));
5104     }
5105   /* [temp.arg.nontype]/5, bullet 4
5106
5107      For a non-type template-parameter of type pointer to function, only
5108      the function-to-pointer conversion (_conv.func_) is applied. If the
5109      template-argument represents a set of overloaded functions (or a
5110      pointer to such), the matching function is selected from the set
5111      (_over.over_).  */
5112   else if (TYPE_PTRFN_P (type))
5113     {
5114       /* If the argument is a template-id, we might not have enough
5115          context information to decay the pointer.  */
5116       if (!type_unknown_p (expr_type))
5117         {
5118           expr = decay_conversion (expr);
5119           if (expr == error_mark_node)
5120             return error_mark_node;
5121         }
5122
5123       expr = convert_nontype_argument_function (type, expr);
5124       if (!expr || expr == error_mark_node)
5125         return expr;
5126
5127       if (TREE_CODE (expr) != ADDR_EXPR)
5128         {
5129           error ("%qE is not a valid template argument for type %qT", expr, type);
5130           error ("it must be the address of a function with external linkage");
5131           return NULL_TREE;
5132         }
5133     }
5134   /* [temp.arg.nontype]/5, bullet 5
5135
5136      For a non-type template-parameter of type reference to function, no
5137      conversions apply. If the template-argument represents a set of
5138      overloaded functions, the matching function is selected from the set
5139      (_over.over_).  */
5140   else if (TYPE_REFFN_P (type))
5141     {
5142       if (TREE_CODE (expr) == ADDR_EXPR)
5143         {
5144           error ("%qE is not a valid template argument for type %qT "
5145                  "because it is a pointer", expr, type);
5146           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5147           return NULL_TREE;
5148         }
5149
5150       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5151       if (!expr || expr == error_mark_node)
5152         return expr;
5153
5154       expr = build_nop (type, build_address (expr));
5155     }
5156   /* [temp.arg.nontype]/5, bullet 6
5157
5158      For a non-type template-parameter of type pointer to member function,
5159      no conversions apply. If the template-argument represents a set of
5160      overloaded member functions, the matching member function is selected
5161      from the set (_over.over_).  */
5162   else if (TYPE_PTRMEMFUNC_P (type))
5163     {
5164       expr = instantiate_type (type, expr, tf_none);
5165       if (expr == error_mark_node)
5166         return error_mark_node;
5167
5168       /* [temp.arg.nontype] bullet 1 says the pointer to member
5169          expression must be a pointer-to-member constant.  */
5170       if (!check_valid_ptrmem_cst_expr (type, expr))
5171         return error_mark_node;
5172
5173       /* There is no way to disable standard conversions in
5174          resolve_address_of_overloaded_function (called by
5175          instantiate_type). It is possible that the call succeeded by
5176          converting &B::I to &D::I (where B is a base of D), so we need
5177          to reject this conversion here.
5178
5179          Actually, even if there was a way to disable standard conversions,
5180          it would still be better to reject them here so that we can
5181          provide a superior diagnostic.  */
5182       if (!same_type_p (TREE_TYPE (expr), type))
5183         {
5184           error ("%qE is not a valid template argument for type %qT "
5185                  "because it is of type %qT", expr, type,
5186                  TREE_TYPE (expr));
5187           /* If we are just one standard conversion off, explain.  */
5188           if (can_convert (type, TREE_TYPE (expr)))
5189             inform (input_location,
5190                     "standard conversions are not allowed in this context");
5191           return NULL_TREE;
5192         }
5193     }
5194   /* [temp.arg.nontype]/5, bullet 7
5195
5196      For a non-type template-parameter of type pointer to data member,
5197      qualification conversions (_conv.qual_) are applied.  */
5198   else if (TYPE_PTRMEM_P (type))
5199     {
5200       /* [temp.arg.nontype] bullet 1 says the pointer to member
5201          expression must be a pointer-to-member constant.  */
5202       if (!check_valid_ptrmem_cst_expr (type, expr))
5203         return error_mark_node;
5204
5205       expr = perform_qualification_conversions (type, expr);
5206       if (expr == error_mark_node)
5207         return expr;
5208     }
5209   /* A template non-type parameter must be one of the above.  */
5210   else
5211     gcc_unreachable ();
5212
5213   /* Sanity check: did we actually convert the argument to the
5214      right type?  */
5215   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
5216   return expr;
5217 }
5218
5219 /* Subroutine of coerce_template_template_parms, which returns 1 if
5220    PARM_PARM and ARG_PARM match using the rule for the template
5221    parameters of template template parameters. Both PARM and ARG are
5222    template parameters; the rest of the arguments are the same as for
5223    coerce_template_template_parms.
5224  */
5225 static int
5226 coerce_template_template_parm (tree parm,
5227                               tree arg,
5228                               tsubst_flags_t complain,
5229                               tree in_decl,
5230                               tree outer_args)
5231 {
5232   if (arg == NULL_TREE || arg == error_mark_node
5233       || parm == NULL_TREE || parm == error_mark_node)
5234     return 0;
5235   
5236   if (TREE_CODE (arg) != TREE_CODE (parm))
5237     return 0;
5238   
5239   switch (TREE_CODE (parm))
5240     {
5241     case TEMPLATE_DECL:
5242       /* We encounter instantiations of templates like
5243          template <template <template <class> class> class TT>
5244          class C;  */
5245       {
5246         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5247         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5248         
5249         if (!coerce_template_template_parms
5250             (parmparm, argparm, complain, in_decl, outer_args))
5251           return 0;
5252       }
5253       /* Fall through.  */
5254       
5255     case TYPE_DECL:
5256       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5257           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5258         /* Argument is a parameter pack but parameter is not.  */
5259         return 0;
5260       break;
5261       
5262     case PARM_DECL:
5263       /* The tsubst call is used to handle cases such as
5264          
5265            template <int> class C {};
5266            template <class T, template <T> class TT> class D {};
5267            D<int, C> d;
5268
5269          i.e. the parameter list of TT depends on earlier parameters.  */
5270       if (!uses_template_parms (TREE_TYPE (arg))
5271           && !same_type_p
5272                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5273                  TREE_TYPE (arg)))
5274         return 0;
5275       
5276       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5277           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5278         /* Argument is a parameter pack but parameter is not.  */
5279         return 0;
5280       
5281       break;
5282
5283     default:
5284       gcc_unreachable ();
5285     }
5286
5287   return 1;
5288 }
5289
5290
5291 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5292    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5293    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5294    or PARM_DECL.
5295
5296    Consider the example:
5297      template <class T> class A;
5298      template<template <class U> class TT> class B;
5299
5300    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5301    the parameters to A, and OUTER_ARGS contains A.  */
5302
5303 static int
5304 coerce_template_template_parms (tree parm_parms,
5305                                 tree arg_parms,
5306                                 tsubst_flags_t complain,
5307                                 tree in_decl,
5308                                 tree outer_args)
5309 {
5310   int nparms, nargs, i;
5311   tree parm, arg;
5312   int variadic_p = 0;
5313
5314   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5315   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5316
5317   nparms = TREE_VEC_LENGTH (parm_parms);
5318   nargs = TREE_VEC_LENGTH (arg_parms);
5319
5320   /* Determine whether we have a parameter pack at the end of the
5321      template template parameter's template parameter list.  */
5322   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5323     {
5324       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5325       
5326       if (parm == error_mark_node)
5327         return 0;
5328
5329       switch (TREE_CODE (parm))
5330         {
5331         case TEMPLATE_DECL:
5332         case TYPE_DECL:
5333           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5334             variadic_p = 1;
5335           break;
5336           
5337         case PARM_DECL:
5338           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5339             variadic_p = 1;
5340           break;
5341           
5342         default:
5343           gcc_unreachable ();
5344         }
5345     }
5346  
5347   if (nargs != nparms
5348       && !(variadic_p && nargs >= nparms - 1))
5349     return 0;
5350
5351   /* Check all of the template parameters except the parameter pack at
5352      the end (if any).  */
5353   for (i = 0; i < nparms - variadic_p; ++i)
5354     {
5355       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5356           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5357         continue;
5358
5359       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5360       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5361
5362       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5363                                           outer_args))
5364         return 0;
5365
5366     }
5367
5368   if (variadic_p)
5369     {
5370       /* Check each of the template parameters in the template
5371          argument against the template parameter pack at the end of
5372          the template template parameter.  */
5373       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5374         return 0;
5375
5376       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5377
5378       for (; i < nargs; ++i)
5379         {
5380           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5381             continue;
5382  
5383           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5384  
5385           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5386                                               outer_args))
5387             return 0;
5388         }
5389     }
5390
5391   return 1;
5392 }
5393
5394 /* Verifies that the deduced template arguments (in TARGS) for the
5395    template template parameters (in TPARMS) represent valid bindings,
5396    by comparing the template parameter list of each template argument
5397    to the template parameter list of its corresponding template
5398    template parameter, in accordance with DR150. This
5399    routine can only be called after all template arguments have been
5400    deduced. It will return TRUE if all of the template template
5401    parameter bindings are okay, FALSE otherwise.  */
5402 bool 
5403 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5404 {
5405   int i, ntparms = TREE_VEC_LENGTH (tparms);
5406   bool ret = true;
5407
5408   /* We're dealing with template parms in this process.  */
5409   ++processing_template_decl;
5410
5411   targs = INNERMOST_TEMPLATE_ARGS (targs);
5412
5413   for (i = 0; i < ntparms; ++i)
5414     {
5415       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5416       tree targ = TREE_VEC_ELT (targs, i);
5417
5418       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5419         {
5420           tree packed_args = NULL_TREE;
5421           int idx, len = 1;
5422
5423           if (ARGUMENT_PACK_P (targ))
5424             {
5425               /* Look inside the argument pack.  */
5426               packed_args = ARGUMENT_PACK_ARGS (targ);
5427               len = TREE_VEC_LENGTH (packed_args);
5428             }
5429
5430           for (idx = 0; idx < len; ++idx)
5431             {
5432               tree targ_parms = NULL_TREE;
5433
5434               if (packed_args)
5435                 /* Extract the next argument from the argument
5436                    pack.  */
5437                 targ = TREE_VEC_ELT (packed_args, idx);
5438
5439               if (PACK_EXPANSION_P (targ))
5440                 /* Look at the pattern of the pack expansion.  */
5441                 targ = PACK_EXPANSION_PATTERN (targ);
5442
5443               /* Extract the template parameters from the template
5444                  argument.  */
5445               if (TREE_CODE (targ) == TEMPLATE_DECL)
5446                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5447               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5448                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5449
5450               /* Verify that we can coerce the template template
5451                  parameters from the template argument to the template
5452                  parameter.  This requires an exact match.  */
5453               if (targ_parms
5454                   && !coerce_template_template_parms
5455                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5456                         targ_parms,
5457                         tf_none,
5458                         tparm,
5459                         targs))
5460                 {
5461                   ret = false;
5462                   goto out;
5463                 }
5464             }
5465         }
5466     }
5467
5468  out:
5469
5470   --processing_template_decl;
5471   return ret;
5472 }
5473
5474 /* Convert the indicated template ARG as necessary to match the
5475    indicated template PARM.  Returns the converted ARG, or
5476    error_mark_node if the conversion was unsuccessful.  Error and
5477    warning messages are issued under control of COMPLAIN.  This
5478    conversion is for the Ith parameter in the parameter list.  ARGS is
5479    the full set of template arguments deduced so far.  */
5480
5481 static tree
5482 convert_template_argument (tree parm,
5483                            tree arg,
5484                            tree args,
5485                            tsubst_flags_t complain,
5486                            int i,
5487                            tree in_decl)
5488 {
5489   tree orig_arg;
5490   tree val;
5491   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5492
5493   if (TREE_CODE (arg) == TREE_LIST
5494       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5495     {
5496       /* The template argument was the name of some
5497          member function.  That's usually
5498          invalid, but static members are OK.  In any
5499          case, grab the underlying fields/functions
5500          and issue an error later if required.  */
5501       orig_arg = TREE_VALUE (arg);
5502       TREE_TYPE (arg) = unknown_type_node;
5503     }
5504
5505   orig_arg = arg;
5506
5507   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5508   requires_type = (TREE_CODE (parm) == TYPE_DECL
5509                    || requires_tmpl_type);
5510
5511   /* When determining whether an argument pack expansion is a template,
5512      look at the pattern.  */
5513   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5514     arg = PACK_EXPANSION_PATTERN (arg);
5515
5516   /* Deal with an injected-class-name used as a template template arg.  */
5517   if (requires_tmpl_type && CLASS_TYPE_P (arg))
5518     {
5519       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
5520       if (TREE_CODE (t) == TEMPLATE_DECL)
5521         {
5522           if (complain & tf_warning_or_error)
5523             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
5524                      " used as template template argument", TYPE_NAME (arg));
5525           else if (flag_pedantic_errors)
5526             t = arg;
5527
5528           arg = t;
5529         }
5530     }
5531
5532   is_tmpl_type = 
5533     ((TREE_CODE (arg) == TEMPLATE_DECL
5534       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5535      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5536      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5537
5538   if (is_tmpl_type
5539       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5540           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5541     arg = TYPE_STUB_DECL (arg);
5542
5543   is_type = TYPE_P (arg) || is_tmpl_type;
5544
5545   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
5546       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
5547     {
5548       permerror (input_location, "to refer to a type member of a template parameter, "
5549                  "use %<typename %E%>", orig_arg);
5550
5551       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
5552                                      TREE_OPERAND (arg, 1),
5553                                      typename_type,
5554                                      complain & tf_error);
5555       arg = orig_arg;
5556       is_type = 1;
5557     }
5558   if (is_type != requires_type)
5559     {
5560       if (in_decl)
5561         {
5562           if (complain & tf_error)
5563             {
5564               error ("type/value mismatch at argument %d in template "
5565                      "parameter list for %qD",
5566                      i + 1, in_decl);
5567               if (is_type)
5568                 error ("  expected a constant of type %qT, got %qT",
5569                        TREE_TYPE (parm),
5570                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
5571               else if (requires_tmpl_type)
5572                 error ("  expected a class template, got %qE", orig_arg);
5573               else
5574                 error ("  expected a type, got %qE", orig_arg);
5575             }
5576         }
5577       return error_mark_node;
5578     }
5579   if (is_tmpl_type ^ requires_tmpl_type)
5580     {
5581       if (in_decl && (complain & tf_error))
5582         {
5583           error ("type/value mismatch at argument %d in template "
5584                  "parameter list for %qD",
5585                  i + 1, in_decl);
5586           if (is_tmpl_type)
5587             error ("  expected a type, got %qT", DECL_NAME (arg));
5588           else
5589             error ("  expected a class template, got %qT", orig_arg);
5590         }
5591       return error_mark_node;
5592     }
5593
5594   if (is_type)
5595     {
5596       if (requires_tmpl_type)
5597         {
5598           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5599             /* The number of argument required is not known yet.
5600                Just accept it for now.  */
5601             val = TREE_TYPE (arg);
5602           else
5603             {
5604               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5605               tree argparm;
5606
5607               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5608
5609               if (coerce_template_template_parms (parmparm, argparm,
5610                                                   complain, in_decl,
5611                                                   args))
5612                 {
5613                   val = arg;
5614
5615                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5616                      TEMPLATE_DECL.  */
5617                   if (val != error_mark_node)
5618                     {
5619                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5620                         val = TREE_TYPE (val);
5621                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
5622                         val = make_pack_expansion (val);
5623                     }
5624                 }
5625               else
5626                 {
5627                   if (in_decl && (complain & tf_error))
5628                     {
5629                       error ("type/value mismatch at argument %d in "
5630                              "template parameter list for %qD",
5631                              i + 1, in_decl);
5632                       error ("  expected a template of type %qD, got %qT",
5633                              parm, orig_arg);
5634                     }
5635
5636                   val = error_mark_node;
5637                 }
5638             }
5639         }
5640       else
5641         val = orig_arg;
5642       /* We only form one instance of each template specialization.
5643          Therefore, if we use a non-canonical variant (i.e., a
5644          typedef), any future messages referring to the type will use
5645          the typedef, which is confusing if those future uses do not
5646          themselves also use the typedef.  */
5647       if (TYPE_P (val))
5648         val = strip_typedefs (val);
5649     }
5650   else
5651     {
5652       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5653
5654       if (invalid_nontype_parm_type_p (t, complain))
5655         return error_mark_node;
5656
5657       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5658         {
5659           if (same_type_p (t, TREE_TYPE (orig_arg)))
5660             val = orig_arg;
5661           else
5662             {
5663               /* Not sure if this is reachable, but it doesn't hurt
5664                  to be robust.  */
5665               error ("type mismatch in nontype parameter pack");
5666               val = error_mark_node;
5667             }
5668         }
5669       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5670         /* We used to call digest_init here.  However, digest_init
5671            will report errors, which we don't want when complain
5672            is zero.  More importantly, digest_init will try too
5673            hard to convert things: for example, `0' should not be
5674            converted to pointer type at this point according to
5675            the standard.  Accepting this is not merely an
5676            extension, since deciding whether or not these
5677            conversions can occur is part of determining which
5678            function template to call, or whether a given explicit
5679            argument specification is valid.  */
5680         val = convert_nontype_argument (t, orig_arg);
5681       else
5682         val = orig_arg;
5683
5684       if (val == NULL_TREE)
5685         val = error_mark_node;
5686       else if (val == error_mark_node && (complain & tf_error))
5687         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5688
5689       if (TREE_CODE (val) == SCOPE_REF)
5690         {
5691           /* Strip typedefs from the SCOPE_REF.  */
5692           tree type = strip_typedefs (TREE_TYPE (val));
5693           tree scope = strip_typedefs (TREE_OPERAND (val, 0));
5694           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
5695                                       QUALIFIED_NAME_IS_TEMPLATE (val));
5696         }
5697     }
5698
5699   return val;
5700 }
5701
5702 /* Coerces the remaining template arguments in INNER_ARGS (from
5703    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5704    Returns the coerced argument pack. PARM_IDX is the position of this
5705    parameter in the template parameter list. ARGS is the original
5706    template argument list.  */
5707 static tree
5708 coerce_template_parameter_pack (tree parms,
5709                                 int parm_idx,
5710                                 tree args,
5711                                 tree inner_args,
5712                                 int arg_idx,
5713                                 tree new_args,
5714                                 int* lost,
5715                                 tree in_decl,
5716                                 tsubst_flags_t complain)
5717 {
5718   tree parm = TREE_VEC_ELT (parms, parm_idx);
5719   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5720   tree packed_args;
5721   tree argument_pack;
5722   tree packed_types = NULL_TREE;
5723
5724   if (arg_idx > nargs)
5725     arg_idx = nargs;
5726
5727   packed_args = make_tree_vec (nargs - arg_idx);
5728
5729   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5730       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5731     {
5732       /* When the template parameter is a non-type template
5733          parameter pack whose type uses parameter packs, we need
5734          to look at each of the template arguments
5735          separately. Build a vector of the types for these
5736          non-type template parameters in PACKED_TYPES.  */
5737       tree expansion 
5738         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5739       packed_types = tsubst_pack_expansion (expansion, args,
5740                                             complain, in_decl);
5741
5742       if (packed_types == error_mark_node)
5743         return error_mark_node;
5744
5745       /* Check that we have the right number of arguments.  */
5746       if (arg_idx < nargs
5747           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5748           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5749         {
5750           int needed_parms 
5751             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5752           error ("wrong number of template arguments (%d, should be %d)",
5753                  nargs, needed_parms);
5754           return error_mark_node;
5755         }
5756
5757       /* If we aren't able to check the actual arguments now
5758          (because they haven't been expanded yet), we can at least
5759          verify that all of the types used for the non-type
5760          template parameter pack are, in fact, valid for non-type
5761          template parameters.  */
5762       if (arg_idx < nargs 
5763           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5764         {
5765           int j, len = TREE_VEC_LENGTH (packed_types);
5766           for (j = 0; j < len; ++j)
5767             {
5768               tree t = TREE_VEC_ELT (packed_types, j);
5769               if (invalid_nontype_parm_type_p (t, complain))
5770                 return error_mark_node;
5771             }
5772         }
5773     }
5774
5775   /* Convert the remaining arguments, which will be a part of the
5776      parameter pack "parm".  */
5777   for (; arg_idx < nargs; ++arg_idx)
5778     {
5779       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5780       tree actual_parm = TREE_VALUE (parm);
5781
5782       if (packed_types && !PACK_EXPANSION_P (arg))
5783         {
5784           /* When we have a vector of types (corresponding to the
5785              non-type template parameter pack that uses parameter
5786              packs in its type, as mention above), and the
5787              argument is not an expansion (which expands to a
5788              currently unknown number of arguments), clone the
5789              parm and give it the next type in PACKED_TYPES.  */
5790           actual_parm = copy_node (actual_parm);
5791           TREE_TYPE (actual_parm) = 
5792             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5793         }
5794
5795       if (arg != error_mark_node)
5796         arg = convert_template_argument (actual_parm, 
5797                                          arg, new_args, complain, parm_idx,
5798                                          in_decl);
5799       if (arg == error_mark_node)
5800         (*lost)++;
5801       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5802     }
5803
5804   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5805       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5806     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
5807   else
5808     {
5809       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5810       TREE_TYPE (argument_pack) 
5811         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5812       TREE_CONSTANT (argument_pack) = 1;
5813     }
5814
5815   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5816 #ifdef ENABLE_CHECKING
5817   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
5818                                        TREE_VEC_LENGTH (packed_args));
5819 #endif
5820   return argument_pack;
5821 }
5822
5823 /* Convert all template arguments to their appropriate types, and
5824    return a vector containing the innermost resulting template
5825    arguments.  If any error occurs, return error_mark_node. Error and
5826    warning messages are issued under control of COMPLAIN.
5827
5828    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5829    for arguments not specified in ARGS.  Otherwise, if
5830    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5831    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5832    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5833    ARGS.  */
5834
5835 static tree
5836 coerce_template_parms (tree parms,
5837                        tree args,
5838                        tree in_decl,
5839                        tsubst_flags_t complain,
5840                        bool require_all_args,
5841                        bool use_default_args)
5842 {
5843   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5844   tree inner_args;
5845   tree new_args;
5846   tree new_inner_args;
5847   int saved_unevaluated_operand;
5848   int saved_inhibit_evaluation_warnings;
5849
5850   /* When used as a boolean value, indicates whether this is a
5851      variadic template parameter list. Since it's an int, we can also
5852      subtract it from nparms to get the number of non-variadic
5853      parameters.  */
5854   int variadic_p = 0;
5855
5856   nparms = TREE_VEC_LENGTH (parms);
5857
5858   /* Determine if there are any parameter packs.  */
5859   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5860     {
5861       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5862       if (template_parameter_pack_p (tparm))
5863         ++variadic_p;
5864     }
5865
5866   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5867   /* If there are 0 or 1 parameter packs, we need to expand any argument
5868      packs so that we can deduce a parameter pack from some non-packed args
5869      followed by an argument pack, as in variadic85.C.  If there are more
5870      than that, we need to leave argument packs intact so the arguments are
5871      assigned to the right parameter packs.  This should only happen when
5872      dealing with a nested class inside a partial specialization of a class
5873      template, as in variadic92.C.  */
5874   if (variadic_p <= 1)
5875     inner_args = expand_template_argument_pack (inner_args);
5876
5877   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5878   if ((nargs > nparms && !variadic_p)
5879       || (nargs < nparms - variadic_p
5880           && require_all_args
5881           && (!use_default_args
5882               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5883                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5884     {
5885       if (complain & tf_error)
5886         {
5887           const char *or_more = "";
5888           if (variadic_p)
5889             {
5890               or_more = " or more";
5891               --nparms;
5892             }
5893
5894           error ("wrong number of template arguments (%d, should be %d%s)",
5895                  nargs, nparms, or_more);
5896
5897           if (in_decl)
5898             error ("provided for %q+D", in_decl);
5899         }
5900
5901       return error_mark_node;
5902     }
5903
5904   /* We need to evaluate the template arguments, even though this
5905      template-id may be nested within a "sizeof".  */
5906   saved_unevaluated_operand = cp_unevaluated_operand;
5907   cp_unevaluated_operand = 0;
5908   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
5909   c_inhibit_evaluation_warnings = 0;
5910   new_inner_args = make_tree_vec (nparms);
5911   new_args = add_outermost_template_args (args, new_inner_args);
5912   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5913     {
5914       tree arg;
5915       tree parm;
5916
5917       /* Get the Ith template parameter.  */
5918       parm = TREE_VEC_ELT (parms, parm_idx);
5919  
5920       if (parm == error_mark_node)
5921       {
5922         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5923         continue;
5924       }
5925
5926       /* Calculate the next argument.  */
5927       if (arg_idx < nargs)
5928         arg = TREE_VEC_ELT (inner_args, arg_idx);
5929       else
5930         arg = NULL_TREE;
5931
5932       if (template_parameter_pack_p (TREE_VALUE (parm))
5933           && !(arg && ARGUMENT_PACK_P (arg)))
5934         {
5935           /* All remaining arguments will be placed in the
5936              template parameter pack PARM.  */
5937           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5938                                                 inner_args, arg_idx,
5939                                                 new_args, &lost,
5940                                                 in_decl, complain);
5941
5942           /* Store this argument.  */
5943           if (arg == error_mark_node)
5944             lost++;
5945           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5946
5947           /* We are done with all of the arguments.  */
5948           arg_idx = nargs;
5949           
5950           continue;
5951         }
5952       else if (arg)
5953         {
5954           if (PACK_EXPANSION_P (arg))
5955             {
5956               if (complain & tf_error)
5957                 {
5958                   /* FIXME this restriction was removed by N2555; see
5959                      bug 35722.  */
5960                   /* If ARG is a pack expansion, but PARM is not a
5961                      template parameter pack (if it were, we would have
5962                      handled it above), we're trying to expand into a
5963                      fixed-length argument list.  */
5964                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5965                     sorry ("cannot expand %<%E%> into a fixed-length "
5966                            "argument list", arg);
5967                   else
5968                     sorry ("cannot expand %<%T%> into a fixed-length "
5969                            "argument list", arg);
5970                 }
5971               return error_mark_node;
5972             }
5973         }
5974       else if (require_all_args)
5975         {
5976           /* There must be a default arg in this case.  */
5977           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
5978                                      complain, in_decl);
5979           /* The position of the first default template argument,
5980              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
5981              Record that.  */
5982           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
5983             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
5984         }
5985       else
5986         break;
5987
5988       if (arg == error_mark_node)
5989         {
5990           if (complain & tf_error)
5991             error ("template argument %d is invalid", arg_idx + 1);
5992         }
5993       else if (!arg)
5994         /* This only occurs if there was an error in the template
5995            parameter list itself (which we would already have
5996            reported) that we are trying to recover from, e.g., a class
5997            template with a parameter list such as
5998            template<typename..., typename>.  */
5999         return error_mark_node;
6000       else
6001         arg = convert_template_argument (TREE_VALUE (parm),
6002                                          arg, new_args, complain, 
6003                                          parm_idx, in_decl);
6004
6005       if (arg == error_mark_node)
6006         lost++;
6007       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6008     }
6009   cp_unevaluated_operand = saved_unevaluated_operand;
6010   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6011
6012   if (lost)
6013     return error_mark_node;
6014
6015 #ifdef ENABLE_CHECKING
6016   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6017     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6018                                          TREE_VEC_LENGTH (new_inner_args));
6019 #endif
6020
6021   return new_inner_args;
6022 }
6023
6024 /* Returns 1 if template args OT and NT are equivalent.  */
6025
6026 static int
6027 template_args_equal (tree ot, tree nt)
6028 {
6029   if (nt == ot)
6030     return 1;
6031
6032   if (TREE_CODE (nt) == TREE_VEC)
6033     /* For member templates */
6034     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6035   else if (PACK_EXPANSION_P (ot))
6036     return PACK_EXPANSION_P (nt) 
6037       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6038                               PACK_EXPANSION_PATTERN (nt));
6039   else if (ARGUMENT_PACK_P (ot))
6040     {
6041       int i, len;
6042       tree opack, npack;
6043
6044       if (!ARGUMENT_PACK_P (nt))
6045         return 0;
6046
6047       opack = ARGUMENT_PACK_ARGS (ot);
6048       npack = ARGUMENT_PACK_ARGS (nt);
6049       len = TREE_VEC_LENGTH (opack);
6050       if (TREE_VEC_LENGTH (npack) != len)
6051         return 0;
6052       for (i = 0; i < len; ++i)
6053         if (!template_args_equal (TREE_VEC_ELT (opack, i),
6054                                   TREE_VEC_ELT (npack, i)))
6055           return 0;
6056       return 1;
6057     }
6058   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6059     {
6060       /* We get here probably because we are in the middle of substituting
6061          into the pattern of a pack expansion. In that case the
6062          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6063          interested in. So we want to use the initial pack argument for
6064          the comparison.  */
6065       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6066       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6067         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6068       return template_args_equal (ot, nt);
6069     }
6070   else if (TYPE_P (nt))
6071     return TYPE_P (ot) && same_type_p (ot, nt);
6072   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6073     return 0;
6074   else
6075     return cp_tree_equal (ot, nt);
6076 }
6077
6078 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6079    of template arguments.  Returns 0 otherwise.  */
6080
6081 int
6082 comp_template_args (tree oldargs, tree newargs)
6083 {
6084   int i;
6085
6086   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6087     return 0;
6088
6089   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6090     {
6091       tree nt = TREE_VEC_ELT (newargs, i);
6092       tree ot = TREE_VEC_ELT (oldargs, i);
6093
6094       if (! template_args_equal (ot, nt))
6095         return 0;
6096     }
6097   return 1;
6098 }
6099
6100 static void
6101 add_pending_template (tree d)
6102 {
6103   tree ti = (TYPE_P (d)
6104              ? CLASSTYPE_TEMPLATE_INFO (d)
6105              : DECL_TEMPLATE_INFO (d));
6106   struct pending_template *pt;
6107   int level;
6108
6109   if (TI_PENDING_TEMPLATE_FLAG (ti))
6110     return;
6111
6112   /* We are called both from instantiate_decl, where we've already had a
6113      tinst_level pushed, and instantiate_template, where we haven't.
6114      Compensate.  */
6115   level = !current_tinst_level || current_tinst_level->decl != d;
6116
6117   if (level)
6118     push_tinst_level (d);
6119
6120   pt = GGC_NEW (struct pending_template);
6121   pt->next = NULL;
6122   pt->tinst = current_tinst_level;
6123   if (last_pending_template)
6124     last_pending_template->next = pt;
6125   else
6126     pending_templates = pt;
6127
6128   last_pending_template = pt;
6129
6130   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6131
6132   if (level)
6133     pop_tinst_level ();
6134 }
6135
6136
6137 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6138    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6139    documentation for TEMPLATE_ID_EXPR.  */
6140
6141 tree
6142 lookup_template_function (tree fns, tree arglist)
6143 {
6144   tree type;
6145
6146   if (fns == error_mark_node || arglist == error_mark_node)
6147     return error_mark_node;
6148
6149   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6150   gcc_assert (fns && (is_overloaded_fn (fns)
6151                       || TREE_CODE (fns) == IDENTIFIER_NODE));
6152
6153   if (BASELINK_P (fns))
6154     {
6155       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6156                                          unknown_type_node,
6157                                          BASELINK_FUNCTIONS (fns),
6158                                          arglist);
6159       return fns;
6160     }
6161
6162   type = TREE_TYPE (fns);
6163   if (TREE_CODE (fns) == OVERLOAD || !type)
6164     type = unknown_type_node;
6165
6166   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6167 }
6168
6169 /* Within the scope of a template class S<T>, the name S gets bound
6170    (in build_self_reference) to a TYPE_DECL for the class, not a
6171    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6172    or one of its enclosing classes, and that type is a template,
6173    return the associated TEMPLATE_DECL.  Otherwise, the original
6174    DECL is returned.
6175
6176    Also handle the case when DECL is a TREE_LIST of ambiguous
6177    injected-class-names from different bases.  */
6178
6179 tree
6180 maybe_get_template_decl_from_type_decl (tree decl)
6181 {
6182   if (decl == NULL_TREE)
6183     return decl;
6184
6185   /* DR 176: A lookup that finds an injected-class-name (10.2
6186      [class.member.lookup]) can result in an ambiguity in certain cases
6187      (for example, if it is found in more than one base class). If all of
6188      the injected-class-names that are found refer to specializations of
6189      the same class template, and if the name is followed by a
6190      template-argument-list, the reference refers to the class template
6191      itself and not a specialization thereof, and is not ambiguous.  */
6192   if (TREE_CODE (decl) == TREE_LIST)
6193     {
6194       tree t, tmpl = NULL_TREE;
6195       for (t = decl; t; t = TREE_CHAIN (t))
6196         {
6197           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6198           if (!tmpl)
6199             tmpl = elt;
6200           else if (tmpl != elt)
6201             break;
6202         }
6203       if (tmpl && t == NULL_TREE)
6204         return tmpl;
6205       else
6206         return decl;
6207     }
6208
6209   return (decl != NULL_TREE
6210           && DECL_SELF_REFERENCE_P (decl)
6211           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
6212     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
6213 }
6214
6215 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
6216    parameters, find the desired type.
6217
6218    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
6219
6220    IN_DECL, if non-NULL, is the template declaration we are trying to
6221    instantiate.
6222
6223    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
6224    the class we are looking up.
6225
6226    Issue error and warning messages under control of COMPLAIN.
6227
6228    If the template class is really a local class in a template
6229    function, then the FUNCTION_CONTEXT is the function in which it is
6230    being instantiated.
6231
6232    ??? Note that this function is currently called *twice* for each
6233    template-id: the first time from the parser, while creating the
6234    incomplete type (finish_template_type), and the second type during the
6235    real instantiation (instantiate_template_class). This is surely something
6236    that we want to avoid. It also causes some problems with argument
6237    coercion (see convert_nontype_argument for more information on this).  */
6238
6239 tree
6240 lookup_template_class (tree d1,
6241                        tree arglist,
6242                        tree in_decl,
6243                        tree context,
6244                        int entering_scope,
6245                        tsubst_flags_t complain)
6246 {
6247   tree templ = NULL_TREE, parmlist;
6248   tree t;
6249   spec_entry **slot;
6250   spec_entry *entry;
6251   spec_entry elt;
6252   hashval_t hash;
6253
6254   timevar_push (TV_NAME_LOOKUP);
6255
6256   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6257     {
6258       tree value = innermost_non_namespace_value (d1);
6259       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6260         templ = value;
6261       else
6262         {
6263           if (context)
6264             push_decl_namespace (context);
6265           templ = lookup_name (d1);
6266           templ = maybe_get_template_decl_from_type_decl (templ);
6267           if (context)
6268             pop_decl_namespace ();
6269         }
6270       if (templ)
6271         context = DECL_CONTEXT (templ);
6272     }
6273   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6274     {
6275       tree type = TREE_TYPE (d1);
6276
6277       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6278          an implicit typename for the second A.  Deal with it.  */
6279       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6280         type = TREE_TYPE (type);
6281
6282       if (CLASSTYPE_TEMPLATE_INFO (type))
6283         {
6284           templ = CLASSTYPE_TI_TEMPLATE (type);
6285           d1 = DECL_NAME (templ);
6286         }
6287     }
6288   else if (TREE_CODE (d1) == ENUMERAL_TYPE
6289            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6290     {
6291       templ = TYPE_TI_TEMPLATE (d1);
6292       d1 = DECL_NAME (templ);
6293     }
6294   else if (TREE_CODE (d1) == TEMPLATE_DECL
6295            && DECL_TEMPLATE_RESULT (d1)
6296            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6297     {
6298       templ = d1;
6299       d1 = DECL_NAME (templ);
6300       context = DECL_CONTEXT (templ);
6301     }
6302
6303   /* Issue an error message if we didn't find a template.  */
6304   if (! templ)
6305     {
6306       if (complain & tf_error)
6307         error ("%qT is not a template", d1);
6308       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6309     }
6310
6311   if (TREE_CODE (templ) != TEMPLATE_DECL
6312          /* Make sure it's a user visible template, if it was named by
6313             the user.  */
6314       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6315           && !PRIMARY_TEMPLATE_P (templ)))
6316     {
6317       if (complain & tf_error)
6318         {
6319           error ("non-template type %qT used as a template", d1);
6320           if (in_decl)
6321             error ("for template declaration %q+D", in_decl);
6322         }
6323       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6324     }
6325
6326   complain &= ~tf_user;
6327
6328   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6329     {
6330       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6331          template arguments */
6332
6333       tree parm;
6334       tree arglist2;
6335       tree outer;
6336
6337       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6338
6339       /* Consider an example where a template template parameter declared as
6340
6341            template <class T, class U = std::allocator<T> > class TT
6342
6343          The template parameter level of T and U are one level larger than
6344          of TT.  To proper process the default argument of U, say when an
6345          instantiation `TT<int>' is seen, we need to build the full
6346          arguments containing {int} as the innermost level.  Outer levels,
6347          available when not appearing as default template argument, can be
6348          obtained from the arguments of the enclosing template.
6349
6350          Suppose that TT is later substituted with std::vector.  The above
6351          instantiation is `TT<int, std::allocator<T> >' with TT at
6352          level 1, and T at level 2, while the template arguments at level 1
6353          becomes {std::vector} and the inner level 2 is {int}.  */
6354
6355       outer = DECL_CONTEXT (templ);
6356       if (outer)
6357         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
6358       else if (current_template_parms)
6359         /* This is an argument of the current template, so we haven't set
6360            DECL_CONTEXT yet.  */
6361         outer = current_template_args ();
6362
6363       if (outer)
6364         arglist = add_to_template_args (outer, arglist);
6365
6366       arglist2 = coerce_template_parms (parmlist, arglist, templ,
6367                                         complain,
6368                                         /*require_all_args=*/true,
6369                                         /*use_default_args=*/true);
6370       if (arglist2 == error_mark_node
6371           || (!uses_template_parms (arglist2)
6372               && check_instantiated_args (templ, arglist2, complain)))
6373         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6374
6375       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
6376       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
6377     }
6378   else
6379     {
6380       tree template_type = TREE_TYPE (templ);
6381       tree gen_tmpl;
6382       tree type_decl;
6383       tree found = NULL_TREE;
6384       int arg_depth;
6385       int parm_depth;
6386       int is_dependent_type;
6387       int use_partial_inst_tmpl = false;
6388
6389       gen_tmpl = most_general_template (templ);
6390       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
6391       parm_depth = TMPL_PARMS_DEPTH (parmlist);
6392       arg_depth = TMPL_ARGS_DEPTH (arglist);
6393
6394       if (arg_depth == 1 && parm_depth > 1)
6395         {
6396           /* We've been given an incomplete set of template arguments.
6397              For example, given:
6398
6399                template <class T> struct S1 {
6400                  template <class U> struct S2 {};
6401                  template <class U> struct S2<U*> {};
6402                 };
6403
6404              we will be called with an ARGLIST of `U*', but the
6405              TEMPLATE will be `template <class T> template
6406              <class U> struct S1<T>::S2'.  We must fill in the missing
6407              arguments.  */
6408           arglist
6409             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
6410                                            arglist);
6411           arg_depth = TMPL_ARGS_DEPTH (arglist);
6412         }
6413
6414       /* Now we should have enough arguments.  */
6415       gcc_assert (parm_depth == arg_depth);
6416
6417       /* From here on, we're only interested in the most general
6418          template.  */
6419
6420       /* Calculate the BOUND_ARGS.  These will be the args that are
6421          actually tsubst'd into the definition to create the
6422          instantiation.  */
6423       if (parm_depth > 1)
6424         {
6425           /* We have multiple levels of arguments to coerce, at once.  */
6426           int i;
6427           int saved_depth = TMPL_ARGS_DEPTH (arglist);
6428
6429           tree bound_args = make_tree_vec (parm_depth);
6430
6431           for (i = saved_depth,
6432                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
6433                i > 0 && t != NULL_TREE;
6434                --i, t = TREE_CHAIN (t))
6435             {
6436               tree a = coerce_template_parms (TREE_VALUE (t),
6437                                               arglist, gen_tmpl,
6438                                               complain,
6439                                               /*require_all_args=*/true,
6440                                               /*use_default_args=*/true);
6441
6442               /* Don't process further if one of the levels fails.  */
6443               if (a == error_mark_node)
6444                 {
6445                   /* Restore the ARGLIST to its full size.  */
6446                   TREE_VEC_LENGTH (arglist) = saved_depth;
6447                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6448                 }
6449
6450               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6451
6452               /* We temporarily reduce the length of the ARGLIST so
6453                  that coerce_template_parms will see only the arguments
6454                  corresponding to the template parameters it is
6455                  examining.  */
6456               TREE_VEC_LENGTH (arglist)--;
6457             }
6458
6459           /* Restore the ARGLIST to its full size.  */
6460           TREE_VEC_LENGTH (arglist) = saved_depth;
6461
6462           arglist = bound_args;
6463         }
6464       else
6465         arglist
6466           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6467                                    INNERMOST_TEMPLATE_ARGS (arglist),
6468                                    gen_tmpl,
6469                                    complain,
6470                                    /*require_all_args=*/true,
6471                                    /*use_default_args=*/true);
6472
6473       if (arglist == error_mark_node)
6474         /* We were unable to bind the arguments.  */
6475         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6476
6477       /* In the scope of a template class, explicit references to the
6478          template class refer to the type of the template, not any
6479          instantiation of it.  For example, in:
6480
6481            template <class T> class C { void f(C<T>); }
6482
6483          the `C<T>' is just the same as `C'.  Outside of the
6484          class, however, such a reference is an instantiation.  */
6485       if ((entering_scope
6486            || !PRIMARY_TEMPLATE_P (gen_tmpl)
6487            || currently_open_class (template_type))
6488           /* comp_template_args is expensive, check it last.  */
6489           && comp_template_args (TYPE_TI_ARGS (template_type),
6490                                  arglist))
6491         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, template_type);
6492
6493       /* If we already have this specialization, return it.  */
6494       elt.tmpl = gen_tmpl;
6495       elt.args = arglist;
6496       hash = hash_specialization (&elt);
6497       entry = (spec_entry *) htab_find_with_hash (type_specializations,
6498                                                   &elt, hash);
6499
6500       if (entry)
6501         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->spec);
6502
6503       is_dependent_type = uses_template_parms (arglist);
6504
6505       /* If the deduced arguments are invalid, then the binding
6506          failed.  */
6507       if (!is_dependent_type
6508           && check_instantiated_args (gen_tmpl,
6509                                       INNERMOST_TEMPLATE_ARGS (arglist),
6510                                       complain))
6511         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6512
6513       if (!is_dependent_type
6514           && !PRIMARY_TEMPLATE_P (gen_tmpl)
6515           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
6516           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6517         {
6518           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6519                                       DECL_NAME (gen_tmpl),
6520                                       /*tag_scope=*/ts_global);
6521           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
6522         }
6523
6524       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
6525                         complain, in_decl);
6526       if (!context)
6527         context = global_namespace;
6528
6529       /* Create the type.  */
6530       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
6531         {
6532           if (!is_dependent_type)
6533             {
6534               set_current_access_from_decl (TYPE_NAME (template_type));
6535               t = start_enum (TYPE_IDENTIFIER (template_type),
6536                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
6537                                       arglist, complain, in_decl),
6538                               SCOPED_ENUM_P (template_type));
6539             }
6540           else
6541             {
6542               /* We don't want to call start_enum for this type, since
6543                  the values for the enumeration constants may involve
6544                  template parameters.  And, no one should be interested
6545                  in the enumeration constants for such a type.  */
6546               t = cxx_make_type (ENUMERAL_TYPE);
6547               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
6548             }
6549         }
6550       else
6551         {
6552           t = make_class_type (TREE_CODE (template_type));
6553           CLASSTYPE_DECLARED_CLASS (t)
6554             = CLASSTYPE_DECLARED_CLASS (template_type);
6555           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
6556           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
6557
6558           /* A local class.  Make sure the decl gets registered properly.  */
6559           if (context == current_function_decl)
6560             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
6561
6562           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
6563             /* This instantiation is another name for the primary
6564                template type. Set the TYPE_CANONICAL field
6565                appropriately. */
6566             TYPE_CANONICAL (t) = template_type;
6567           else if (any_template_arguments_need_structural_equality_p (arglist))
6568             /* Some of the template arguments require structural
6569                equality testing, so this template class requires
6570                structural equality testing. */
6571             SET_TYPE_STRUCTURAL_EQUALITY (t);
6572         }
6573
6574       /* If we called start_enum or pushtag above, this information
6575          will already be set up.  */
6576       if (!TYPE_NAME (t))
6577         {
6578           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
6579
6580           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
6581           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
6582           DECL_SOURCE_LOCATION (type_decl)
6583             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
6584         }
6585       else
6586         type_decl = TYPE_NAME (t);
6587
6588       TREE_PRIVATE (type_decl)
6589         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
6590       TREE_PROTECTED (type_decl)
6591         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
6592       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
6593         {
6594           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
6595           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
6596         }
6597
6598       /* Let's consider the explicit specialization of a member
6599          of a class template specialization that is implicitely instantiated,
6600          e.g.:
6601              template<class T>
6602              struct S
6603              {
6604                template<class U> struct M {}; //#0
6605              };
6606
6607              template<>
6608              template<>
6609              struct S<int>::M<char> //#1
6610              {
6611                int i;
6612              };
6613         [temp.expl.spec]/4 says this is valid.
6614
6615         In this case, when we write:
6616         S<int>::M<char> m;
6617
6618         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
6619         the one of #0.
6620
6621         When we encounter #1, we want to store the partial instantiation
6622         of M (template<class T> S<int>::M<T>) in it's CLASSTYPE_TI_TEMPLATE.
6623
6624         For all cases other than this "explicit specialization of member of a
6625         class template", we just want to store the most general template into
6626         the CLASSTYPE_TI_TEMPLATE of M.
6627
6628         This case of "explicit specialization of member of a class template"
6629         only happens when:
6630         1/ the enclosing class is an instantiation of, and therefore not
6631         the same as, the context of the most general template, and
6632         2/ we aren't looking at the partial instantiation itself, i.e.
6633         the innermost arguments are not the same as the innermost parms of
6634         the most general template.
6635
6636         So it's only when 1/ and 2/ happens that we want to use the partial
6637         instantiation of the member template in lieu of its most general
6638         template.  */
6639
6640       if (PRIMARY_TEMPLATE_P (gen_tmpl)
6641           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
6642           /* the enclosing class must be an instantiation...  */
6643           && CLASS_TYPE_P (context)
6644           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
6645         {
6646           tree partial_inst_args;
6647           TREE_VEC_LENGTH (arglist)--;
6648           ++processing_template_decl;
6649           partial_inst_args =
6650             tsubst (INNERMOST_TEMPLATE_ARGS
6651                         (CLASSTYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
6652                     arglist, complain, NULL_TREE);
6653           --processing_template_decl;
6654           TREE_VEC_LENGTH (arglist)++;
6655           use_partial_inst_tmpl =
6656             /*...and we must not be looking at the partial instantiation
6657              itself. */
6658             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
6659                                  partial_inst_args);
6660         }
6661
6662       if (!use_partial_inst_tmpl)
6663         /* This case is easy; there are no member templates involved.  */
6664         found = gen_tmpl;
6665       else
6666         {
6667           /* This is a full instantiation of a member template.  Find
6668              the partial instantiation of which this is an instance.  */
6669
6670           /* Temporarily reduce by one the number of levels in the ARGLIST
6671              so as to avoid comparing the last set of arguments.  */
6672           TREE_VEC_LENGTH (arglist)--;
6673           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
6674           TREE_VEC_LENGTH (arglist)++;
6675           found = CLASSTYPE_TI_TEMPLATE (found);
6676         }
6677
6678       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
6679
6680       elt.spec = t;
6681       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
6682                                                        &elt, hash, INSERT);
6683       *slot = GGC_NEW (spec_entry);
6684       **slot = elt;
6685
6686       /* Note this use of the partial instantiation so we can check it
6687          later in maybe_process_partial_specialization.  */
6688       DECL_TEMPLATE_INSTANTIATIONS (templ)
6689         = tree_cons (arglist, t,
6690                      DECL_TEMPLATE_INSTANTIATIONS (templ));
6691
6692       if (TREE_CODE (t) == ENUMERAL_TYPE && !is_dependent_type)
6693         /* Now that the type has been registered on the instantiations
6694            list, we set up the enumerators.  Because the enumeration
6695            constants may involve the enumeration type itself, we make
6696            sure to register the type first, and then create the
6697            constants.  That way, doing tsubst_expr for the enumeration
6698            constants won't result in recursive calls here; we'll find
6699            the instantiation and exit above.  */
6700         tsubst_enum (template_type, t, arglist);
6701
6702       if (is_dependent_type)
6703         /* If the type makes use of template parameters, the
6704            code that generates debugging information will crash.  */
6705         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6706
6707       /* Possibly limit visibility based on template args.  */
6708       TREE_PUBLIC (type_decl) = 1;
6709       determine_visibility (type_decl);
6710
6711       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6712     }
6713   timevar_pop (TV_NAME_LOOKUP);
6714 }
6715 \f
6716 struct pair_fn_data
6717 {
6718   tree_fn_t fn;
6719   void *data;
6720   /* True when we should also visit template parameters that occur in
6721      non-deduced contexts.  */
6722   bool include_nondeduced_p;
6723   struct pointer_set_t *visited;
6724 };
6725
6726 /* Called from for_each_template_parm via walk_tree.  */
6727
6728 static tree
6729 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6730 {
6731   tree t = *tp;
6732   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6733   tree_fn_t fn = pfd->fn;
6734   void *data = pfd->data;
6735
6736   if (TYPE_P (t)
6737       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6738       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6739                                  pfd->include_nondeduced_p))
6740     return error_mark_node;
6741
6742   switch (TREE_CODE (t))
6743     {
6744     case RECORD_TYPE:
6745       if (TYPE_PTRMEMFUNC_P (t))
6746         break;
6747       /* Fall through.  */
6748
6749     case UNION_TYPE:
6750     case ENUMERAL_TYPE:
6751       if (!TYPE_TEMPLATE_INFO (t))
6752         *walk_subtrees = 0;
6753       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
6754                                        fn, data, pfd->visited, 
6755                                        pfd->include_nondeduced_p))
6756         return error_mark_node;
6757       break;
6758
6759     case INTEGER_TYPE:
6760       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6761                                   fn, data, pfd->visited, 
6762                                   pfd->include_nondeduced_p)
6763           || for_each_template_parm (TYPE_MAX_VALUE (t),
6764                                      fn, data, pfd->visited,
6765                                      pfd->include_nondeduced_p))
6766         return error_mark_node;
6767       break;
6768
6769     case METHOD_TYPE:
6770       /* Since we're not going to walk subtrees, we have to do this
6771          explicitly here.  */
6772       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6773                                   pfd->visited, pfd->include_nondeduced_p))
6774         return error_mark_node;
6775       /* Fall through.  */
6776
6777     case FUNCTION_TYPE:
6778       /* Check the return type.  */
6779       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6780                                   pfd->include_nondeduced_p))
6781         return error_mark_node;
6782
6783       /* Check the parameter types.  Since default arguments are not
6784          instantiated until they are needed, the TYPE_ARG_TYPES may
6785          contain expressions that involve template parameters.  But,
6786          no-one should be looking at them yet.  And, once they're
6787          instantiated, they don't contain template parameters, so
6788          there's no point in looking at them then, either.  */
6789       {
6790         tree parm;
6791
6792         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6793           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6794                                       pfd->visited, pfd->include_nondeduced_p))
6795             return error_mark_node;
6796
6797         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6798            want walk_tree walking into them itself.  */
6799         *walk_subtrees = 0;
6800       }
6801       break;
6802
6803     case TYPEOF_TYPE:
6804       if (pfd->include_nondeduced_p
6805           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6806                                      pfd->visited, 
6807                                      pfd->include_nondeduced_p))
6808         return error_mark_node;
6809       break;
6810
6811     case FUNCTION_DECL:
6812     case VAR_DECL:
6813       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6814           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6815                                      pfd->visited, pfd->include_nondeduced_p))
6816         return error_mark_node;
6817       /* Fall through.  */
6818
6819     case PARM_DECL:
6820     case CONST_DECL:
6821       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6822           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6823                                      pfd->visited, pfd->include_nondeduced_p))
6824         return error_mark_node;
6825       if (DECL_CONTEXT (t)
6826           && pfd->include_nondeduced_p
6827           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6828                                      pfd->visited, pfd->include_nondeduced_p))
6829         return error_mark_node;
6830       break;
6831
6832     case BOUND_TEMPLATE_TEMPLATE_PARM:
6833       /* Record template parameters such as `T' inside `TT<T>'.  */
6834       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6835                                   pfd->include_nondeduced_p))
6836         return error_mark_node;
6837       /* Fall through.  */
6838
6839     case TEMPLATE_TEMPLATE_PARM:
6840     case TEMPLATE_TYPE_PARM:
6841     case TEMPLATE_PARM_INDEX:
6842       if (fn && (*fn)(t, data))
6843         return error_mark_node;
6844       else if (!fn)
6845         return error_mark_node;
6846       break;
6847
6848     case TEMPLATE_DECL:
6849       /* A template template parameter is encountered.  */
6850       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6851           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6852                                      pfd->include_nondeduced_p))
6853         return error_mark_node;
6854
6855       /* Already substituted template template parameter */
6856       *walk_subtrees = 0;
6857       break;
6858
6859     case TYPENAME_TYPE:
6860       if (!fn
6861           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6862                                      data, pfd->visited, 
6863                                      pfd->include_nondeduced_p))
6864         return error_mark_node;
6865       break;
6866
6867     case CONSTRUCTOR:
6868       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6869           && pfd->include_nondeduced_p
6870           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6871                                      (TREE_TYPE (t)), fn, data,
6872                                      pfd->visited, pfd->include_nondeduced_p))
6873         return error_mark_node;
6874       break;
6875
6876     case INDIRECT_REF:
6877     case COMPONENT_REF:
6878       /* If there's no type, then this thing must be some expression
6879          involving template parameters.  */
6880       if (!fn && !TREE_TYPE (t))
6881         return error_mark_node;
6882       break;
6883
6884     case MODOP_EXPR:
6885     case CAST_EXPR:
6886     case REINTERPRET_CAST_EXPR:
6887     case CONST_CAST_EXPR:
6888     case STATIC_CAST_EXPR:
6889     case DYNAMIC_CAST_EXPR:
6890     case ARROW_EXPR:
6891     case DOTSTAR_EXPR:
6892     case TYPEID_EXPR:
6893     case PSEUDO_DTOR_EXPR:
6894       if (!fn)
6895         return error_mark_node;
6896       break;
6897
6898     default:
6899       break;
6900     }
6901
6902   /* We didn't find any template parameters we liked.  */
6903   return NULL_TREE;
6904 }
6905
6906 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6907    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6908    call FN with the parameter and the DATA.
6909    If FN returns nonzero, the iteration is terminated, and
6910    for_each_template_parm returns 1.  Otherwise, the iteration
6911    continues.  If FN never returns a nonzero value, the value
6912    returned by for_each_template_parm is 0.  If FN is NULL, it is
6913    considered to be the function which always returns 1.
6914
6915    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6916    parameters that occur in non-deduced contexts.  When false, only
6917    visits those template parameters that can be deduced.  */
6918
6919 static int
6920 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6921                         struct pointer_set_t *visited,
6922                         bool include_nondeduced_p)
6923 {
6924   struct pair_fn_data pfd;
6925   int result;
6926
6927   /* Set up.  */
6928   pfd.fn = fn;
6929   pfd.data = data;
6930   pfd.include_nondeduced_p = include_nondeduced_p;
6931
6932   /* Walk the tree.  (Conceptually, we would like to walk without
6933      duplicates, but for_each_template_parm_r recursively calls
6934      for_each_template_parm, so we would need to reorganize a fair
6935      bit to use walk_tree_without_duplicates, so we keep our own
6936      visited list.)  */
6937   if (visited)
6938     pfd.visited = visited;
6939   else
6940     pfd.visited = pointer_set_create ();
6941   result = cp_walk_tree (&t,
6942                          for_each_template_parm_r,
6943                          &pfd,
6944                          pfd.visited) != NULL_TREE;
6945
6946   /* Clean up.  */
6947   if (!visited)
6948     {
6949       pointer_set_destroy (pfd.visited);
6950       pfd.visited = 0;
6951     }
6952
6953   return result;
6954 }
6955
6956 /* Returns true if T depends on any template parameter.  */
6957
6958 int
6959 uses_template_parms (tree t)
6960 {
6961   bool dependent_p;
6962   int saved_processing_template_decl;
6963
6964   saved_processing_template_decl = processing_template_decl;
6965   if (!saved_processing_template_decl)
6966     processing_template_decl = 1;
6967   if (TYPE_P (t))
6968     dependent_p = dependent_type_p (t);
6969   else if (TREE_CODE (t) == TREE_VEC)
6970     dependent_p = any_dependent_template_arguments_p (t);
6971   else if (TREE_CODE (t) == TREE_LIST)
6972     dependent_p = (uses_template_parms (TREE_VALUE (t))
6973                    || uses_template_parms (TREE_CHAIN (t)));
6974   else if (TREE_CODE (t) == TYPE_DECL)
6975     dependent_p = dependent_type_p (TREE_TYPE (t));
6976   else if (DECL_P (t)
6977            || EXPR_P (t)
6978            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
6979            || TREE_CODE (t) == OVERLOAD
6980            || TREE_CODE (t) == BASELINK
6981            || TREE_CODE (t) == IDENTIFIER_NODE
6982            || TREE_CODE (t) == TRAIT_EXPR
6983            || TREE_CODE (t) == CONSTRUCTOR
6984            || CONSTANT_CLASS_P (t))
6985     dependent_p = (type_dependent_expression_p (t)
6986                    || value_dependent_expression_p (t));
6987   else
6988     {
6989       gcc_assert (t == error_mark_node);
6990       dependent_p = false;
6991     }
6992
6993   processing_template_decl = saved_processing_template_decl;
6994
6995   return dependent_p;
6996 }
6997
6998 /* Returns true if T depends on any template parameter with level LEVEL.  */
6999
7000 int
7001 uses_template_parms_level (tree t, int level)
7002 {
7003   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
7004                                  /*include_nondeduced_p=*/true);
7005 }
7006
7007 static int tinst_depth;
7008 extern int max_tinst_depth;
7009 #ifdef GATHER_STATISTICS
7010 int depth_reached;
7011 #endif
7012 static int tinst_level_tick;
7013 static int last_template_error_tick;
7014
7015 /* We're starting to instantiate D; record the template instantiation context
7016    for diagnostics and to restore it later.  */
7017
7018 int
7019 push_tinst_level (tree d)
7020 {
7021   struct tinst_level *new_level;
7022
7023   if (tinst_depth >= max_tinst_depth)
7024     {
7025       /* If the instantiation in question still has unbound template parms,
7026          we don't really care if we can't instantiate it, so just return.
7027          This happens with base instantiation for implicit `typename'.  */
7028       if (uses_template_parms (d))
7029         return 0;
7030
7031       last_template_error_tick = tinst_level_tick;
7032       error ("template instantiation depth exceeds maximum of %d (use "
7033              "-ftemplate-depth= to increase the maximum) instantiating %qD",
7034              max_tinst_depth, d);
7035
7036       print_instantiation_context ();
7037
7038       return 0;
7039     }
7040
7041   new_level = GGC_NEW (struct tinst_level);
7042   new_level->decl = d;
7043   new_level->locus = input_location;
7044   new_level->in_system_header_p = in_system_header;
7045   new_level->next = current_tinst_level;
7046   current_tinst_level = new_level;
7047
7048   ++tinst_depth;
7049 #ifdef GATHER_STATISTICS
7050   if (tinst_depth > depth_reached)
7051     depth_reached = tinst_depth;
7052 #endif
7053
7054   ++tinst_level_tick;
7055   return 1;
7056 }
7057
7058 /* We're done instantiating this template; return to the instantiation
7059    context.  */
7060
7061 void
7062 pop_tinst_level (void)
7063 {
7064   /* Restore the filename and line number stashed away when we started
7065      this instantiation.  */
7066   input_location = current_tinst_level->locus;
7067   current_tinst_level = current_tinst_level->next;
7068   --tinst_depth;
7069   ++tinst_level_tick;
7070 }
7071
7072 /* We're instantiating a deferred template; restore the template
7073    instantiation context in which the instantiation was requested, which
7074    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
7075
7076 static tree
7077 reopen_tinst_level (struct tinst_level *level)
7078 {
7079   struct tinst_level *t;
7080
7081   tinst_depth = 0;
7082   for (t = level; t; t = t->next)
7083     ++tinst_depth;
7084
7085   current_tinst_level = level;
7086   pop_tinst_level ();
7087   return level->decl;
7088 }
7089
7090 /* Returns the TINST_LEVEL which gives the original instantiation
7091    context.  */
7092
7093 struct tinst_level *
7094 outermost_tinst_level (void)
7095 {
7096   struct tinst_level *level = current_tinst_level;
7097   if (level)
7098     while (level->next)
7099       level = level->next;
7100   return level;
7101 }
7102
7103 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
7104
7105 bool
7106 parameter_of_template_p (tree parm, tree templ)
7107 {
7108   tree parms;
7109   int i;
7110
7111   if (!parm || !templ)
7112     return false;
7113
7114   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
7115   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7116
7117   parms = DECL_TEMPLATE_PARMS (templ);
7118   parms = INNERMOST_TEMPLATE_PARMS (parms);
7119
7120   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
7121     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
7122       return true;
7123
7124   return false;
7125 }
7126
7127 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
7128    vector of template arguments, as for tsubst.
7129
7130    Returns an appropriate tsubst'd friend declaration.  */
7131
7132 static tree
7133 tsubst_friend_function (tree decl, tree args)
7134 {
7135   tree new_friend;
7136
7137   if (TREE_CODE (decl) == FUNCTION_DECL
7138       && DECL_TEMPLATE_INSTANTIATION (decl)
7139       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
7140     /* This was a friend declared with an explicit template
7141        argument list, e.g.:
7142
7143        friend void f<>(T);
7144
7145        to indicate that f was a template instantiation, not a new
7146        function declaration.  Now, we have to figure out what
7147        instantiation of what template.  */
7148     {
7149       tree template_id, arglist, fns;
7150       tree new_args;
7151       tree tmpl;
7152       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
7153
7154       /* Friend functions are looked up in the containing namespace scope.
7155          We must enter that scope, to avoid finding member functions of the
7156          current class with same name.  */
7157       push_nested_namespace (ns);
7158       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
7159                          tf_warning_or_error, NULL_TREE,
7160                          /*integral_constant_expression_p=*/false);
7161       pop_nested_namespace (ns);
7162       arglist = tsubst (DECL_TI_ARGS (decl), args,
7163                         tf_warning_or_error, NULL_TREE);
7164       template_id = lookup_template_function (fns, arglist);
7165
7166       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7167       tmpl = determine_specialization (template_id, new_friend,
7168                                        &new_args,
7169                                        /*need_member_template=*/0,
7170                                        TREE_VEC_LENGTH (args),
7171                                        tsk_none);
7172       return instantiate_template (tmpl, new_args, tf_error);
7173     }
7174
7175   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7176
7177   /* The NEW_FRIEND will look like an instantiation, to the
7178      compiler, but is not an instantiation from the point of view of
7179      the language.  For example, we might have had:
7180
7181      template <class T> struct S {
7182        template <class U> friend void f(T, U);
7183      };
7184
7185      Then, in S<int>, template <class U> void f(int, U) is not an
7186      instantiation of anything.  */
7187   if (new_friend == error_mark_node)
7188     return error_mark_node;
7189
7190   DECL_USE_TEMPLATE (new_friend) = 0;
7191   if (TREE_CODE (decl) == TEMPLATE_DECL)
7192     {
7193       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
7194       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
7195         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
7196     }
7197
7198   /* The mangled name for the NEW_FRIEND is incorrect.  The function
7199      is not a template instantiation and should not be mangled like
7200      one.  Therefore, we forget the mangling here; we'll recompute it
7201      later if we need it.  */
7202   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
7203     {
7204       SET_DECL_RTL (new_friend, NULL_RTX);
7205       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
7206     }
7207
7208   if (DECL_NAMESPACE_SCOPE_P (new_friend))
7209     {
7210       tree old_decl;
7211       tree new_friend_template_info;
7212       tree new_friend_result_template_info;
7213       tree ns;
7214       int  new_friend_is_defn;
7215
7216       /* We must save some information from NEW_FRIEND before calling
7217          duplicate decls since that function will free NEW_FRIEND if
7218          possible.  */
7219       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
7220       new_friend_is_defn =
7221             (DECL_INITIAL (DECL_TEMPLATE_RESULT
7222                            (template_for_substitution (new_friend)))
7223              != NULL_TREE);
7224       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
7225         {
7226           /* This declaration is a `primary' template.  */
7227           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
7228
7229           new_friend_result_template_info
7230             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
7231         }
7232       else
7233         new_friend_result_template_info = NULL_TREE;
7234
7235       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
7236       if (new_friend_is_defn)
7237         DECL_INITIAL (new_friend) = error_mark_node;
7238
7239       /* Inside pushdecl_namespace_level, we will push into the
7240          current namespace. However, the friend function should go
7241          into the namespace of the template.  */
7242       ns = decl_namespace_context (new_friend);
7243       push_nested_namespace (ns);
7244       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
7245       pop_nested_namespace (ns);
7246
7247       if (old_decl == error_mark_node)
7248         return error_mark_node;
7249
7250       if (old_decl != new_friend)
7251         {
7252           /* This new friend declaration matched an existing
7253              declaration.  For example, given:
7254
7255                template <class T> void f(T);
7256                template <class U> class C {
7257                  template <class T> friend void f(T) {}
7258                };
7259
7260              the friend declaration actually provides the definition
7261              of `f', once C has been instantiated for some type.  So,
7262              old_decl will be the out-of-class template declaration,
7263              while new_friend is the in-class definition.
7264
7265              But, if `f' was called before this point, the
7266              instantiation of `f' will have DECL_TI_ARGS corresponding
7267              to `T' but not to `U', references to which might appear
7268              in the definition of `f'.  Previously, the most general
7269              template for an instantiation of `f' was the out-of-class
7270              version; now it is the in-class version.  Therefore, we
7271              run through all specialization of `f', adding to their
7272              DECL_TI_ARGS appropriately.  In particular, they need a
7273              new set of outer arguments, corresponding to the
7274              arguments for this class instantiation.
7275
7276              The same situation can arise with something like this:
7277
7278                friend void f(int);
7279                template <class T> class C {
7280                  friend void f(T) {}
7281                };
7282
7283              when `C<int>' is instantiated.  Now, `f(int)' is defined
7284              in the class.  */
7285
7286           if (!new_friend_is_defn)
7287             /* On the other hand, if the in-class declaration does
7288                *not* provide a definition, then we don't want to alter
7289                existing definitions.  We can just leave everything
7290                alone.  */
7291             ;
7292           else
7293             {
7294               tree new_template = TI_TEMPLATE (new_friend_template_info);
7295               tree new_args = TI_ARGS (new_friend_template_info);
7296
7297               /* Overwrite whatever template info was there before, if
7298                  any, with the new template information pertaining to
7299                  the declaration.  */
7300               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
7301
7302               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
7303                 /* We should have called reregister_specialization in
7304                    duplicate_decls.  */
7305                 gcc_assert (retrieve_specialization (new_template,
7306                                                      new_args, 0)
7307                             == old_decl);
7308               else
7309                 {
7310                   tree t;
7311
7312                   /* Indicate that the old function template is a partial
7313                      instantiation.  */
7314                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
7315                     = new_friend_result_template_info;
7316
7317                   gcc_assert (new_template
7318                               == most_general_template (new_template));
7319                   gcc_assert (new_template != old_decl);
7320
7321                   /* Reassign any specializations already in the hash table
7322                      to the new more general template, and add the
7323                      additional template args.  */
7324                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
7325                        t != NULL_TREE;
7326                        t = TREE_CHAIN (t))
7327                     {
7328                       tree spec = TREE_VALUE (t);
7329                       spec_entry elt;
7330
7331                       elt.tmpl = old_decl;
7332                       elt.args = DECL_TI_ARGS (spec);
7333                       elt.spec = NULL_TREE;
7334
7335                       htab_remove_elt (decl_specializations, &elt);
7336
7337                       DECL_TI_ARGS (spec)
7338                         = add_outermost_template_args (new_args,
7339                                                        DECL_TI_ARGS (spec));
7340
7341                       register_specialization
7342                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
7343
7344                     }
7345                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
7346                 }
7347             }
7348
7349           /* The information from NEW_FRIEND has been merged into OLD_DECL
7350              by duplicate_decls.  */
7351           new_friend = old_decl;
7352         }
7353     }
7354   else
7355     {
7356       tree context = DECL_CONTEXT (new_friend);
7357       bool dependent_p;
7358
7359       /* In the code
7360            template <class T> class C {
7361              template <class U> friend void C1<U>::f (); // case 1
7362              friend void C2<T>::f ();                    // case 2
7363            };
7364          we only need to make sure CONTEXT is a complete type for
7365          case 2.  To distinguish between the two cases, we note that
7366          CONTEXT of case 1 remains dependent type after tsubst while
7367          this isn't true for case 2.  */
7368       ++processing_template_decl;
7369       dependent_p = dependent_type_p (context);
7370       --processing_template_decl;
7371
7372       if (!dependent_p
7373           && !complete_type_or_else (context, NULL_TREE))
7374         return error_mark_node;
7375
7376       if (COMPLETE_TYPE_P (context))
7377         {
7378           /* Check to see that the declaration is really present, and,
7379              possibly obtain an improved declaration.  */
7380           tree fn = check_classfn (context,
7381                                    new_friend, NULL_TREE);
7382
7383           if (fn)
7384             new_friend = fn;
7385         }
7386     }
7387
7388   return new_friend;
7389 }
7390
7391 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
7392    template arguments, as for tsubst.
7393
7394    Returns an appropriate tsubst'd friend type or error_mark_node on
7395    failure.  */
7396
7397 static tree
7398 tsubst_friend_class (tree friend_tmpl, tree args)
7399 {
7400   tree friend_type;
7401   tree tmpl;
7402   tree context;
7403
7404   context = DECL_CONTEXT (friend_tmpl);
7405
7406   if (context)
7407     {
7408       if (TREE_CODE (context) == NAMESPACE_DECL)
7409         push_nested_namespace (context);
7410       else
7411         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
7412     }
7413
7414   /* Look for a class template declaration.  We look for hidden names
7415      because two friend declarations of the same template are the
7416      same.  For example, in:
7417
7418        struct A { 
7419          template <typename> friend class F;
7420        };
7421        template <typename> struct B { 
7422          template <typename> friend class F;
7423        };
7424
7425      both F templates are the same.  */
7426   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
7427                            /*block_p=*/true, 0, 
7428                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
7429
7430   /* But, if we don't find one, it might be because we're in a
7431      situation like this:
7432
7433        template <class T>
7434        struct S {
7435          template <class U>
7436          friend struct S;
7437        };
7438
7439      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
7440      for `S<int>', not the TEMPLATE_DECL.  */
7441   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
7442     {
7443       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
7444       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
7445     }
7446
7447   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
7448     {
7449       /* The friend template has already been declared.  Just
7450          check to see that the declarations match, and install any new
7451          default parameters.  We must tsubst the default parameters,
7452          of course.  We only need the innermost template parameters
7453          because that is all that redeclare_class_template will look
7454          at.  */
7455       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
7456           > TMPL_ARGS_DEPTH (args))
7457         {
7458           tree parms;
7459           location_t saved_input_location;
7460           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
7461                                          args, tf_warning_or_error);
7462
7463           saved_input_location = input_location;
7464           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
7465           redeclare_class_template (TREE_TYPE (tmpl), parms);
7466           input_location = saved_input_location;
7467           
7468         }
7469
7470       friend_type = TREE_TYPE (tmpl);
7471     }
7472   else
7473     {
7474       /* The friend template has not already been declared.  In this
7475          case, the instantiation of the template class will cause the
7476          injection of this template into the global scope.  */
7477       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7478       if (tmpl == error_mark_node)
7479         return error_mark_node;
7480
7481       /* The new TMPL is not an instantiation of anything, so we
7482          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7483          the new type because that is supposed to be the corresponding
7484          template decl, i.e., TMPL.  */
7485       DECL_USE_TEMPLATE (tmpl) = 0;
7486       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7487       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7488       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7489         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7490
7491       /* Inject this template into the global scope.  */
7492       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7493     }
7494
7495   if (context)
7496     {
7497       if (TREE_CODE (context) == NAMESPACE_DECL)
7498         pop_nested_namespace (context);
7499       else
7500         pop_nested_class ();
7501     }
7502
7503   return friend_type;
7504 }
7505
7506 /* Returns zero if TYPE cannot be completed later due to circularity.
7507    Otherwise returns one.  */
7508
7509 static int
7510 can_complete_type_without_circularity (tree type)
7511 {
7512   if (type == NULL_TREE || type == error_mark_node)
7513     return 0;
7514   else if (COMPLETE_TYPE_P (type))
7515     return 1;
7516   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
7517     return can_complete_type_without_circularity (TREE_TYPE (type));
7518   else if (CLASS_TYPE_P (type)
7519            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
7520     return 0;
7521   else
7522     return 1;
7523 }
7524
7525 /* Apply any attributes which had to be deferred until instantiation
7526    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
7527    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
7528
7529 static void
7530 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
7531                                 tree args, tsubst_flags_t complain, tree in_decl)
7532 {
7533   tree last_dep = NULL_TREE;
7534   tree t;
7535   tree *p;
7536
7537   for (t = attributes; t; t = TREE_CHAIN (t))
7538     if (ATTR_IS_DEPENDENT (t))
7539       {
7540         last_dep = t;
7541         attributes = copy_list (attributes);
7542         break;
7543       }
7544
7545   if (DECL_P (*decl_p))
7546     {
7547       if (TREE_TYPE (*decl_p) == error_mark_node)
7548         return;
7549       p = &DECL_ATTRIBUTES (*decl_p);
7550     }
7551   else
7552     p = &TYPE_ATTRIBUTES (*decl_p);
7553
7554   if (last_dep)
7555     {
7556       tree late_attrs = NULL_TREE;
7557       tree *q = &late_attrs;
7558
7559       for (*p = attributes; *p; )
7560         {
7561           t = *p;
7562           if (ATTR_IS_DEPENDENT (t))
7563             {
7564               *p = TREE_CHAIN (t);
7565               TREE_CHAIN (t) = NULL_TREE;
7566               /* If the first attribute argument is an identifier, don't
7567                  pass it through tsubst.  Attributes like mode, format,
7568                  cleanup and several target specific attributes expect it
7569                  unmodified.  */
7570               if (TREE_VALUE (t)
7571                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
7572                   && TREE_VALUE (TREE_VALUE (t))
7573                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
7574                       == IDENTIFIER_NODE))
7575                 {
7576                   tree chain
7577                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
7578                                    in_decl,
7579                                    /*integral_constant_expression_p=*/false);
7580                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
7581                     TREE_VALUE (t)
7582                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
7583                                    chain);
7584                 }
7585               else
7586                 TREE_VALUE (t)
7587                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
7588                                  /*integral_constant_expression_p=*/false);
7589               *q = t;
7590               q = &TREE_CHAIN (t);
7591             }
7592           else
7593             p = &TREE_CHAIN (t);
7594         }
7595
7596       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
7597     }
7598 }
7599
7600 /* Perform (or defer) access check for typedefs that were referenced
7601    from within the template TMPL code.
7602    This is a subroutine of instantiate_template and instantiate_class_template.
7603    TMPL is the template to consider and TARGS is the list of arguments of
7604    that template.  */
7605
7606 static void
7607 perform_typedefs_access_check (tree tmpl, tree targs)
7608 {
7609   location_t saved_location;
7610   int i;
7611   qualified_typedef_usage_t *iter;
7612
7613   if (!tmpl
7614       || (!CLASS_TYPE_P (tmpl)
7615           && TREE_CODE (tmpl) != FUNCTION_DECL))
7616     return;
7617
7618   saved_location = input_location;
7619   for (i = 0;
7620        VEC_iterate (qualified_typedef_usage_t,
7621                     get_types_needing_access_check (tmpl),
7622                     i, iter);
7623         ++i)
7624     {
7625       tree type_decl = iter->typedef_decl;
7626       tree type_scope = iter->context;
7627
7628       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
7629         continue;
7630
7631       if (uses_template_parms (type_decl))
7632         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
7633       if (uses_template_parms (type_scope))
7634         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
7635
7636       /* Make access check error messages point to the location
7637          of the use of the typedef.  */
7638       input_location = iter->locus;
7639       perform_or_defer_access_check (TYPE_BINFO (type_scope),
7640                                      type_decl, type_decl);
7641     }
7642     input_location = saved_location;
7643 }
7644
7645 tree
7646 instantiate_class_template (tree type)
7647 {
7648   tree templ, args, pattern, t, member;
7649   tree typedecl;
7650   tree pbinfo;
7651   tree base_list;
7652   unsigned int saved_maximum_field_alignment;
7653
7654   if (type == error_mark_node)
7655     return error_mark_node;
7656
7657   if (TYPE_BEING_DEFINED (type)
7658       || COMPLETE_TYPE_P (type)
7659       || uses_template_parms (type))
7660     return type;
7661
7662   /* Figure out which template is being instantiated.  */
7663   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
7664   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7665
7666   /* Determine what specialization of the original template to
7667      instantiate.  */
7668   t = most_specialized_class (type, templ);
7669   if (t == error_mark_node)
7670     {
7671       TYPE_BEING_DEFINED (type) = 1;
7672       return error_mark_node;
7673     }
7674   else if (t)
7675     {
7676       /* This TYPE is actually an instantiation of a partial
7677          specialization.  We replace the innermost set of ARGS with
7678          the arguments appropriate for substitution.  For example,
7679          given:
7680
7681            template <class T> struct S {};
7682            template <class T> struct S<T*> {};
7683
7684          and supposing that we are instantiating S<int*>, ARGS will
7685          presently be {int*} -- but we need {int}.  */
7686       pattern = TREE_TYPE (t);
7687       args = TREE_PURPOSE (t);
7688     }
7689   else
7690     {
7691       pattern = TREE_TYPE (templ);
7692       args = CLASSTYPE_TI_ARGS (type);
7693     }
7694
7695   /* If the template we're instantiating is incomplete, then clearly
7696      there's nothing we can do.  */
7697   if (!COMPLETE_TYPE_P (pattern))
7698     return type;
7699
7700   /* If we've recursively instantiated too many templates, stop.  */
7701   if (! push_tinst_level (type))
7702     return type;
7703
7704   /* Now we're really doing the instantiation.  Mark the type as in
7705      the process of being defined.  */
7706   TYPE_BEING_DEFINED (type) = 1;
7707
7708   /* We may be in the middle of deferred access check.  Disable
7709      it now.  */
7710   push_deferring_access_checks (dk_no_deferred);
7711
7712   push_to_top_level ();
7713   /* Use #pragma pack from the template context.  */
7714   saved_maximum_field_alignment = maximum_field_alignment;
7715   maximum_field_alignment = TYPE_PRECISION (pattern);
7716
7717   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
7718
7719   /* Set the input location to the most specialized template definition.
7720      This is needed if tsubsting causes an error.  */
7721   typedecl = TYPE_MAIN_DECL (pattern);
7722   input_location = DECL_SOURCE_LOCATION (typedecl);
7723
7724   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7725   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7726   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7727   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7728   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
7729   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
7730   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
7731   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
7732   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7733   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7734   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7735   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7736   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7737   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7738   if (ANON_AGGR_TYPE_P (pattern))
7739     SET_ANON_AGGR_TYPE_P (type);
7740   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7741     {
7742       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7743       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7744     }
7745
7746   pbinfo = TYPE_BINFO (pattern);
7747
7748   /* We should never instantiate a nested class before its enclosing
7749      class; we need to look up the nested class by name before we can
7750      instantiate it, and that lookup should instantiate the enclosing
7751      class.  */
7752   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7753               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
7754               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
7755
7756   base_list = NULL_TREE;
7757   if (BINFO_N_BASE_BINFOS (pbinfo))
7758     {
7759       tree pbase_binfo;
7760       tree context = TYPE_CONTEXT (type);
7761       tree pushed_scope;
7762       int i;
7763
7764       /* We must enter the scope containing the type, as that is where
7765          the accessibility of types named in dependent bases are
7766          looked up from.  */
7767       pushed_scope = push_scope (context ? context : global_namespace);
7768
7769       /* Substitute into each of the bases to determine the actual
7770          basetypes.  */
7771       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7772         {
7773           tree base;
7774           tree access = BINFO_BASE_ACCESS (pbinfo, i);
7775           tree expanded_bases = NULL_TREE;
7776           int idx, len = 1;
7777
7778           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7779             {
7780               expanded_bases = 
7781                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7782                                        args, tf_error, NULL_TREE);
7783               if (expanded_bases == error_mark_node)
7784                 continue;
7785
7786               len = TREE_VEC_LENGTH (expanded_bases);
7787             }
7788
7789           for (idx = 0; idx < len; idx++)
7790             {
7791               if (expanded_bases)
7792                 /* Extract the already-expanded base class.  */
7793                 base = TREE_VEC_ELT (expanded_bases, idx);
7794               else
7795                 /* Substitute to figure out the base class.  */
7796                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
7797                                NULL_TREE);
7798
7799               if (base == error_mark_node)
7800                 continue;
7801
7802               base_list = tree_cons (access, base, base_list);
7803               if (BINFO_VIRTUAL_P (pbase_binfo))
7804                 TREE_TYPE (base_list) = integer_type_node;
7805             }
7806         }
7807
7808       /* The list is now in reverse order; correct that.  */
7809       base_list = nreverse (base_list);
7810
7811       if (pushed_scope)
7812         pop_scope (pushed_scope);
7813     }
7814   /* Now call xref_basetypes to set up all the base-class
7815      information.  */
7816   xref_basetypes (type, base_list);
7817
7818   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7819                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7820                                   args, tf_error, NULL_TREE);
7821
7822   /* Now that our base classes are set up, enter the scope of the
7823      class, so that name lookups into base classes, etc. will work
7824      correctly.  This is precisely analogous to what we do in
7825      begin_class_definition when defining an ordinary non-template
7826      class, except we also need to push the enclosing classes.  */
7827   push_nested_class (type);
7828
7829   /* Now members are processed in the order of declaration.  */
7830   for (member = CLASSTYPE_DECL_LIST (pattern);
7831        member; member = TREE_CHAIN (member))
7832     {
7833       tree t = TREE_VALUE (member);
7834
7835       if (TREE_PURPOSE (member))
7836         {
7837           if (TYPE_P (t))
7838             {
7839               /* Build new CLASSTYPE_NESTED_UTDS.  */
7840
7841               tree newtag;
7842               bool class_template_p;
7843
7844               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7845                                   && TYPE_LANG_SPECIFIC (t)
7846                                   && CLASSTYPE_IS_TEMPLATE (t));
7847               /* If the member is a class template, then -- even after
7848                  substitution -- there may be dependent types in the
7849                  template argument list for the class.  We increment
7850                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7851                  that function will assume that no types are dependent
7852                  when outside of a template.  */
7853               if (class_template_p)
7854                 ++processing_template_decl;
7855               newtag = tsubst (t, args, tf_error, NULL_TREE);
7856               if (class_template_p)
7857                 --processing_template_decl;
7858               if (newtag == error_mark_node)
7859                 continue;
7860
7861               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7862                 {
7863                   tree name = TYPE_IDENTIFIER (t);
7864
7865                   if (class_template_p)
7866                     /* Unfortunately, lookup_template_class sets
7867                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7868                        instantiation (i.e., for the type of a member
7869                        template class nested within a template class.)
7870                        This behavior is required for
7871                        maybe_process_partial_specialization to work
7872                        correctly, but is not accurate in this case;
7873                        the TAG is not an instantiation of anything.
7874                        (The corresponding TEMPLATE_DECL is an
7875                        instantiation, but the TYPE is not.) */
7876                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7877
7878                   /* Now, we call pushtag to put this NEWTAG into the scope of
7879                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7880                      pushtag calling push_template_decl.  We don't have to do
7881                      this for enums because it will already have been done in
7882                      tsubst_enum.  */
7883                   if (name)
7884                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7885                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7886                 }
7887             }
7888           else if (TREE_CODE (t) == FUNCTION_DECL
7889                    || DECL_FUNCTION_TEMPLATE_P (t))
7890             {
7891               /* Build new TYPE_METHODS.  */
7892               tree r;
7893
7894               if (TREE_CODE (t) == TEMPLATE_DECL)
7895                 ++processing_template_decl;
7896               r = tsubst (t, args, tf_error, NULL_TREE);
7897               if (TREE_CODE (t) == TEMPLATE_DECL)
7898                 --processing_template_decl;
7899               set_current_access_from_decl (r);
7900               finish_member_declaration (r);
7901             }
7902           else
7903             {
7904               /* Build new TYPE_FIELDS.  */
7905               if (TREE_CODE (t) == STATIC_ASSERT)
7906                 {
7907                   tree condition = 
7908                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7909                                  tf_warning_or_error, NULL_TREE,
7910                                  /*integral_constant_expression_p=*/true);
7911                   finish_static_assert (condition,
7912                                         STATIC_ASSERT_MESSAGE (t), 
7913                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7914                                         /*member_p=*/true);
7915                 }
7916               else if (TREE_CODE (t) != CONST_DECL)
7917                 {
7918                   tree r;
7919
7920                   /* The file and line for this declaration, to
7921                      assist in error message reporting.  Since we
7922                      called push_tinst_level above, we don't need to
7923                      restore these.  */
7924                   input_location = DECL_SOURCE_LOCATION (t);
7925
7926                   if (TREE_CODE (t) == TEMPLATE_DECL)
7927                     ++processing_template_decl;
7928                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7929                   if (TREE_CODE (t) == TEMPLATE_DECL)
7930                     --processing_template_decl;
7931                   if (TREE_CODE (r) == VAR_DECL)
7932                     {
7933                       /* In [temp.inst]:
7934
7935                            [t]he initialization (and any associated
7936                            side-effects) of a static data member does
7937                            not occur unless the static data member is
7938                            itself used in a way that requires the
7939                            definition of the static data member to
7940                            exist.
7941
7942                          Therefore, we do not substitute into the
7943                          initialized for the static data member here.  */
7944                       finish_static_data_member_decl
7945                         (r,
7946                          /*init=*/NULL_TREE,
7947                          /*init_const_expr_p=*/false,
7948                          /*asmspec_tree=*/NULL_TREE,
7949                          /*flags=*/0);
7950                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7951                         check_static_variable_definition (r, TREE_TYPE (r));
7952                     }
7953                   else if (TREE_CODE (r) == FIELD_DECL)
7954                     {
7955                       /* Determine whether R has a valid type and can be
7956                          completed later.  If R is invalid, then it is
7957                          replaced by error_mark_node so that it will not be
7958                          added to TYPE_FIELDS.  */
7959                       tree rtype = TREE_TYPE (r);
7960                       if (can_complete_type_without_circularity (rtype))
7961                         complete_type (rtype);
7962
7963                       if (!COMPLETE_TYPE_P (rtype))
7964                         {
7965                           cxx_incomplete_type_error (r, rtype);
7966                           r = error_mark_node;
7967                         }
7968                     }
7969
7970                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
7971                      such a thing will already have been added to the field
7972                      list by tsubst_enum in finish_member_declaration in the
7973                      CLASSTYPE_NESTED_UTDS case above.  */
7974                   if (!(TREE_CODE (r) == TYPE_DECL
7975                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
7976                         && DECL_ARTIFICIAL (r)))
7977                     {
7978                       set_current_access_from_decl (r);
7979                       finish_member_declaration (r);
7980                     }
7981                 }
7982             }
7983         }
7984       else
7985         {
7986           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
7987             {
7988               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
7989
7990               tree friend_type = t;
7991               bool adjust_processing_template_decl = false;
7992
7993               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7994                 {
7995                   /* template <class T> friend class C;  */
7996                   friend_type = tsubst_friend_class (friend_type, args);
7997                   adjust_processing_template_decl = true;
7998                 }
7999               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
8000                 {
8001                   /* template <class T> friend class C::D;  */
8002                   friend_type = tsubst (friend_type, args,
8003                                         tf_warning_or_error, NULL_TREE);
8004                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8005                     friend_type = TREE_TYPE (friend_type);
8006                   adjust_processing_template_decl = true;
8007                 }
8008               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
8009                 {
8010                   /* This could be either
8011
8012                        friend class T::C;
8013
8014                      when dependent_type_p is false or
8015
8016                        template <class U> friend class T::C;
8017
8018                      otherwise.  */
8019                   friend_type = tsubst (friend_type, args,
8020                                         tf_warning_or_error, NULL_TREE);
8021                   /* Bump processing_template_decl for correct
8022                      dependent_type_p calculation.  */
8023                   ++processing_template_decl;
8024                   if (dependent_type_p (friend_type))
8025                     adjust_processing_template_decl = true;
8026                   --processing_template_decl;
8027                 }
8028               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
8029                        && hidden_name_p (TYPE_NAME (friend_type)))
8030                 {
8031                   /* friend class C;
8032
8033                      where C hasn't been declared yet.  Let's lookup name
8034                      from namespace scope directly, bypassing any name that
8035                      come from dependent base class.  */
8036                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
8037
8038                   /* The call to xref_tag_from_type does injection for friend
8039                      classes.  */
8040                   push_nested_namespace (ns);
8041                   friend_type =
8042                     xref_tag_from_type (friend_type, NULL_TREE,
8043                                         /*tag_scope=*/ts_current);
8044                   pop_nested_namespace (ns);
8045                 }
8046               else if (uses_template_parms (friend_type))
8047                 /* friend class C<T>;  */
8048                 friend_type = tsubst (friend_type, args,
8049                                       tf_warning_or_error, NULL_TREE);
8050               /* Otherwise it's
8051
8052                    friend class C;
8053
8054                  where C is already declared or
8055
8056                    friend class C<int>;
8057
8058                  We don't have to do anything in these cases.  */
8059
8060               if (adjust_processing_template_decl)
8061                 /* Trick make_friend_class into realizing that the friend
8062                    we're adding is a template, not an ordinary class.  It's
8063                    important that we use make_friend_class since it will
8064                    perform some error-checking and output cross-reference
8065                    information.  */
8066                 ++processing_template_decl;
8067
8068               if (friend_type != error_mark_node)
8069                 make_friend_class (type, friend_type, /*complain=*/false);
8070
8071               if (adjust_processing_template_decl)
8072                 --processing_template_decl;
8073             }
8074           else
8075             {
8076               /* Build new DECL_FRIENDLIST.  */
8077               tree r;
8078
8079               /* The file and line for this declaration, to
8080                  assist in error message reporting.  Since we
8081                  called push_tinst_level above, we don't need to
8082                  restore these.  */
8083               input_location = DECL_SOURCE_LOCATION (t);
8084
8085               if (TREE_CODE (t) == TEMPLATE_DECL)
8086                 {
8087                   ++processing_template_decl;
8088                   push_deferring_access_checks (dk_no_check);
8089                 }
8090
8091               r = tsubst_friend_function (t, args);
8092               add_friend (type, r, /*complain=*/false);
8093               if (TREE_CODE (t) == TEMPLATE_DECL)
8094                 {
8095                   pop_deferring_access_checks ();
8096                   --processing_template_decl;
8097                 }
8098             }
8099         }
8100     }
8101
8102   /* Set the file and line number information to whatever is given for
8103      the class itself.  This puts error messages involving generated
8104      implicit functions at a predictable point, and the same point
8105      that would be used for non-template classes.  */
8106   input_location = DECL_SOURCE_LOCATION (typedecl);
8107
8108   unreverse_member_declarations (type);
8109   finish_struct_1 (type);
8110   TYPE_BEING_DEFINED (type) = 0;
8111
8112   /* Now that the class is complete, instantiate default arguments for
8113      any member functions.  We don't do this earlier because the
8114      default arguments may reference members of the class.  */
8115   if (!PRIMARY_TEMPLATE_P (templ))
8116     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
8117       if (TREE_CODE (t) == FUNCTION_DECL
8118           /* Implicitly generated member functions will not have template
8119              information; they are not instantiations, but instead are
8120              created "fresh" for each instantiation.  */
8121           && DECL_TEMPLATE_INFO (t))
8122         tsubst_default_arguments (t);
8123
8124   /* Some typedefs referenced from within the template code need to be access
8125      checked at template instantiation time, i.e now. These types were
8126      added to the template at parsing time. Let's get those and perform
8127      the access checks then.  */
8128   perform_typedefs_access_check (pattern, args);
8129   perform_deferred_access_checks ();
8130   pop_nested_class ();
8131   maximum_field_alignment = saved_maximum_field_alignment;
8132   pop_from_top_level ();
8133   pop_deferring_access_checks ();
8134   pop_tinst_level ();
8135
8136   /* The vtable for a template class can be emitted in any translation
8137      unit in which the class is instantiated.  When there is no key
8138      method, however, finish_struct_1 will already have added TYPE to
8139      the keyed_classes list.  */
8140   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
8141     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
8142
8143   return type;
8144 }
8145
8146 static tree
8147 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8148 {
8149   tree r;
8150
8151   if (!t)
8152     r = t;
8153   else if (TYPE_P (t))
8154     r = tsubst (t, args, complain, in_decl);
8155   else
8156     {
8157       r = tsubst_expr (t, args, complain, in_decl,
8158                        /*integral_constant_expression_p=*/true);
8159       r = fold_non_dependent_expr (r);
8160     }
8161   return r;
8162 }
8163
8164 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
8165    NONTYPE_ARGUMENT_PACK.  */
8166
8167 static tree
8168 make_fnparm_pack (tree spec_parm)
8169 {
8170   /* Collect all of the extra "packed" parameters into an
8171      argument pack.  */
8172   tree parmvec;
8173   tree parmtypevec;
8174   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
8175   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
8176   int i, len = list_length (spec_parm);
8177
8178   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
8179   parmvec = make_tree_vec (len);
8180   parmtypevec = make_tree_vec (len);
8181   for (i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
8182     {
8183       TREE_VEC_ELT (parmvec, i) = spec_parm;
8184       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
8185     }
8186
8187   /* Build the argument packs.  */
8188   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
8189   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
8190   TREE_TYPE (argpack) = argtypepack;
8191
8192   return argpack;
8193 }        
8194
8195 /* Substitute ARGS into T, which is an pack expansion
8196    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
8197    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
8198    (if only a partial substitution could be performed) or
8199    ERROR_MARK_NODE if there was an error.  */
8200 tree
8201 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
8202                        tree in_decl)
8203 {
8204   tree pattern;
8205   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
8206   int i, len = -1;
8207   tree result;
8208   int incomplete = 0;
8209   bool very_local_specializations = false;
8210
8211   gcc_assert (PACK_EXPANSION_P (t));
8212   pattern = PACK_EXPANSION_PATTERN (t);
8213
8214   /* Determine the argument packs that will instantiate the parameter
8215      packs used in the expansion expression. While we're at it,
8216      compute the number of arguments to be expanded and make sure it
8217      is consistent.  */
8218   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
8219        pack = TREE_CHAIN (pack))
8220     {
8221       tree parm_pack = TREE_VALUE (pack);
8222       tree arg_pack = NULL_TREE;
8223       tree orig_arg = NULL_TREE;
8224
8225       if (TREE_CODE (parm_pack) == PARM_DECL)
8226         {
8227           arg_pack = retrieve_local_specialization (parm_pack);
8228           if (arg_pack == NULL_TREE)
8229             {
8230               /* This can happen for a parameter name used later in a function
8231                  declaration (such as in a late-specified return type).  Just
8232                  make a dummy decl, since it's only used for its type.  */
8233               gcc_assert (cp_unevaluated_operand != 0);
8234               arg_pack = tsubst_decl (parm_pack, args, complain);
8235               arg_pack = make_fnparm_pack (arg_pack);
8236             }
8237         }
8238       else
8239         {
8240           int level, idx, levels;
8241           template_parm_level_and_index (parm_pack, &level, &idx);
8242
8243           levels = TMPL_ARGS_DEPTH (args);
8244           if (level <= levels)
8245             arg_pack = TMPL_ARG (args, level, idx);
8246         }
8247
8248       orig_arg = arg_pack;
8249       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
8250         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
8251       
8252       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
8253         /* This can only happen if we forget to expand an argument
8254            pack somewhere else. Just return an error, silently.  */
8255         {
8256           result = make_tree_vec (1);
8257           TREE_VEC_ELT (result, 0) = error_mark_node;
8258           return result;
8259         }
8260
8261       if (arg_pack
8262           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
8263           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
8264         {
8265           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
8266           tree pattern = PACK_EXPANSION_PATTERN (expansion);
8267           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
8268               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
8269             /* The argument pack that the parameter maps to is just an
8270                expansion of the parameter itself, such as one would
8271                find in the implicit typedef of a class inside the
8272                class itself.  Consider this parameter "unsubstituted",
8273                so that we will maintain the outer pack expansion.  */
8274             arg_pack = NULL_TREE;
8275         }
8276           
8277       if (arg_pack)
8278         {
8279           int my_len = 
8280             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
8281
8282           /* It's all-or-nothing with incomplete argument packs.  */
8283           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8284             return error_mark_node;
8285           
8286           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8287             incomplete = 1;
8288
8289           if (len < 0)
8290             len = my_len;
8291           else if (len != my_len)
8292             {
8293               if (incomplete)
8294                 /* We got explicit args for some packs but not others;
8295                    do nothing now and try again after deduction.  */
8296                 return t;
8297               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
8298                 error ("mismatched argument pack lengths while expanding "
8299                        "%<%T%>",
8300                        pattern);
8301               else
8302                 error ("mismatched argument pack lengths while expanding "
8303                        "%<%E%>",
8304                        pattern);
8305               return error_mark_node;
8306             }
8307
8308           /* Keep track of the parameter packs and their corresponding
8309              argument packs.  */
8310           packs = tree_cons (parm_pack, arg_pack, packs);
8311           TREE_TYPE (packs) = orig_arg;
8312         }
8313       else
8314         /* We can't substitute for this parameter pack.  */
8315         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
8316                                          TREE_VALUE (pack),
8317                                          unsubstituted_packs);
8318     }
8319
8320   /* We cannot expand this expansion expression, because we don't have
8321      all of the argument packs we need. Substitute into the pattern
8322      and return a PACK_EXPANSION_*. The caller will need to deal with
8323      that.  */
8324   if (unsubstituted_packs)
8325     {
8326       tree new_pat;
8327       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8328         new_pat = tsubst_expr (pattern, args, complain, in_decl,
8329                                /*integral_constant_expression_p=*/false);
8330       else
8331         new_pat = tsubst (pattern, args, complain, in_decl);
8332       return make_pack_expansion (new_pat);
8333     }
8334
8335   /* We could not find any argument packs that work.  */
8336   if (len < 0)
8337     return error_mark_node;
8338
8339   if (!local_specializations)
8340     {
8341       /* We're in a late-specified return type, so we don't have a local
8342          specializations table.  Create one for doing this expansion.  */
8343       very_local_specializations = true;
8344       local_specializations = htab_create (37,
8345                                            hash_local_specialization,
8346                                            eq_local_specializations,
8347                                            NULL);
8348     }
8349
8350   /* For each argument in each argument pack, substitute into the
8351      pattern.  */
8352   result = make_tree_vec (len + incomplete);
8353   for (i = 0; i < len + incomplete; ++i)
8354     {
8355       /* For parameter pack, change the substitution of the parameter
8356          pack to the ith argument in its argument pack, then expand
8357          the pattern.  */
8358       for (pack = packs; pack; pack = TREE_CHAIN (pack))
8359         {
8360           tree parm = TREE_PURPOSE (pack);
8361
8362           if (TREE_CODE (parm) == PARM_DECL)
8363             {
8364               /* Select the Ith argument from the pack.  */
8365               tree arg = make_node (ARGUMENT_PACK_SELECT);
8366               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
8367               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
8368               mark_used (parm);
8369               register_local_specialization (arg, parm);
8370             }
8371           else
8372             {
8373               tree value = parm;
8374               int idx, level;
8375               template_parm_level_and_index (parm, &level, &idx);
8376               
8377               if (i < len) 
8378                 {
8379                   /* Select the Ith argument from the pack. */
8380                   value = make_node (ARGUMENT_PACK_SELECT);
8381                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
8382                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
8383                 }
8384
8385               /* Update the corresponding argument.  */
8386               TMPL_ARG (args, level, idx) = value;
8387             }
8388         }
8389
8390       /* Substitute into the PATTERN with the altered arguments.  */
8391       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8392         TREE_VEC_ELT (result, i) = 
8393           tsubst_expr (pattern, args, complain, in_decl,
8394                        /*integral_constant_expression_p=*/false);
8395       else
8396         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
8397
8398       if (i == len)
8399         /* When we have incomplete argument packs, the last "expanded"
8400            result is itself a pack expansion, which allows us
8401            to deduce more arguments.  */
8402         TREE_VEC_ELT (result, i) = 
8403           make_pack_expansion (TREE_VEC_ELT (result, i));
8404
8405       if (TREE_VEC_ELT (result, i) == error_mark_node)
8406         {
8407           result = error_mark_node;
8408           break;
8409         }
8410     }
8411
8412   /* Update ARGS to restore the substitution from parameter packs to
8413      their argument packs.  */
8414   for (pack = packs; pack; pack = TREE_CHAIN (pack))
8415     {
8416       tree parm = TREE_PURPOSE (pack);
8417
8418       if (TREE_CODE (parm) == PARM_DECL)
8419         register_local_specialization (TREE_TYPE (pack), parm);
8420       else
8421         {
8422           int idx, level;
8423           template_parm_level_and_index (parm, &level, &idx);
8424           
8425           /* Update the corresponding argument.  */
8426           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
8427             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
8428               TREE_TYPE (pack);
8429           else
8430             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
8431         }
8432     }
8433
8434   if (very_local_specializations)
8435     {
8436       htab_delete (local_specializations);
8437       local_specializations = NULL;
8438     }
8439   
8440   return result;
8441 }
8442
8443 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
8444    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
8445    parameter packs; all parms generated from a function parameter pack will
8446    have the same DECL_PARM_INDEX.  */
8447
8448 tree
8449 get_pattern_parm (tree parm, tree tmpl)
8450 {
8451   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
8452   tree patparm;
8453
8454   if (DECL_ARTIFICIAL (parm))
8455     {
8456       for (patparm = DECL_ARGUMENTS (pattern);
8457            patparm; patparm = TREE_CHAIN (patparm))
8458         if (DECL_ARTIFICIAL (patparm)
8459             && DECL_NAME (parm) == DECL_NAME (patparm))
8460           break;
8461     }
8462   else
8463     {
8464       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
8465       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
8466       gcc_assert (DECL_PARM_INDEX (patparm)
8467                   == DECL_PARM_INDEX (parm));
8468     }
8469
8470   return patparm;
8471 }
8472
8473 /* Substitute ARGS into the vector or list of template arguments T.  */
8474
8475 static tree
8476 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8477 {
8478   tree orig_t = t;
8479   int len = TREE_VEC_LENGTH (t);
8480   int need_new = 0, i, expanded_len_adjust = 0, out;
8481   tree *elts = (tree *) alloca (len * sizeof (tree));
8482
8483   for (i = 0; i < len; i++)
8484     {
8485       tree orig_arg = TREE_VEC_ELT (t, i);
8486       tree new_arg;
8487
8488       if (TREE_CODE (orig_arg) == TREE_VEC)
8489         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
8490       else if (PACK_EXPANSION_P (orig_arg))
8491         {
8492           /* Substitute into an expansion expression.  */
8493           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
8494
8495           if (TREE_CODE (new_arg) == TREE_VEC)
8496             /* Add to the expanded length adjustment the number of
8497                expanded arguments. We subtract one from this
8498                measurement, because the argument pack expression
8499                itself is already counted as 1 in
8500                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
8501                the argument pack is empty.  */
8502             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
8503         }
8504       else if (ARGUMENT_PACK_P (orig_arg))
8505         {
8506           /* Substitute into each of the arguments.  */
8507           new_arg = TYPE_P (orig_arg)
8508             ? cxx_make_type (TREE_CODE (orig_arg))
8509             : make_node (TREE_CODE (orig_arg));
8510           
8511           SET_ARGUMENT_PACK_ARGS (
8512             new_arg,
8513             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
8514                                   args, complain, in_decl));
8515
8516           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
8517             new_arg = error_mark_node;
8518
8519           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
8520             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
8521                                           complain, in_decl);
8522             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
8523
8524             if (TREE_TYPE (new_arg) == error_mark_node)
8525               new_arg = error_mark_node;
8526           }
8527         }
8528       else
8529         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
8530
8531       if (new_arg == error_mark_node)
8532         return error_mark_node;
8533
8534       elts[i] = new_arg;
8535       if (new_arg != orig_arg)
8536         need_new = 1;
8537     }
8538
8539   if (!need_new)
8540     return t;
8541
8542   /* Make space for the expanded arguments coming from template
8543      argument packs.  */
8544   t = make_tree_vec (len + expanded_len_adjust);
8545   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
8546      arguments for a member template.
8547      In that case each TREE_VEC in ORIG_T represents a level of template
8548      arguments, and ORIG_T won't carry any non defaulted argument count.
8549      It will rather be the nested TREE_VECs that will carry one.
8550      In other words, ORIG_T carries a non defaulted argument count only
8551      if it doesn't contain any nested TREE_VEC.  */
8552   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
8553     {
8554       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
8555       count += expanded_len_adjust;
8556       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
8557     }
8558   for (i = 0, out = 0; i < len; i++)
8559     {
8560       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
8561            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
8562           && TREE_CODE (elts[i]) == TREE_VEC)
8563         {
8564           int idx;
8565
8566           /* Now expand the template argument pack "in place".  */
8567           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
8568             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
8569         }
8570       else
8571         {
8572           TREE_VEC_ELT (t, out) = elts[i];
8573           out++;
8574         }
8575     }
8576
8577   return t;
8578 }
8579
8580 /* Return the result of substituting ARGS into the template parameters
8581    given by PARMS.  If there are m levels of ARGS and m + n levels of
8582    PARMS, then the result will contain n levels of PARMS.  For
8583    example, if PARMS is `template <class T> template <class U>
8584    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
8585    result will be `template <int*, double, class V>'.  */
8586
8587 static tree
8588 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
8589 {
8590   tree r = NULL_TREE;
8591   tree* new_parms;
8592
8593   /* When substituting into a template, we must set
8594      PROCESSING_TEMPLATE_DECL as the template parameters may be
8595      dependent if they are based on one-another, and the dependency
8596      predicates are short-circuit outside of templates.  */
8597   ++processing_template_decl;
8598
8599   for (new_parms = &r;
8600        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
8601        new_parms = &(TREE_CHAIN (*new_parms)),
8602          parms = TREE_CHAIN (parms))
8603     {
8604       tree new_vec =
8605         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
8606       int i;
8607
8608       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
8609         {
8610           tree tuple;
8611           tree default_value;
8612           tree parm_decl;
8613
8614           if (parms == error_mark_node)
8615             continue;
8616
8617           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
8618
8619           if (tuple == error_mark_node)
8620             continue;
8621
8622           default_value = TREE_PURPOSE (tuple);
8623           parm_decl = TREE_VALUE (tuple);
8624
8625           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
8626           if (TREE_CODE (parm_decl) == PARM_DECL
8627               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
8628             parm_decl = error_mark_node;
8629           default_value = tsubst_template_arg (default_value, args,
8630                                                complain, NULL_TREE);
8631
8632           tuple = build_tree_list (default_value, parm_decl);
8633           TREE_VEC_ELT (new_vec, i) = tuple;
8634         }
8635
8636       *new_parms =
8637         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
8638                              - TMPL_ARGS_DEPTH (args)),
8639                    new_vec, NULL_TREE);
8640     }
8641
8642   --processing_template_decl;
8643
8644   return r;
8645 }
8646
8647 /* Substitute the ARGS into the indicated aggregate (or enumeration)
8648    type T.  If T is not an aggregate or enumeration type, it is
8649    handled as if by tsubst.  IN_DECL is as for tsubst.  If
8650    ENTERING_SCOPE is nonzero, T is the context for a template which
8651    we are presently tsubst'ing.  Return the substituted value.  */
8652
8653 static tree
8654 tsubst_aggr_type (tree t,
8655                   tree args,
8656                   tsubst_flags_t complain,
8657                   tree in_decl,
8658                   int entering_scope)
8659 {
8660   if (t == NULL_TREE)
8661     return NULL_TREE;
8662
8663   switch (TREE_CODE (t))
8664     {
8665     case RECORD_TYPE:
8666       if (TYPE_PTRMEMFUNC_P (t))
8667         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
8668
8669       /* Else fall through.  */
8670     case ENUMERAL_TYPE:
8671     case UNION_TYPE:
8672       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
8673         {
8674           tree argvec;
8675           tree context;
8676           tree r;
8677           int saved_unevaluated_operand;
8678           int saved_inhibit_evaluation_warnings;
8679
8680           /* In "sizeof(X<I>)" we need to evaluate "I".  */
8681           saved_unevaluated_operand = cp_unevaluated_operand;
8682           cp_unevaluated_operand = 0;
8683           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
8684           c_inhibit_evaluation_warnings = 0;
8685
8686           /* First, determine the context for the type we are looking
8687              up.  */
8688           context = TYPE_CONTEXT (t);
8689           if (context)
8690             {
8691               context = tsubst_aggr_type (context, args, complain,
8692                                           in_decl, /*entering_scope=*/1);
8693               /* If context is a nested class inside a class template,
8694                  it may still need to be instantiated (c++/33959).  */
8695               if (TYPE_P (context))
8696                 context = complete_type (context);
8697             }
8698
8699           /* Then, figure out what arguments are appropriate for the
8700              type we are trying to find.  For example, given:
8701
8702                template <class T> struct S;
8703                template <class T, class U> void f(T, U) { S<U> su; }
8704
8705              and supposing that we are instantiating f<int, double>,
8706              then our ARGS will be {int, double}, but, when looking up
8707              S we only want {double}.  */
8708           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
8709                                          complain, in_decl);
8710           if (argvec == error_mark_node)
8711             r = error_mark_node;
8712           else
8713             {
8714               r = lookup_template_class (t, argvec, in_decl, context,
8715                                          entering_scope, complain);
8716               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
8717             }
8718
8719           cp_unevaluated_operand = saved_unevaluated_operand;
8720           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
8721
8722           return r;
8723         }
8724       else
8725         /* This is not a template type, so there's nothing to do.  */
8726         return t;
8727
8728     default:
8729       return tsubst (t, args, complain, in_decl);
8730     }
8731 }
8732
8733 /* Substitute into the default argument ARG (a default argument for
8734    FN), which has the indicated TYPE.  */
8735
8736 tree
8737 tsubst_default_argument (tree fn, tree type, tree arg)
8738 {
8739   tree saved_class_ptr = NULL_TREE;
8740   tree saved_class_ref = NULL_TREE;
8741
8742   /* This default argument came from a template.  Instantiate the
8743      default argument here, not in tsubst.  In the case of
8744      something like:
8745
8746        template <class T>
8747        struct S {
8748          static T t();
8749          void f(T = t());
8750        };
8751
8752      we must be careful to do name lookup in the scope of S<T>,
8753      rather than in the current class.  */
8754   push_access_scope (fn);
8755   /* The "this" pointer is not valid in a default argument.  */
8756   if (cfun)
8757     {
8758       saved_class_ptr = current_class_ptr;
8759       cp_function_chain->x_current_class_ptr = NULL_TREE;
8760       saved_class_ref = current_class_ref;
8761       cp_function_chain->x_current_class_ref = NULL_TREE;
8762     }
8763
8764   push_deferring_access_checks(dk_no_deferred);
8765   /* The default argument expression may cause implicitly defined
8766      member functions to be synthesized, which will result in garbage
8767      collection.  We must treat this situation as if we were within
8768      the body of function so as to avoid collecting live data on the
8769      stack.  */
8770   ++function_depth;
8771   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
8772                      tf_warning_or_error, NULL_TREE,
8773                      /*integral_constant_expression_p=*/false);
8774   --function_depth;
8775   pop_deferring_access_checks();
8776
8777   /* Restore the "this" pointer.  */
8778   if (cfun)
8779     {
8780       cp_function_chain->x_current_class_ptr = saved_class_ptr;
8781       cp_function_chain->x_current_class_ref = saved_class_ref;
8782     }
8783
8784   /* Make sure the default argument is reasonable.  */
8785   arg = check_default_argument (type, arg);
8786
8787   pop_access_scope (fn);
8788
8789   return arg;
8790 }
8791
8792 /* Substitute into all the default arguments for FN.  */
8793
8794 static void
8795 tsubst_default_arguments (tree fn)
8796 {
8797   tree arg;
8798   tree tmpl_args;
8799
8800   tmpl_args = DECL_TI_ARGS (fn);
8801
8802   /* If this function is not yet instantiated, we certainly don't need
8803      its default arguments.  */
8804   if (uses_template_parms (tmpl_args))
8805     return;
8806
8807   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
8808        arg;
8809        arg = TREE_CHAIN (arg))
8810     if (TREE_PURPOSE (arg))
8811       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
8812                                                     TREE_VALUE (arg),
8813                                                     TREE_PURPOSE (arg));
8814 }
8815
8816 /* Substitute the ARGS into the T, which is a _DECL.  Return the
8817    result of the substitution.  Issue error and warning messages under
8818    control of COMPLAIN.  */
8819
8820 static tree
8821 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
8822 {
8823 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
8824   location_t saved_loc;
8825   tree r = NULL_TREE;
8826   tree in_decl = t;
8827   hashval_t hash = 0;
8828
8829   /* Set the filename and linenumber to improve error-reporting.  */
8830   saved_loc = input_location;
8831   input_location = DECL_SOURCE_LOCATION (t);
8832
8833   switch (TREE_CODE (t))
8834     {
8835     case TEMPLATE_DECL:
8836       {
8837         /* We can get here when processing a member function template,
8838            member class template, or template template parameter.  */
8839         tree decl = DECL_TEMPLATE_RESULT (t);
8840         tree spec;
8841         tree tmpl_args;
8842         tree full_args;
8843
8844         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8845           {
8846             /* Template template parameter is treated here.  */
8847             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8848             if (new_type == error_mark_node)
8849               RETURN (error_mark_node);
8850
8851             r = copy_decl (t);
8852             TREE_CHAIN (r) = NULL_TREE;
8853             TREE_TYPE (r) = new_type;
8854             DECL_TEMPLATE_RESULT (r)
8855               = build_decl (DECL_SOURCE_LOCATION (decl),
8856                             TYPE_DECL, DECL_NAME (decl), new_type);
8857             DECL_TEMPLATE_PARMS (r)
8858               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8859                                        complain);
8860             TYPE_NAME (new_type) = r;
8861             break;
8862           }
8863
8864         /* We might already have an instance of this template.
8865            The ARGS are for the surrounding class type, so the
8866            full args contain the tsubst'd args for the context,
8867            plus the innermost args from the template decl.  */
8868         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8869           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8870           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8871         /* Because this is a template, the arguments will still be
8872            dependent, even after substitution.  If
8873            PROCESSING_TEMPLATE_DECL is not set, the dependency
8874            predicates will short-circuit.  */
8875         ++processing_template_decl;
8876         full_args = tsubst_template_args (tmpl_args, args,
8877                                           complain, in_decl);
8878         --processing_template_decl;
8879         if (full_args == error_mark_node)
8880           RETURN (error_mark_node);
8881
8882         /* If this is a default template template argument,
8883            tsubst might not have changed anything.  */
8884         if (full_args == tmpl_args)
8885           RETURN (t);
8886
8887         hash = hash_tmpl_and_args (t, full_args);
8888         spec = retrieve_specialization (t, full_args, hash);
8889         if (spec != NULL_TREE)
8890           {
8891             r = spec;
8892             break;
8893           }
8894
8895         /* Make a new template decl.  It will be similar to the
8896            original, but will record the current template arguments.
8897            We also create a new function declaration, which is just
8898            like the old one, but points to this new template, rather
8899            than the old one.  */
8900         r = copy_decl (t);
8901         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
8902         TREE_CHAIN (r) = NULL_TREE;
8903
8904         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
8905
8906         if (TREE_CODE (decl) == TYPE_DECL)
8907           {
8908             tree new_type;
8909             ++processing_template_decl;
8910             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8911             --processing_template_decl;
8912             if (new_type == error_mark_node)
8913               RETURN (error_mark_node);
8914
8915             TREE_TYPE (r) = new_type;
8916             CLASSTYPE_TI_TEMPLATE (new_type) = r;
8917             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
8918             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
8919             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
8920           }
8921         else
8922           {
8923             tree new_decl;
8924             ++processing_template_decl;
8925             new_decl = tsubst (decl, args, complain, in_decl);
8926             --processing_template_decl;
8927             if (new_decl == error_mark_node)
8928               RETURN (error_mark_node);
8929
8930             DECL_TEMPLATE_RESULT (r) = new_decl;
8931             DECL_TI_TEMPLATE (new_decl) = r;
8932             TREE_TYPE (r) = TREE_TYPE (new_decl);
8933             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
8934             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
8935           }
8936
8937         SET_DECL_IMPLICIT_INSTANTIATION (r);
8938         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
8939         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
8940
8941         /* The template parameters for this new template are all the
8942            template parameters for the old template, except the
8943            outermost level of parameters.  */
8944         DECL_TEMPLATE_PARMS (r)
8945           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8946                                    complain);
8947
8948         if (PRIMARY_TEMPLATE_P (t))
8949           DECL_PRIMARY_TEMPLATE (r) = r;
8950
8951         if (TREE_CODE (decl) != TYPE_DECL)
8952           /* Record this non-type partial instantiation.  */
8953           register_specialization (r, t,
8954                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
8955                                    false, hash);
8956       }
8957       break;
8958
8959     case FUNCTION_DECL:
8960       {
8961         tree ctx;
8962         tree argvec = NULL_TREE;
8963         tree *friends;
8964         tree gen_tmpl;
8965         tree type;
8966         int member;
8967         int args_depth;
8968         int parms_depth;
8969
8970         /* Nobody should be tsubst'ing into non-template functions.  */
8971         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
8972
8973         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
8974           {
8975             tree spec;
8976             bool dependent_p;
8977
8978             /* If T is not dependent, just return it.  We have to
8979                increment PROCESSING_TEMPLATE_DECL because
8980                value_dependent_expression_p assumes that nothing is
8981                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
8982             ++processing_template_decl;
8983             dependent_p = value_dependent_expression_p (t);
8984             --processing_template_decl;
8985             if (!dependent_p)
8986               RETURN (t);
8987
8988             /* Calculate the most general template of which R is a
8989                specialization, and the complete set of arguments used to
8990                specialize R.  */
8991             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
8992             argvec = tsubst_template_args (DECL_TI_ARGS
8993                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
8994                                            args, complain, in_decl);
8995
8996             /* Check to see if we already have this specialization.  */
8997             hash = hash_tmpl_and_args (gen_tmpl, argvec);
8998             spec = retrieve_specialization (gen_tmpl, argvec, hash);
8999
9000             if (spec)
9001               {
9002                 r = spec;
9003                 break;
9004               }
9005
9006             /* We can see more levels of arguments than parameters if
9007                there was a specialization of a member template, like
9008                this:
9009
9010                  template <class T> struct S { template <class U> void f(); }
9011                  template <> template <class U> void S<int>::f(U);
9012
9013                Here, we'll be substituting into the specialization,
9014                because that's where we can find the code we actually
9015                want to generate, but we'll have enough arguments for
9016                the most general template.
9017
9018                We also deal with the peculiar case:
9019
9020                  template <class T> struct S {
9021                    template <class U> friend void f();
9022                  };
9023                  template <class U> void f() {}
9024                  template S<int>;
9025                  template void f<double>();
9026
9027                Here, the ARGS for the instantiation of will be {int,
9028                double}.  But, we only need as many ARGS as there are
9029                levels of template parameters in CODE_PATTERN.  We are
9030                careful not to get fooled into reducing the ARGS in
9031                situations like:
9032
9033                  template <class T> struct S { template <class U> void f(U); }
9034                  template <class T> template <> void S<T>::f(int) {}
9035
9036                which we can spot because the pattern will be a
9037                specialization in this case.  */
9038             args_depth = TMPL_ARGS_DEPTH (args);
9039             parms_depth =
9040               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
9041             if (args_depth > parms_depth
9042                 && !DECL_TEMPLATE_SPECIALIZATION (t))
9043               args = get_innermost_template_args (args, parms_depth);
9044           }
9045         else
9046           {
9047             /* This special case arises when we have something like this:
9048
9049                  template <class T> struct S {
9050                    friend void f<int>(int, double);
9051                  };
9052
9053                Here, the DECL_TI_TEMPLATE for the friend declaration
9054                will be an IDENTIFIER_NODE.  We are being called from
9055                tsubst_friend_function, and we want only to create a
9056                new decl (R) with appropriate types so that we can call
9057                determine_specialization.  */
9058             gen_tmpl = NULL_TREE;
9059           }
9060
9061         if (DECL_CLASS_SCOPE_P (t))
9062           {
9063             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
9064               member = 2;
9065             else
9066               member = 1;
9067             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
9068                                     complain, t, /*entering_scope=*/1);
9069           }
9070         else
9071           {
9072             member = 0;
9073             ctx = DECL_CONTEXT (t);
9074           }
9075         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9076         if (type == error_mark_node)
9077           RETURN (error_mark_node);
9078
9079         /* We do NOT check for matching decls pushed separately at this
9080            point, as they may not represent instantiations of this
9081            template, and in any case are considered separate under the
9082            discrete model.  */
9083         r = copy_decl (t);
9084         DECL_USE_TEMPLATE (r) = 0;
9085         TREE_TYPE (r) = type;
9086         /* Clear out the mangled name and RTL for the instantiation.  */
9087         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9088         SET_DECL_RTL (r, NULL_RTX);
9089         /* Leave DECL_INITIAL set on deleted instantiations.  */
9090         if (!DECL_DELETED_FN (r))
9091           DECL_INITIAL (r) = NULL_TREE;
9092         DECL_CONTEXT (r) = ctx;
9093
9094         if (member && DECL_CONV_FN_P (r))
9095           /* Type-conversion operator.  Reconstruct the name, in
9096              case it's the name of one of the template's parameters.  */
9097           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
9098
9099         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
9100                                      complain, t);
9101         DECL_RESULT (r) = NULL_TREE;
9102
9103         TREE_STATIC (r) = 0;
9104         TREE_PUBLIC (r) = TREE_PUBLIC (t);
9105         DECL_EXTERNAL (r) = 1;
9106         /* If this is an instantiation of a function with internal
9107            linkage, we already know what object file linkage will be
9108            assigned to the instantiation.  */
9109         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
9110         DECL_DEFER_OUTPUT (r) = 0;
9111         TREE_CHAIN (r) = NULL_TREE;
9112         DECL_PENDING_INLINE_INFO (r) = 0;
9113         DECL_PENDING_INLINE_P (r) = 0;
9114         DECL_SAVED_TREE (r) = NULL_TREE;
9115         DECL_STRUCT_FUNCTION (r) = NULL;
9116         TREE_USED (r) = 0;
9117         /* We'll re-clone as appropriate in instantiate_template.  */
9118         DECL_CLONED_FUNCTION (r) = NULL_TREE;
9119
9120         /* If we aren't complaining now, return on error before we register
9121            the specialization so that we'll complain eventually.  */
9122         if ((complain & tf_error) == 0
9123             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9124             && !grok_op_properties (r, /*complain=*/false))
9125           RETURN (error_mark_node);
9126
9127         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
9128            this in the special friend case mentioned above where
9129            GEN_TMPL is NULL.  */
9130         if (gen_tmpl)
9131           {
9132             DECL_TEMPLATE_INFO (r)
9133               = build_template_info (gen_tmpl, argvec);
9134             SET_DECL_IMPLICIT_INSTANTIATION (r);
9135             register_specialization (r, gen_tmpl, argvec, false, hash);
9136
9137             /* We're not supposed to instantiate default arguments
9138                until they are called, for a template.  But, for a
9139                declaration like:
9140
9141                  template <class T> void f ()
9142                  { extern void g(int i = T()); }
9143
9144                we should do the substitution when the template is
9145                instantiated.  We handle the member function case in
9146                instantiate_class_template since the default arguments
9147                might refer to other members of the class.  */
9148             if (!member
9149                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
9150                 && !uses_template_parms (argvec))
9151               tsubst_default_arguments (r);
9152           }
9153         else
9154           DECL_TEMPLATE_INFO (r) = NULL_TREE;
9155
9156         /* Copy the list of befriending classes.  */
9157         for (friends = &DECL_BEFRIENDING_CLASSES (r);
9158              *friends;
9159              friends = &TREE_CHAIN (*friends))
9160           {
9161             *friends = copy_node (*friends);
9162             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
9163                                             args, complain,
9164                                             in_decl);
9165           }
9166
9167         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
9168           {
9169             maybe_retrofit_in_chrg (r);
9170             if (DECL_CONSTRUCTOR_P (r))
9171               grok_ctor_properties (ctx, r);
9172             /* If this is an instantiation of a member template, clone it.
9173                If it isn't, that'll be handled by
9174                clone_constructors_and_destructors.  */
9175             if (PRIMARY_TEMPLATE_P (gen_tmpl))
9176               clone_function_decl (r, /*update_method_vec_p=*/0);
9177           }
9178         else if ((complain & tf_error) != 0
9179                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9180                  && !grok_op_properties (r, /*complain=*/true))
9181           RETURN (error_mark_node);
9182
9183         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
9184           SET_DECL_FRIEND_CONTEXT (r,
9185                                    tsubst (DECL_FRIEND_CONTEXT (t),
9186                                             args, complain, in_decl));
9187
9188         /* Possibly limit visibility based on template args.  */
9189         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9190         if (DECL_VISIBILITY_SPECIFIED (t))
9191           {
9192             DECL_VISIBILITY_SPECIFIED (r) = 0;
9193             DECL_ATTRIBUTES (r)
9194               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9195           }
9196         determine_visibility (r);
9197         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
9198             && !processing_template_decl)
9199           defaulted_late_check (r);
9200
9201         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9202                                         args, complain, in_decl);
9203       }
9204       break;
9205
9206     case PARM_DECL:
9207       {
9208         tree type = NULL_TREE;
9209         int i, len = 1;
9210         tree expanded_types = NULL_TREE;
9211         tree prev_r = NULL_TREE;
9212         tree first_r = NULL_TREE;
9213
9214         if (FUNCTION_PARAMETER_PACK_P (t))
9215           {
9216             /* If there is a local specialization that isn't a
9217                parameter pack, it means that we're doing a "simple"
9218                substitution from inside tsubst_pack_expansion. Just
9219                return the local specialization (which will be a single
9220                parm).  */
9221             tree spec = retrieve_local_specialization (t);
9222             if (spec 
9223                 && TREE_CODE (spec) == PARM_DECL
9224                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
9225               RETURN (spec);
9226
9227             /* Expand the TYPE_PACK_EXPANSION that provides the types for
9228                the parameters in this function parameter pack.  */
9229             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
9230                                                     complain, in_decl);
9231             if (TREE_CODE (expanded_types) == TREE_VEC)
9232               {
9233                 len = TREE_VEC_LENGTH (expanded_types);
9234
9235                 /* Zero-length parameter packs are boring. Just substitute
9236                    into the chain.  */
9237                 if (len == 0)
9238                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
9239                                   TREE_CHAIN (t)));
9240               }
9241             else
9242               {
9243                 /* All we did was update the type. Make a note of that.  */
9244                 type = expanded_types;
9245                 expanded_types = NULL_TREE;
9246               }
9247           }
9248
9249         /* Loop through all of the parameter's we'll build. When T is
9250            a function parameter pack, LEN is the number of expanded
9251            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
9252         r = NULL_TREE;
9253         for (i = 0; i < len; ++i)
9254           {
9255             prev_r = r;
9256             r = copy_node (t);
9257             if (DECL_TEMPLATE_PARM_P (t))
9258               SET_DECL_TEMPLATE_PARM_P (r);
9259
9260             /* An argument of a function parameter pack is not a parameter
9261                pack.  */
9262             FUNCTION_PARAMETER_PACK_P (r) = false;
9263
9264             if (expanded_types)
9265               /* We're on the Ith parameter of the function parameter
9266                  pack.  */
9267               {
9268                 /* Get the Ith type.  */
9269                 type = TREE_VEC_ELT (expanded_types, i);
9270
9271                 if (DECL_NAME (r))
9272                   /* Rename the parameter to include the index.  */
9273                   DECL_NAME (r) =
9274                     make_ith_pack_parameter_name (DECL_NAME (r), i);
9275               }
9276             else if (!type)
9277               /* We're dealing with a normal parameter.  */
9278               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9279
9280             type = type_decays_to (type);
9281             TREE_TYPE (r) = type;
9282             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9283
9284             if (DECL_INITIAL (r))
9285               {
9286                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
9287                   DECL_INITIAL (r) = TREE_TYPE (r);
9288                 else
9289                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
9290                                              complain, in_decl);
9291               }
9292
9293             DECL_CONTEXT (r) = NULL_TREE;
9294
9295             if (!DECL_TEMPLATE_PARM_P (r))
9296               DECL_ARG_TYPE (r) = type_passed_as (type);
9297
9298             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9299                                             args, complain, in_decl);
9300
9301             /* Keep track of the first new parameter we
9302                generate. That's what will be returned to the
9303                caller.  */
9304             if (!first_r)
9305               first_r = r;
9306
9307             /* Build a proper chain of parameters when substituting
9308                into a function parameter pack.  */
9309             if (prev_r)
9310               TREE_CHAIN (prev_r) = r;
9311           }
9312
9313         if (TREE_CHAIN (t))
9314           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
9315                                    complain, TREE_CHAIN (t));
9316
9317         /* FIRST_R contains the start of the chain we've built.  */
9318         r = first_r;
9319       }
9320       break;
9321
9322     case FIELD_DECL:
9323       {
9324         tree type;
9325
9326         r = copy_decl (t);
9327         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9328         if (type == error_mark_node)
9329           RETURN (error_mark_node);
9330         TREE_TYPE (r) = type;
9331         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9332
9333         /* DECL_INITIAL gives the number of bits in a bit-field.  */
9334         DECL_INITIAL (r)
9335           = tsubst_expr (DECL_INITIAL (t), args,
9336                          complain, in_decl,
9337                          /*integral_constant_expression_p=*/true);
9338         /* We don't have to set DECL_CONTEXT here; it is set by
9339            finish_member_declaration.  */
9340         TREE_CHAIN (r) = NULL_TREE;
9341         if (VOID_TYPE_P (type))
9342           error ("instantiation of %q+D as type %qT", r, type);
9343
9344         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9345                                         args, complain, in_decl);
9346       }
9347       break;
9348
9349     case USING_DECL:
9350       /* We reach here only for member using decls.  */
9351       if (DECL_DEPENDENT_P (t))
9352         {
9353           r = do_class_using_decl
9354             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
9355              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
9356           if (!r)
9357             r = error_mark_node;
9358           else
9359             {
9360               TREE_PROTECTED (r) = TREE_PROTECTED (t);
9361               TREE_PRIVATE (r) = TREE_PRIVATE (t);
9362             }
9363         }
9364       else
9365         {
9366           r = copy_node (t);
9367           TREE_CHAIN (r) = NULL_TREE;
9368         }
9369       break;
9370
9371     case TYPE_DECL:
9372     case VAR_DECL:
9373       {
9374         tree argvec = NULL_TREE;
9375         tree gen_tmpl = NULL_TREE;
9376         tree spec;
9377         tree tmpl = NULL_TREE;
9378         tree ctx;
9379         tree type = NULL_TREE;
9380         bool local_p;
9381
9382         if (TREE_CODE (t) == TYPE_DECL
9383             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
9384           {
9385             /* If this is the canonical decl, we don't have to
9386                mess with instantiations, and often we can't (for
9387                typename, template type parms and such).  Note that
9388                TYPE_NAME is not correct for the above test if
9389                we've copied the type for a typedef.  */
9390             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9391             if (type == error_mark_node)
9392               RETURN (error_mark_node);
9393             r = TYPE_NAME (type);
9394             break;
9395           }
9396
9397         /* Check to see if we already have the specialization we
9398            need.  */
9399         spec = NULL_TREE;
9400         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
9401           {
9402             /* T is a static data member or namespace-scope entity.
9403                We have to substitute into namespace-scope variables
9404                (even though such entities are never templates) because
9405                of cases like:
9406                
9407                  template <class T> void f() { extern T t; }
9408
9409                where the entity referenced is not known until
9410                instantiation time.  */
9411             local_p = false;
9412             ctx = DECL_CONTEXT (t);
9413             if (DECL_CLASS_SCOPE_P (t))
9414               {
9415                 ctx = tsubst_aggr_type (ctx, args,
9416                                         complain,
9417                                         in_decl, /*entering_scope=*/1);
9418                 /* If CTX is unchanged, then T is in fact the
9419                    specialization we want.  That situation occurs when
9420                    referencing a static data member within in its own
9421                    class.  We can use pointer equality, rather than
9422                    same_type_p, because DECL_CONTEXT is always
9423                    canonical.  */
9424                 if (ctx == DECL_CONTEXT (t))
9425                   spec = t;
9426               }
9427
9428             if (!spec)
9429               {
9430                 tmpl = DECL_TI_TEMPLATE (t);
9431                 gen_tmpl = most_general_template (tmpl);
9432                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
9433                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
9434                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
9435               }
9436           }
9437         else
9438           {
9439             /* A local variable.  */
9440             local_p = true;
9441             /* Subsequent calls to pushdecl will fill this in.  */
9442             ctx = NULL_TREE;
9443             spec = retrieve_local_specialization (t);
9444           }
9445         /* If we already have the specialization we need, there is
9446            nothing more to do.  */ 
9447         if (spec)
9448           {
9449             r = spec;
9450             break;
9451           }
9452
9453         /* Create a new node for the specialization we need.  */
9454         r = copy_decl (t);
9455         if (type == NULL_TREE)
9456           {
9457             if (is_typedef_decl (t))
9458               type = DECL_ORIGINAL_TYPE (t);
9459             else
9460               type = TREE_TYPE (t);
9461             type = tsubst (type, args, complain, in_decl);
9462           }
9463         if (TREE_CODE (r) == VAR_DECL)
9464           {
9465             /* Even if the original location is out of scope, the
9466                newly substituted one is not.  */
9467             DECL_DEAD_FOR_LOCAL (r) = 0;
9468             DECL_INITIALIZED_P (r) = 0;
9469             DECL_TEMPLATE_INSTANTIATED (r) = 0;
9470             if (type == error_mark_node)
9471               RETURN (error_mark_node);
9472             if (TREE_CODE (type) == FUNCTION_TYPE)
9473               {
9474                 /* It may seem that this case cannot occur, since:
9475
9476                      typedef void f();
9477                      void g() { f x; }
9478
9479                    declares a function, not a variable.  However:
9480       
9481                      typedef void f();
9482                      template <typename T> void g() { T t; }
9483                      template void g<f>();
9484
9485                    is an attempt to declare a variable with function
9486                    type.  */
9487                 error ("variable %qD has function type",
9488                        /* R is not yet sufficiently initialized, so we
9489                           just use its name.  */
9490                        DECL_NAME (r));
9491                 RETURN (error_mark_node);
9492               }
9493             type = complete_type (type);
9494             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
9495               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
9496             type = check_var_type (DECL_NAME (r), type);
9497
9498             if (DECL_HAS_VALUE_EXPR_P (t))
9499               {
9500                 tree ve = DECL_VALUE_EXPR (t);
9501                 ve = tsubst_expr (ve, args, complain, in_decl,
9502                                   /*constant_expression_p=*/false);
9503                 SET_DECL_VALUE_EXPR (r, ve);
9504               }
9505           }
9506         else if (DECL_SELF_REFERENCE_P (t))
9507           SET_DECL_SELF_REFERENCE_P (r);
9508         TREE_TYPE (r) = type;
9509         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9510         DECL_CONTEXT (r) = ctx;
9511         /* Clear out the mangled name and RTL for the instantiation.  */
9512         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9513         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9514           SET_DECL_RTL (r, NULL_RTX);
9515         /* The initializer must not be expanded until it is required;
9516            see [temp.inst].  */
9517         DECL_INITIAL (r) = NULL_TREE;
9518         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9519           SET_DECL_RTL (r, NULL_RTX);
9520         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
9521         if (TREE_CODE (r) == VAR_DECL)
9522           {
9523             /* Possibly limit visibility based on template args.  */
9524             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9525             if (DECL_VISIBILITY_SPECIFIED (t))
9526               {
9527                 DECL_VISIBILITY_SPECIFIED (r) = 0;
9528                 DECL_ATTRIBUTES (r)
9529                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9530               }
9531             determine_visibility (r);
9532           }
9533
9534         if (!local_p)
9535           {
9536             /* A static data member declaration is always marked
9537                external when it is declared in-class, even if an
9538                initializer is present.  We mimic the non-template
9539                processing here.  */
9540             DECL_EXTERNAL (r) = 1;
9541
9542             register_specialization (r, gen_tmpl, argvec, false, hash);
9543             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
9544             SET_DECL_IMPLICIT_INSTANTIATION (r);
9545           }
9546         else if (cp_unevaluated_operand)
9547           {
9548             /* We're substituting this var in a decltype outside of its
9549                scope, such as for a lambda return type.  Don't add it to
9550                local_specializations, do perform auto deduction.  */
9551             tree auto_node = type_uses_auto (type);
9552             tree init
9553               = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
9554                              /*constant_expression_p=*/false);
9555
9556             if (auto_node && init && describable_type (init))
9557               {
9558                 type = do_auto_deduction (type, init, auto_node);
9559                 TREE_TYPE (r) = type;
9560               }
9561           }
9562         else
9563           register_local_specialization (r, t);
9564
9565         TREE_CHAIN (r) = NULL_TREE;
9566
9567         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
9568                                         /*flags=*/0,
9569                                         args, complain, in_decl);
9570
9571         /* Preserve a typedef that names a type.  */
9572         if (is_typedef_decl (r))
9573           {
9574             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
9575             set_underlying_type (r);
9576           }
9577
9578         layout_decl (r, 0);
9579       }
9580       break;
9581
9582     default:
9583       gcc_unreachable ();
9584     }
9585 #undef RETURN
9586
9587  out:
9588   /* Restore the file and line information.  */
9589   input_location = saved_loc;
9590
9591   return r;
9592 }
9593
9594 /* Substitute into the ARG_TYPES of a function type.  */
9595
9596 static tree
9597 tsubst_arg_types (tree arg_types,
9598                   tree args,
9599                   tsubst_flags_t complain,
9600                   tree in_decl)
9601 {
9602   tree remaining_arg_types;
9603   tree type = NULL_TREE;
9604   int i = 1;
9605   tree expanded_args = NULL_TREE;
9606   tree default_arg;
9607
9608   if (!arg_types || arg_types == void_list_node)
9609     return arg_types;
9610
9611   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
9612                                           args, complain, in_decl);
9613   if (remaining_arg_types == error_mark_node)
9614     return error_mark_node;
9615
9616   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
9617     {
9618       /* For a pack expansion, perform substitution on the
9619          entire expression. Later on, we'll handle the arguments
9620          one-by-one.  */
9621       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
9622                                             args, complain, in_decl);
9623
9624       if (TREE_CODE (expanded_args) == TREE_VEC)
9625         /* So that we'll spin through the parameters, one by one.  */
9626         i = TREE_VEC_LENGTH (expanded_args);
9627       else
9628         {
9629           /* We only partially substituted into the parameter
9630              pack. Our type is TYPE_PACK_EXPANSION.  */
9631           type = expanded_args;
9632           expanded_args = NULL_TREE;
9633         }
9634     }
9635
9636   while (i > 0) {
9637     --i;
9638     
9639     if (expanded_args)
9640       type = TREE_VEC_ELT (expanded_args, i);
9641     else if (!type)
9642       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
9643
9644     if (type == error_mark_node)
9645       return error_mark_node;
9646     if (VOID_TYPE_P (type))
9647       {
9648         if (complain & tf_error)
9649           {
9650             error ("invalid parameter type %qT", type);
9651             if (in_decl)
9652               error ("in declaration %q+D", in_decl);
9653           }
9654         return error_mark_node;
9655     }
9656     
9657     /* Do array-to-pointer, function-to-pointer conversion, and ignore
9658        top-level qualifiers as required.  */
9659     type = TYPE_MAIN_VARIANT (type_decays_to (type));
9660
9661     /* We do not substitute into default arguments here.  The standard
9662        mandates that they be instantiated only when needed, which is
9663        done in build_over_call.  */
9664     default_arg = TREE_PURPOSE (arg_types);
9665
9666     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
9667       {
9668         /* We've instantiated a template before its default arguments
9669            have been parsed.  This can happen for a nested template
9670            class, and is not an error unless we require the default
9671            argument in a call of this function.  */
9672         remaining_arg_types = 
9673           tree_cons (default_arg, type, remaining_arg_types);
9674         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
9675                        remaining_arg_types);
9676       }
9677     else
9678       remaining_arg_types = 
9679         hash_tree_cons (default_arg, type, remaining_arg_types);
9680   }
9681         
9682   return remaining_arg_types;
9683 }
9684
9685 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
9686    *not* handle the exception-specification for FNTYPE, because the
9687    initial substitution of explicitly provided template parameters
9688    during argument deduction forbids substitution into the
9689    exception-specification:
9690
9691      [temp.deduct]
9692
9693      All references in the function type of the function template to  the
9694      corresponding template parameters are replaced by the specified tem-
9695      plate argument values.  If a substitution in a template parameter or
9696      in  the function type of the function template results in an invalid
9697      type, type deduction fails.  [Note: The equivalent  substitution  in
9698      exception specifications is done only when the function is instanti-
9699      ated, at which point a program is  ill-formed  if  the  substitution
9700      results in an invalid type.]  */
9701
9702 static tree
9703 tsubst_function_type (tree t,
9704                       tree args,
9705                       tsubst_flags_t complain,
9706                       tree in_decl)
9707 {
9708   tree return_type;
9709   tree arg_types;
9710   tree fntype;
9711
9712   /* The TYPE_CONTEXT is not used for function/method types.  */
9713   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
9714
9715   /* Substitute the return type.  */
9716   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9717   if (return_type == error_mark_node)
9718     return error_mark_node;
9719   /* The standard does not presently indicate that creation of a
9720      function type with an invalid return type is a deduction failure.
9721      However, that is clearly analogous to creating an array of "void"
9722      or a reference to a reference.  This is core issue #486.  */
9723   if (TREE_CODE (return_type) == ARRAY_TYPE
9724       || TREE_CODE (return_type) == FUNCTION_TYPE)
9725     {
9726       if (complain & tf_error)
9727         {
9728           if (TREE_CODE (return_type) == ARRAY_TYPE)
9729             error ("function returning an array");
9730           else
9731             error ("function returning a function");
9732         }
9733       return error_mark_node;
9734     }
9735
9736   /* Substitute the argument types.  */
9737   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
9738                                 complain, in_decl);
9739   if (arg_types == error_mark_node)
9740     return error_mark_node;
9741
9742   /* Construct a new type node and return it.  */
9743   if (TREE_CODE (t) == FUNCTION_TYPE)
9744     fntype = build_function_type (return_type, arg_types);
9745   else
9746     {
9747       tree r = TREE_TYPE (TREE_VALUE (arg_types));
9748       if (! MAYBE_CLASS_TYPE_P (r))
9749         {
9750           /* [temp.deduct]
9751
9752              Type deduction may fail for any of the following
9753              reasons:
9754
9755              -- Attempting to create "pointer to member of T" when T
9756              is not a class type.  */
9757           if (complain & tf_error)
9758             error ("creating pointer to member function of non-class type %qT",
9759                       r);
9760           return error_mark_node;
9761         }
9762
9763       fntype = build_method_type_directly (r, return_type,
9764                                            TREE_CHAIN (arg_types));
9765     }
9766   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
9767   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
9768
9769   return fntype;
9770 }
9771
9772 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
9773    ARGS into that specification, and return the substituted
9774    specification.  If there is no specification, return NULL_TREE.  */
9775
9776 static tree
9777 tsubst_exception_specification (tree fntype,
9778                                 tree args,
9779                                 tsubst_flags_t complain,
9780                                 tree in_decl)
9781 {
9782   tree specs;
9783   tree new_specs;
9784
9785   specs = TYPE_RAISES_EXCEPTIONS (fntype);
9786   new_specs = NULL_TREE;
9787   if (specs)
9788     {
9789       if (! TREE_VALUE (specs))
9790         new_specs = specs;
9791       else
9792         while (specs)
9793           {
9794             tree spec;
9795             int i, len = 1;
9796             tree expanded_specs = NULL_TREE;
9797
9798             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
9799               {
9800                 /* Expand the pack expansion type.  */
9801                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
9802                                                        args, complain,
9803                                                        in_decl);
9804
9805                 if (expanded_specs == error_mark_node)
9806                   return error_mark_node;
9807                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
9808                   len = TREE_VEC_LENGTH (expanded_specs);
9809                 else
9810                   {
9811                     /* We're substituting into a member template, so
9812                        we got a TYPE_PACK_EXPANSION back.  Add that
9813                        expansion and move on.  */
9814                     gcc_assert (TREE_CODE (expanded_specs) 
9815                                 == TYPE_PACK_EXPANSION);
9816                     new_specs = add_exception_specifier (new_specs,
9817                                                          expanded_specs,
9818                                                          complain);
9819                     specs = TREE_CHAIN (specs);
9820                     continue;
9821                   }
9822               }
9823
9824             for (i = 0; i < len; ++i)
9825               {
9826                 if (expanded_specs)
9827                   spec = TREE_VEC_ELT (expanded_specs, i);
9828                 else
9829                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
9830                 if (spec == error_mark_node)
9831                   return spec;
9832                 new_specs = add_exception_specifier (new_specs, spec, 
9833                                                      complain);
9834               }
9835
9836             specs = TREE_CHAIN (specs);
9837           }
9838     }
9839   return new_specs;
9840 }
9841
9842 /* Take the tree structure T and replace template parameters used
9843    therein with the argument vector ARGS.  IN_DECL is an associated
9844    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
9845    Issue error and warning messages under control of COMPLAIN.  Note
9846    that we must be relatively non-tolerant of extensions here, in
9847    order to preserve conformance; if we allow substitutions that
9848    should not be allowed, we may allow argument deductions that should
9849    not succeed, and therefore report ambiguous overload situations
9850    where there are none.  In theory, we could allow the substitution,
9851    but indicate that it should have failed, and allow our caller to
9852    make sure that the right thing happens, but we don't try to do this
9853    yet.
9854
9855    This function is used for dealing with types, decls and the like;
9856    for expressions, use tsubst_expr or tsubst_copy.  */
9857
9858 tree
9859 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9860 {
9861   tree type, r;
9862
9863   if (t == NULL_TREE || t == error_mark_node
9864       || t == integer_type_node
9865       || t == void_type_node
9866       || t == char_type_node
9867       || t == unknown_type_node
9868       || TREE_CODE (t) == NAMESPACE_DECL)
9869     return t;
9870
9871   if (DECL_P (t))
9872     return tsubst_decl (t, args, complain);
9873
9874   if (args == NULL_TREE)
9875     return t;
9876
9877   if (TREE_CODE (t) == IDENTIFIER_NODE)
9878     type = IDENTIFIER_TYPE_VALUE (t);
9879   else
9880     type = TREE_TYPE (t);
9881
9882   gcc_assert (type != unknown_type_node);
9883
9884   /* Reuse typedefs.  We need to do this to handle dependent attributes,
9885      such as attribute aligned.  */
9886   if (TYPE_P (t)
9887       && TYPE_NAME (t)
9888       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
9889     {
9890       tree decl = TYPE_NAME (t);
9891       
9892       if (DECL_CLASS_SCOPE_P (decl)
9893           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
9894           && uses_template_parms (DECL_CONTEXT (decl)))
9895         {
9896           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
9897           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
9898           r = retrieve_specialization (tmpl, gen_args, 0);
9899         }
9900       else if (DECL_FUNCTION_SCOPE_P (decl)
9901                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
9902                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
9903         r = retrieve_local_specialization (decl);
9904       else
9905         /* The typedef is from a non-template context.  */
9906         return t;
9907
9908       if (r)
9909         {
9910           r = TREE_TYPE (r);
9911           r = cp_build_qualified_type_real
9912             (r, cp_type_quals (t) | cp_type_quals (r),
9913              complain | tf_ignore_bad_quals);
9914           return r;
9915         }
9916       /* Else we must be instantiating the typedef, so fall through.  */
9917     }
9918
9919   if (type
9920       && TREE_CODE (t) != TYPENAME_TYPE
9921       && TREE_CODE (t) != IDENTIFIER_NODE
9922       && TREE_CODE (t) != FUNCTION_TYPE
9923       && TREE_CODE (t) != METHOD_TYPE)
9924     type = tsubst (type, args, complain, in_decl);
9925   if (type == error_mark_node)
9926     return error_mark_node;
9927
9928   switch (TREE_CODE (t))
9929     {
9930     case RECORD_TYPE:
9931     case UNION_TYPE:
9932     case ENUMERAL_TYPE:
9933       return tsubst_aggr_type (t, args, complain, in_decl,
9934                                /*entering_scope=*/0);
9935
9936     case ERROR_MARK:
9937     case IDENTIFIER_NODE:
9938     case VOID_TYPE:
9939     case REAL_TYPE:
9940     case COMPLEX_TYPE:
9941     case VECTOR_TYPE:
9942     case BOOLEAN_TYPE:
9943     case INTEGER_CST:
9944     case REAL_CST:
9945     case STRING_CST:
9946       return t;
9947
9948     case INTEGER_TYPE:
9949       if (t == integer_type_node)
9950         return t;
9951
9952       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
9953           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
9954         return t;
9955
9956       {
9957         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
9958
9959         max = tsubst_expr (omax, args, complain, in_decl,
9960                            /*integral_constant_expression_p=*/false);
9961
9962         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
9963            needed.  */
9964         if (TREE_CODE (max) == NOP_EXPR
9965             && TREE_SIDE_EFFECTS (omax)
9966             && !TREE_TYPE (max))
9967           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
9968
9969         max = fold_decl_constant_value (max);
9970
9971         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
9972            with TREE_SIDE_EFFECTS that indicates this is not an integral
9973            constant expression.  */
9974         if (processing_template_decl
9975             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
9976           {
9977             gcc_assert (TREE_CODE (max) == NOP_EXPR);
9978             TREE_SIDE_EFFECTS (max) = 1;
9979           }
9980
9981         if (TREE_CODE (max) != INTEGER_CST
9982             && !at_function_scope_p ()
9983             && !TREE_SIDE_EFFECTS (max)
9984             && !value_dependent_expression_p (max))
9985           {
9986             if (complain & tf_error)
9987               error ("array bound is not an integer constant");
9988             return error_mark_node;
9989           }
9990
9991         /* [temp.deduct]
9992
9993            Type deduction may fail for any of the following
9994            reasons:
9995
9996              Attempting to create an array with a size that is
9997              zero or negative.  */
9998         if (integer_zerop (max) && !(complain & tf_error))
9999           /* We must fail if performing argument deduction (as
10000              indicated by the state of complain), so that
10001              another substitution can be found.  */
10002           return error_mark_node;
10003         else if (TREE_CODE (max) == INTEGER_CST
10004                  && INT_CST_LT (max, integer_zero_node))
10005           {
10006             if (complain & tf_error)
10007               error ("creating array with negative size (%qE)", max);
10008
10009             return error_mark_node;
10010           }
10011
10012         return compute_array_index_type (NULL_TREE, max);
10013       }
10014
10015     case TEMPLATE_TYPE_PARM:
10016     case TEMPLATE_TEMPLATE_PARM:
10017     case BOUND_TEMPLATE_TEMPLATE_PARM:
10018     case TEMPLATE_PARM_INDEX:
10019       {
10020         int idx;
10021         int level;
10022         int levels;
10023         tree arg = NULL_TREE;
10024
10025         r = NULL_TREE;
10026
10027         gcc_assert (TREE_VEC_LENGTH (args) > 0);
10028         template_parm_level_and_index (t, &level, &idx); 
10029
10030         levels = TMPL_ARGS_DEPTH (args);
10031         if (level <= levels)
10032           {
10033             arg = TMPL_ARG (args, level, idx);
10034
10035             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
10036               /* See through ARGUMENT_PACK_SELECT arguments. */
10037               arg = ARGUMENT_PACK_SELECT_ARG (arg);
10038           }
10039
10040         if (arg == error_mark_node)
10041           return error_mark_node;
10042         else if (arg != NULL_TREE)
10043           {
10044             if (ARGUMENT_PACK_P (arg))
10045               /* If ARG is an argument pack, we don't actually want to
10046                  perform a substitution here, because substitutions
10047                  for argument packs are only done
10048                  element-by-element. We can get to this point when
10049                  substituting the type of a non-type template
10050                  parameter pack, when that type actually contains
10051                  template parameter packs from an outer template, e.g.,
10052
10053                  template<typename... Types> struct A {
10054                    template<Types... Values> struct B { };
10055                  };  */
10056               return t;
10057
10058             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
10059               {
10060                 int quals;
10061                 gcc_assert (TYPE_P (arg));
10062
10063                 /* cv-quals from the template are discarded when
10064                    substituting in a function or reference type.  */
10065                 if (TREE_CODE (arg) == FUNCTION_TYPE
10066                     || TREE_CODE (arg) == METHOD_TYPE
10067                     || TREE_CODE (arg) == REFERENCE_TYPE)
10068                   quals = cp_type_quals (arg);
10069                 else
10070                   quals = cp_type_quals (arg) | cp_type_quals (t);
10071                   
10072                 return cp_build_qualified_type_real
10073                   (arg, quals, complain | tf_ignore_bad_quals);
10074               }
10075             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10076               {
10077                 /* We are processing a type constructed from a
10078                    template template parameter.  */
10079                 tree argvec = tsubst (TYPE_TI_ARGS (t),
10080                                       args, complain, in_decl);
10081                 if (argvec == error_mark_node)
10082                   return error_mark_node;
10083
10084                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
10085                    are resolving nested-types in the signature of a
10086                    member function templates.  Otherwise ARG is a
10087                    TEMPLATE_DECL and is the real template to be
10088                    instantiated.  */
10089                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
10090                   arg = TYPE_NAME (arg);
10091
10092                 r = lookup_template_class (arg,
10093                                            argvec, in_decl,
10094                                            DECL_CONTEXT (arg),
10095                                             /*entering_scope=*/0,
10096                                            complain);
10097                 return cp_build_qualified_type_real
10098                   (r, TYPE_QUALS (t), complain);
10099               }
10100             else
10101               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
10102               return arg;
10103           }
10104
10105         if (level == 1)
10106           /* This can happen during the attempted tsubst'ing in
10107              unify.  This means that we don't yet have any information
10108              about the template parameter in question.  */
10109           return t;
10110
10111         /* If we get here, we must have been looking at a parm for a
10112            more deeply nested template.  Make a new version of this
10113            template parameter, but with a lower level.  */
10114         switch (TREE_CODE (t))
10115           {
10116           case TEMPLATE_TYPE_PARM:
10117           case TEMPLATE_TEMPLATE_PARM:
10118           case BOUND_TEMPLATE_TEMPLATE_PARM:
10119             if (cp_type_quals (t))
10120               {
10121                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
10122                 r = cp_build_qualified_type_real
10123                   (r, cp_type_quals (t),
10124                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
10125                                ? tf_ignore_bad_quals : 0));
10126               }
10127             else
10128               {
10129                 r = copy_type (t);
10130                 TEMPLATE_TYPE_PARM_INDEX (r)
10131                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
10132                                                 r, levels, args, complain);
10133                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
10134                 TYPE_MAIN_VARIANT (r) = r;
10135                 TYPE_POINTER_TO (r) = NULL_TREE;
10136                 TYPE_REFERENCE_TO (r) = NULL_TREE;
10137
10138                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
10139                   /* We have reduced the level of the template
10140                      template parameter, but not the levels of its
10141                      template parameters, so canonical_type_parameter
10142                      will not be able to find the canonical template
10143                      template parameter for this level. Thus, we
10144                      require structural equality checking to compare
10145                      TEMPLATE_TEMPLATE_PARMs. */
10146                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10147                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
10148                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10149                 else
10150                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
10151
10152                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10153                   {
10154                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
10155                                           complain, in_decl);
10156                     if (argvec == error_mark_node)
10157                       return error_mark_node;
10158
10159                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
10160                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
10161                   }
10162               }
10163             break;
10164
10165           case TEMPLATE_PARM_INDEX:
10166             r = reduce_template_parm_level (t, type, levels, args, complain);
10167             break;
10168
10169           default:
10170             gcc_unreachable ();
10171           }
10172
10173         return r;
10174       }
10175
10176     case TREE_LIST:
10177       {
10178         tree purpose, value, chain;
10179
10180         if (t == void_list_node)
10181           return t;
10182
10183         purpose = TREE_PURPOSE (t);
10184         if (purpose)
10185           {
10186             purpose = tsubst (purpose, args, complain, in_decl);
10187             if (purpose == error_mark_node)
10188               return error_mark_node;
10189           }
10190         value = TREE_VALUE (t);
10191         if (value)
10192           {
10193             value = tsubst (value, args, complain, in_decl);
10194             if (value == error_mark_node)
10195               return error_mark_node;
10196           }
10197         chain = TREE_CHAIN (t);
10198         if (chain && chain != void_type_node)
10199           {
10200             chain = tsubst (chain, args, complain, in_decl);
10201             if (chain == error_mark_node)
10202               return error_mark_node;
10203           }
10204         if (purpose == TREE_PURPOSE (t)
10205             && value == TREE_VALUE (t)
10206             && chain == TREE_CHAIN (t))
10207           return t;
10208         return hash_tree_cons (purpose, value, chain);
10209       }
10210
10211     case TREE_BINFO:
10212       /* We should never be tsubsting a binfo.  */
10213       gcc_unreachable ();
10214
10215     case TREE_VEC:
10216       /* A vector of template arguments.  */
10217       gcc_assert (!type);
10218       return tsubst_template_args (t, args, complain, in_decl);
10219
10220     case POINTER_TYPE:
10221     case REFERENCE_TYPE:
10222       {
10223         enum tree_code code;
10224
10225         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
10226           return t;
10227
10228         code = TREE_CODE (t);
10229
10230
10231         /* [temp.deduct]
10232
10233            Type deduction may fail for any of the following
10234            reasons:
10235
10236            -- Attempting to create a pointer to reference type.
10237            -- Attempting to create a reference to a reference type or
10238               a reference to void.
10239
10240           Core issue 106 says that creating a reference to a reference
10241           during instantiation is no longer a cause for failure. We
10242           only enforce this check in strict C++98 mode.  */
10243         if ((TREE_CODE (type) == REFERENCE_TYPE
10244              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
10245             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
10246           {
10247             static location_t last_loc;
10248
10249             /* We keep track of the last time we issued this error
10250                message to avoid spewing a ton of messages during a
10251                single bad template instantiation.  */
10252             if (complain & tf_error
10253                 && last_loc != input_location)
10254               {
10255                 if (TREE_CODE (type) == VOID_TYPE)
10256                   error ("forming reference to void");
10257                else if (code == POINTER_TYPE)
10258                  error ("forming pointer to reference type %qT", type);
10259                else
10260                   error ("forming reference to reference type %qT", type);
10261                 last_loc = input_location;
10262               }
10263
10264             return error_mark_node;
10265           }
10266         else if (code == POINTER_TYPE)
10267           {
10268             r = build_pointer_type (type);
10269             if (TREE_CODE (type) == METHOD_TYPE)
10270               r = build_ptrmemfunc_type (r);
10271           }
10272         else if (TREE_CODE (type) == REFERENCE_TYPE)
10273           /* In C++0x, during template argument substitution, when there is an
10274              attempt to create a reference to a reference type, reference
10275              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
10276
10277              "If a template-argument for a template-parameter T names a type
10278              that is a reference to a type A, an attempt to create the type
10279              'lvalue reference to cv T' creates the type 'lvalue reference to
10280              A,' while an attempt to create the type type rvalue reference to
10281              cv T' creates the type T"
10282           */
10283           r = cp_build_reference_type
10284               (TREE_TYPE (type),
10285                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
10286         else
10287           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
10288         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
10289
10290         if (r != error_mark_node)
10291           /* Will this ever be needed for TYPE_..._TO values?  */
10292           layout_type (r);
10293
10294         return r;
10295       }
10296     case OFFSET_TYPE:
10297       {
10298         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
10299         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
10300           {
10301             /* [temp.deduct]
10302
10303                Type deduction may fail for any of the following
10304                reasons:
10305
10306                -- Attempting to create "pointer to member of T" when T
10307                   is not a class type.  */
10308             if (complain & tf_error)
10309               error ("creating pointer to member of non-class type %qT", r);
10310             return error_mark_node;
10311           }
10312         if (TREE_CODE (type) == REFERENCE_TYPE)
10313           {
10314             if (complain & tf_error)
10315               error ("creating pointer to member reference type %qT", type);
10316             return error_mark_node;
10317           }
10318         if (TREE_CODE (type) == VOID_TYPE)
10319           {
10320             if (complain & tf_error)
10321               error ("creating pointer to member of type void");
10322             return error_mark_node;
10323           }
10324         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
10325         if (TREE_CODE (type) == FUNCTION_TYPE)
10326           {
10327             /* The type of the implicit object parameter gets its
10328                cv-qualifiers from the FUNCTION_TYPE. */
10329             tree memptr;
10330             tree method_type = build_memfn_type (type, r, cp_type_quals (type));
10331             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
10332             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
10333                                                  complain);
10334           }
10335         else
10336           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
10337                                                TYPE_QUALS (t),
10338                                                complain);
10339       }
10340     case FUNCTION_TYPE:
10341     case METHOD_TYPE:
10342       {
10343         tree fntype;
10344         tree specs;
10345         fntype = tsubst_function_type (t, args, complain, in_decl);
10346         if (fntype == error_mark_node)
10347           return error_mark_node;
10348
10349         /* Substitute the exception specification.  */
10350         specs = tsubst_exception_specification (t, args, complain,
10351                                                 in_decl);
10352         if (specs == error_mark_node)
10353           return error_mark_node;
10354         if (specs)
10355           fntype = build_exception_variant (fntype, specs);
10356         return fntype;
10357       }
10358     case ARRAY_TYPE:
10359       {
10360         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
10361         if (domain == error_mark_node)
10362           return error_mark_node;
10363
10364         /* As an optimization, we avoid regenerating the array type if
10365            it will obviously be the same as T.  */
10366         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
10367           return t;
10368
10369         /* These checks should match the ones in grokdeclarator.
10370
10371            [temp.deduct]
10372
10373            The deduction may fail for any of the following reasons:
10374
10375            -- Attempting to create an array with an element type that
10376               is void, a function type, or a reference type, or [DR337]
10377               an abstract class type.  */
10378         if (TREE_CODE (type) == VOID_TYPE
10379             || TREE_CODE (type) == FUNCTION_TYPE
10380             || TREE_CODE (type) == REFERENCE_TYPE)
10381           {
10382             if (complain & tf_error)
10383               error ("creating array of %qT", type);
10384             return error_mark_node;
10385           }
10386         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
10387           {
10388             if (complain & tf_error)
10389               error ("creating array of %qT, which is an abstract class type",
10390                      type);
10391             return error_mark_node;
10392           }
10393
10394         r = build_cplus_array_type (type, domain);
10395
10396         if (TYPE_USER_ALIGN (t))
10397           {
10398             TYPE_ALIGN (r) = TYPE_ALIGN (t);
10399             TYPE_USER_ALIGN (r) = 1;
10400           }
10401
10402         return r;
10403       }
10404
10405     case PLUS_EXPR:
10406     case MINUS_EXPR:
10407       {
10408         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10409         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10410
10411         if (e1 == error_mark_node || e2 == error_mark_node)
10412           return error_mark_node;
10413
10414         return fold_build2_loc (input_location,
10415                             TREE_CODE (t), TREE_TYPE (t), e1, e2);
10416       }
10417
10418     case NEGATE_EXPR:
10419     case NOP_EXPR:
10420       {
10421         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10422         if (e == error_mark_node)
10423           return error_mark_node;
10424
10425         return fold_build1_loc (input_location, TREE_CODE (t), TREE_TYPE (t), e);
10426       }
10427
10428     case TYPENAME_TYPE:
10429       {
10430         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10431                                      in_decl, /*entering_scope=*/1);
10432         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
10433                               complain, in_decl);
10434
10435         if (ctx == error_mark_node || f == error_mark_node)
10436           return error_mark_node;
10437
10438         if (!MAYBE_CLASS_TYPE_P (ctx))
10439           {
10440             if (complain & tf_error)
10441               error ("%qT is not a class, struct, or union type", ctx);
10442             return error_mark_node;
10443           }
10444         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
10445           {
10446             /* Normally, make_typename_type does not require that the CTX
10447                have complete type in order to allow things like:
10448
10449                  template <class T> struct S { typename S<T>::X Y; };
10450
10451                But, such constructs have already been resolved by this
10452                point, so here CTX really should have complete type, unless
10453                it's a partial instantiation.  */
10454             if (!(complain & tf_no_class_instantiations))
10455               ctx = complete_type (ctx);
10456             if (!COMPLETE_TYPE_P (ctx))
10457               {
10458                 if (complain & tf_error)
10459                   cxx_incomplete_type_error (NULL_TREE, ctx);
10460                 return error_mark_node;
10461               }
10462           }
10463
10464         f = make_typename_type (ctx, f, typename_type,
10465                                 (complain & tf_error) | tf_keep_type_decl);
10466         if (f == error_mark_node)
10467           return f;
10468         if (TREE_CODE (f) == TYPE_DECL)
10469           {
10470             complain |= tf_ignore_bad_quals;
10471             f = TREE_TYPE (f);
10472           }
10473
10474         if (TREE_CODE (f) != TYPENAME_TYPE)
10475           {
10476             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
10477               error ("%qT resolves to %qT, which is not an enumeration type",
10478                      t, f);
10479             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
10480               error ("%qT resolves to %qT, which is is not a class type",
10481                      t, f);
10482           }
10483
10484         return cp_build_qualified_type_real
10485           (f, cp_type_quals (f) | cp_type_quals (t), complain);
10486       }
10487
10488     case UNBOUND_CLASS_TEMPLATE:
10489       {
10490         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10491                                      in_decl, /*entering_scope=*/1);
10492         tree name = TYPE_IDENTIFIER (t);
10493         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
10494
10495         if (ctx == error_mark_node || name == error_mark_node)
10496           return error_mark_node;
10497
10498         if (parm_list)
10499           parm_list = tsubst_template_parms (parm_list, args, complain);
10500         return make_unbound_class_template (ctx, name, parm_list, complain);
10501       }
10502
10503     case INDIRECT_REF:
10504     case ADDR_EXPR:
10505     case CALL_EXPR:
10506       gcc_unreachable ();
10507
10508     case ARRAY_REF:
10509       {
10510         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10511         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
10512                                /*integral_constant_expression_p=*/false);
10513         if (e1 == error_mark_node || e2 == error_mark_node)
10514           return error_mark_node;
10515
10516         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
10517       }
10518
10519     case SCOPE_REF:
10520       {
10521         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10522         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10523         if (e1 == error_mark_node || e2 == error_mark_node)
10524           return error_mark_node;
10525
10526         return build_qualified_name (/*type=*/NULL_TREE,
10527                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
10528       }
10529
10530     case TYPEOF_TYPE:
10531       {
10532         tree type;
10533
10534         ++cp_unevaluated_operand;
10535         ++c_inhibit_evaluation_warnings;
10536
10537         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
10538                             complain, in_decl,
10539                             /*integral_constant_expression_p=*/false);
10540
10541         --cp_unevaluated_operand;
10542         --c_inhibit_evaluation_warnings;
10543
10544         type = finish_typeof (type);
10545         return cp_build_qualified_type_real (type,
10546                                              cp_type_quals (t)
10547                                              | cp_type_quals (type),
10548                                              complain);
10549       }
10550
10551     case DECLTYPE_TYPE:
10552       {
10553         tree type;
10554
10555         ++cp_unevaluated_operand;
10556         ++c_inhibit_evaluation_warnings;
10557
10558         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
10559                             complain, in_decl,
10560                             /*integral_constant_expression_p=*/false);
10561
10562         --cp_unevaluated_operand;
10563         --c_inhibit_evaluation_warnings;
10564
10565         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
10566           type = lambda_capture_field_type (type);
10567         else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
10568           type = lambda_return_type (type);
10569         else
10570           type = finish_decltype_type
10571             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
10572         return cp_build_qualified_type_real (type,
10573                                              cp_type_quals (t)
10574                                              | cp_type_quals (type),
10575                                              complain);
10576       }
10577
10578     case TYPE_ARGUMENT_PACK:
10579     case NONTYPE_ARGUMENT_PACK:
10580       {
10581         tree r = TYPE_P (t)
10582           ? cxx_make_type (TREE_CODE (t))
10583           : make_node (TREE_CODE (t));
10584         tree packed_out = 
10585           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
10586                                 args,
10587                                 complain,
10588                                 in_decl);
10589         SET_ARGUMENT_PACK_ARGS (r, packed_out);
10590
10591         /* For template nontype argument packs, also substitute into
10592            the type.  */
10593         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
10594           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
10595
10596         return r;
10597       }
10598       break;
10599
10600     default:
10601       sorry ("use of %qs in template",
10602              tree_code_name [(int) TREE_CODE (t)]);
10603       return error_mark_node;
10604     }
10605 }
10606
10607 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
10608    type of the expression on the left-hand side of the "." or "->"
10609    operator.  */
10610
10611 static tree
10612 tsubst_baselink (tree baselink, tree object_type,
10613                  tree args, tsubst_flags_t complain, tree in_decl)
10614 {
10615     tree name;
10616     tree qualifying_scope;
10617     tree fns;
10618     tree optype;
10619     tree template_args = 0;
10620     bool template_id_p = false;
10621
10622     /* A baselink indicates a function from a base class.  Both the
10623        BASELINK_ACCESS_BINFO and the base class referenced may
10624        indicate bases of the template class, rather than the
10625        instantiated class.  In addition, lookups that were not
10626        ambiguous before may be ambiguous now.  Therefore, we perform
10627        the lookup again.  */
10628     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
10629     qualifying_scope = tsubst (qualifying_scope, args,
10630                                complain, in_decl);
10631     fns = BASELINK_FUNCTIONS (baselink);
10632     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
10633     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
10634       {
10635         template_id_p = true;
10636         template_args = TREE_OPERAND (fns, 1);
10637         fns = TREE_OPERAND (fns, 0);
10638         if (template_args)
10639           template_args = tsubst_template_args (template_args, args,
10640                                                 complain, in_decl);
10641       }
10642     name = DECL_NAME (get_first_fn (fns));
10643     if (IDENTIFIER_TYPENAME_P (name))
10644       name = mangle_conv_op_name_for_type (optype);
10645     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
10646
10647     /* If lookup found a single function, mark it as used at this
10648        point.  (If it lookup found multiple functions the one selected
10649        later by overload resolution will be marked as used at that
10650        point.)  */
10651     if (BASELINK_P (baselink))
10652       fns = BASELINK_FUNCTIONS (baselink);
10653     if (!template_id_p && !really_overloaded_fn (fns))
10654       mark_used (OVL_CURRENT (fns));
10655
10656     /* Add back the template arguments, if present.  */
10657     if (BASELINK_P (baselink) && template_id_p)
10658       BASELINK_FUNCTIONS (baselink)
10659         = build_nt (TEMPLATE_ID_EXPR,
10660                     BASELINK_FUNCTIONS (baselink),
10661                     template_args);
10662     /* Update the conversion operator type.  */
10663     BASELINK_OPTYPE (baselink) = optype;
10664
10665     if (!object_type)
10666       object_type = current_class_type;
10667     return adjust_result_of_qualified_name_lookup (baselink,
10668                                                    qualifying_scope,
10669                                                    object_type);
10670 }
10671
10672 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
10673    true if the qualified-id will be a postfix-expression in-and-of
10674    itself; false if more of the postfix-expression follows the
10675    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
10676    of "&".  */
10677
10678 static tree
10679 tsubst_qualified_id (tree qualified_id, tree args,
10680                      tsubst_flags_t complain, tree in_decl,
10681                      bool done, bool address_p)
10682 {
10683   tree expr;
10684   tree scope;
10685   tree name;
10686   bool is_template;
10687   tree template_args;
10688
10689   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
10690
10691   /* Figure out what name to look up.  */
10692   name = TREE_OPERAND (qualified_id, 1);
10693   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
10694     {
10695       is_template = true;
10696       template_args = TREE_OPERAND (name, 1);
10697       if (template_args)
10698         template_args = tsubst_template_args (template_args, args,
10699                                               complain, in_decl);
10700       name = TREE_OPERAND (name, 0);
10701     }
10702   else
10703     {
10704       is_template = false;
10705       template_args = NULL_TREE;
10706     }
10707
10708   /* Substitute into the qualifying scope.  When there are no ARGS, we
10709      are just trying to simplify a non-dependent expression.  In that
10710      case the qualifying scope may be dependent, and, in any case,
10711      substituting will not help.  */
10712   scope = TREE_OPERAND (qualified_id, 0);
10713   if (args)
10714     {
10715       scope = tsubst (scope, args, complain, in_decl);
10716       expr = tsubst_copy (name, args, complain, in_decl);
10717     }
10718   else
10719     expr = name;
10720
10721   if (dependent_scope_p (scope))
10722     return build_qualified_name (NULL_TREE, scope, expr,
10723                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
10724
10725   if (!BASELINK_P (name) && !DECL_P (expr))
10726     {
10727       if (TREE_CODE (expr) == BIT_NOT_EXPR)
10728         {
10729           /* A BIT_NOT_EXPR is used to represent a destructor.  */
10730           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
10731             {
10732               error ("qualifying type %qT does not match destructor name ~%qT",
10733                      scope, TREE_OPERAND (expr, 0));
10734               expr = error_mark_node;
10735             }
10736           else
10737             expr = lookup_qualified_name (scope, complete_dtor_identifier,
10738                                           /*is_type_p=*/0, false);
10739         }
10740       else
10741         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
10742       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
10743                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
10744         {
10745           if (complain & tf_error)
10746             {
10747               error ("dependent-name %qE is parsed as a non-type, but "
10748                      "instantiation yields a type", qualified_id);
10749               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
10750             }
10751           return error_mark_node;
10752         }
10753     }
10754
10755   if (DECL_P (expr))
10756     {
10757       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
10758                                            scope);
10759       /* Remember that there was a reference to this entity.  */
10760       mark_used (expr);
10761     }
10762
10763   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
10764     {
10765       if (complain & tf_error)
10766         qualified_name_lookup_error (scope,
10767                                      TREE_OPERAND (qualified_id, 1),
10768                                      expr, input_location);
10769       return error_mark_node;
10770     }
10771
10772   if (is_template)
10773     expr = lookup_template_function (expr, template_args);
10774
10775   if (expr == error_mark_node && complain & tf_error)
10776     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
10777                                  expr, input_location);
10778   else if (TYPE_P (scope))
10779     {
10780       expr = (adjust_result_of_qualified_name_lookup
10781               (expr, scope, current_class_type));
10782       expr = (finish_qualified_id_expr
10783               (scope, expr, done, address_p,
10784                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
10785                /*template_arg_p=*/false));
10786     }
10787
10788   /* Expressions do not generally have reference type.  */
10789   if (TREE_CODE (expr) != SCOPE_REF
10790       /* However, if we're about to form a pointer-to-member, we just
10791          want the referenced member referenced.  */
10792       && TREE_CODE (expr) != OFFSET_REF)
10793     expr = convert_from_reference (expr);
10794
10795   return expr;
10796 }
10797
10798 /* Like tsubst, but deals with expressions.  This function just replaces
10799    template parms; to finish processing the resultant expression, use
10800    tsubst_expr.  */
10801
10802 static tree
10803 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10804 {
10805   enum tree_code code;
10806   tree r;
10807
10808   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
10809     return t;
10810
10811   code = TREE_CODE (t);
10812
10813   switch (code)
10814     {
10815     case PARM_DECL:
10816       r = retrieve_local_specialization (t);
10817
10818       if (r == NULL)
10819         {
10820           tree c;
10821           /* This can happen for a parameter name used later in a function
10822              declaration (such as in a late-specified return type).  Just
10823              make a dummy decl, since it's only used for its type.  */
10824           gcc_assert (cp_unevaluated_operand != 0);
10825           /* We copy T because want to tsubst the PARM_DECL only,
10826              not the following PARM_DECLs that are chained to T.  */
10827           c = copy_node (t);
10828           r = tsubst_decl (c, args, complain);
10829           /* Give it the template pattern as its context; its true context
10830              hasn't been instantiated yet and this is good enough for
10831              mangling.  */
10832           DECL_CONTEXT (r) = DECL_CONTEXT (t);
10833         }
10834       
10835       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10836         r = ARGUMENT_PACK_SELECT_ARG (r);
10837       mark_used (r);
10838       return r;
10839
10840     case CONST_DECL:
10841       {
10842         tree enum_type;
10843         tree v;
10844
10845         if (DECL_TEMPLATE_PARM_P (t))
10846           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10847         /* There is no need to substitute into namespace-scope
10848            enumerators.  */
10849         if (DECL_NAMESPACE_SCOPE_P (t))
10850           return t;
10851         /* If ARGS is NULL, then T is known to be non-dependent.  */
10852         if (args == NULL_TREE)
10853           return integral_constant_value (t);
10854
10855         /* Unfortunately, we cannot just call lookup_name here.
10856            Consider:
10857
10858              template <int I> int f() {
10859              enum E { a = I };
10860              struct S { void g() { E e = a; } };
10861              };
10862
10863            When we instantiate f<7>::S::g(), say, lookup_name is not
10864            clever enough to find f<7>::a.  */
10865         enum_type
10866           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10867                               /*entering_scope=*/0);
10868
10869         for (v = TYPE_VALUES (enum_type);
10870              v != NULL_TREE;
10871              v = TREE_CHAIN (v))
10872           if (TREE_PURPOSE (v) == DECL_NAME (t))
10873             return TREE_VALUE (v);
10874
10875           /* We didn't find the name.  That should never happen; if
10876              name-lookup found it during preliminary parsing, we
10877              should find it again here during instantiation.  */
10878         gcc_unreachable ();
10879       }
10880       return t;
10881
10882     case FIELD_DECL:
10883       if (DECL_CONTEXT (t))
10884         {
10885           tree ctx;
10886
10887           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
10888                                   /*entering_scope=*/1);
10889           if (ctx != DECL_CONTEXT (t))
10890             {
10891               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
10892               if (!r)
10893                 {
10894                   if (complain & tf_error)
10895                     error ("using invalid field %qD", t);
10896                   return error_mark_node;
10897                 }
10898               return r;
10899             }
10900         }
10901
10902       return t;
10903
10904     case VAR_DECL:
10905     case FUNCTION_DECL:
10906       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10907           || local_variable_p (t))
10908         t = tsubst (t, args, complain, in_decl);
10909       mark_used (t);
10910       return t;
10911
10912     case BASELINK:
10913       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
10914
10915     case TEMPLATE_DECL:
10916       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10917         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
10918                        args, complain, in_decl);
10919       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
10920         return tsubst (t, args, complain, in_decl);
10921       else if (DECL_CLASS_SCOPE_P (t)
10922                && uses_template_parms (DECL_CONTEXT (t)))
10923         {
10924           /* Template template argument like the following example need
10925              special treatment:
10926
10927                template <template <class> class TT> struct C {};
10928                template <class T> struct D {
10929                  template <class U> struct E {};
10930                  C<E> c;                                // #1
10931                };
10932                D<int> d;                                // #2
10933
10934              We are processing the template argument `E' in #1 for
10935              the template instantiation #2.  Originally, `E' is a
10936              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
10937              have to substitute this with one having context `D<int>'.  */
10938
10939           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
10940           return lookup_field (context, DECL_NAME(t), 0, false);
10941         }
10942       else
10943         /* Ordinary template template argument.  */
10944         return t;
10945
10946     case CAST_EXPR:
10947     case REINTERPRET_CAST_EXPR:
10948     case CONST_CAST_EXPR:
10949     case STATIC_CAST_EXPR:
10950     case DYNAMIC_CAST_EXPR:
10951     case NOP_EXPR:
10952       return build1
10953         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10954          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10955
10956     case SIZEOF_EXPR:
10957       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10958         {
10959           /* We only want to compute the number of arguments.  */
10960           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
10961                                                 complain, in_decl);
10962           int len = 0;
10963
10964           if (TREE_CODE (expanded) == TREE_VEC)
10965             len = TREE_VEC_LENGTH (expanded);
10966
10967           if (expanded == error_mark_node)
10968             return error_mark_node;
10969           else if (PACK_EXPANSION_P (expanded)
10970                    || (TREE_CODE (expanded) == TREE_VEC
10971                        && len > 0
10972                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
10973             {
10974               if (TREE_CODE (expanded) == TREE_VEC)
10975                 expanded = TREE_VEC_ELT (expanded, len - 1);
10976
10977               if (TYPE_P (expanded))
10978                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
10979                                                    complain & tf_error);
10980               else
10981                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
10982                                                    complain & tf_error);
10983             }
10984           else
10985             return build_int_cst (size_type_node, len);
10986         }
10987       /* Fall through */
10988
10989     case INDIRECT_REF:
10990     case NEGATE_EXPR:
10991     case TRUTH_NOT_EXPR:
10992     case BIT_NOT_EXPR:
10993     case ADDR_EXPR:
10994     case UNARY_PLUS_EXPR:      /* Unary + */
10995     case ALIGNOF_EXPR:
10996     case ARROW_EXPR:
10997     case THROW_EXPR:
10998     case TYPEID_EXPR:
10999     case REALPART_EXPR:
11000     case IMAGPART_EXPR:
11001       return build1
11002         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11003          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11004
11005     case COMPONENT_REF:
11006       {
11007         tree object;
11008         tree name;
11009
11010         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
11011         name = TREE_OPERAND (t, 1);
11012         if (TREE_CODE (name) == BIT_NOT_EXPR)
11013           {
11014             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11015                                 complain, in_decl);
11016             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11017           }
11018         else if (TREE_CODE (name) == SCOPE_REF
11019                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
11020           {
11021             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
11022                                      complain, in_decl);
11023             name = TREE_OPERAND (name, 1);
11024             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11025                                 complain, in_decl);
11026             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11027             name = build_qualified_name (/*type=*/NULL_TREE,
11028                                          base, name,
11029                                          /*template_p=*/false);
11030           }
11031         else if (TREE_CODE (name) == BASELINK)
11032           name = tsubst_baselink (name,
11033                                   non_reference (TREE_TYPE (object)),
11034                                   args, complain,
11035                                   in_decl);
11036         else
11037           name = tsubst_copy (name, args, complain, in_decl);
11038         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
11039       }
11040
11041     case PLUS_EXPR:
11042     case MINUS_EXPR:
11043     case MULT_EXPR:
11044     case TRUNC_DIV_EXPR:
11045     case CEIL_DIV_EXPR:
11046     case FLOOR_DIV_EXPR:
11047     case ROUND_DIV_EXPR:
11048     case EXACT_DIV_EXPR:
11049     case BIT_AND_EXPR:
11050     case BIT_IOR_EXPR:
11051     case BIT_XOR_EXPR:
11052     case TRUNC_MOD_EXPR:
11053     case FLOOR_MOD_EXPR:
11054     case TRUTH_ANDIF_EXPR:
11055     case TRUTH_ORIF_EXPR:
11056     case TRUTH_AND_EXPR:
11057     case TRUTH_OR_EXPR:
11058     case RSHIFT_EXPR:
11059     case LSHIFT_EXPR:
11060     case RROTATE_EXPR:
11061     case LROTATE_EXPR:
11062     case EQ_EXPR:
11063     case NE_EXPR:
11064     case MAX_EXPR:
11065     case MIN_EXPR:
11066     case LE_EXPR:
11067     case GE_EXPR:
11068     case LT_EXPR:
11069     case GT_EXPR:
11070     case COMPOUND_EXPR:
11071     case DOTSTAR_EXPR:
11072     case MEMBER_REF:
11073     case PREDECREMENT_EXPR:
11074     case PREINCREMENT_EXPR:
11075     case POSTDECREMENT_EXPR:
11076     case POSTINCREMENT_EXPR:
11077       return build_nt
11078         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11079          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11080
11081     case SCOPE_REF:
11082       return build_qualified_name (/*type=*/NULL_TREE,
11083                                    tsubst_copy (TREE_OPERAND (t, 0),
11084                                                 args, complain, in_decl),
11085                                    tsubst_copy (TREE_OPERAND (t, 1),
11086                                                 args, complain, in_decl),
11087                                    QUALIFIED_NAME_IS_TEMPLATE (t));
11088
11089     case ARRAY_REF:
11090       return build_nt
11091         (ARRAY_REF,
11092          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11093          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11094          NULL_TREE, NULL_TREE);
11095
11096     case CALL_EXPR:
11097       {
11098         int n = VL_EXP_OPERAND_LENGTH (t);
11099         tree result = build_vl_exp (CALL_EXPR, n);
11100         int i;
11101         for (i = 0; i < n; i++)
11102           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
11103                                              complain, in_decl);
11104         return result;
11105       }
11106
11107     case COND_EXPR:
11108     case MODOP_EXPR:
11109     case PSEUDO_DTOR_EXPR:
11110       {
11111         r = build_nt
11112           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11113            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11114            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11115         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11116         return r;
11117       }
11118
11119     case NEW_EXPR:
11120       {
11121         r = build_nt
11122         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11123          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11124          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11125         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
11126         return r;
11127       }
11128
11129     case DELETE_EXPR:
11130       {
11131         r = build_nt
11132         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11133          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11134         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
11135         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
11136         return r;
11137       }
11138
11139     case TEMPLATE_ID_EXPR:
11140       {
11141         /* Substituted template arguments */
11142         tree fn = TREE_OPERAND (t, 0);
11143         tree targs = TREE_OPERAND (t, 1);
11144
11145         fn = tsubst_copy (fn, args, complain, in_decl);
11146         if (targs)
11147           targs = tsubst_template_args (targs, args, complain, in_decl);
11148
11149         return lookup_template_function (fn, targs);
11150       }
11151
11152     case TREE_LIST:
11153       {
11154         tree purpose, value, chain;
11155
11156         if (t == void_list_node)
11157           return t;
11158
11159         purpose = TREE_PURPOSE (t);
11160         if (purpose)
11161           purpose = tsubst_copy (purpose, args, complain, in_decl);
11162         value = TREE_VALUE (t);
11163         if (value)
11164           value = tsubst_copy (value, args, complain, in_decl);
11165         chain = TREE_CHAIN (t);
11166         if (chain && chain != void_type_node)
11167           chain = tsubst_copy (chain, args, complain, in_decl);
11168         if (purpose == TREE_PURPOSE (t)
11169             && value == TREE_VALUE (t)
11170             && chain == TREE_CHAIN (t))
11171           return t;
11172         return tree_cons (purpose, value, chain);
11173       }
11174
11175     case RECORD_TYPE:
11176     case UNION_TYPE:
11177     case ENUMERAL_TYPE:
11178     case INTEGER_TYPE:
11179     case TEMPLATE_TYPE_PARM:
11180     case TEMPLATE_TEMPLATE_PARM:
11181     case BOUND_TEMPLATE_TEMPLATE_PARM:
11182     case TEMPLATE_PARM_INDEX:
11183     case POINTER_TYPE:
11184     case REFERENCE_TYPE:
11185     case OFFSET_TYPE:
11186     case FUNCTION_TYPE:
11187     case METHOD_TYPE:
11188     case ARRAY_TYPE:
11189     case TYPENAME_TYPE:
11190     case UNBOUND_CLASS_TEMPLATE:
11191     case TYPEOF_TYPE:
11192     case DECLTYPE_TYPE:
11193     case TYPE_DECL:
11194       return tsubst (t, args, complain, in_decl);
11195
11196     case IDENTIFIER_NODE:
11197       if (IDENTIFIER_TYPENAME_P (t))
11198         {
11199           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11200           return mangle_conv_op_name_for_type (new_type);
11201         }
11202       else
11203         return t;
11204
11205     case CONSTRUCTOR:
11206       /* This is handled by tsubst_copy_and_build.  */
11207       gcc_unreachable ();
11208
11209     case VA_ARG_EXPR:
11210       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
11211                                           in_decl),
11212                              tsubst (TREE_TYPE (t), args, complain, in_decl));
11213
11214     case CLEANUP_POINT_EXPR:
11215       /* We shouldn't have built any of these during initial template
11216          generation.  Instead, they should be built during instantiation
11217          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
11218       gcc_unreachable ();
11219
11220     case OFFSET_REF:
11221       mark_used (TREE_OPERAND (t, 1));
11222       return t;
11223
11224     case EXPR_PACK_EXPANSION:
11225       error ("invalid use of pack expansion expression");
11226       return error_mark_node;
11227
11228     case NONTYPE_ARGUMENT_PACK:
11229       error ("use %<...%> to expand argument pack");
11230       return error_mark_node;
11231
11232     default:
11233       return t;
11234     }
11235 }
11236
11237 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
11238
11239 static tree
11240 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
11241                     tree in_decl)
11242 {
11243   tree new_clauses = NULL, nc, oc;
11244
11245   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
11246     {
11247       nc = copy_node (oc);
11248       OMP_CLAUSE_CHAIN (nc) = new_clauses;
11249       new_clauses = nc;
11250
11251       switch (OMP_CLAUSE_CODE (nc))
11252         {
11253         case OMP_CLAUSE_LASTPRIVATE:
11254           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
11255             {
11256               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
11257               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
11258                            in_decl, /*integral_constant_expression_p=*/false);
11259               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
11260                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
11261             }
11262           /* FALLTHRU */
11263         case OMP_CLAUSE_PRIVATE:
11264         case OMP_CLAUSE_SHARED:
11265         case OMP_CLAUSE_FIRSTPRIVATE:
11266         case OMP_CLAUSE_REDUCTION:
11267         case OMP_CLAUSE_COPYIN:
11268         case OMP_CLAUSE_COPYPRIVATE:
11269         case OMP_CLAUSE_IF:
11270         case OMP_CLAUSE_NUM_THREADS:
11271         case OMP_CLAUSE_SCHEDULE:
11272         case OMP_CLAUSE_COLLAPSE:
11273           OMP_CLAUSE_OPERAND (nc, 0)
11274             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
11275                            in_decl, /*integral_constant_expression_p=*/false);
11276           break;
11277         case OMP_CLAUSE_NOWAIT:
11278         case OMP_CLAUSE_ORDERED:
11279         case OMP_CLAUSE_DEFAULT:
11280         case OMP_CLAUSE_UNTIED:
11281           break;
11282         default:
11283           gcc_unreachable ();
11284         }
11285     }
11286
11287   return finish_omp_clauses (nreverse (new_clauses));
11288 }
11289
11290 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
11291
11292 static tree
11293 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
11294                           tree in_decl)
11295 {
11296 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
11297
11298   tree purpose, value, chain;
11299
11300   if (t == NULL)
11301     return t;
11302
11303   if (TREE_CODE (t) != TREE_LIST)
11304     return tsubst_copy_and_build (t, args, complain, in_decl,
11305                                   /*function_p=*/false,
11306                                   /*integral_constant_expression_p=*/false);
11307
11308   if (t == void_list_node)
11309     return t;
11310
11311   purpose = TREE_PURPOSE (t);
11312   if (purpose)
11313     purpose = RECUR (purpose);
11314   value = TREE_VALUE (t);
11315   if (value && TREE_CODE (value) != LABEL_DECL)
11316     value = RECUR (value);
11317   chain = TREE_CHAIN (t);
11318   if (chain && chain != void_type_node)
11319     chain = RECUR (chain);
11320   return tree_cons (purpose, value, chain);
11321 #undef RECUR
11322 }
11323
11324 /* Substitute one OMP_FOR iterator.  */
11325
11326 static void
11327 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
11328                          tree condv, tree incrv, tree *clauses,
11329                          tree args, tsubst_flags_t complain, tree in_decl,
11330                          bool integral_constant_expression_p)
11331 {
11332 #define RECUR(NODE)                             \
11333   tsubst_expr ((NODE), args, complain, in_decl, \
11334                integral_constant_expression_p)
11335   tree decl, init, cond, incr, auto_node;
11336
11337   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
11338   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
11339   decl = RECUR (TREE_OPERAND (init, 0));
11340   init = TREE_OPERAND (init, 1);
11341   auto_node = type_uses_auto (TREE_TYPE (decl));
11342   if (auto_node && init)
11343     {
11344       tree init_expr = init;
11345       if (TREE_CODE (init_expr) == DECL_EXPR)
11346         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
11347       init_expr = RECUR (init_expr);
11348       TREE_TYPE (decl)
11349         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
11350     }
11351   gcc_assert (!type_dependent_expression_p (decl));
11352
11353   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
11354     {
11355       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
11356       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11357       if (TREE_CODE (incr) == MODIFY_EXPR)
11358         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
11359                                     RECUR (TREE_OPERAND (incr, 1)),
11360                                     complain);
11361       else
11362         incr = RECUR (incr);
11363       TREE_VEC_ELT (declv, i) = decl;
11364       TREE_VEC_ELT (initv, i) = init;
11365       TREE_VEC_ELT (condv, i) = cond;
11366       TREE_VEC_ELT (incrv, i) = incr;
11367       return;
11368     }
11369
11370   if (init && TREE_CODE (init) != DECL_EXPR)
11371     {
11372       tree c;
11373       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
11374         {
11375           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
11376                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
11377               && OMP_CLAUSE_DECL (c) == decl)
11378             break;
11379           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
11380                    && OMP_CLAUSE_DECL (c) == decl)
11381             error ("iteration variable %qD should not be firstprivate", decl);
11382           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
11383                    && OMP_CLAUSE_DECL (c) == decl)
11384             error ("iteration variable %qD should not be reduction", decl);
11385         }
11386       if (c == NULL)
11387         {
11388           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
11389           OMP_CLAUSE_DECL (c) = decl;
11390           c = finish_omp_clauses (c);
11391           if (c)
11392             {
11393               OMP_CLAUSE_CHAIN (c) = *clauses;
11394               *clauses = c;
11395             }
11396         }
11397     }
11398   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
11399   if (COMPARISON_CLASS_P (cond))
11400     cond = build2 (TREE_CODE (cond), boolean_type_node,
11401                    RECUR (TREE_OPERAND (cond, 0)),
11402                    RECUR (TREE_OPERAND (cond, 1)));
11403   else
11404     cond = RECUR (cond);
11405   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11406   switch (TREE_CODE (incr))
11407     {
11408     case PREINCREMENT_EXPR:
11409     case PREDECREMENT_EXPR:
11410     case POSTINCREMENT_EXPR:
11411     case POSTDECREMENT_EXPR:
11412       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
11413                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
11414       break;
11415     case MODIFY_EXPR:
11416       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11417           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11418         {
11419           tree rhs = TREE_OPERAND (incr, 1);
11420           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11421                          RECUR (TREE_OPERAND (incr, 0)),
11422                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11423                                  RECUR (TREE_OPERAND (rhs, 0)),
11424                                  RECUR (TREE_OPERAND (rhs, 1))));
11425         }
11426       else
11427         incr = RECUR (incr);
11428       break;
11429     case MODOP_EXPR:
11430       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11431           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11432         {
11433           tree lhs = RECUR (TREE_OPERAND (incr, 0));
11434           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
11435                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
11436                                  TREE_TYPE (decl), lhs,
11437                                  RECUR (TREE_OPERAND (incr, 2))));
11438         }
11439       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
11440                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
11441                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
11442         {
11443           tree rhs = TREE_OPERAND (incr, 2);
11444           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11445                          RECUR (TREE_OPERAND (incr, 0)),
11446                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11447                                  RECUR (TREE_OPERAND (rhs, 0)),
11448                                  RECUR (TREE_OPERAND (rhs, 1))));
11449         }
11450       else
11451         incr = RECUR (incr);
11452       break;
11453     default:
11454       incr = RECUR (incr);
11455       break;
11456     }
11457
11458   TREE_VEC_ELT (declv, i) = decl;
11459   TREE_VEC_ELT (initv, i) = init;
11460   TREE_VEC_ELT (condv, i) = cond;
11461   TREE_VEC_ELT (incrv, i) = incr;
11462 #undef RECUR
11463 }
11464
11465 /* Like tsubst_copy for expressions, etc. but also does semantic
11466    processing.  */
11467
11468 static tree
11469 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
11470              bool integral_constant_expression_p)
11471 {
11472 #define RECUR(NODE)                             \
11473   tsubst_expr ((NODE), args, complain, in_decl, \
11474                integral_constant_expression_p)
11475
11476   tree stmt, tmp;
11477
11478   if (t == NULL_TREE || t == error_mark_node)
11479     return t;
11480
11481   if (EXPR_HAS_LOCATION (t))
11482     input_location = EXPR_LOCATION (t);
11483   if (STATEMENT_CODE_P (TREE_CODE (t)))
11484     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
11485
11486   switch (TREE_CODE (t))
11487     {
11488     case STATEMENT_LIST:
11489       {
11490         tree_stmt_iterator i;
11491         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
11492           RECUR (tsi_stmt (i));
11493         break;
11494       }
11495
11496     case CTOR_INITIALIZER:
11497       finish_mem_initializers (tsubst_initializer_list
11498                                (TREE_OPERAND (t, 0), args));
11499       break;
11500
11501     case RETURN_EXPR:
11502       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
11503       break;
11504
11505     case EXPR_STMT:
11506       tmp = RECUR (EXPR_STMT_EXPR (t));
11507       if (EXPR_STMT_STMT_EXPR_RESULT (t))
11508         finish_stmt_expr_expr (tmp, cur_stmt_expr);
11509       else
11510         finish_expr_stmt (tmp);
11511       break;
11512
11513     case USING_STMT:
11514       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
11515       break;
11516
11517     case DECL_EXPR:
11518       {
11519         tree decl;
11520         tree init;
11521
11522         decl = DECL_EXPR_DECL (t);
11523         if (TREE_CODE (decl) == LABEL_DECL)
11524           finish_label_decl (DECL_NAME (decl));
11525         else if (TREE_CODE (decl) == USING_DECL)
11526           {
11527             tree scope = USING_DECL_SCOPE (decl);
11528             tree name = DECL_NAME (decl);
11529             tree decl;
11530
11531             scope = RECUR (scope);
11532             decl = lookup_qualified_name (scope, name,
11533                                           /*is_type_p=*/false,
11534                                           /*complain=*/false);
11535             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
11536               qualified_name_lookup_error (scope, name, decl, input_location);
11537             else
11538               do_local_using_decl (decl, scope, name);
11539           }
11540         else
11541           {
11542             init = DECL_INITIAL (decl);
11543             decl = tsubst (decl, args, complain, in_decl);
11544             if (decl != error_mark_node)
11545               {
11546                 /* By marking the declaration as instantiated, we avoid
11547                    trying to instantiate it.  Since instantiate_decl can't
11548                    handle local variables, and since we've already done
11549                    all that needs to be done, that's the right thing to
11550                    do.  */
11551                 if (TREE_CODE (decl) == VAR_DECL)
11552                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11553                 if (TREE_CODE (decl) == VAR_DECL
11554                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
11555                   /* Anonymous aggregates are a special case.  */
11556                   finish_anon_union (decl);
11557                 else
11558                   {
11559                     maybe_push_decl (decl);
11560                     if (TREE_CODE (decl) == VAR_DECL
11561                         && DECL_PRETTY_FUNCTION_P (decl))
11562                       {
11563                         /* For __PRETTY_FUNCTION__ we have to adjust the
11564                            initializer.  */
11565                         const char *const name
11566                           = cxx_printable_name (current_function_decl, 2);
11567                         init = cp_fname_init (name, &TREE_TYPE (decl));
11568                       }
11569                     else
11570                       {
11571                         tree t = RECUR (init);
11572
11573                         if (init && !t)
11574                           /* If we had an initializer but it
11575                              instantiated to nothing,
11576                              value-initialize the object.  This will
11577                              only occur when the initializer was a
11578                              pack expansion where the parameter packs
11579                              used in that expansion were of length
11580                              zero.  */
11581                           init = build_value_init (TREE_TYPE (decl));
11582                         else
11583                           init = t;
11584                       }
11585
11586                     cp_finish_decl (decl, init, false, NULL_TREE, 0);
11587                   }
11588               }
11589           }
11590
11591         /* A DECL_EXPR can also be used as an expression, in the condition
11592            clause of an if/for/while construct.  */
11593         return decl;
11594       }
11595
11596     case FOR_STMT:
11597       stmt = begin_for_stmt ();
11598                           RECUR (FOR_INIT_STMT (t));
11599       finish_for_init_stmt (stmt);
11600       tmp = RECUR (FOR_COND (t));
11601       finish_for_cond (tmp, stmt);
11602       tmp = RECUR (FOR_EXPR (t));
11603       finish_for_expr (tmp, stmt);
11604       RECUR (FOR_BODY (t));
11605       finish_for_stmt (stmt);
11606       break;
11607
11608     case WHILE_STMT:
11609       stmt = begin_while_stmt ();
11610       tmp = RECUR (WHILE_COND (t));
11611       finish_while_stmt_cond (tmp, stmt);
11612       RECUR (WHILE_BODY (t));
11613       finish_while_stmt (stmt);
11614       break;
11615
11616     case DO_STMT:
11617       stmt = begin_do_stmt ();
11618       RECUR (DO_BODY (t));
11619       finish_do_body (stmt);
11620       tmp = RECUR (DO_COND (t));
11621       finish_do_stmt (tmp, stmt);
11622       break;
11623
11624     case IF_STMT:
11625       stmt = begin_if_stmt ();
11626       tmp = RECUR (IF_COND (t));
11627       finish_if_stmt_cond (tmp, stmt);
11628       RECUR (THEN_CLAUSE (t));
11629       finish_then_clause (stmt);
11630
11631       if (ELSE_CLAUSE (t))
11632         {
11633           begin_else_clause (stmt);
11634           RECUR (ELSE_CLAUSE (t));
11635           finish_else_clause (stmt);
11636         }
11637
11638       finish_if_stmt (stmt);
11639       break;
11640
11641     case BIND_EXPR:
11642       if (BIND_EXPR_BODY_BLOCK (t))
11643         stmt = begin_function_body ();
11644       else
11645         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
11646                                     ? BCS_TRY_BLOCK : 0);
11647
11648       RECUR (BIND_EXPR_BODY (t));
11649
11650       if (BIND_EXPR_BODY_BLOCK (t))
11651         finish_function_body (stmt);
11652       else
11653         finish_compound_stmt (stmt);
11654       break;
11655
11656     case BREAK_STMT:
11657       finish_break_stmt ();
11658       break;
11659
11660     case CONTINUE_STMT:
11661       finish_continue_stmt ();
11662       break;
11663
11664     case SWITCH_STMT:
11665       stmt = begin_switch_stmt ();
11666       tmp = RECUR (SWITCH_STMT_COND (t));
11667       finish_switch_cond (tmp, stmt);
11668       RECUR (SWITCH_STMT_BODY (t));
11669       finish_switch_stmt (stmt);
11670       break;
11671
11672     case CASE_LABEL_EXPR:
11673       finish_case_label (EXPR_LOCATION (t),
11674                          RECUR (CASE_LOW (t)),
11675                          RECUR (CASE_HIGH (t)));
11676       break;
11677
11678     case LABEL_EXPR:
11679       {
11680         tree decl = LABEL_EXPR_LABEL (t);
11681         tree label;
11682
11683         label = finish_label_stmt (DECL_NAME (decl));
11684         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
11685           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
11686       }
11687       break;
11688
11689     case GOTO_EXPR:
11690       tmp = GOTO_DESTINATION (t);
11691       if (TREE_CODE (tmp) != LABEL_DECL)
11692         /* Computed goto's must be tsubst'd into.  On the other hand,
11693            non-computed gotos must not be; the identifier in question
11694            will have no binding.  */
11695         tmp = RECUR (tmp);
11696       else
11697         tmp = DECL_NAME (tmp);
11698       finish_goto_stmt (tmp);
11699       break;
11700
11701     case ASM_EXPR:
11702       tmp = finish_asm_stmt
11703         (ASM_VOLATILE_P (t),
11704          RECUR (ASM_STRING (t)),
11705          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
11706          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
11707          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
11708          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
11709       {
11710         tree asm_expr = tmp;
11711         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
11712           asm_expr = TREE_OPERAND (asm_expr, 0);
11713         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
11714       }
11715       break;
11716
11717     case TRY_BLOCK:
11718       if (CLEANUP_P (t))
11719         {
11720           stmt = begin_try_block ();
11721           RECUR (TRY_STMTS (t));
11722           finish_cleanup_try_block (stmt);
11723           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
11724         }
11725       else
11726         {
11727           tree compound_stmt = NULL_TREE;
11728
11729           if (FN_TRY_BLOCK_P (t))
11730             stmt = begin_function_try_block (&compound_stmt);
11731           else
11732             stmt = begin_try_block ();
11733
11734           RECUR (TRY_STMTS (t));
11735
11736           if (FN_TRY_BLOCK_P (t))
11737             finish_function_try_block (stmt);
11738           else
11739             finish_try_block (stmt);
11740
11741           RECUR (TRY_HANDLERS (t));
11742           if (FN_TRY_BLOCK_P (t))
11743             finish_function_handler_sequence (stmt, compound_stmt);
11744           else
11745             finish_handler_sequence (stmt);
11746         }
11747       break;
11748
11749     case HANDLER:
11750       {
11751         tree decl = HANDLER_PARMS (t);
11752
11753         if (decl)
11754           {
11755             decl = tsubst (decl, args, complain, in_decl);
11756             /* Prevent instantiate_decl from trying to instantiate
11757                this variable.  We've already done all that needs to be
11758                done.  */
11759             if (decl != error_mark_node)
11760               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11761           }
11762         stmt = begin_handler ();
11763         finish_handler_parms (decl, stmt);
11764         RECUR (HANDLER_BODY (t));
11765         finish_handler (stmt);
11766       }
11767       break;
11768
11769     case TAG_DEFN:
11770       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
11771       break;
11772
11773     case STATIC_ASSERT:
11774       {
11775         tree condition = 
11776           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
11777                        args,
11778                        complain, in_decl,
11779                        /*integral_constant_expression_p=*/true);
11780         finish_static_assert (condition,
11781                               STATIC_ASSERT_MESSAGE (t),
11782                               STATIC_ASSERT_SOURCE_LOCATION (t),
11783                               /*member_p=*/false);
11784       }
11785       break;
11786
11787     case OMP_PARALLEL:
11788       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
11789                                 args, complain, in_decl);
11790       stmt = begin_omp_parallel ();
11791       RECUR (OMP_PARALLEL_BODY (t));
11792       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
11793         = OMP_PARALLEL_COMBINED (t);
11794       break;
11795
11796     case OMP_TASK:
11797       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
11798                                 args, complain, in_decl);
11799       stmt = begin_omp_task ();
11800       RECUR (OMP_TASK_BODY (t));
11801       finish_omp_task (tmp, stmt);
11802       break;
11803
11804     case OMP_FOR:
11805       {
11806         tree clauses, body, pre_body;
11807         tree declv, initv, condv, incrv;
11808         int i;
11809
11810         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
11811                                       args, complain, in_decl);
11812         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11813         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11814         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11815         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11816
11817         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
11818           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
11819                                    &clauses, args, complain, in_decl,
11820                                    integral_constant_expression_p);
11821
11822         stmt = begin_omp_structured_block ();
11823
11824         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
11825           if (TREE_VEC_ELT (initv, i) == NULL
11826               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
11827             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
11828           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
11829             {
11830               tree init = RECUR (TREE_VEC_ELT (initv, i));
11831               gcc_assert (init == TREE_VEC_ELT (declv, i));
11832               TREE_VEC_ELT (initv, i) = NULL_TREE;
11833             }
11834           else
11835             {
11836               tree decl_expr = TREE_VEC_ELT (initv, i);
11837               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
11838               gcc_assert (init != NULL);
11839               TREE_VEC_ELT (initv, i) = RECUR (init);
11840               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
11841               RECUR (decl_expr);
11842               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
11843             }
11844
11845         pre_body = push_stmt_list ();
11846         RECUR (OMP_FOR_PRE_BODY (t));
11847         pre_body = pop_stmt_list (pre_body);
11848
11849         body = push_stmt_list ();
11850         RECUR (OMP_FOR_BODY (t));
11851         body = pop_stmt_list (body);
11852
11853         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
11854                             body, pre_body, clauses);
11855
11856         add_stmt (finish_omp_structured_block (stmt));
11857       }
11858       break;
11859
11860     case OMP_SECTIONS:
11861     case OMP_SINGLE:
11862       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
11863       stmt = push_stmt_list ();
11864       RECUR (OMP_BODY (t));
11865       stmt = pop_stmt_list (stmt);
11866
11867       t = copy_node (t);
11868       OMP_BODY (t) = stmt;
11869       OMP_CLAUSES (t) = tmp;
11870       add_stmt (t);
11871       break;
11872
11873     case OMP_SECTION:
11874     case OMP_CRITICAL:
11875     case OMP_MASTER:
11876     case OMP_ORDERED:
11877       stmt = push_stmt_list ();
11878       RECUR (OMP_BODY (t));
11879       stmt = pop_stmt_list (stmt);
11880
11881       t = copy_node (t);
11882       OMP_BODY (t) = stmt;
11883       add_stmt (t);
11884       break;
11885
11886     case OMP_ATOMIC:
11887       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
11888       {
11889         tree op1 = TREE_OPERAND (t, 1);
11890         tree lhs = RECUR (TREE_OPERAND (op1, 0));
11891         tree rhs = RECUR (TREE_OPERAND (op1, 1));
11892         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
11893       }
11894       break;
11895
11896     case EXPR_PACK_EXPANSION:
11897       error ("invalid use of pack expansion expression");
11898       return error_mark_node;
11899
11900     case NONTYPE_ARGUMENT_PACK:
11901       error ("use %<...%> to expand argument pack");
11902       return error_mark_node;
11903
11904     default:
11905       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
11906
11907       return tsubst_copy_and_build (t, args, complain, in_decl,
11908                                     /*function_p=*/false,
11909                                     integral_constant_expression_p);
11910     }
11911
11912   return NULL_TREE;
11913 #undef RECUR
11914 }
11915
11916 /* T is a postfix-expression that is not being used in a function
11917    call.  Return the substituted version of T.  */
11918
11919 static tree
11920 tsubst_non_call_postfix_expression (tree t, tree args,
11921                                     tsubst_flags_t complain,
11922                                     tree in_decl)
11923 {
11924   if (TREE_CODE (t) == SCOPE_REF)
11925     t = tsubst_qualified_id (t, args, complain, in_decl,
11926                              /*done=*/false, /*address_p=*/false);
11927   else
11928     t = tsubst_copy_and_build (t, args, complain, in_decl,
11929                                /*function_p=*/false,
11930                                /*integral_constant_expression_p=*/false);
11931
11932   return t;
11933 }
11934
11935 /* Like tsubst but deals with expressions and performs semantic
11936    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
11937
11938 tree
11939 tsubst_copy_and_build (tree t,
11940                        tree args,
11941                        tsubst_flags_t complain,
11942                        tree in_decl,
11943                        bool function_p,
11944                        bool integral_constant_expression_p)
11945 {
11946 #define RECUR(NODE)                                             \
11947   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
11948                          /*function_p=*/false,                  \
11949                          integral_constant_expression_p)
11950
11951   tree op1;
11952
11953   if (t == NULL_TREE || t == error_mark_node)
11954     return t;
11955
11956   switch (TREE_CODE (t))
11957     {
11958     case USING_DECL:
11959       t = DECL_NAME (t);
11960       /* Fall through.  */
11961     case IDENTIFIER_NODE:
11962       {
11963         tree decl;
11964         cp_id_kind idk;
11965         bool non_integral_constant_expression_p;
11966         const char *error_msg;
11967
11968         if (IDENTIFIER_TYPENAME_P (t))
11969           {
11970             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11971             t = mangle_conv_op_name_for_type (new_type);
11972           }
11973
11974         /* Look up the name.  */
11975         decl = lookup_name (t);
11976
11977         /* By convention, expressions use ERROR_MARK_NODE to indicate
11978            failure, not NULL_TREE.  */
11979         if (decl == NULL_TREE)
11980           decl = error_mark_node;
11981
11982         decl = finish_id_expression (t, decl, NULL_TREE,
11983                                      &idk,
11984                                      integral_constant_expression_p,
11985                                      /*allow_non_integral_constant_expression_p=*/false,
11986                                      &non_integral_constant_expression_p,
11987                                      /*template_p=*/false,
11988                                      /*done=*/true,
11989                                      /*address_p=*/false,
11990                                      /*template_arg_p=*/false,
11991                                      &error_msg,
11992                                      input_location);
11993         if (error_msg)
11994           error (error_msg);
11995         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
11996           decl = unqualified_name_lookup_error (decl);
11997         return decl;
11998       }
11999
12000     case TEMPLATE_ID_EXPR:
12001       {
12002         tree object;
12003         tree templ = RECUR (TREE_OPERAND (t, 0));
12004         tree targs = TREE_OPERAND (t, 1);
12005
12006         if (targs)
12007           targs = tsubst_template_args (targs, args, complain, in_decl);
12008
12009         if (TREE_CODE (templ) == COMPONENT_REF)
12010           {
12011             object = TREE_OPERAND (templ, 0);
12012             templ = TREE_OPERAND (templ, 1);
12013           }
12014         else
12015           object = NULL_TREE;
12016         templ = lookup_template_function (templ, targs);
12017
12018         if (object)
12019           return build3 (COMPONENT_REF, TREE_TYPE (templ),
12020                          object, templ, NULL_TREE);
12021         else
12022           return baselink_for_fns (templ);
12023       }
12024
12025     case INDIRECT_REF:
12026       {
12027         tree r = RECUR (TREE_OPERAND (t, 0));
12028
12029         if (REFERENCE_REF_P (t))
12030           {
12031             /* A type conversion to reference type will be enclosed in
12032                such an indirect ref, but the substitution of the cast
12033                will have also added such an indirect ref.  */
12034             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
12035               r = convert_from_reference (r);
12036           }
12037         else
12038           r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
12039         return r;
12040       }
12041
12042     case NOP_EXPR:
12043       return build_nop
12044         (tsubst (TREE_TYPE (t), args, complain, in_decl),
12045          RECUR (TREE_OPERAND (t, 0)));
12046
12047     case CAST_EXPR:
12048     case REINTERPRET_CAST_EXPR:
12049     case CONST_CAST_EXPR:
12050     case DYNAMIC_CAST_EXPR:
12051     case STATIC_CAST_EXPR:
12052       {
12053         tree type;
12054         tree op;
12055
12056         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12057         if (integral_constant_expression_p
12058             && !cast_valid_in_integral_constant_expression_p (type))
12059           {
12060             if (complain & tf_error)
12061               error ("a cast to a type other than an integral or "
12062                      "enumeration type cannot appear in a constant-expression");
12063             return error_mark_node; 
12064           }
12065
12066         op = RECUR (TREE_OPERAND (t, 0));
12067
12068         switch (TREE_CODE (t))
12069           {
12070           case CAST_EXPR:
12071             return build_functional_cast (type, op, complain);
12072           case REINTERPRET_CAST_EXPR:
12073             return build_reinterpret_cast (type, op, complain);
12074           case CONST_CAST_EXPR:
12075             return build_const_cast (type, op, complain);
12076           case DYNAMIC_CAST_EXPR:
12077             return build_dynamic_cast (type, op, complain);
12078           case STATIC_CAST_EXPR:
12079             return build_static_cast (type, op, complain);
12080           default:
12081             gcc_unreachable ();
12082           }
12083       }
12084
12085     case POSTDECREMENT_EXPR:
12086     case POSTINCREMENT_EXPR:
12087       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12088                                                 args, complain, in_decl);
12089       return build_x_unary_op (TREE_CODE (t), op1, complain);
12090
12091     case PREDECREMENT_EXPR:
12092     case PREINCREMENT_EXPR:
12093     case NEGATE_EXPR:
12094     case BIT_NOT_EXPR:
12095     case ABS_EXPR:
12096     case TRUTH_NOT_EXPR:
12097     case UNARY_PLUS_EXPR:  /* Unary + */
12098     case REALPART_EXPR:
12099     case IMAGPART_EXPR:
12100       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
12101                                complain);
12102
12103     case ADDR_EXPR:
12104       op1 = TREE_OPERAND (t, 0);
12105       if (TREE_CODE (op1) == SCOPE_REF)
12106         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
12107                                    /*done=*/true, /*address_p=*/true);
12108       else
12109         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
12110                                                   in_decl);
12111       if (TREE_CODE (op1) == LABEL_DECL)
12112         return finish_label_address_expr (DECL_NAME (op1),
12113                                           EXPR_LOCATION (op1));
12114       return build_x_unary_op (ADDR_EXPR, op1, complain);
12115
12116     case PLUS_EXPR:
12117     case MINUS_EXPR:
12118     case MULT_EXPR:
12119     case TRUNC_DIV_EXPR:
12120     case CEIL_DIV_EXPR:
12121     case FLOOR_DIV_EXPR:
12122     case ROUND_DIV_EXPR:
12123     case EXACT_DIV_EXPR:
12124     case BIT_AND_EXPR:
12125     case BIT_IOR_EXPR:
12126     case BIT_XOR_EXPR:
12127     case TRUNC_MOD_EXPR:
12128     case FLOOR_MOD_EXPR:
12129     case TRUTH_ANDIF_EXPR:
12130     case TRUTH_ORIF_EXPR:
12131     case TRUTH_AND_EXPR:
12132     case TRUTH_OR_EXPR:
12133     case RSHIFT_EXPR:
12134     case LSHIFT_EXPR:
12135     case RROTATE_EXPR:
12136     case LROTATE_EXPR:
12137     case EQ_EXPR:
12138     case NE_EXPR:
12139     case MAX_EXPR:
12140     case MIN_EXPR:
12141     case LE_EXPR:
12142     case GE_EXPR:
12143     case LT_EXPR:
12144     case GT_EXPR:
12145     case MEMBER_REF:
12146     case DOTSTAR_EXPR:
12147       return build_x_binary_op
12148         (TREE_CODE (t),
12149          RECUR (TREE_OPERAND (t, 0)),
12150          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
12151           ? ERROR_MARK
12152           : TREE_CODE (TREE_OPERAND (t, 0))),
12153          RECUR (TREE_OPERAND (t, 1)),
12154          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
12155           ? ERROR_MARK
12156           : TREE_CODE (TREE_OPERAND (t, 1))),
12157          /*overloaded_p=*/NULL,
12158          complain);
12159
12160     case SCOPE_REF:
12161       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
12162                                   /*address_p=*/false);
12163     case ARRAY_REF:
12164       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12165                                                 args, complain, in_decl);
12166       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
12167
12168     case SIZEOF_EXPR:
12169       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
12170         return tsubst_copy (t, args, complain, in_decl);
12171       /* Fall through */
12172       
12173     case ALIGNOF_EXPR:
12174       op1 = TREE_OPERAND (t, 0);
12175       if (!args)
12176         {
12177           /* When there are no ARGS, we are trying to evaluate a
12178              non-dependent expression from the parser.  Trying to do
12179              the substitutions may not work.  */
12180           if (!TYPE_P (op1))
12181             op1 = TREE_TYPE (op1);
12182         }
12183       else
12184         {
12185           ++cp_unevaluated_operand;
12186           ++c_inhibit_evaluation_warnings;
12187           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12188                                        /*function_p=*/false,
12189                                        /*integral_constant_expression_p=*/false);
12190           --cp_unevaluated_operand;
12191           --c_inhibit_evaluation_warnings;
12192         }
12193       if (TYPE_P (op1))
12194         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
12195                                            complain & tf_error);
12196       else
12197         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
12198                                            complain & tf_error);
12199
12200     case MODOP_EXPR:
12201       {
12202         tree r = build_x_modify_expr
12203           (RECUR (TREE_OPERAND (t, 0)),
12204            TREE_CODE (TREE_OPERAND (t, 1)),
12205            RECUR (TREE_OPERAND (t, 2)),
12206            complain);
12207         /* TREE_NO_WARNING must be set if either the expression was
12208            parenthesized or it uses an operator such as >>= rather
12209            than plain assignment.  In the former case, it was already
12210            set and must be copied.  In the latter case,
12211            build_x_modify_expr sets it and it must not be reset
12212            here.  */
12213         if (TREE_NO_WARNING (t))
12214           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12215         return r;
12216       }
12217
12218     case ARROW_EXPR:
12219       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12220                                                 args, complain, in_decl);
12221       /* Remember that there was a reference to this entity.  */
12222       if (DECL_P (op1))
12223         mark_used (op1);
12224       return build_x_arrow (op1);
12225
12226     case NEW_EXPR:
12227       {
12228         tree placement = RECUR (TREE_OPERAND (t, 0));
12229         tree init = RECUR (TREE_OPERAND (t, 3));
12230         VEC(tree,gc) *placement_vec;
12231         VEC(tree,gc) *init_vec;
12232         tree ret;
12233
12234         if (placement == NULL_TREE)
12235           placement_vec = NULL;
12236         else
12237           {
12238             placement_vec = make_tree_vector ();
12239             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
12240               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
12241           }
12242
12243         /* If there was an initializer in the original tree, but it
12244            instantiated to an empty list, then we should pass a
12245            non-NULL empty vector to tell build_new that it was an
12246            empty initializer() rather than no initializer.  This can
12247            only happen when the initializer is a pack expansion whose
12248            parameter packs are of length zero.  */
12249         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
12250           init_vec = NULL;
12251         else
12252           {
12253             init_vec = make_tree_vector ();
12254             if (init == void_zero_node)
12255               gcc_assert (init_vec != NULL);
12256             else
12257               {
12258                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
12259                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
12260               }
12261           }
12262
12263         ret = build_new (&placement_vec,
12264                          RECUR (TREE_OPERAND (t, 1)),
12265                          RECUR (TREE_OPERAND (t, 2)),
12266                          &init_vec,
12267                          NEW_EXPR_USE_GLOBAL (t),
12268                          complain);
12269
12270         if (placement_vec != NULL)
12271           release_tree_vector (placement_vec);
12272         if (init_vec != NULL)
12273           release_tree_vector (init_vec);
12274
12275         return ret;
12276       }
12277
12278     case DELETE_EXPR:
12279      return delete_sanity
12280        (RECUR (TREE_OPERAND (t, 0)),
12281         RECUR (TREE_OPERAND (t, 1)),
12282         DELETE_EXPR_USE_VEC (t),
12283         DELETE_EXPR_USE_GLOBAL (t));
12284
12285     case COMPOUND_EXPR:
12286       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
12287                                     RECUR (TREE_OPERAND (t, 1)),
12288                                     complain);
12289
12290     case CALL_EXPR:
12291       {
12292         tree function;
12293         VEC(tree,gc) *call_args;
12294         unsigned int nargs, i;
12295         bool qualified_p;
12296         bool koenig_p;
12297         tree ret;
12298
12299         function = CALL_EXPR_FN (t);
12300         /* When we parsed the expression,  we determined whether or
12301            not Koenig lookup should be performed.  */
12302         koenig_p = KOENIG_LOOKUP_P (t);
12303         if (TREE_CODE (function) == SCOPE_REF)
12304           {
12305             qualified_p = true;
12306             function = tsubst_qualified_id (function, args, complain, in_decl,
12307                                             /*done=*/false,
12308                                             /*address_p=*/false);
12309           }
12310         else
12311           {
12312             if (TREE_CODE (function) == COMPONENT_REF)
12313               {
12314                 tree op = TREE_OPERAND (function, 1);
12315
12316                 qualified_p = (TREE_CODE (op) == SCOPE_REF
12317                                || (BASELINK_P (op)
12318                                    && BASELINK_QUALIFIED_P (op)));
12319               }
12320             else
12321               qualified_p = false;
12322
12323             function = tsubst_copy_and_build (function, args, complain,
12324                                               in_decl,
12325                                               !qualified_p,
12326                                               integral_constant_expression_p);
12327
12328             if (BASELINK_P (function))
12329               qualified_p = true;
12330           }
12331
12332         nargs = call_expr_nargs (t);
12333         call_args = make_tree_vector ();
12334         for (i = 0; i < nargs; ++i)
12335           {
12336             tree arg = CALL_EXPR_ARG (t, i);
12337
12338             if (!PACK_EXPANSION_P (arg))
12339               VEC_safe_push (tree, gc, call_args,
12340                              RECUR (CALL_EXPR_ARG (t, i)));
12341             else
12342               {
12343                 /* Expand the pack expansion and push each entry onto
12344                    CALL_ARGS.  */
12345                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
12346                 if (TREE_CODE (arg) == TREE_VEC)
12347                   {
12348                     unsigned int len, j;
12349
12350                     len = TREE_VEC_LENGTH (arg);
12351                     for (j = 0; j < len; ++j)
12352                       {
12353                         tree value = TREE_VEC_ELT (arg, j);
12354                         if (value != NULL_TREE)
12355                           value = convert_from_reference (value);
12356                         VEC_safe_push (tree, gc, call_args, value);
12357                       }
12358                   }
12359                 else
12360                   {
12361                     /* A partial substitution.  Add one entry.  */
12362                     VEC_safe_push (tree, gc, call_args, arg);
12363                   }
12364               }
12365           }
12366
12367         /* We do not perform argument-dependent lookup if normal
12368            lookup finds a non-function, in accordance with the
12369            expected resolution of DR 218.  */
12370         if (koenig_p
12371             && ((is_overloaded_fn (function)
12372                  /* If lookup found a member function, the Koenig lookup is
12373                     not appropriate, even if an unqualified-name was used
12374                     to denote the function.  */
12375                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
12376                 || TREE_CODE (function) == IDENTIFIER_NODE)
12377             /* Only do this when substitution turns a dependent call
12378                into a non-dependent call.  */
12379             && type_dependent_expression_p_push (t)
12380             && !any_type_dependent_arguments_p (call_args))
12381           function = perform_koenig_lookup (function, call_args);
12382
12383         if (TREE_CODE (function) == IDENTIFIER_NODE)
12384           {
12385             unqualified_name_lookup_error (function);
12386             release_tree_vector (call_args);
12387             return error_mark_node;
12388           }
12389
12390         /* Remember that there was a reference to this entity.  */
12391         if (DECL_P (function))
12392           mark_used (function);
12393
12394         if (TREE_CODE (function) == OFFSET_REF)
12395           ret = build_offset_ref_call_from_tree (function, &call_args);
12396         else if (TREE_CODE (function) == COMPONENT_REF)
12397           {
12398             if (!BASELINK_P (TREE_OPERAND (function, 1)))
12399               ret = finish_call_expr (function, &call_args,
12400                                        /*disallow_virtual=*/false,
12401                                        /*koenig_p=*/false,
12402                                        complain);
12403             else
12404               ret = (build_new_method_call
12405                       (TREE_OPERAND (function, 0),
12406                        TREE_OPERAND (function, 1),
12407                        &call_args, NULL_TREE,
12408                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
12409                        /*fn_p=*/NULL,
12410                        complain));
12411           }
12412         else
12413           ret = finish_call_expr (function, &call_args,
12414                                   /*disallow_virtual=*/qualified_p,
12415                                   koenig_p,
12416                                   complain);
12417
12418         release_tree_vector (call_args);
12419
12420         return ret;
12421       }
12422
12423     case COND_EXPR:
12424       return build_x_conditional_expr
12425         (RECUR (TREE_OPERAND (t, 0)),
12426          RECUR (TREE_OPERAND (t, 1)),
12427          RECUR (TREE_OPERAND (t, 2)),
12428          complain);
12429
12430     case PSEUDO_DTOR_EXPR:
12431       return finish_pseudo_destructor_expr
12432         (RECUR (TREE_OPERAND (t, 0)),
12433          RECUR (TREE_OPERAND (t, 1)),
12434          RECUR (TREE_OPERAND (t, 2)));
12435
12436     case TREE_LIST:
12437       {
12438         tree purpose, value, chain;
12439
12440         if (t == void_list_node)
12441           return t;
12442
12443         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
12444             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
12445           {
12446             /* We have pack expansions, so expand those and
12447                create a new list out of it.  */
12448             tree purposevec = NULL_TREE;
12449             tree valuevec = NULL_TREE;
12450             tree chain;
12451             int i, len = -1;
12452
12453             /* Expand the argument expressions.  */
12454             if (TREE_PURPOSE (t))
12455               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
12456                                                  complain, in_decl);
12457             if (TREE_VALUE (t))
12458               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
12459                                                complain, in_decl);
12460
12461             /* Build the rest of the list.  */
12462             chain = TREE_CHAIN (t);
12463             if (chain && chain != void_type_node)
12464               chain = RECUR (chain);
12465
12466             /* Determine the number of arguments.  */
12467             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
12468               {
12469                 len = TREE_VEC_LENGTH (purposevec);
12470                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
12471               }
12472             else if (TREE_CODE (valuevec) == TREE_VEC)
12473               len = TREE_VEC_LENGTH (valuevec);
12474             else
12475               {
12476                 /* Since we only performed a partial substitution into
12477                    the argument pack, we only return a single list
12478                    node.  */
12479                 if (purposevec == TREE_PURPOSE (t)
12480                     && valuevec == TREE_VALUE (t)
12481                     && chain == TREE_CHAIN (t))
12482                   return t;
12483
12484                 return tree_cons (purposevec, valuevec, chain);
12485               }
12486             
12487             /* Convert the argument vectors into a TREE_LIST */
12488             i = len;
12489             while (i > 0)
12490               {
12491                 /* Grab the Ith values.  */
12492                 i--;
12493                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
12494                                      : NULL_TREE;
12495                 value 
12496                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
12497                              : NULL_TREE;
12498
12499                 /* Build the list (backwards).  */
12500                 chain = tree_cons (purpose, value, chain);
12501               }
12502
12503             return chain;
12504           }
12505
12506         purpose = TREE_PURPOSE (t);
12507         if (purpose)
12508           purpose = RECUR (purpose);
12509         value = TREE_VALUE (t);
12510         if (value)
12511           value = RECUR (value);
12512         chain = TREE_CHAIN (t);
12513         if (chain && chain != void_type_node)
12514           chain = RECUR (chain);
12515         if (purpose == TREE_PURPOSE (t)
12516             && value == TREE_VALUE (t)
12517             && chain == TREE_CHAIN (t))
12518           return t;
12519         return tree_cons (purpose, value, chain);
12520       }
12521
12522     case COMPONENT_REF:
12523       {
12524         tree object;
12525         tree object_type;
12526         tree member;
12527
12528         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12529                                                      args, complain, in_decl);
12530         /* Remember that there was a reference to this entity.  */
12531         if (DECL_P (object))
12532           mark_used (object);
12533         object_type = TREE_TYPE (object);
12534
12535         member = TREE_OPERAND (t, 1);
12536         if (BASELINK_P (member))
12537           member = tsubst_baselink (member,
12538                                     non_reference (TREE_TYPE (object)),
12539                                     args, complain, in_decl);
12540         else
12541           member = tsubst_copy (member, args, complain, in_decl);
12542         if (member == error_mark_node)
12543           return error_mark_node;
12544
12545         if (object_type && !CLASS_TYPE_P (object_type))
12546           {
12547             if (SCALAR_TYPE_P (object_type))
12548               {
12549                 tree s = NULL_TREE;
12550                 tree dtor = member;
12551
12552                 if (TREE_CODE (dtor) == SCOPE_REF)
12553                   {
12554                     s = TREE_OPERAND (dtor, 0);
12555                     dtor = TREE_OPERAND (dtor, 1);
12556                   }
12557                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
12558                   {
12559                     dtor = TREE_OPERAND (dtor, 0);
12560                     if (TYPE_P (dtor))
12561                       return finish_pseudo_destructor_expr (object, s, dtor);
12562                   }
12563               }
12564           }
12565         else if (TREE_CODE (member) == SCOPE_REF
12566                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
12567           {
12568             tree tmpl;
12569             tree args;
12570
12571             /* Lookup the template functions now that we know what the
12572                scope is.  */
12573             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
12574             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
12575             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
12576                                             /*is_type_p=*/false,
12577                                             /*complain=*/false);
12578             if (BASELINK_P (member))
12579               {
12580                 BASELINK_FUNCTIONS (member)
12581                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
12582                               args);
12583                 member = (adjust_result_of_qualified_name_lookup
12584                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
12585                            object_type));
12586               }
12587             else
12588               {
12589                 qualified_name_lookup_error (object_type, tmpl, member,
12590                                              input_location);
12591                 return error_mark_node;
12592               }
12593           }
12594         else if (TREE_CODE (member) == SCOPE_REF
12595                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
12596                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
12597           {
12598             if (complain & tf_error)
12599               {
12600                 if (TYPE_P (TREE_OPERAND (member, 0)))
12601                   error ("%qT is not a class or namespace",
12602                          TREE_OPERAND (member, 0));
12603                 else
12604                   error ("%qD is not a class or namespace",
12605                          TREE_OPERAND (member, 0));
12606               }
12607             return error_mark_node;
12608           }
12609         else if (TREE_CODE (member) == FIELD_DECL)
12610           return finish_non_static_data_member (member, object, NULL_TREE);
12611
12612         return finish_class_member_access_expr (object, member,
12613                                                 /*template_p=*/false,
12614                                                 complain);
12615       }
12616
12617     case THROW_EXPR:
12618       return build_throw
12619         (RECUR (TREE_OPERAND (t, 0)));
12620
12621     case CONSTRUCTOR:
12622       {
12623         VEC(constructor_elt,gc) *n;
12624         constructor_elt *ce;
12625         unsigned HOST_WIDE_INT idx;
12626         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12627         bool process_index_p;
12628         int newlen;
12629         bool need_copy_p = false;
12630         tree r;
12631
12632         if (type == error_mark_node)
12633           return error_mark_node;
12634
12635         /* digest_init will do the wrong thing if we let it.  */
12636         if (type && TYPE_PTRMEMFUNC_P (type))
12637           return t;
12638
12639         /* We do not want to process the index of aggregate
12640            initializers as they are identifier nodes which will be
12641            looked up by digest_init.  */
12642         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
12643
12644         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
12645         newlen = VEC_length (constructor_elt, n);
12646         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
12647           {
12648             if (ce->index && process_index_p)
12649               ce->index = RECUR (ce->index);
12650
12651             if (PACK_EXPANSION_P (ce->value))
12652               {
12653                 /* Substitute into the pack expansion.  */
12654                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
12655                                                   in_decl);
12656
12657                 if (ce->value == error_mark_node)
12658                   ;
12659                 else if (TREE_VEC_LENGTH (ce->value) == 1)
12660                   /* Just move the argument into place.  */
12661                   ce->value = TREE_VEC_ELT (ce->value, 0);
12662                 else
12663                   {
12664                     /* Update the length of the final CONSTRUCTOR
12665                        arguments vector, and note that we will need to
12666                        copy.*/
12667                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
12668                     need_copy_p = true;
12669                   }
12670               }
12671             else
12672               ce->value = RECUR (ce->value);
12673           }
12674
12675         if (need_copy_p)
12676           {
12677             VEC(constructor_elt,gc) *old_n = n;
12678
12679             n = VEC_alloc (constructor_elt, gc, newlen);
12680             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
12681                  idx++)
12682               {
12683                 if (TREE_CODE (ce->value) == TREE_VEC)
12684                   {
12685                     int i, len = TREE_VEC_LENGTH (ce->value);
12686                     for (i = 0; i < len; ++i)
12687                       CONSTRUCTOR_APPEND_ELT (n, 0,
12688                                               TREE_VEC_ELT (ce->value, i));
12689                   }
12690                 else
12691                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
12692               }
12693           }
12694
12695         r = build_constructor (init_list_type_node, n);
12696         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
12697
12698         if (TREE_HAS_CONSTRUCTOR (t))
12699           return finish_compound_literal (type, r);
12700
12701         return r;
12702       }
12703
12704     case TYPEID_EXPR:
12705       {
12706         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
12707         if (TYPE_P (operand_0))
12708           return get_typeid (operand_0);
12709         return build_typeid (operand_0);
12710       }
12711
12712     case VAR_DECL:
12713       if (!args)
12714         return t;
12715       /* Fall through */
12716
12717     case PARM_DECL:
12718       {
12719         tree r = tsubst_copy (t, args, complain, in_decl);
12720
12721         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
12722           /* If the original type was a reference, we'll be wrapped in
12723              the appropriate INDIRECT_REF.  */
12724           r = convert_from_reference (r);
12725         return r;
12726       }
12727
12728     case VA_ARG_EXPR:
12729       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
12730                              tsubst_copy (TREE_TYPE (t), args, complain,
12731                                           in_decl));
12732
12733     case OFFSETOF_EXPR:
12734       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
12735
12736     case TRAIT_EXPR:
12737       {
12738         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
12739                                   complain, in_decl);
12740
12741         tree type2 = TRAIT_EXPR_TYPE2 (t);
12742         if (type2)
12743           type2 = tsubst_copy (type2, args, complain, in_decl);
12744         
12745         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
12746       }
12747
12748     case STMT_EXPR:
12749       {
12750         tree old_stmt_expr = cur_stmt_expr;
12751         tree stmt_expr = begin_stmt_expr ();
12752
12753         cur_stmt_expr = stmt_expr;
12754         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
12755                      integral_constant_expression_p);
12756         stmt_expr = finish_stmt_expr (stmt_expr, false);
12757         cur_stmt_expr = old_stmt_expr;
12758
12759         /* If the resulting list of expression statement is empty,
12760            fold it further into void_zero_node.  */
12761         if (empty_expr_stmt_p (stmt_expr))
12762           stmt_expr = void_zero_node;
12763
12764         return stmt_expr;
12765       }
12766
12767     case CONST_DECL:
12768       t = tsubst_copy (t, args, complain, in_decl);
12769       /* As in finish_id_expression, we resolve enumeration constants
12770          to their underlying values.  */
12771       if (TREE_CODE (t) == CONST_DECL)
12772         {
12773           used_types_insert (TREE_TYPE (t));
12774           return DECL_INITIAL (t);
12775         }
12776       return t;
12777
12778     case LAMBDA_EXPR:
12779       {
12780         tree r = build_lambda_expr ();
12781
12782         tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12783         TREE_TYPE (r) = type;
12784         CLASSTYPE_LAMBDA_EXPR (type) = r;
12785
12786         LAMBDA_EXPR_LOCATION (r)
12787           = LAMBDA_EXPR_LOCATION (t);
12788         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
12789           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
12790         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
12791         LAMBDA_EXPR_DISCRIMINATOR (r)
12792           = (LAMBDA_EXPR_DISCRIMINATOR (t));
12793         LAMBDA_EXPR_CAPTURE_LIST (r)
12794           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
12795         LAMBDA_EXPR_THIS_CAPTURE (r)
12796           = RECUR (LAMBDA_EXPR_THIS_CAPTURE (t));
12797         LAMBDA_EXPR_EXTRA_SCOPE (r)
12798           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
12799
12800         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
12801         determine_visibility (TYPE_NAME (type));
12802         /* Now that we know visibility, instantiate the type so we have a
12803            declaration of the op() for later calls to lambda_function.  */
12804         complete_type (type);
12805
12806         type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
12807         if (type)
12808           apply_lambda_return_type (r, type);
12809
12810         return build_lambda_object (r);
12811       }
12812
12813     default:
12814       /* Handle Objective-C++ constructs, if appropriate.  */
12815       {
12816         tree subst
12817           = objcp_tsubst_copy_and_build (t, args, complain,
12818                                          in_decl, /*function_p=*/false);
12819         if (subst)
12820           return subst;
12821       }
12822       return tsubst_copy (t, args, complain, in_decl);
12823     }
12824
12825 #undef RECUR
12826 }
12827
12828 /* Verify that the instantiated ARGS are valid. For type arguments,
12829    make sure that the type's linkage is ok. For non-type arguments,
12830    make sure they are constants if they are integral or enumerations.
12831    Emit an error under control of COMPLAIN, and return TRUE on error.  */
12832
12833 static bool
12834 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
12835 {
12836   if (ARGUMENT_PACK_P (t))
12837     {
12838       tree vec = ARGUMENT_PACK_ARGS (t);
12839       int len = TREE_VEC_LENGTH (vec);
12840       bool result = false;
12841       int i;
12842
12843       for (i = 0; i < len; ++i)
12844         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
12845           result = true;
12846       return result;
12847     }
12848   else if (TYPE_P (t))
12849     {
12850       /* [basic.link]: A name with no linkage (notably, the name
12851          of a class or enumeration declared in a local scope)
12852          shall not be used to declare an entity with linkage.
12853          This implies that names with no linkage cannot be used as
12854          template arguments
12855
12856          DR 757 relaxes this restriction for C++0x.  */
12857       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
12858                  : no_linkage_check (t, /*relaxed_p=*/false));
12859
12860       if (nt)
12861         {
12862           /* DR 488 makes use of a type with no linkage cause
12863              type deduction to fail.  */
12864           if (complain & tf_error)
12865             {
12866               if (TYPE_ANONYMOUS_P (nt))
12867                 error ("%qT is/uses anonymous type", t);
12868               else
12869                 error ("template argument for %qD uses local type %qT",
12870                        tmpl, t);
12871             }
12872           return true;
12873         }
12874       /* In order to avoid all sorts of complications, we do not
12875          allow variably-modified types as template arguments.  */
12876       else if (variably_modified_type_p (t, NULL_TREE))
12877         {
12878           if (complain & tf_error)
12879             error ("%qT is a variably modified type", t);
12880           return true;
12881         }
12882     }
12883   /* A non-type argument of integral or enumerated type must be a
12884      constant.  */
12885   else if (TREE_TYPE (t)
12886            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
12887            && !TREE_CONSTANT (t))
12888     {
12889       if (complain & tf_error)
12890         error ("integral expression %qE is not constant", t);
12891       return true;
12892     }
12893   return false;
12894 }
12895
12896 static bool
12897 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
12898 {
12899   int ix, len = DECL_NTPARMS (tmpl);
12900   bool result = false;
12901
12902   for (ix = 0; ix != len; ix++)
12903     {
12904       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
12905         result = true;
12906     }
12907   if (result && (complain & tf_error))
12908     error ("  trying to instantiate %qD", tmpl);
12909   return result;
12910 }
12911
12912 /* Instantiate the indicated variable or function template TMPL with
12913    the template arguments in TARG_PTR.  */
12914
12915 tree
12916 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
12917 {
12918   tree targ_ptr = orig_args;
12919   tree fndecl;
12920   tree gen_tmpl;
12921   tree spec;
12922   HOST_WIDE_INT saved_processing_template_decl;
12923
12924   if (tmpl == error_mark_node)
12925     return error_mark_node;
12926
12927   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
12928
12929   /* If this function is a clone, handle it specially.  */
12930   if (DECL_CLONED_FUNCTION_P (tmpl))
12931     {
12932       tree spec;
12933       tree clone;
12934
12935       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
12936          DECL_CLONED_FUNCTION.  */
12937       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
12938                                    targ_ptr, complain);
12939       if (spec == error_mark_node)
12940         return error_mark_node;
12941
12942       /* Look for the clone.  */
12943       FOR_EACH_CLONE (clone, spec)
12944         if (DECL_NAME (clone) == DECL_NAME (tmpl))
12945           return clone;
12946       /* We should always have found the clone by now.  */
12947       gcc_unreachable ();
12948       return NULL_TREE;
12949     }
12950
12951   /* Check to see if we already have this specialization.  */
12952   gen_tmpl = most_general_template (tmpl);
12953   if (tmpl != gen_tmpl)
12954     /* The TMPL is a partial instantiation.  To get a full set of
12955        arguments we must add the arguments used to perform the
12956        partial instantiation.  */
12957     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
12958                                             targ_ptr);
12959
12960   /* It would be nice to avoid hashing here and then again in tsubst_decl,
12961      but it doesn't seem to be on the hot path.  */
12962   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
12963
12964   gcc_assert (tmpl == gen_tmpl
12965               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
12966                   == spec)
12967               || fndecl == NULL_TREE);
12968
12969   if (spec != NULL_TREE)
12970     return spec;
12971
12972   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
12973                                complain))
12974     return error_mark_node;
12975
12976   /* We are building a FUNCTION_DECL, during which the access of its
12977      parameters and return types have to be checked.  However this
12978      FUNCTION_DECL which is the desired context for access checking
12979      is not built yet.  We solve this chicken-and-egg problem by
12980      deferring all checks until we have the FUNCTION_DECL.  */
12981   push_deferring_access_checks (dk_deferred);
12982
12983   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
12984      (because, for example, we have encountered a non-dependent
12985      function call in the body of a template function and must now
12986      determine which of several overloaded functions will be called),
12987      within the instantiation itself we are not processing a
12988      template.  */  
12989   saved_processing_template_decl = processing_template_decl;
12990   processing_template_decl = 0;
12991   /* Substitute template parameters to obtain the specialization.  */
12992   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
12993                    targ_ptr, complain, gen_tmpl);
12994   processing_template_decl = saved_processing_template_decl;
12995   if (fndecl == error_mark_node)
12996     return error_mark_node;
12997
12998   /* Now we know the specialization, compute access previously
12999      deferred.  */
13000   push_access_scope (fndecl);
13001
13002   /* Some typedefs referenced from within the template code need to be access
13003      checked at template instantiation time, i.e now. These types were
13004      added to the template at parsing time. Let's get those and perfom
13005      the acces checks then.  */
13006   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
13007   perform_deferred_access_checks ();
13008   pop_access_scope (fndecl);
13009   pop_deferring_access_checks ();
13010
13011   /* The DECL_TI_TEMPLATE should always be the immediate parent
13012      template, not the most general template.  */
13013   DECL_TI_TEMPLATE (fndecl) = tmpl;
13014
13015   /* If we've just instantiated the main entry point for a function,
13016      instantiate all the alternate entry points as well.  We do this
13017      by cloning the instantiation of the main entry point, not by
13018      instantiating the template clones.  */
13019   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
13020     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
13021
13022   return fndecl;
13023 }
13024
13025 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
13026    NARGS elements of the arguments that are being used when calling
13027    it.  TARGS is a vector into which the deduced template arguments
13028    are placed.
13029
13030    Return zero for success, 2 for an incomplete match that doesn't resolve
13031    all the types, and 1 for complete failure.  An error message will be
13032    printed only for an incomplete match.
13033
13034    If FN is a conversion operator, or we are trying to produce a specific
13035    specialization, RETURN_TYPE is the return type desired.
13036
13037    The EXPLICIT_TARGS are explicit template arguments provided via a
13038    template-id.
13039
13040    The parameter STRICT is one of:
13041
13042    DEDUCE_CALL:
13043      We are deducing arguments for a function call, as in
13044      [temp.deduct.call].
13045
13046    DEDUCE_CONV:
13047      We are deducing arguments for a conversion function, as in
13048      [temp.deduct.conv].
13049
13050    DEDUCE_EXACT:
13051      We are deducing arguments when doing an explicit instantiation
13052      as in [temp.explicit], when determining an explicit specialization
13053      as in [temp.expl.spec], or when taking the address of a function
13054      template, as in [temp.deduct.funcaddr].  */
13055
13056 int
13057 fn_type_unification (tree fn,
13058                      tree explicit_targs,
13059                      tree targs,
13060                      const tree *args,
13061                      unsigned int nargs,
13062                      tree return_type,
13063                      unification_kind_t strict,
13064                      int flags)
13065 {
13066   tree parms;
13067   tree fntype;
13068   int result;
13069   bool incomplete_argument_packs_p = false;
13070
13071   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
13072
13073   fntype = TREE_TYPE (fn);
13074   if (explicit_targs)
13075     {
13076       /* [temp.deduct]
13077
13078          The specified template arguments must match the template
13079          parameters in kind (i.e., type, nontype, template), and there
13080          must not be more arguments than there are parameters;
13081          otherwise type deduction fails.
13082
13083          Nontype arguments must match the types of the corresponding
13084          nontype template parameters, or must be convertible to the
13085          types of the corresponding nontype parameters as specified in
13086          _temp.arg.nontype_, otherwise type deduction fails.
13087
13088          All references in the function type of the function template
13089          to the corresponding template parameters are replaced by the
13090          specified template argument values.  If a substitution in a
13091          template parameter or in the function type of the function
13092          template results in an invalid type, type deduction fails.  */
13093       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
13094       int i, len = TREE_VEC_LENGTH (tparms);
13095       tree converted_args;
13096       bool incomplete = false;
13097
13098       if (explicit_targs == error_mark_node)
13099         return 1;
13100
13101       converted_args
13102         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
13103                                   /*require_all_args=*/false,
13104                                   /*use_default_args=*/false));
13105       if (converted_args == error_mark_node)
13106         return 1;
13107
13108       /* Substitute the explicit args into the function type.  This is
13109          necessary so that, for instance, explicitly declared function
13110          arguments can match null pointed constants.  If we were given
13111          an incomplete set of explicit args, we must not do semantic
13112          processing during substitution as we could create partial
13113          instantiations.  */
13114       for (i = 0; i < len; i++)
13115         {
13116           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13117           bool parameter_pack = false;
13118
13119           /* Dig out the actual parm.  */
13120           if (TREE_CODE (parm) == TYPE_DECL
13121               || TREE_CODE (parm) == TEMPLATE_DECL)
13122             {
13123               parm = TREE_TYPE (parm);
13124               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
13125             }
13126           else if (TREE_CODE (parm) == PARM_DECL)
13127             {
13128               parm = DECL_INITIAL (parm);
13129               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
13130             }
13131
13132           if (parameter_pack)
13133             {
13134               int level, idx;
13135               tree targ;
13136               template_parm_level_and_index (parm, &level, &idx);
13137
13138               /* Mark the argument pack as "incomplete". We could
13139                  still deduce more arguments during unification.  */
13140               targ = TMPL_ARG (converted_args, level, idx);
13141               if (targ)
13142                 {
13143                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
13144                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
13145                     = ARGUMENT_PACK_ARGS (targ);
13146                 }
13147
13148               /* We have some incomplete argument packs.  */
13149               incomplete_argument_packs_p = true;
13150             }
13151         }
13152
13153       if (incomplete_argument_packs_p)
13154         /* Any substitution is guaranteed to be incomplete if there
13155            are incomplete argument packs, because we can still deduce
13156            more arguments.  */
13157         incomplete = 1;
13158       else
13159         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
13160
13161       processing_template_decl += incomplete;
13162       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
13163       processing_template_decl -= incomplete;
13164
13165       if (fntype == error_mark_node)
13166         return 1;
13167
13168       /* Place the explicitly specified arguments in TARGS.  */
13169       for (i = NUM_TMPL_ARGS (converted_args); i--;)
13170         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
13171     }
13172
13173   /* Never do unification on the 'this' parameter.  */
13174   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
13175
13176   if (return_type)
13177     {
13178       tree *new_args;
13179
13180       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
13181       new_args = XALLOCAVEC (tree, nargs + 1);
13182       new_args[0] = return_type;
13183       memcpy (new_args + 1, args, nargs * sizeof (tree));
13184       args = new_args;
13185       ++nargs;
13186     }
13187
13188   /* We allow incomplete unification without an error message here
13189      because the standard doesn't seem to explicitly prohibit it.  Our
13190      callers must be ready to deal with unification failures in any
13191      event.  */
13192   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
13193                                   targs, parms, args, nargs, /*subr=*/0,
13194                                   strict, flags);
13195
13196   if (result == 0 && incomplete_argument_packs_p)
13197     {
13198       int i, len = NUM_TMPL_ARGS (targs);
13199
13200       /* Clear the "incomplete" flags on all argument packs.  */
13201       for (i = 0; i < len; i++)
13202         {
13203           tree arg = TREE_VEC_ELT (targs, i);
13204           if (ARGUMENT_PACK_P (arg))
13205             {
13206               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
13207               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
13208             }
13209         }
13210     }
13211
13212   /* Now that we have bindings for all of the template arguments,
13213      ensure that the arguments deduced for the template template
13214      parameters have compatible template parameter lists.  We cannot
13215      check this property before we have deduced all template
13216      arguments, because the template parameter types of a template
13217      template parameter might depend on prior template parameters
13218      deduced after the template template parameter.  The following
13219      ill-formed example illustrates this issue:
13220
13221        template<typename T, template<T> class C> void f(C<5>, T);
13222
13223        template<int N> struct X {};
13224
13225        void g() {
13226          f(X<5>(), 5l); // error: template argument deduction fails
13227        }
13228
13229      The template parameter list of 'C' depends on the template type
13230      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
13231      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
13232      time that we deduce 'C'.  */
13233   if (result == 0
13234       && !template_template_parm_bindings_ok_p 
13235            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
13236     return 1;
13237
13238   if (result == 0)
13239     /* All is well so far.  Now, check:
13240
13241        [temp.deduct]
13242
13243        When all template arguments have been deduced, all uses of
13244        template parameters in nondeduced contexts are replaced with
13245        the corresponding deduced argument values.  If the
13246        substitution results in an invalid type, as described above,
13247        type deduction fails.  */
13248     {
13249       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
13250       if (substed == error_mark_node)
13251         return 1;
13252
13253       /* If we're looking for an exact match, check that what we got
13254          is indeed an exact match.  It might not be if some template
13255          parameters are used in non-deduced contexts.  */
13256       if (strict == DEDUCE_EXACT)
13257         {
13258           unsigned int i;
13259
13260           tree sarg
13261             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
13262           if (return_type)
13263             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
13264           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
13265             if (!same_type_p (args[i], TREE_VALUE (sarg)))
13266               return 1;
13267         }
13268     }
13269
13270   return result;
13271 }
13272
13273 /* Adjust types before performing type deduction, as described in
13274    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
13275    sections are symmetric.  PARM is the type of a function parameter
13276    or the return type of the conversion function.  ARG is the type of
13277    the argument passed to the call, or the type of the value
13278    initialized with the result of the conversion function.
13279    ARG_EXPR is the original argument expression, which may be null.  */
13280
13281 static int
13282 maybe_adjust_types_for_deduction (unification_kind_t strict,
13283                                   tree* parm,
13284                                   tree* arg,
13285                                   tree arg_expr)
13286 {
13287   int result = 0;
13288
13289   switch (strict)
13290     {
13291     case DEDUCE_CALL:
13292       break;
13293
13294     case DEDUCE_CONV:
13295       {
13296         /* Swap PARM and ARG throughout the remainder of this
13297            function; the handling is precisely symmetric since PARM
13298            will initialize ARG rather than vice versa.  */
13299         tree* temp = parm;
13300         parm = arg;
13301         arg = temp;
13302         break;
13303       }
13304
13305     case DEDUCE_EXACT:
13306       /* Core issue #873: Do the DR606 thing (see below) for these cases,
13307          too, but here handle it by stripping the reference from PARM
13308          rather than by adding it to ARG.  */
13309       if (TREE_CODE (*parm) == REFERENCE_TYPE
13310           && TYPE_REF_IS_RVALUE (*parm)
13311           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13312           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13313           && TREE_CODE (*arg) == REFERENCE_TYPE
13314           && !TYPE_REF_IS_RVALUE (*arg))
13315         *parm = TREE_TYPE (*parm);
13316       /* Nothing else to do in this case.  */
13317       return 0;
13318
13319     default:
13320       gcc_unreachable ();
13321     }
13322
13323   if (TREE_CODE (*parm) != REFERENCE_TYPE)
13324     {
13325       /* [temp.deduct.call]
13326
13327          If P is not a reference type:
13328
13329          --If A is an array type, the pointer type produced by the
13330          array-to-pointer standard conversion (_conv.array_) is
13331          used in place of A for type deduction; otherwise,
13332
13333          --If A is a function type, the pointer type produced by
13334          the function-to-pointer standard conversion
13335          (_conv.func_) is used in place of A for type deduction;
13336          otherwise,
13337
13338          --If A is a cv-qualified type, the top level
13339          cv-qualifiers of A's type are ignored for type
13340          deduction.  */
13341       if (TREE_CODE (*arg) == ARRAY_TYPE)
13342         *arg = build_pointer_type (TREE_TYPE (*arg));
13343       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
13344         *arg = build_pointer_type (*arg);
13345       else
13346         *arg = TYPE_MAIN_VARIANT (*arg);
13347     }
13348
13349   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
13350      of the form T&&, where T is a template parameter, and the argument
13351      is an lvalue, T is deduced as A& */
13352   if (TREE_CODE (*parm) == REFERENCE_TYPE
13353       && TYPE_REF_IS_RVALUE (*parm)
13354       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13355       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13356       && arg_expr && real_lvalue_p (arg_expr))
13357     *arg = build_reference_type (*arg);
13358
13359   /* [temp.deduct.call]
13360
13361      If P is a cv-qualified type, the top level cv-qualifiers
13362      of P's type are ignored for type deduction.  If P is a
13363      reference type, the type referred to by P is used for
13364      type deduction.  */
13365   *parm = TYPE_MAIN_VARIANT (*parm);
13366   if (TREE_CODE (*parm) == REFERENCE_TYPE)
13367     {
13368       *parm = TREE_TYPE (*parm);
13369       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13370     }
13371
13372   /* DR 322. For conversion deduction, remove a reference type on parm
13373      too (which has been swapped into ARG).  */
13374   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
13375     *arg = TREE_TYPE (*arg);
13376
13377   return result;
13378 }
13379
13380 /* Most parms like fn_type_unification.
13381
13382    If SUBR is 1, we're being called recursively (to unify the
13383    arguments of a function or method parameter of a function
13384    template). */
13385
13386 static int
13387 type_unification_real (tree tparms,
13388                        tree targs,
13389                        tree xparms,
13390                        const tree *xargs,
13391                        unsigned int xnargs,
13392                        int subr,
13393                        unification_kind_t strict,
13394                        int flags)
13395 {
13396   tree parm, arg, arg_expr;
13397   int i;
13398   int ntparms = TREE_VEC_LENGTH (tparms);
13399   int sub_strict;
13400   int saw_undeduced = 0;
13401   tree parms;
13402   const tree *args;
13403   unsigned int nargs;
13404   unsigned int ia;
13405
13406   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
13407   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
13408   gcc_assert (ntparms > 0);
13409
13410   /* Reset the number of non-defaulted template arguments contained
13411      in in TARGS.  */
13412   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
13413
13414   switch (strict)
13415     {
13416     case DEDUCE_CALL:
13417       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
13418                     | UNIFY_ALLOW_DERIVED);
13419       break;
13420
13421     case DEDUCE_CONV:
13422       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13423       break;
13424
13425     case DEDUCE_EXACT:
13426       sub_strict = UNIFY_ALLOW_NONE;
13427       break;
13428
13429     default:
13430       gcc_unreachable ();
13431     }
13432
13433  again:
13434   parms = xparms;
13435   args = xargs;
13436   nargs = xnargs;
13437
13438   ia = 0;
13439   while (parms && parms != void_list_node
13440          && ia < nargs)
13441     {
13442       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13443         break;
13444
13445       parm = TREE_VALUE (parms);
13446       parms = TREE_CHAIN (parms);
13447       arg = args[ia];
13448       ++ia;
13449       arg_expr = NULL;
13450
13451       if (arg == error_mark_node)
13452         return 1;
13453       if (arg == unknown_type_node)
13454         /* We can't deduce anything from this, but we might get all the
13455            template args from other function args.  */
13456         continue;
13457
13458       /* Conversions will be performed on a function argument that
13459          corresponds with a function parameter that contains only
13460          non-deducible template parameters and explicitly specified
13461          template parameters.  */
13462       if (!uses_template_parms (parm))
13463         {
13464           tree type;
13465
13466           if (!TYPE_P (arg))
13467             type = TREE_TYPE (arg);
13468           else
13469             type = arg;
13470
13471           if (same_type_p (parm, type))
13472             continue;
13473           if (strict != DEDUCE_EXACT
13474               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
13475                                   flags))
13476             continue;
13477
13478           return 1;
13479         }
13480
13481       if (!TYPE_P (arg))
13482         {
13483           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13484           if (type_unknown_p (arg))
13485             {
13486               /* [temp.deduct.type] 
13487
13488                  A template-argument can be deduced from a pointer to
13489                  function or pointer to member function argument if
13490                  the set of overloaded functions does not contain
13491                  function templates and at most one of a set of
13492                  overloaded functions provides a unique match.  */
13493               if (resolve_overloaded_unification
13494                   (tparms, targs, parm, arg, strict, sub_strict))
13495                 continue;
13496
13497               return 1;
13498             }
13499           arg_expr = arg;
13500           arg = unlowered_expr_type (arg);
13501           if (arg == error_mark_node)
13502             return 1;
13503         }
13504
13505       {
13506         int arg_strict = sub_strict;
13507
13508         if (!subr)
13509           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
13510                                                           arg_expr);
13511
13512         if (arg == init_list_type_node && arg_expr)
13513           arg = arg_expr;
13514         if (unify (tparms, targs, parm, arg, arg_strict))
13515           return 1;
13516       }
13517     }
13518
13519
13520   if (parms 
13521       && parms != void_list_node
13522       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13523     {
13524       /* Unify the remaining arguments with the pack expansion type.  */
13525       tree argvec;
13526       tree parmvec = make_tree_vec (1);
13527
13528       /* Allocate a TREE_VEC and copy in all of the arguments */ 
13529       argvec = make_tree_vec (nargs - ia);
13530       for (i = 0; ia < nargs; ++ia, ++i)
13531         TREE_VEC_ELT (argvec, i) = args[ia];
13532
13533       /* Copy the parameter into parmvec.  */
13534       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
13535       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
13536                                 /*call_args_p=*/true, /*subr=*/subr))
13537         return 1;
13538
13539       /* Advance to the end of the list of parameters.  */
13540       parms = TREE_CHAIN (parms);
13541     }
13542
13543   /* Fail if we've reached the end of the parm list, and more args
13544      are present, and the parm list isn't variadic.  */
13545   if (ia < nargs && parms == void_list_node)
13546     return 1;
13547   /* Fail if parms are left and they don't have default values.  */
13548   if (parms && parms != void_list_node
13549       && TREE_PURPOSE (parms) == NULL_TREE)
13550     return 1;
13551
13552   if (!subr)
13553     for (i = 0; i < ntparms; i++)
13554       if (!TREE_VEC_ELT (targs, i))
13555         {
13556           tree tparm;
13557
13558           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
13559             continue;
13560
13561           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13562
13563           /* If this is an undeduced nontype parameter that depends on
13564              a type parameter, try another pass; its type may have been
13565              deduced from a later argument than the one from which
13566              this parameter can be deduced.  */
13567           if (TREE_CODE (tparm) == PARM_DECL
13568               && uses_template_parms (TREE_TYPE (tparm))
13569               && !saw_undeduced++)
13570             goto again;
13571
13572           /* Core issue #226 (C++0x) [temp.deduct]:
13573
13574                If a template argument has not been deduced, its
13575                default template argument, if any, is used. 
13576
13577              When we are in C++98 mode, TREE_PURPOSE will either
13578              be NULL_TREE or ERROR_MARK_NODE, so we do not need
13579              to explicitly check cxx_dialect here.  */
13580           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
13581             {
13582               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13583               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
13584               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
13585               arg = convert_template_argument (parm, arg, targs, tf_none,
13586                                                i, NULL_TREE);
13587               if (arg == error_mark_node)
13588                 return 1;
13589               else
13590                 {
13591                   TREE_VEC_ELT (targs, i) = arg;
13592                   /* The position of the first default template argument,
13593                      is also the number of non-defaulted arguments in TARGS.
13594                      Record that.  */
13595                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
13596                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
13597                   continue;
13598                 }
13599             }
13600
13601           /* If the type parameter is a parameter pack, then it will
13602              be deduced to an empty parameter pack.  */
13603           if (template_parameter_pack_p (tparm))
13604             {
13605               tree arg;
13606
13607               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
13608                 {
13609                   arg = make_node (NONTYPE_ARGUMENT_PACK);
13610                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
13611                   TREE_CONSTANT (arg) = 1;
13612                 }
13613               else
13614                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
13615
13616               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
13617
13618               TREE_VEC_ELT (targs, i) = arg;
13619               continue;
13620             }
13621
13622           return 2;
13623         }
13624 #ifdef ENABLE_CHECKING
13625   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
13626     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
13627 #endif
13628
13629   return 0;
13630 }
13631
13632 /* Subroutine of type_unification_real.  Args are like the variables
13633    at the call site.  ARG is an overloaded function (or template-id);
13634    we try deducing template args from each of the overloads, and if
13635    only one succeeds, we go with that.  Modifies TARGS and returns
13636    true on success.  */
13637
13638 static bool
13639 resolve_overloaded_unification (tree tparms,
13640                                 tree targs,
13641                                 tree parm,
13642                                 tree arg,
13643                                 unification_kind_t strict,
13644                                 int sub_strict)
13645 {
13646   tree tempargs = copy_node (targs);
13647   int good = 0;
13648   tree goodfn = NULL_TREE;
13649   bool addr_p;
13650
13651   if (TREE_CODE (arg) == ADDR_EXPR)
13652     {
13653       arg = TREE_OPERAND (arg, 0);
13654       addr_p = true;
13655     }
13656   else
13657     addr_p = false;
13658
13659   if (TREE_CODE (arg) == COMPONENT_REF)
13660     /* Handle `&x' where `x' is some static or non-static member
13661        function name.  */
13662     arg = TREE_OPERAND (arg, 1);
13663
13664   if (TREE_CODE (arg) == OFFSET_REF)
13665     arg = TREE_OPERAND (arg, 1);
13666
13667   /* Strip baselink information.  */
13668   if (BASELINK_P (arg))
13669     arg = BASELINK_FUNCTIONS (arg);
13670
13671   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
13672     {
13673       /* If we got some explicit template args, we need to plug them into
13674          the affected templates before we try to unify, in case the
13675          explicit args will completely resolve the templates in question.  */
13676
13677       tree expl_subargs = TREE_OPERAND (arg, 1);
13678       arg = TREE_OPERAND (arg, 0);
13679
13680       for (; arg; arg = OVL_NEXT (arg))
13681         {
13682           tree fn = OVL_CURRENT (arg);
13683           tree subargs, elem;
13684
13685           if (TREE_CODE (fn) != TEMPLATE_DECL)
13686             continue;
13687
13688           ++processing_template_decl;
13689           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13690                                   expl_subargs, /*check_ret=*/false);
13691           if (subargs)
13692             {
13693               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
13694               if (try_one_overload (tparms, targs, tempargs, parm,
13695                                     elem, strict, sub_strict, addr_p)
13696                   && (!goodfn || !decls_match (goodfn, elem)))
13697                 {
13698                   goodfn = elem;
13699                   ++good;
13700                 }
13701             }
13702           --processing_template_decl;
13703         }
13704     }
13705   else if (TREE_CODE (arg) != OVERLOAD
13706            && TREE_CODE (arg) != FUNCTION_DECL)
13707     /* If ARG is, for example, "(0, &f)" then its type will be unknown
13708        -- but the deduction does not succeed because the expression is
13709        not just the function on its own.  */
13710     return false;
13711   else
13712     for (; arg; arg = OVL_NEXT (arg))
13713       if (try_one_overload (tparms, targs, tempargs, parm,
13714                             TREE_TYPE (OVL_CURRENT (arg)),
13715                             strict, sub_strict, addr_p)
13716           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
13717         {
13718           goodfn = OVL_CURRENT (arg);
13719           ++good;
13720         }
13721
13722   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13723      to function or pointer to member function argument if the set of
13724      overloaded functions does not contain function templates and at most
13725      one of a set of overloaded functions provides a unique match.
13726
13727      So if we found multiple possibilities, we return success but don't
13728      deduce anything.  */
13729
13730   if (good == 1)
13731     {
13732       int i = TREE_VEC_LENGTH (targs);
13733       for (; i--; )
13734         if (TREE_VEC_ELT (tempargs, i))
13735           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
13736     }
13737   if (good)
13738     return true;
13739
13740   return false;
13741 }
13742
13743 /* Core DR 115: In contexts where deduction is done and fails, or in
13744    contexts where deduction is not done, if a template argument list is
13745    specified and it, along with any default template arguments, identifies
13746    a single function template specialization, then the template-id is an
13747    lvalue for the function template specialization.  */
13748
13749 tree
13750 resolve_nondeduced_context (tree orig_expr)
13751 {
13752   tree expr, offset, baselink;
13753   bool addr;
13754
13755   if (!type_unknown_p (orig_expr))
13756     return orig_expr;
13757
13758   expr = orig_expr;
13759   addr = false;
13760   offset = NULL_TREE;
13761   baselink = NULL_TREE;
13762
13763   if (TREE_CODE (expr) == ADDR_EXPR)
13764     {
13765       expr = TREE_OPERAND (expr, 0);
13766       addr = true;
13767     }
13768   if (TREE_CODE (expr) == OFFSET_REF)
13769     {
13770       offset = expr;
13771       expr = TREE_OPERAND (expr, 1);
13772     }
13773   if (TREE_CODE (expr) == BASELINK)
13774     {
13775       baselink = expr;
13776       expr = BASELINK_FUNCTIONS (expr);
13777     }
13778
13779   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
13780     {
13781       int good = 0;
13782       tree goodfn = NULL_TREE;
13783
13784       /* If we got some explicit template args, we need to plug them into
13785          the affected templates before we try to unify, in case the
13786          explicit args will completely resolve the templates in question.  */
13787
13788       tree expl_subargs = TREE_OPERAND (expr, 1);
13789       tree arg = TREE_OPERAND (expr, 0);
13790       tree badfn = NULL_TREE;
13791       tree badargs = NULL_TREE;
13792
13793       for (; arg; arg = OVL_NEXT (arg))
13794         {
13795           tree fn = OVL_CURRENT (arg);
13796           tree subargs, elem;
13797
13798           if (TREE_CODE (fn) != TEMPLATE_DECL)
13799             continue;
13800
13801           ++processing_template_decl;
13802           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13803                                   expl_subargs, /*check_ret=*/false);
13804           if (subargs && !any_dependent_template_arguments_p (subargs))
13805             {
13806               elem = instantiate_template (fn, subargs, tf_none);
13807               if (elem == error_mark_node)
13808                 {
13809                   badfn = fn;
13810                   badargs = subargs;
13811                 }
13812               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
13813                 {
13814                   goodfn = elem;
13815                   ++good;
13816                 }
13817             }
13818           --processing_template_decl;
13819         }
13820       if (good == 1)
13821         {
13822           expr = goodfn;
13823           if (baselink)
13824             expr = build_baselink (BASELINK_BINFO (baselink),
13825                                    BASELINK_ACCESS_BINFO (baselink),
13826                                    expr, BASELINK_OPTYPE (baselink));
13827           if (offset)
13828             expr = build2 (OFFSET_REF, TREE_TYPE (expr),
13829                            TREE_OPERAND (offset, 0), expr);
13830           if (addr)
13831             expr = build_address (expr);
13832           return expr;
13833         }
13834       else if (good == 0 && badargs)
13835         /* There were no good options and at least one bad one, so let the
13836            user know what the problem is.  */
13837         instantiate_template (badfn, badargs, tf_warning_or_error);
13838     }
13839   return orig_expr;
13840 }
13841
13842 /* Subroutine of resolve_overloaded_unification; does deduction for a single
13843    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
13844    different overloads deduce different arguments for a given parm.
13845    ADDR_P is true if the expression for which deduction is being
13846    performed was of the form "& fn" rather than simply "fn".
13847
13848    Returns 1 on success.  */
13849
13850 static int
13851 try_one_overload (tree tparms,
13852                   tree orig_targs,
13853                   tree targs,
13854                   tree parm,
13855                   tree arg,
13856                   unification_kind_t strict,
13857                   int sub_strict,
13858                   bool addr_p)
13859 {
13860   int nargs;
13861   tree tempargs;
13862   int i;
13863
13864   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13865      to function or pointer to member function argument if the set of
13866      overloaded functions does not contain function templates and at most
13867      one of a set of overloaded functions provides a unique match.
13868
13869      So if this is a template, just return success.  */
13870
13871   if (uses_template_parms (arg))
13872     return 1;
13873
13874   if (TREE_CODE (arg) == METHOD_TYPE)
13875     arg = build_ptrmemfunc_type (build_pointer_type (arg));
13876   else if (addr_p)
13877     arg = build_pointer_type (arg);
13878
13879   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
13880
13881   /* We don't copy orig_targs for this because if we have already deduced
13882      some template args from previous args, unify would complain when we
13883      try to deduce a template parameter for the same argument, even though
13884      there isn't really a conflict.  */
13885   nargs = TREE_VEC_LENGTH (targs);
13886   tempargs = make_tree_vec (nargs);
13887
13888   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
13889     return 0;
13890
13891   /* First make sure we didn't deduce anything that conflicts with
13892      explicitly specified args.  */
13893   for (i = nargs; i--; )
13894     {
13895       tree elt = TREE_VEC_ELT (tempargs, i);
13896       tree oldelt = TREE_VEC_ELT (orig_targs, i);
13897
13898       if (!elt)
13899         /*NOP*/;
13900       else if (uses_template_parms (elt))
13901         /* Since we're unifying against ourselves, we will fill in
13902            template args used in the function parm list with our own
13903            template parms.  Discard them.  */
13904         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
13905       else if (oldelt && !template_args_equal (oldelt, elt))
13906         return 0;
13907     }
13908
13909   for (i = nargs; i--; )
13910     {
13911       tree elt = TREE_VEC_ELT (tempargs, i);
13912
13913       if (elt)
13914         TREE_VEC_ELT (targs, i) = elt;
13915     }
13916
13917   return 1;
13918 }
13919
13920 /* PARM is a template class (perhaps with unbound template
13921    parameters).  ARG is a fully instantiated type.  If ARG can be
13922    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
13923    TARGS are as for unify.  */
13924
13925 static tree
13926 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
13927 {
13928   tree copy_of_targs;
13929
13930   if (!CLASSTYPE_TEMPLATE_INFO (arg)
13931       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
13932           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
13933     return NULL_TREE;
13934
13935   /* We need to make a new template argument vector for the call to
13936      unify.  If we used TARGS, we'd clutter it up with the result of
13937      the attempted unification, even if this class didn't work out.
13938      We also don't want to commit ourselves to all the unifications
13939      we've already done, since unification is supposed to be done on
13940      an argument-by-argument basis.  In other words, consider the
13941      following pathological case:
13942
13943        template <int I, int J, int K>
13944        struct S {};
13945
13946        template <int I, int J>
13947        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
13948
13949        template <int I, int J, int K>
13950        void f(S<I, J, K>, S<I, I, I>);
13951
13952        void g() {
13953          S<0, 0, 0> s0;
13954          S<0, 1, 2> s2;
13955
13956          f(s0, s2);
13957        }
13958
13959      Now, by the time we consider the unification involving `s2', we
13960      already know that we must have `f<0, 0, 0>'.  But, even though
13961      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
13962      because there are two ways to unify base classes of S<0, 1, 2>
13963      with S<I, I, I>.  If we kept the already deduced knowledge, we
13964      would reject the possibility I=1.  */
13965   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
13966
13967   /* If unification failed, we're done.  */
13968   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
13969              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
13970     return NULL_TREE;
13971
13972   return arg;
13973 }
13974
13975 /* Given a template type PARM and a class type ARG, find the unique
13976    base type in ARG that is an instance of PARM.  We do not examine
13977    ARG itself; only its base-classes.  If there is not exactly one
13978    appropriate base class, return NULL_TREE.  PARM may be the type of
13979    a partial specialization, as well as a plain template type.  Used
13980    by unify.  */
13981
13982 static tree
13983 get_template_base (tree tparms, tree targs, tree parm, tree arg)
13984 {
13985   tree rval = NULL_TREE;
13986   tree binfo;
13987
13988   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
13989
13990   binfo = TYPE_BINFO (complete_type (arg));
13991   if (!binfo)
13992     /* The type could not be completed.  */
13993     return NULL_TREE;
13994
13995   /* Walk in inheritance graph order.  The search order is not
13996      important, and this avoids multiple walks of virtual bases.  */
13997   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
13998     {
13999       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
14000
14001       if (r)
14002         {
14003           /* If there is more than one satisfactory baseclass, then:
14004
14005                [temp.deduct.call]
14006
14007               If they yield more than one possible deduced A, the type
14008               deduction fails.
14009
14010              applies.  */
14011           if (rval && !same_type_p (r, rval))
14012             return NULL_TREE;
14013
14014           rval = r;
14015         }
14016     }
14017
14018   return rval;
14019 }
14020
14021 /* Returns the level of DECL, which declares a template parameter.  */
14022
14023 static int
14024 template_decl_level (tree decl)
14025 {
14026   switch (TREE_CODE (decl))
14027     {
14028     case TYPE_DECL:
14029     case TEMPLATE_DECL:
14030       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
14031
14032     case PARM_DECL:
14033       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
14034
14035     default:
14036       gcc_unreachable ();
14037     }
14038   return 0;
14039 }
14040
14041 /* Decide whether ARG can be unified with PARM, considering only the
14042    cv-qualifiers of each type, given STRICT as documented for unify.
14043    Returns nonzero iff the unification is OK on that basis.  */
14044
14045 static int
14046 check_cv_quals_for_unify (int strict, tree arg, tree parm)
14047 {
14048   int arg_quals = cp_type_quals (arg);
14049   int parm_quals = cp_type_quals (parm);
14050
14051   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14052       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14053     {
14054       /*  Although a CVR qualifier is ignored when being applied to a
14055           substituted template parameter ([8.3.2]/1 for example), that
14056           does not apply during deduction [14.8.2.4]/1, (even though
14057           that is not explicitly mentioned, [14.8.2.4]/9 indicates
14058           this).  Except when we're allowing additional CV qualifiers
14059           at the outer level [14.8.2.1]/3,1st bullet.  */
14060       if ((TREE_CODE (arg) == REFERENCE_TYPE
14061            || TREE_CODE (arg) == FUNCTION_TYPE
14062            || TREE_CODE (arg) == METHOD_TYPE)
14063           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
14064         return 0;
14065
14066       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
14067           && (parm_quals & TYPE_QUAL_RESTRICT))
14068         return 0;
14069     }
14070
14071   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14072       && (arg_quals & parm_quals) != parm_quals)
14073     return 0;
14074
14075   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
14076       && (parm_quals & arg_quals) != arg_quals)
14077     return 0;
14078
14079   return 1;
14080 }
14081
14082 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
14083 void 
14084 template_parm_level_and_index (tree parm, int* level, int* index)
14085 {
14086   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14087       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14088       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14089     {
14090       *index = TEMPLATE_TYPE_IDX (parm);
14091       *level = TEMPLATE_TYPE_LEVEL (parm);
14092     }
14093   else
14094     {
14095       *index = TEMPLATE_PARM_IDX (parm);
14096       *level = TEMPLATE_PARM_LEVEL (parm);
14097     }
14098 }
14099
14100 /* Unifies the remaining arguments in PACKED_ARGS with the pack
14101    expansion at the end of PACKED_PARMS. Returns 0 if the type
14102    deduction succeeds, 1 otherwise. STRICT is the same as in
14103    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
14104    call argument list. We'll need to adjust the arguments to make them
14105    types. SUBR tells us if this is from a recursive call to
14106    type_unification_real.  */
14107 int
14108 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
14109                       tree packed_args, int strict, bool call_args_p,
14110                       bool subr)
14111 {
14112   tree parm 
14113     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
14114   tree pattern = PACK_EXPANSION_PATTERN (parm);
14115   tree pack, packs = NULL_TREE;
14116   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
14117   int len = TREE_VEC_LENGTH (packed_args);
14118
14119   /* Determine the parameter packs we will be deducing from the
14120      pattern, and record their current deductions.  */
14121   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
14122        pack; pack = TREE_CHAIN (pack))
14123     {
14124       tree parm_pack = TREE_VALUE (pack);
14125       int idx, level;
14126
14127       /* Determine the index and level of this parameter pack.  */
14128       template_parm_level_and_index (parm_pack, &level, &idx);
14129
14130       /* Keep track of the parameter packs and their corresponding
14131          argument packs.  */
14132       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
14133       TREE_TYPE (packs) = make_tree_vec (len - start);
14134     }
14135   
14136   /* Loop through all of the arguments that have not yet been
14137      unified and unify each with the pattern.  */
14138   for (i = start; i < len; i++)
14139     {
14140       tree parm = pattern;
14141
14142       /* For each parameter pack, clear out the deduced value so that
14143          we can deduce it again.  */
14144       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14145         {
14146           int idx, level;
14147           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14148
14149           TMPL_ARG (targs, level, idx) = NULL_TREE;
14150         }
14151
14152       /* Unify the pattern with the current argument.  */
14153       {
14154         tree arg = TREE_VEC_ELT (packed_args, i);
14155         tree arg_expr = NULL_TREE;
14156         int arg_strict = strict;
14157         bool skip_arg_p = false;
14158
14159         if (call_args_p)
14160           {
14161             int sub_strict;
14162
14163             /* This mirrors what we do in type_unification_real.  */
14164             switch (strict)
14165               {
14166               case DEDUCE_CALL:
14167                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
14168                               | UNIFY_ALLOW_MORE_CV_QUAL
14169                               | UNIFY_ALLOW_DERIVED);
14170                 break;
14171                 
14172               case DEDUCE_CONV:
14173                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14174                 break;
14175                 
14176               case DEDUCE_EXACT:
14177                 sub_strict = UNIFY_ALLOW_NONE;
14178                 break;
14179                 
14180               default:
14181                 gcc_unreachable ();
14182               }
14183
14184             if (!TYPE_P (arg))
14185               {
14186                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14187                 if (type_unknown_p (arg))
14188                   {
14189                     /* [temp.deduct.type] A template-argument can be
14190                        deduced from a pointer to function or pointer
14191                        to member function argument if the set of
14192                        overloaded functions does not contain function
14193                        templates and at most one of a set of
14194                        overloaded functions provides a unique
14195                        match.  */
14196
14197                     if (resolve_overloaded_unification
14198                         (tparms, targs, parm, arg,
14199                          (unification_kind_t) strict,
14200                          sub_strict)
14201                         != 0)
14202                       return 1;
14203                     skip_arg_p = true;
14204                   }
14205
14206                 if (!skip_arg_p)
14207                   {
14208                     arg_expr = arg;
14209                     arg = unlowered_expr_type (arg);
14210                     if (arg == error_mark_node)
14211                       return 1;
14212                   }
14213               }
14214       
14215             arg_strict = sub_strict;
14216
14217             if (!subr)
14218               arg_strict |= 
14219                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
14220                                                   &parm, &arg, arg_expr);
14221           }
14222
14223         if (!skip_arg_p)
14224           {
14225             /* For deduction from an init-list we need the actual list.  */
14226             if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
14227               arg = arg_expr;
14228             if (unify (tparms, targs, parm, arg, arg_strict))
14229               return 1;
14230           }
14231       }
14232
14233       /* For each parameter pack, collect the deduced value.  */
14234       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14235         {
14236           int idx, level;
14237           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14238
14239           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
14240             TMPL_ARG (targs, level, idx);
14241         }
14242     }
14243
14244   /* Verify that the results of unification with the parameter packs
14245      produce results consistent with what we've seen before, and make
14246      the deduced argument packs available.  */
14247   for (pack = packs; pack; pack = TREE_CHAIN (pack))
14248     {
14249       tree old_pack = TREE_VALUE (pack);
14250       tree new_args = TREE_TYPE (pack);
14251       int i, len = TREE_VEC_LENGTH (new_args);
14252       int idx, level;
14253       bool nondeduced_p = false;
14254
14255       /* By default keep the original deduced argument pack.
14256          If necessary, more specific code is going to update the
14257          resulting deduced argument later down in this function.  */
14258       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14259       TMPL_ARG (targs, level, idx) = old_pack;
14260
14261       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
14262          actually deduce anything.  */
14263       for (i = 0; i < len && !nondeduced_p; ++i)
14264         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
14265           nondeduced_p = true;
14266       if (nondeduced_p)
14267         continue;
14268
14269       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
14270         {
14271           /* Prepend the explicit arguments onto NEW_ARGS.  */
14272           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14273           tree old_args = new_args;
14274           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
14275           int len = explicit_len + TREE_VEC_LENGTH (old_args);
14276
14277           /* Copy the explicit arguments.  */
14278           new_args = make_tree_vec (len);
14279           for (i = 0; i < explicit_len; i++)
14280             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
14281
14282           /* Copy the deduced arguments.  */
14283           for (; i < len; i++)
14284             TREE_VEC_ELT (new_args, i) =
14285               TREE_VEC_ELT (old_args, i - explicit_len);
14286         }
14287
14288       if (!old_pack)
14289         {
14290           tree result;
14291           /* Build the deduced *_ARGUMENT_PACK.  */
14292           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
14293             {
14294               result = make_node (NONTYPE_ARGUMENT_PACK);
14295               TREE_TYPE (result) = 
14296                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
14297               TREE_CONSTANT (result) = 1;
14298             }
14299           else
14300             result = cxx_make_type (TYPE_ARGUMENT_PACK);
14301
14302           SET_ARGUMENT_PACK_ARGS (result, new_args);
14303
14304           /* Note the deduced argument packs for this parameter
14305              pack.  */
14306           TMPL_ARG (targs, level, idx) = result;
14307         }
14308       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
14309                && (ARGUMENT_PACK_ARGS (old_pack) 
14310                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
14311         {
14312           /* We only had the explicitly-provided arguments before, but
14313              now we have a complete set of arguments.  */
14314           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14315
14316           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
14317           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
14318           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
14319         }
14320       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
14321                                     new_args))
14322         /* Inconsistent unification of this parameter pack.  */
14323         return 1;
14324     }
14325
14326   return 0;
14327 }
14328
14329 /* Deduce the value of template parameters.  TPARMS is the (innermost)
14330    set of template parameters to a template.  TARGS is the bindings
14331    for those template parameters, as determined thus far; TARGS may
14332    include template arguments for outer levels of template parameters
14333    as well.  PARM is a parameter to a template function, or a
14334    subcomponent of that parameter; ARG is the corresponding argument.
14335    This function attempts to match PARM with ARG in a manner
14336    consistent with the existing assignments in TARGS.  If more values
14337    are deduced, then TARGS is updated.
14338
14339    Returns 0 if the type deduction succeeds, 1 otherwise.  The
14340    parameter STRICT is a bitwise or of the following flags:
14341
14342      UNIFY_ALLOW_NONE:
14343        Require an exact match between PARM and ARG.
14344      UNIFY_ALLOW_MORE_CV_QUAL:
14345        Allow the deduced ARG to be more cv-qualified (by qualification
14346        conversion) than ARG.
14347      UNIFY_ALLOW_LESS_CV_QUAL:
14348        Allow the deduced ARG to be less cv-qualified than ARG.
14349      UNIFY_ALLOW_DERIVED:
14350        Allow the deduced ARG to be a template base class of ARG,
14351        or a pointer to a template base class of the type pointed to by
14352        ARG.
14353      UNIFY_ALLOW_INTEGER:
14354        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
14355        case for more information.
14356      UNIFY_ALLOW_OUTER_LEVEL:
14357        This is the outermost level of a deduction. Used to determine validity
14358        of qualification conversions. A valid qualification conversion must
14359        have const qualified pointers leading up to the inner type which
14360        requires additional CV quals, except at the outer level, where const
14361        is not required [conv.qual]. It would be normal to set this flag in
14362        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
14363      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
14364        This is the outermost level of a deduction, and PARM can be more CV
14365        qualified at this point.
14366      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
14367        This is the outermost level of a deduction, and PARM can be less CV
14368        qualified at this point.  */
14369
14370 static int
14371 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
14372 {
14373   int idx;
14374   tree targ;
14375   tree tparm;
14376   int strict_in = strict;
14377
14378   /* I don't think this will do the right thing with respect to types.
14379      But the only case I've seen it in so far has been array bounds, where
14380      signedness is the only information lost, and I think that will be
14381      okay.  */
14382   while (TREE_CODE (parm) == NOP_EXPR)
14383     parm = TREE_OPERAND (parm, 0);
14384
14385   if (arg == error_mark_node)
14386     return 1;
14387   if (arg == unknown_type_node
14388       || arg == init_list_type_node)
14389     /* We can't deduce anything from this, but we might get all the
14390        template args from other function args.  */
14391     return 0;
14392
14393   /* If PARM uses template parameters, then we can't bail out here,
14394      even if ARG == PARM, since we won't record unifications for the
14395      template parameters.  We might need them if we're trying to
14396      figure out which of two things is more specialized.  */
14397   if (arg == parm && !uses_template_parms (parm))
14398     return 0;
14399
14400   /* Handle init lists early, so the rest of the function can assume
14401      we're dealing with a type. */
14402   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
14403     {
14404       tree elt, elttype;
14405       unsigned i;
14406       tree orig_parm = parm;
14407
14408       /* Replace T with std::initializer_list<T> for deduction.  */
14409       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14410           && flag_deduce_init_list)
14411         parm = listify (parm);
14412
14413       if (!is_std_init_list (parm))
14414         /* We can only deduce from an initializer list argument if the
14415            parameter is std::initializer_list; otherwise this is a
14416            non-deduced context. */
14417         return 0;
14418
14419       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
14420
14421       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
14422         {
14423           int elt_strict = strict;
14424           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
14425             {
14426               tree type = TREE_TYPE (elt);
14427               /* It should only be possible to get here for a call.  */
14428               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
14429               elt_strict |= maybe_adjust_types_for_deduction
14430                 (DEDUCE_CALL, &elttype, &type, elt);
14431               elt = type;
14432             }
14433
14434           if (unify (tparms, targs, elttype, elt, elt_strict))
14435             return 1;
14436         }
14437
14438       /* If the std::initializer_list<T> deduction worked, replace the
14439          deduced A with std::initializer_list<A>.  */
14440       if (orig_parm != parm)
14441         {
14442           idx = TEMPLATE_TYPE_IDX (orig_parm);
14443           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14444           targ = listify (targ);
14445           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
14446         }
14447       return 0;
14448     }
14449
14450   /* Immediately reject some pairs that won't unify because of
14451      cv-qualification mismatches.  */
14452   if (TREE_CODE (arg) == TREE_CODE (parm)
14453       && TYPE_P (arg)
14454       /* It is the elements of the array which hold the cv quals of an array
14455          type, and the elements might be template type parms. We'll check
14456          when we recurse.  */
14457       && TREE_CODE (arg) != ARRAY_TYPE
14458       /* We check the cv-qualifiers when unifying with template type
14459          parameters below.  We want to allow ARG `const T' to unify with
14460          PARM `T' for example, when computing which of two templates
14461          is more specialized, for example.  */
14462       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
14463       && !check_cv_quals_for_unify (strict_in, arg, parm))
14464     return 1;
14465
14466   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
14467       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
14468     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
14469   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
14470   strict &= ~UNIFY_ALLOW_DERIVED;
14471   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14472   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
14473
14474   switch (TREE_CODE (parm))
14475     {
14476     case TYPENAME_TYPE:
14477     case SCOPE_REF:
14478     case UNBOUND_CLASS_TEMPLATE:
14479       /* In a type which contains a nested-name-specifier, template
14480          argument values cannot be deduced for template parameters used
14481          within the nested-name-specifier.  */
14482       return 0;
14483
14484     case TEMPLATE_TYPE_PARM:
14485     case TEMPLATE_TEMPLATE_PARM:
14486     case BOUND_TEMPLATE_TEMPLATE_PARM:
14487       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14488       if (tparm == error_mark_node)
14489         return 1;
14490
14491       if (TEMPLATE_TYPE_LEVEL (parm)
14492           != template_decl_level (tparm))
14493         /* The PARM is not one we're trying to unify.  Just check
14494            to see if it matches ARG.  */
14495         return (TREE_CODE (arg) == TREE_CODE (parm)
14496                 && same_type_p (parm, arg)) ? 0 : 1;
14497       idx = TEMPLATE_TYPE_IDX (parm);
14498       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14499       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
14500
14501       /* Check for mixed types and values.  */
14502       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14503            && TREE_CODE (tparm) != TYPE_DECL)
14504           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14505               && TREE_CODE (tparm) != TEMPLATE_DECL))
14506         return 1;
14507
14508       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14509         {
14510           /* ARG must be constructed from a template class or a template
14511              template parameter.  */
14512           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
14513               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
14514             return 1;
14515
14516           {
14517             tree parmvec = TYPE_TI_ARGS (parm);
14518             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
14519             tree parm_parms 
14520               = DECL_INNERMOST_TEMPLATE_PARMS
14521                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
14522             int i, len;
14523             int parm_variadic_p = 0;
14524
14525             /* The resolution to DR150 makes clear that default
14526                arguments for an N-argument may not be used to bind T
14527                to a template template parameter with fewer than N
14528                parameters.  It is not safe to permit the binding of
14529                default arguments as an extension, as that may change
14530                the meaning of a conforming program.  Consider:
14531
14532                   struct Dense { static const unsigned int dim = 1; };
14533
14534                   template <template <typename> class View,
14535                             typename Block>
14536                   void operator+(float, View<Block> const&);
14537
14538                   template <typename Block,
14539                             unsigned int Dim = Block::dim>
14540                   struct Lvalue_proxy { operator float() const; };
14541
14542                   void
14543                   test_1d (void) {
14544                     Lvalue_proxy<Dense> p;
14545                     float b;
14546                     b + p;
14547                   }
14548
14549               Here, if Lvalue_proxy is permitted to bind to View, then
14550               the global operator+ will be used; if they are not, the
14551               Lvalue_proxy will be converted to float.  */
14552             if (coerce_template_parms (parm_parms,
14553                                        argvec,
14554                                        TYPE_TI_TEMPLATE (parm),
14555                                        tf_none,
14556                                        /*require_all_args=*/true,
14557                                        /*use_default_args=*/false)
14558                 == error_mark_node)
14559               return 1;
14560
14561             /* Deduce arguments T, i from TT<T> or TT<i>.
14562                We check each element of PARMVEC and ARGVEC individually
14563                rather than the whole TREE_VEC since they can have
14564                different number of elements.  */
14565
14566             parmvec = expand_template_argument_pack (parmvec);
14567             argvec = expand_template_argument_pack (argvec);
14568
14569             len = TREE_VEC_LENGTH (parmvec);
14570
14571             /* Check if the parameters end in a pack, making them
14572                variadic.  */
14573             if (len > 0
14574                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
14575               parm_variadic_p = 1;
14576             
14577             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
14578               return 1;
14579
14580              for (i = 0; i < len - parm_variadic_p; ++i)
14581               {
14582                 if (unify (tparms, targs,
14583                            TREE_VEC_ELT (parmvec, i),
14584                            TREE_VEC_ELT (argvec, i),
14585                            UNIFY_ALLOW_NONE))
14586                   return 1;
14587               }
14588
14589             if (parm_variadic_p
14590                 && unify_pack_expansion (tparms, targs,
14591                                          parmvec, argvec,
14592                                          UNIFY_ALLOW_NONE,
14593                                          /*call_args_p=*/false,
14594                                          /*subr=*/false))
14595               return 1;
14596           }
14597           arg = TYPE_TI_TEMPLATE (arg);
14598
14599           /* Fall through to deduce template name.  */
14600         }
14601
14602       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14603           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14604         {
14605           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
14606
14607           /* Simple cases: Value already set, does match or doesn't.  */
14608           if (targ != NULL_TREE && template_args_equal (targ, arg))
14609             return 0;
14610           else if (targ)
14611             return 1;
14612         }
14613       else
14614         {
14615           /* If PARM is `const T' and ARG is only `int', we don't have
14616              a match unless we are allowing additional qualification.
14617              If ARG is `const int' and PARM is just `T' that's OK;
14618              that binds `const int' to `T'.  */
14619           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
14620                                          arg, parm))
14621             return 1;
14622
14623           /* Consider the case where ARG is `const volatile int' and
14624              PARM is `const T'.  Then, T should be `volatile int'.  */
14625           arg = cp_build_qualified_type_real
14626             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
14627           if (arg == error_mark_node)
14628             return 1;
14629
14630           /* Simple cases: Value already set, does match or doesn't.  */
14631           if (targ != NULL_TREE && same_type_p (targ, arg))
14632             return 0;
14633           else if (targ)
14634             return 1;
14635
14636           /* Make sure that ARG is not a variable-sized array.  (Note
14637              that were talking about variable-sized arrays (like
14638              `int[n]'), rather than arrays of unknown size (like
14639              `int[]').)  We'll get very confused by such a type since
14640              the bound of the array will not be computable in an
14641              instantiation.  Besides, such types are not allowed in
14642              ISO C++, so we can do as we please here.  */
14643           if (variably_modified_type_p (arg, NULL_TREE))
14644             return 1;
14645
14646           /* Strip typedefs as in convert_template_argument.  */
14647           arg = strip_typedefs (arg);
14648         }
14649
14650       /* If ARG is a parameter pack or an expansion, we cannot unify
14651          against it unless PARM is also a parameter pack.  */
14652       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14653           && !template_parameter_pack_p (parm))
14654         return 1;
14655
14656       /* If the argument deduction results is a METHOD_TYPE,
14657          then there is a problem.
14658          METHOD_TYPE doesn't map to any real C++ type the result of
14659          the deduction can not be of that type.  */
14660       if (TREE_CODE (arg) == METHOD_TYPE)
14661         return 1;
14662
14663       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14664       return 0;
14665
14666     case TEMPLATE_PARM_INDEX:
14667       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14668       if (tparm == error_mark_node)
14669         return 1;
14670
14671       if (TEMPLATE_PARM_LEVEL (parm)
14672           != template_decl_level (tparm))
14673         /* The PARM is not one we're trying to unify.  Just check
14674            to see if it matches ARG.  */
14675         return !(TREE_CODE (arg) == TREE_CODE (parm)
14676                  && cp_tree_equal (parm, arg));
14677
14678       idx = TEMPLATE_PARM_IDX (parm);
14679       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14680
14681       if (targ)
14682         return !cp_tree_equal (targ, arg);
14683
14684       /* [temp.deduct.type] If, in the declaration of a function template
14685          with a non-type template-parameter, the non-type
14686          template-parameter is used in an expression in the function
14687          parameter-list and, if the corresponding template-argument is
14688          deduced, the template-argument type shall match the type of the
14689          template-parameter exactly, except that a template-argument
14690          deduced from an array bound may be of any integral type.
14691          The non-type parameter might use already deduced type parameters.  */
14692       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
14693       if (!TREE_TYPE (arg))
14694         /* Template-parameter dependent expression.  Just accept it for now.
14695            It will later be processed in convert_template_argument.  */
14696         ;
14697       else if (same_type_p (TREE_TYPE (arg), tparm))
14698         /* OK */;
14699       else if ((strict & UNIFY_ALLOW_INTEGER)
14700                && (TREE_CODE (tparm) == INTEGER_TYPE
14701                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
14702         /* Convert the ARG to the type of PARM; the deduced non-type
14703            template argument must exactly match the types of the
14704            corresponding parameter.  */
14705         arg = fold (build_nop (tparm, arg));
14706       else if (uses_template_parms (tparm))
14707         /* We haven't deduced the type of this parameter yet.  Try again
14708            later.  */
14709         return 0;
14710       else
14711         return 1;
14712
14713       /* If ARG is a parameter pack or an expansion, we cannot unify
14714          against it unless PARM is also a parameter pack.  */
14715       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14716           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
14717         return 1;
14718
14719       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14720       return 0;
14721
14722     case PTRMEM_CST:
14723      {
14724         /* A pointer-to-member constant can be unified only with
14725          another constant.  */
14726       if (TREE_CODE (arg) != PTRMEM_CST)
14727         return 1;
14728
14729       /* Just unify the class member. It would be useless (and possibly
14730          wrong, depending on the strict flags) to unify also
14731          PTRMEM_CST_CLASS, because we want to be sure that both parm and
14732          arg refer to the same variable, even if through different
14733          classes. For instance:
14734
14735          struct A { int x; };
14736          struct B : A { };
14737
14738          Unification of &A::x and &B::x must succeed.  */
14739       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
14740                     PTRMEM_CST_MEMBER (arg), strict);
14741      }
14742
14743     case POINTER_TYPE:
14744       {
14745         if (TREE_CODE (arg) != POINTER_TYPE)
14746           return 1;
14747
14748         /* [temp.deduct.call]
14749
14750            A can be another pointer or pointer to member type that can
14751            be converted to the deduced A via a qualification
14752            conversion (_conv.qual_).
14753
14754            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
14755            This will allow for additional cv-qualification of the
14756            pointed-to types if appropriate.  */
14757
14758         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
14759           /* The derived-to-base conversion only persists through one
14760              level of pointers.  */
14761           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
14762
14763         return unify (tparms, targs, TREE_TYPE (parm),
14764                       TREE_TYPE (arg), strict);
14765       }
14766
14767     case REFERENCE_TYPE:
14768       if (TREE_CODE (arg) != REFERENCE_TYPE)
14769         return 1;
14770       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14771                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14772
14773     case ARRAY_TYPE:
14774       if (TREE_CODE (arg) != ARRAY_TYPE)
14775         return 1;
14776       if ((TYPE_DOMAIN (parm) == NULL_TREE)
14777           != (TYPE_DOMAIN (arg) == NULL_TREE))
14778         return 1;
14779       if (TYPE_DOMAIN (parm) != NULL_TREE)
14780         {
14781           tree parm_max;
14782           tree arg_max;
14783           bool parm_cst;
14784           bool arg_cst;
14785
14786           /* Our representation of array types uses "N - 1" as the
14787              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
14788              not an integer constant.  We cannot unify arbitrarily
14789              complex expressions, so we eliminate the MINUS_EXPRs
14790              here.  */
14791           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
14792           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
14793           if (!parm_cst)
14794             {
14795               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
14796               parm_max = TREE_OPERAND (parm_max, 0);
14797             }
14798           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
14799           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
14800           if (!arg_cst)
14801             {
14802               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
14803                  trying to unify the type of a variable with the type
14804                  of a template parameter.  For example:
14805
14806                    template <unsigned int N>
14807                    void f (char (&) [N]);
14808                    int g(); 
14809                    void h(int i) {
14810                      char a[g(i)];
14811                      f(a); 
14812                    }
14813
14814                 Here, the type of the ARG will be "int [g(i)]", and
14815                 may be a SAVE_EXPR, etc.  */
14816               if (TREE_CODE (arg_max) != MINUS_EXPR)
14817                 return 1;
14818               arg_max = TREE_OPERAND (arg_max, 0);
14819             }
14820
14821           /* If only one of the bounds used a MINUS_EXPR, compensate
14822              by adding one to the other bound.  */
14823           if (parm_cst && !arg_cst)
14824             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
14825                                     integer_type_node,
14826                                     parm_max,
14827                                     integer_one_node);
14828           else if (arg_cst && !parm_cst)
14829             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
14830                                    integer_type_node,
14831                                    arg_max,
14832                                    integer_one_node);
14833
14834           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
14835             return 1;
14836         }
14837       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14838                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14839
14840     case REAL_TYPE:
14841     case COMPLEX_TYPE:
14842     case VECTOR_TYPE:
14843     case INTEGER_TYPE:
14844     case BOOLEAN_TYPE:
14845     case ENUMERAL_TYPE:
14846     case VOID_TYPE:
14847       if (TREE_CODE (arg) != TREE_CODE (parm))
14848         return 1;
14849
14850       /* We have already checked cv-qualification at the top of the
14851          function.  */
14852       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
14853         return 1;
14854
14855       /* As far as unification is concerned, this wins.  Later checks
14856          will invalidate it if necessary.  */
14857       return 0;
14858
14859       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
14860       /* Type INTEGER_CST can come from ordinary constant template args.  */
14861     case INTEGER_CST:
14862       while (TREE_CODE (arg) == NOP_EXPR)
14863         arg = TREE_OPERAND (arg, 0);
14864
14865       if (TREE_CODE (arg) != INTEGER_CST)
14866         return 1;
14867       return !tree_int_cst_equal (parm, arg);
14868
14869     case TREE_VEC:
14870       {
14871         int i;
14872         if (TREE_CODE (arg) != TREE_VEC)
14873           return 1;
14874         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
14875           return 1;
14876         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
14877           if (unify (tparms, targs,
14878                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
14879                      UNIFY_ALLOW_NONE))
14880             return 1;
14881         return 0;
14882       }
14883
14884     case RECORD_TYPE:
14885     case UNION_TYPE:
14886       if (TREE_CODE (arg) != TREE_CODE (parm))
14887         return 1;
14888
14889       if (TYPE_PTRMEMFUNC_P (parm))
14890         {
14891           if (!TYPE_PTRMEMFUNC_P (arg))
14892             return 1;
14893
14894           return unify (tparms, targs,
14895                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
14896                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
14897                         strict);
14898         }
14899
14900       if (CLASSTYPE_TEMPLATE_INFO (parm))
14901         {
14902           tree t = NULL_TREE;
14903
14904           if (strict_in & UNIFY_ALLOW_DERIVED)
14905             {
14906               /* First, we try to unify the PARM and ARG directly.  */
14907               t = try_class_unification (tparms, targs,
14908                                          parm, arg);
14909
14910               if (!t)
14911                 {
14912                   /* Fallback to the special case allowed in
14913                      [temp.deduct.call]:
14914
14915                        If P is a class, and P has the form
14916                        template-id, then A can be a derived class of
14917                        the deduced A.  Likewise, if P is a pointer to
14918                        a class of the form template-id, A can be a
14919                        pointer to a derived class pointed to by the
14920                        deduced A.  */
14921                   t = get_template_base (tparms, targs, parm, arg);
14922
14923                   if (!t)
14924                     return 1;
14925                 }
14926             }
14927           else if (CLASSTYPE_TEMPLATE_INFO (arg)
14928                    && (CLASSTYPE_TI_TEMPLATE (parm)
14929                        == CLASSTYPE_TI_TEMPLATE (arg)))
14930             /* Perhaps PARM is something like S<U> and ARG is S<int>.
14931                Then, we should unify `int' and `U'.  */
14932             t = arg;
14933           else
14934             /* There's no chance of unification succeeding.  */
14935             return 1;
14936
14937           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
14938                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
14939         }
14940       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
14941         return 1;
14942       return 0;
14943
14944     case METHOD_TYPE:
14945     case FUNCTION_TYPE:
14946       {
14947         unsigned int nargs;
14948         tree *args;
14949         tree a;
14950         unsigned int i;
14951
14952         if (TREE_CODE (arg) != TREE_CODE (parm))
14953           return 1;
14954
14955         /* CV qualifications for methods can never be deduced, they must
14956            match exactly.  We need to check them explicitly here,
14957            because type_unification_real treats them as any other
14958            cv-qualified parameter.  */
14959         if (TREE_CODE (parm) == METHOD_TYPE
14960             && (!check_cv_quals_for_unify
14961                 (UNIFY_ALLOW_NONE,
14962                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
14963                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
14964           return 1;
14965
14966         if (unify (tparms, targs, TREE_TYPE (parm),
14967                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
14968           return 1;
14969
14970         nargs = list_length (TYPE_ARG_TYPES (arg));
14971         args = XALLOCAVEC (tree, nargs);
14972         for (a = TYPE_ARG_TYPES (arg), i = 0;
14973              a != NULL_TREE && a != void_list_node;
14974              a = TREE_CHAIN (a), ++i)
14975           args[i] = TREE_VALUE (a);
14976         nargs = i;
14977
14978         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
14979                                       args, nargs, 1, DEDUCE_EXACT,
14980                                       LOOKUP_NORMAL);
14981       }
14982
14983     case OFFSET_TYPE:
14984       /* Unify a pointer to member with a pointer to member function, which
14985          deduces the type of the member as a function type. */
14986       if (TYPE_PTRMEMFUNC_P (arg))
14987         {
14988           tree method_type;
14989           tree fntype;
14990           cp_cv_quals cv_quals;
14991
14992           /* Check top-level cv qualifiers */
14993           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
14994             return 1;
14995
14996           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14997                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
14998             return 1;
14999
15000           /* Determine the type of the function we are unifying against. */
15001           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
15002           fntype =
15003             build_function_type (TREE_TYPE (method_type),
15004                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
15005
15006           /* Extract the cv-qualifiers of the member function from the
15007              implicit object parameter and place them on the function
15008              type to be restored later. */
15009           cv_quals =
15010             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
15011           fntype = build_qualified_type (fntype, cv_quals);
15012           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
15013         }
15014
15015       if (TREE_CODE (arg) != OFFSET_TYPE)
15016         return 1;
15017       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15018                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
15019         return 1;
15020       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15021                     strict);
15022
15023     case CONST_DECL:
15024       if (DECL_TEMPLATE_PARM_P (parm))
15025         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
15026       if (arg != integral_constant_value (parm))
15027         return 1;
15028       return 0;
15029
15030     case FIELD_DECL:
15031     case TEMPLATE_DECL:
15032       /* Matched cases are handled by the ARG == PARM test above.  */
15033       return 1;
15034
15035     case TYPE_ARGUMENT_PACK:
15036     case NONTYPE_ARGUMENT_PACK:
15037       {
15038         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
15039         tree packed_args = ARGUMENT_PACK_ARGS (arg);
15040         int i, len = TREE_VEC_LENGTH (packed_parms);
15041         int argslen = TREE_VEC_LENGTH (packed_args);
15042         int parm_variadic_p = 0;
15043
15044         for (i = 0; i < len; ++i)
15045           {
15046             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
15047               {
15048                 if (i == len - 1)
15049                   /* We can unify against something with a trailing
15050                      parameter pack.  */
15051                   parm_variadic_p = 1;
15052                 else
15053                   /* Since there is something following the pack
15054                      expansion, we cannot unify this template argument
15055                      list.  */
15056                   return 0;
15057               }
15058           }
15059           
15060
15061         /* If we don't have enough arguments to satisfy the parameters
15062            (not counting the pack expression at the end), or we have
15063            too many arguments for a parameter list that doesn't end in
15064            a pack expression, we can't unify.  */
15065         if (argslen < (len - parm_variadic_p)
15066             || (argslen > len && !parm_variadic_p))
15067           return 1;
15068
15069         /* Unify all of the parameters that precede the (optional)
15070            pack expression.  */
15071         for (i = 0; i < len - parm_variadic_p; ++i)
15072           {
15073             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
15074                        TREE_VEC_ELT (packed_args, i), strict))
15075               return 1;
15076           }
15077
15078         if (parm_variadic_p)
15079           return unify_pack_expansion (tparms, targs, 
15080                                        packed_parms, packed_args,
15081                                        strict, /*call_args_p=*/false,
15082                                        /*subr=*/false);
15083         return 0;
15084       }
15085
15086       break;
15087
15088     case TYPEOF_TYPE:
15089     case DECLTYPE_TYPE:
15090       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
15091          nodes.  */
15092       return 0;
15093
15094     case ERROR_MARK:
15095       /* Unification fails if we hit an error node.  */
15096       return 1;
15097
15098     default:
15099       gcc_assert (EXPR_P (parm));
15100
15101       /* We must be looking at an expression.  This can happen with
15102          something like:
15103
15104            template <int I>
15105            void foo(S<I>, S<I + 2>);
15106
15107          This is a "nondeduced context":
15108
15109            [deduct.type]
15110
15111            The nondeduced contexts are:
15112
15113            --A type that is a template-id in which one or more of
15114              the template-arguments is an expression that references
15115              a template-parameter.
15116
15117          In these cases, we assume deduction succeeded, but don't
15118          actually infer any unifications.  */
15119
15120       if (!uses_template_parms (parm)
15121           && !template_args_equal (parm, arg))
15122         return 1;
15123       else
15124         return 0;
15125     }
15126 }
15127 \f
15128 /* Note that DECL can be defined in this translation unit, if
15129    required.  */
15130
15131 static void
15132 mark_definable (tree decl)
15133 {
15134   tree clone;
15135   DECL_NOT_REALLY_EXTERN (decl) = 1;
15136   FOR_EACH_CLONE (clone, decl)
15137     DECL_NOT_REALLY_EXTERN (clone) = 1;
15138 }
15139
15140 /* Called if RESULT is explicitly instantiated, or is a member of an
15141    explicitly instantiated class.  */
15142
15143 void
15144 mark_decl_instantiated (tree result, int extern_p)
15145 {
15146   SET_DECL_EXPLICIT_INSTANTIATION (result);
15147
15148   /* If this entity has already been written out, it's too late to
15149      make any modifications.  */
15150   if (TREE_ASM_WRITTEN (result))
15151     return;
15152
15153   if (TREE_CODE (result) != FUNCTION_DECL)
15154     /* The TREE_PUBLIC flag for function declarations will have been
15155        set correctly by tsubst.  */
15156     TREE_PUBLIC (result) = 1;
15157
15158   /* This might have been set by an earlier implicit instantiation.  */
15159   DECL_COMDAT (result) = 0;
15160
15161   if (extern_p)
15162     DECL_NOT_REALLY_EXTERN (result) = 0;
15163   else
15164     {
15165       mark_definable (result);
15166       /* Always make artificials weak.  */
15167       if (DECL_ARTIFICIAL (result) && flag_weak)
15168         comdat_linkage (result);
15169       /* For WIN32 we also want to put explicit instantiations in
15170          linkonce sections.  */
15171       else if (TREE_PUBLIC (result))
15172         maybe_make_one_only (result);
15173     }
15174
15175   /* If EXTERN_P, then this function will not be emitted -- unless
15176      followed by an explicit instantiation, at which point its linkage
15177      will be adjusted.  If !EXTERN_P, then this function will be
15178      emitted here.  In neither circumstance do we want
15179      import_export_decl to adjust the linkage.  */
15180   DECL_INTERFACE_KNOWN (result) = 1;
15181 }
15182
15183 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
15184    important template arguments.  If any are missing, we check whether
15185    they're important by using error_mark_node for substituting into any
15186    args that were used for partial ordering (the ones between ARGS and END)
15187    and seeing if it bubbles up.  */
15188
15189 static bool
15190 check_undeduced_parms (tree targs, tree args, tree end)
15191 {
15192   bool found = false;
15193   int i;
15194   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
15195     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
15196       {
15197         found = true;
15198         TREE_VEC_ELT (targs, i) = error_mark_node;
15199       }
15200   if (found)
15201     {
15202       for (; args != end; args = TREE_CHAIN (args))
15203         {
15204           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
15205           if (substed == error_mark_node)
15206             return true;
15207         }
15208     }
15209   return false;
15210 }
15211
15212 /* Given two function templates PAT1 and PAT2, return:
15213
15214    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
15215    -1 if PAT2 is more specialized than PAT1.
15216    0 if neither is more specialized.
15217
15218    LEN indicates the number of parameters we should consider
15219    (defaulted parameters should not be considered).
15220
15221    The 1998 std underspecified function template partial ordering, and
15222    DR214 addresses the issue.  We take pairs of arguments, one from
15223    each of the templates, and deduce them against each other.  One of
15224    the templates will be more specialized if all the *other*
15225    template's arguments deduce against its arguments and at least one
15226    of its arguments *does* *not* deduce against the other template's
15227    corresponding argument.  Deduction is done as for class templates.
15228    The arguments used in deduction have reference and top level cv
15229    qualifiers removed.  Iff both arguments were originally reference
15230    types *and* deduction succeeds in both directions, the template
15231    with the more cv-qualified argument wins for that pairing (if
15232    neither is more cv-qualified, they both are equal).  Unlike regular
15233    deduction, after all the arguments have been deduced in this way,
15234    we do *not* verify the deduced template argument values can be
15235    substituted into non-deduced contexts.
15236
15237    The logic can be a bit confusing here, because we look at deduce1 and
15238    targs1 to see if pat2 is at least as specialized, and vice versa; if we
15239    can find template arguments for pat1 to make arg1 look like arg2, that
15240    means that arg2 is at least as specialized as arg1.  */
15241
15242 int
15243 more_specialized_fn (tree pat1, tree pat2, int len)
15244 {
15245   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
15246   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
15247   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
15248   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
15249   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
15250   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
15251   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
15252   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
15253   tree origs1, origs2;
15254   bool lose1 = false;
15255   bool lose2 = false;
15256
15257   /* Remove the this parameter from non-static member functions.  If
15258      one is a non-static member function and the other is not a static
15259      member function, remove the first parameter from that function
15260      also.  This situation occurs for operator functions where we
15261      locate both a member function (with this pointer) and non-member
15262      operator (with explicit first operand).  */
15263   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
15264     {
15265       len--; /* LEN is the number of significant arguments for DECL1 */
15266       args1 = TREE_CHAIN (args1);
15267       if (!DECL_STATIC_FUNCTION_P (decl2))
15268         args2 = TREE_CHAIN (args2);
15269     }
15270   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
15271     {
15272       args2 = TREE_CHAIN (args2);
15273       if (!DECL_STATIC_FUNCTION_P (decl1))
15274         {
15275           len--;
15276           args1 = TREE_CHAIN (args1);
15277         }
15278     }
15279
15280   /* If only one is a conversion operator, they are unordered.  */
15281   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
15282     return 0;
15283
15284   /* Consider the return type for a conversion function */
15285   if (DECL_CONV_FN_P (decl1))
15286     {
15287       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
15288       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
15289       len++;
15290     }
15291
15292   processing_template_decl++;
15293
15294   origs1 = args1;
15295   origs2 = args2;
15296
15297   while (len--
15298          /* Stop when an ellipsis is seen.  */
15299          && args1 != NULL_TREE && args2 != NULL_TREE)
15300     {
15301       tree arg1 = TREE_VALUE (args1);
15302       tree arg2 = TREE_VALUE (args2);
15303       int deduce1, deduce2;
15304       int quals1 = -1;
15305       int quals2 = -1;
15306
15307       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15308           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15309         {
15310           /* When both arguments are pack expansions, we need only
15311              unify the patterns themselves.  */
15312           arg1 = PACK_EXPANSION_PATTERN (arg1);
15313           arg2 = PACK_EXPANSION_PATTERN (arg2);
15314
15315           /* This is the last comparison we need to do.  */
15316           len = 0;
15317         }
15318
15319       if (TREE_CODE (arg1) == REFERENCE_TYPE)
15320         {
15321           arg1 = TREE_TYPE (arg1);
15322           quals1 = cp_type_quals (arg1);
15323         }
15324
15325       if (TREE_CODE (arg2) == REFERENCE_TYPE)
15326         {
15327           arg2 = TREE_TYPE (arg2);
15328           quals2 = cp_type_quals (arg2);
15329         }
15330
15331       if ((quals1 < 0) != (quals2 < 0))
15332         {
15333           /* Only of the args is a reference, see if we should apply
15334              array/function pointer decay to it.  This is not part of
15335              DR214, but is, IMHO, consistent with the deduction rules
15336              for the function call itself, and with our earlier
15337              implementation of the underspecified partial ordering
15338              rules.  (nathan).  */
15339           if (quals1 >= 0)
15340             {
15341               switch (TREE_CODE (arg1))
15342                 {
15343                 case ARRAY_TYPE:
15344                   arg1 = TREE_TYPE (arg1);
15345                   /* FALLTHROUGH. */
15346                 case FUNCTION_TYPE:
15347                   arg1 = build_pointer_type (arg1);
15348                   break;
15349
15350                 default:
15351                   break;
15352                 }
15353             }
15354           else
15355             {
15356               switch (TREE_CODE (arg2))
15357                 {
15358                 case ARRAY_TYPE:
15359                   arg2 = TREE_TYPE (arg2);
15360                   /* FALLTHROUGH. */
15361                 case FUNCTION_TYPE:
15362                   arg2 = build_pointer_type (arg2);
15363                   break;
15364
15365                 default:
15366                   break;
15367                 }
15368             }
15369         }
15370
15371       arg1 = TYPE_MAIN_VARIANT (arg1);
15372       arg2 = TYPE_MAIN_VARIANT (arg2);
15373
15374       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
15375         {
15376           int i, len2 = list_length (args2);
15377           tree parmvec = make_tree_vec (1);
15378           tree argvec = make_tree_vec (len2);
15379           tree ta = args2;
15380
15381           /* Setup the parameter vector, which contains only ARG1.  */
15382           TREE_VEC_ELT (parmvec, 0) = arg1;
15383
15384           /* Setup the argument vector, which contains the remaining
15385              arguments.  */
15386           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
15387             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15388
15389           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
15390                                            argvec, UNIFY_ALLOW_NONE, 
15391                                            /*call_args_p=*/false, 
15392                                            /*subr=*/0);
15393
15394           /* We cannot deduce in the other direction, because ARG1 is
15395              a pack expansion but ARG2 is not.  */
15396           deduce2 = 0;
15397         }
15398       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15399         {
15400           int i, len1 = list_length (args1);
15401           tree parmvec = make_tree_vec (1);
15402           tree argvec = make_tree_vec (len1);
15403           tree ta = args1;
15404
15405           /* Setup the parameter vector, which contains only ARG1.  */
15406           TREE_VEC_ELT (parmvec, 0) = arg2;
15407
15408           /* Setup the argument vector, which contains the remaining
15409              arguments.  */
15410           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
15411             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15412
15413           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
15414                                            argvec, UNIFY_ALLOW_NONE, 
15415                                            /*call_args_p=*/false, 
15416                                            /*subr=*/0);
15417
15418           /* We cannot deduce in the other direction, because ARG2 is
15419              a pack expansion but ARG1 is not.*/
15420           deduce1 = 0;
15421         }
15422
15423       else
15424         {
15425           /* The normal case, where neither argument is a pack
15426              expansion.  */
15427           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
15428           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
15429         }
15430
15431       /* If we couldn't deduce arguments for tparms1 to make arg1 match
15432          arg2, then arg2 is not as specialized as arg1.  */
15433       if (!deduce1)
15434         lose2 = true;
15435       if (!deduce2)
15436         lose1 = true;
15437
15438       /* "If, for a given type, deduction succeeds in both directions
15439          (i.e., the types are identical after the transformations above)
15440          and if the type from the argument template is more cv-qualified
15441          than the type from the parameter template (as described above)
15442          that type is considered to be more specialized than the other. If
15443          neither type is more cv-qualified than the other then neither type
15444          is more specialized than the other."
15445
15446          We check same_type_p explicitly because deduction can also succeed
15447          in both directions when there is a nondeduced context.  */
15448       if (deduce1 && deduce2
15449           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0
15450           && same_type_p (arg1, arg2))
15451         {
15452           if ((quals1 & quals2) == quals2)
15453             lose2 = true;
15454           if ((quals1 & quals2) == quals1)
15455             lose1 = true;
15456         }
15457
15458       if (lose1 && lose2)
15459         /* We've failed to deduce something in either direction.
15460            These must be unordered.  */
15461         break;
15462
15463       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15464           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15465         /* We have already processed all of the arguments in our
15466            handing of the pack expansion type.  */
15467         len = 0;
15468
15469       args1 = TREE_CHAIN (args1);
15470       args2 = TREE_CHAIN (args2);
15471     }
15472
15473   /* "In most cases, all template parameters must have values in order for
15474      deduction to succeed, but for partial ordering purposes a template
15475      parameter may remain without a value provided it is not used in the
15476      types being used for partial ordering."
15477
15478      Thus, if we are missing any of the targs1 we need to substitute into
15479      origs1, then pat2 is not as specialized as pat1.  This can happen when
15480      there is a nondeduced context.  */
15481   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
15482     lose2 = true;
15483   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
15484     lose1 = true;
15485
15486   processing_template_decl--;
15487
15488   /* All things being equal, if the next argument is a pack expansion
15489      for one function but not for the other, prefer the
15490      non-variadic function.  FIXME this is bogus; see c++/41958.  */
15491   if (lose1 == lose2
15492       && args1 && TREE_VALUE (args1)
15493       && args2 && TREE_VALUE (args2))
15494     {
15495       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
15496       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
15497     }
15498
15499   if (lose1 == lose2)
15500     return 0;
15501   else if (!lose1)
15502     return 1;
15503   else
15504     return -1;
15505 }
15506
15507 /* Determine which of two partial specializations is more specialized.
15508
15509    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
15510    to the first partial specialization.  The TREE_VALUE is the
15511    innermost set of template parameters for the partial
15512    specialization.  PAT2 is similar, but for the second template.
15513
15514    Return 1 if the first partial specialization is more specialized;
15515    -1 if the second is more specialized; 0 if neither is more
15516    specialized.
15517
15518    See [temp.class.order] for information about determining which of
15519    two templates is more specialized.  */
15520
15521 static int
15522 more_specialized_class (tree pat1, tree pat2)
15523 {
15524   tree targs;
15525   tree tmpl1, tmpl2;
15526   int winner = 0;
15527   bool any_deductions = false;
15528
15529   tmpl1 = TREE_TYPE (pat1);
15530   tmpl2 = TREE_TYPE (pat2);
15531
15532   /* Just like what happens for functions, if we are ordering between
15533      different class template specializations, we may encounter dependent
15534      types in the arguments, and we need our dependency check functions
15535      to behave correctly.  */
15536   ++processing_template_decl;
15537   targs = get_class_bindings (TREE_VALUE (pat1),
15538                               CLASSTYPE_TI_ARGS (tmpl1),
15539                               CLASSTYPE_TI_ARGS (tmpl2));
15540   if (targs)
15541     {
15542       --winner;
15543       any_deductions = true;
15544     }
15545
15546   targs = get_class_bindings (TREE_VALUE (pat2),
15547                               CLASSTYPE_TI_ARGS (tmpl2),
15548                               CLASSTYPE_TI_ARGS (tmpl1));
15549   if (targs)
15550     {
15551       ++winner;
15552       any_deductions = true;
15553     }
15554   --processing_template_decl;
15555
15556   /* In the case of a tie where at least one of the class templates
15557      has a parameter pack at the end, the template with the most
15558      non-packed parameters wins.  */
15559   if (winner == 0
15560       && any_deductions
15561       && (template_args_variadic_p (TREE_PURPOSE (pat1))
15562           || template_args_variadic_p (TREE_PURPOSE (pat2))))
15563     {
15564       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
15565       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
15566       int len1 = TREE_VEC_LENGTH (args1);
15567       int len2 = TREE_VEC_LENGTH (args2);
15568
15569       /* We don't count the pack expansion at the end.  */
15570       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
15571         --len1;
15572       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
15573         --len2;
15574
15575       if (len1 > len2)
15576         return 1;
15577       else if (len1 < len2)
15578         return -1;
15579     }
15580
15581   return winner;
15582 }
15583
15584 /* Return the template arguments that will produce the function signature
15585    DECL from the function template FN, with the explicit template
15586    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
15587    also match.  Return NULL_TREE if no satisfactory arguments could be
15588    found.  */
15589
15590 static tree
15591 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
15592 {
15593   int ntparms = DECL_NTPARMS (fn);
15594   tree targs = make_tree_vec (ntparms);
15595   tree decl_type;
15596   tree decl_arg_types;
15597   tree *args;
15598   unsigned int nargs, ix;
15599   tree arg;
15600
15601   /* Substitute the explicit template arguments into the type of DECL.
15602      The call to fn_type_unification will handle substitution into the
15603      FN.  */
15604   decl_type = TREE_TYPE (decl);
15605   if (explicit_args && uses_template_parms (decl_type))
15606     {
15607       tree tmpl;
15608       tree converted_args;
15609
15610       if (DECL_TEMPLATE_INFO (decl))
15611         tmpl = DECL_TI_TEMPLATE (decl);
15612       else
15613         /* We can get here for some invalid specializations.  */
15614         return NULL_TREE;
15615
15616       converted_args
15617         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
15618                                  explicit_args, NULL_TREE,
15619                                  tf_none,
15620                                  /*require_all_args=*/false,
15621                                  /*use_default_args=*/false);
15622       if (converted_args == error_mark_node)
15623         return NULL_TREE;
15624
15625       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
15626       if (decl_type == error_mark_node)
15627         return NULL_TREE;
15628     }
15629
15630   /* Never do unification on the 'this' parameter.  */
15631   decl_arg_types = skip_artificial_parms_for (decl, 
15632                                               TYPE_ARG_TYPES (decl_type));
15633
15634   nargs = list_length (decl_arg_types);
15635   args = XALLOCAVEC (tree, nargs);
15636   for (arg = decl_arg_types, ix = 0;
15637        arg != NULL_TREE && arg != void_list_node;
15638        arg = TREE_CHAIN (arg), ++ix)
15639     args[ix] = TREE_VALUE (arg);
15640
15641   if (fn_type_unification (fn, explicit_args, targs,
15642                            args, ix,
15643                            (check_rettype || DECL_CONV_FN_P (fn)
15644                             ? TREE_TYPE (decl_type) : NULL_TREE),
15645                            DEDUCE_EXACT, LOOKUP_NORMAL))
15646     return NULL_TREE;
15647
15648   return targs;
15649 }
15650
15651 /* Return the innermost template arguments that, when applied to a
15652    template specialization whose innermost template parameters are
15653    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
15654    ARGS.
15655
15656    For example, suppose we have:
15657
15658      template <class T, class U> struct S {};
15659      template <class T> struct S<T*, int> {};
15660
15661    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
15662    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
15663    int}.  The resulting vector will be {double}, indicating that `T'
15664    is bound to `double'.  */
15665
15666 static tree
15667 get_class_bindings (tree tparms, tree spec_args, tree args)
15668 {
15669   int i, ntparms = TREE_VEC_LENGTH (tparms);
15670   tree deduced_args;
15671   tree innermost_deduced_args;
15672
15673   innermost_deduced_args = make_tree_vec (ntparms);
15674   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15675     {
15676       deduced_args = copy_node (args);
15677       SET_TMPL_ARGS_LEVEL (deduced_args,
15678                            TMPL_ARGS_DEPTH (deduced_args),
15679                            innermost_deduced_args);
15680     }
15681   else
15682     deduced_args = innermost_deduced_args;
15683
15684   if (unify (tparms, deduced_args,
15685              INNERMOST_TEMPLATE_ARGS (spec_args),
15686              INNERMOST_TEMPLATE_ARGS (args),
15687              UNIFY_ALLOW_NONE))
15688     return NULL_TREE;
15689
15690   for (i =  0; i < ntparms; ++i)
15691     if (! TREE_VEC_ELT (innermost_deduced_args, i))
15692       return NULL_TREE;
15693
15694   /* Verify that nondeduced template arguments agree with the type
15695      obtained from argument deduction.
15696
15697      For example:
15698
15699        struct A { typedef int X; };
15700        template <class T, class U> struct C {};
15701        template <class T> struct C<T, typename T::X> {};
15702
15703      Then with the instantiation `C<A, int>', we can deduce that
15704      `T' is `A' but unify () does not check whether `typename T::X'
15705      is `int'.  */
15706   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
15707   if (spec_args == error_mark_node
15708       /* We only need to check the innermost arguments; the other
15709          arguments will always agree.  */
15710       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
15711                               INNERMOST_TEMPLATE_ARGS (args)))
15712     return NULL_TREE;
15713
15714   /* Now that we have bindings for all of the template arguments,
15715      ensure that the arguments deduced for the template template
15716      parameters have compatible template parameter lists.  See the use
15717      of template_template_parm_bindings_ok_p in fn_type_unification
15718      for more information.  */
15719   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
15720     return NULL_TREE;
15721
15722   return deduced_args;
15723 }
15724
15725 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
15726    Return the TREE_LIST node with the most specialized template, if
15727    any.  If there is no most specialized template, the error_mark_node
15728    is returned.
15729
15730    Note that this function does not look at, or modify, the
15731    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
15732    returned is one of the elements of INSTANTIATIONS, callers may
15733    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
15734    and retrieve it from the value returned.  */
15735
15736 tree
15737 most_specialized_instantiation (tree templates)
15738 {
15739   tree fn, champ;
15740
15741   ++processing_template_decl;
15742
15743   champ = templates;
15744   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
15745     {
15746       int fate = 0;
15747
15748       if (get_bindings (TREE_VALUE (champ),
15749                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15750                         NULL_TREE, /*check_ret=*/false))
15751         fate--;
15752
15753       if (get_bindings (TREE_VALUE (fn),
15754                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15755                         NULL_TREE, /*check_ret=*/false))
15756         fate++;
15757
15758       if (fate == -1)
15759         champ = fn;
15760       else if (!fate)
15761         {
15762           /* Equally specialized, move to next function.  If there
15763              is no next function, nothing's most specialized.  */
15764           fn = TREE_CHAIN (fn);
15765           champ = fn;
15766           if (!fn)
15767             break;
15768         }
15769     }
15770
15771   if (champ)
15772     /* Now verify that champ is better than everything earlier in the
15773        instantiation list.  */
15774     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
15775       if (get_bindings (TREE_VALUE (champ),
15776                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15777                         NULL_TREE, /*check_ret=*/false)
15778           || !get_bindings (TREE_VALUE (fn),
15779                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15780                             NULL_TREE, /*check_ret=*/false))
15781         {
15782           champ = NULL_TREE;
15783           break;
15784         }
15785
15786   processing_template_decl--;
15787
15788   if (!champ)
15789     return error_mark_node;
15790
15791   return champ;
15792 }
15793
15794 /* If DECL is a specialization of some template, return the most
15795    general such template.  Otherwise, returns NULL_TREE.
15796
15797    For example, given:
15798
15799      template <class T> struct S { template <class U> void f(U); };
15800
15801    if TMPL is `template <class U> void S<int>::f(U)' this will return
15802    the full template.  This function will not trace past partial
15803    specializations, however.  For example, given in addition:
15804
15805      template <class T> struct S<T*> { template <class U> void f(U); };
15806
15807    if TMPL is `template <class U> void S<int*>::f(U)' this will return
15808    `template <class T> template <class U> S<T*>::f(U)'.  */
15809
15810 tree
15811 most_general_template (tree decl)
15812 {
15813   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
15814      an immediate specialization.  */
15815   if (TREE_CODE (decl) == FUNCTION_DECL)
15816     {
15817       if (DECL_TEMPLATE_INFO (decl)) {
15818         decl = DECL_TI_TEMPLATE (decl);
15819
15820         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
15821            template friend.  */
15822         if (TREE_CODE (decl) != TEMPLATE_DECL)
15823           return NULL_TREE;
15824       } else
15825         return NULL_TREE;
15826     }
15827
15828   /* Look for more and more general templates.  */
15829   while (DECL_TEMPLATE_INFO (decl))
15830     {
15831       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
15832          (See cp-tree.h for details.)  */
15833       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
15834         break;
15835
15836       if (CLASS_TYPE_P (TREE_TYPE (decl))
15837           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
15838         break;
15839
15840       /* Stop if we run into an explicitly specialized class template.  */
15841       if (!DECL_NAMESPACE_SCOPE_P (decl)
15842           && DECL_CONTEXT (decl)
15843           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
15844         break;
15845
15846       decl = DECL_TI_TEMPLATE (decl);
15847     }
15848
15849   return decl;
15850 }
15851
15852 /* Return the most specialized of the class template partial
15853    specializations of TMPL which can produce TYPE, a specialization of
15854    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
15855    a _TYPE node corresponding to the partial specialization, while the
15856    TREE_PURPOSE is the set of template arguments that must be
15857    substituted into the TREE_TYPE in order to generate TYPE.
15858
15859    If the choice of partial specialization is ambiguous, a diagnostic
15860    is issued, and the error_mark_node is returned.  If there are no
15861    partial specializations of TMPL matching TYPE, then NULL_TREE is
15862    returned.  */
15863
15864 static tree
15865 most_specialized_class (tree type, tree tmpl)
15866 {
15867   tree list = NULL_TREE;
15868   tree t;
15869   tree champ;
15870   int fate;
15871   bool ambiguous_p;
15872   tree args;
15873   tree outer_args = NULL_TREE;
15874
15875   tmpl = most_general_template (tmpl);
15876   args = CLASSTYPE_TI_ARGS (type);
15877
15878   /* For determining which partial specialization to use, only the
15879      innermost args are interesting.  */
15880   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15881     {
15882       outer_args = strip_innermost_template_args (args, 1);
15883       args = INNERMOST_TEMPLATE_ARGS (args);
15884     }
15885
15886   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
15887     {
15888       tree partial_spec_args;
15889       tree spec_args;
15890       tree parms = TREE_VALUE (t);
15891
15892       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
15893       if (outer_args)
15894         {
15895           int i;
15896
15897           ++processing_template_decl;
15898
15899           /* Discard the outer levels of args, and then substitute in the
15900              template args from the enclosing class.  */
15901           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
15902           partial_spec_args = tsubst_template_args
15903             (partial_spec_args, outer_args, tf_none, NULL_TREE);
15904
15905           /* PARMS already refers to just the innermost parms, but the
15906              template parms in partial_spec_args had their levels lowered
15907              by tsubst, so we need to do the same for the parm list.  We
15908              can't just tsubst the TREE_VEC itself, as tsubst wants to
15909              treat a TREE_VEC as an argument vector.  */
15910           parms = copy_node (parms);
15911           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
15912             TREE_VEC_ELT (parms, i) =
15913               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
15914
15915           --processing_template_decl;
15916         }
15917       spec_args = get_class_bindings (parms,
15918                                       partial_spec_args,
15919                                       args);
15920       if (spec_args)
15921         {
15922           if (outer_args)
15923             spec_args = add_to_template_args (outer_args, spec_args);
15924           list = tree_cons (spec_args, TREE_VALUE (t), list);
15925           TREE_TYPE (list) = TREE_TYPE (t);
15926         }
15927     }
15928
15929   if (! list)
15930     return NULL_TREE;
15931
15932   ambiguous_p = false;
15933   t = list;
15934   champ = t;
15935   t = TREE_CHAIN (t);
15936   for (; t; t = TREE_CHAIN (t))
15937     {
15938       fate = more_specialized_class (champ, t);
15939       if (fate == 1)
15940         ;
15941       else
15942         {
15943           if (fate == 0)
15944             {
15945               t = TREE_CHAIN (t);
15946               if (! t)
15947                 {
15948                   ambiguous_p = true;
15949                   break;
15950                 }
15951             }
15952           champ = t;
15953         }
15954     }
15955
15956   if (!ambiguous_p)
15957     for (t = list; t && t != champ; t = TREE_CHAIN (t))
15958       {
15959         fate = more_specialized_class (champ, t);
15960         if (fate != 1)
15961           {
15962             ambiguous_p = true;
15963             break;
15964           }
15965       }
15966
15967   if (ambiguous_p)
15968     {
15969       const char *str;
15970       char *spaces = NULL;
15971       error ("ambiguous class template instantiation for %q#T", type);
15972       str = TREE_CHAIN (list) ? _("candidates are:") : _("candidate is:");
15973       for (t = list; t; t = TREE_CHAIN (t))
15974         {
15975           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
15976           spaces = spaces ? spaces : get_spaces (str);
15977         }
15978       free (spaces);
15979       return error_mark_node;
15980     }
15981
15982   return champ;
15983 }
15984
15985 /* Explicitly instantiate DECL.  */
15986
15987 void
15988 do_decl_instantiation (tree decl, tree storage)
15989 {
15990   tree result = NULL_TREE;
15991   int extern_p = 0;
15992
15993   if (!decl || decl == error_mark_node)
15994     /* An error occurred, for which grokdeclarator has already issued
15995        an appropriate message.  */
15996     return;
15997   else if (! DECL_LANG_SPECIFIC (decl))
15998     {
15999       error ("explicit instantiation of non-template %q#D", decl);
16000       return;
16001     }
16002   else if (TREE_CODE (decl) == VAR_DECL)
16003     {
16004       /* There is an asymmetry here in the way VAR_DECLs and
16005          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
16006          the latter, the DECL we get back will be marked as a
16007          template instantiation, and the appropriate
16008          DECL_TEMPLATE_INFO will be set up.  This does not happen for
16009          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
16010          should handle VAR_DECLs as it currently handles
16011          FUNCTION_DECLs.  */
16012       if (!DECL_CLASS_SCOPE_P (decl))
16013         {
16014           error ("%qD is not a static data member of a class template", decl);
16015           return;
16016         }
16017       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
16018       if (!result || TREE_CODE (result) != VAR_DECL)
16019         {
16020           error ("no matching template for %qD found", decl);
16021           return;
16022         }
16023       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
16024         {
16025           error ("type %qT for explicit instantiation %qD does not match "
16026                  "declared type %qT", TREE_TYPE (result), decl,
16027                  TREE_TYPE (decl));
16028           return;
16029         }
16030     }
16031   else if (TREE_CODE (decl) != FUNCTION_DECL)
16032     {
16033       error ("explicit instantiation of %q#D", decl);
16034       return;
16035     }
16036   else
16037     result = decl;
16038
16039   /* Check for various error cases.  Note that if the explicit
16040      instantiation is valid the RESULT will currently be marked as an
16041      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
16042      until we get here.  */
16043
16044   if (DECL_TEMPLATE_SPECIALIZATION (result))
16045     {
16046       /* DR 259 [temp.spec].
16047
16048          Both an explicit instantiation and a declaration of an explicit
16049          specialization shall not appear in a program unless the explicit
16050          instantiation follows a declaration of the explicit specialization.
16051
16052          For a given set of template parameters, if an explicit
16053          instantiation of a template appears after a declaration of an
16054          explicit specialization for that template, the explicit
16055          instantiation has no effect.  */
16056       return;
16057     }
16058   else if (DECL_EXPLICIT_INSTANTIATION (result))
16059     {
16060       /* [temp.spec]
16061
16062          No program shall explicitly instantiate any template more
16063          than once.
16064
16065          We check DECL_NOT_REALLY_EXTERN so as not to complain when
16066          the first instantiation was `extern' and the second is not,
16067          and EXTERN_P for the opposite case.  */
16068       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
16069         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
16070       /* If an "extern" explicit instantiation follows an ordinary
16071          explicit instantiation, the template is instantiated.  */
16072       if (extern_p)
16073         return;
16074     }
16075   else if (!DECL_IMPLICIT_INSTANTIATION (result))
16076     {
16077       error ("no matching template for %qD found", result);
16078       return;
16079     }
16080   else if (!DECL_TEMPLATE_INFO (result))
16081     {
16082       permerror (input_location, "explicit instantiation of non-template %q#D", result);
16083       return;
16084     }
16085
16086   if (storage == NULL_TREE)
16087     ;
16088   else if (storage == ridpointers[(int) RID_EXTERN])
16089     {
16090       if (!in_system_header && (cxx_dialect == cxx98))
16091         pedwarn (input_location, OPT_pedantic, 
16092                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
16093                  "instantiations");
16094       extern_p = 1;
16095     }
16096   else
16097     error ("storage class %qD applied to template instantiation", storage);
16098
16099   check_explicit_instantiation_namespace (result);
16100   mark_decl_instantiated (result, extern_p);
16101   if (! extern_p)
16102     instantiate_decl (result, /*defer_ok=*/1,
16103                       /*expl_inst_class_mem_p=*/false);
16104 }
16105
16106 static void
16107 mark_class_instantiated (tree t, int extern_p)
16108 {
16109   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
16110   SET_CLASSTYPE_INTERFACE_KNOWN (t);
16111   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
16112   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
16113   if (! extern_p)
16114     {
16115       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
16116       rest_of_type_compilation (t, 1);
16117     }
16118 }
16119
16120 /* Called from do_type_instantiation through binding_table_foreach to
16121    do recursive instantiation for the type bound in ENTRY.  */
16122 static void
16123 bt_instantiate_type_proc (binding_entry entry, void *data)
16124 {
16125   tree storage = *(tree *) data;
16126
16127   if (MAYBE_CLASS_TYPE_P (entry->type)
16128       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
16129     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
16130 }
16131
16132 /* Called from do_type_instantiation to instantiate a member
16133    (a member function or a static member variable) of an
16134    explicitly instantiated class template.  */
16135 static void
16136 instantiate_class_member (tree decl, int extern_p)
16137 {
16138   mark_decl_instantiated (decl, extern_p);
16139   if (! extern_p)
16140     instantiate_decl (decl, /*defer_ok=*/1,
16141                       /*expl_inst_class_mem_p=*/true);
16142 }
16143
16144 /* Perform an explicit instantiation of template class T.  STORAGE, if
16145    non-null, is the RID for extern, inline or static.  COMPLAIN is
16146    nonzero if this is called from the parser, zero if called recursively,
16147    since the standard is unclear (as detailed below).  */
16148
16149 void
16150 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
16151 {
16152   int extern_p = 0;
16153   int nomem_p = 0;
16154   int static_p = 0;
16155   int previous_instantiation_extern_p = 0;
16156
16157   if (TREE_CODE (t) == TYPE_DECL)
16158     t = TREE_TYPE (t);
16159
16160   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
16161     {
16162       error ("explicit instantiation of non-template type %qT", t);
16163       return;
16164     }
16165
16166   complete_type (t);
16167
16168   if (!COMPLETE_TYPE_P (t))
16169     {
16170       if (complain & tf_error)
16171         error ("explicit instantiation of %q#T before definition of template",
16172                t);
16173       return;
16174     }
16175
16176   if (storage != NULL_TREE)
16177     {
16178       if (!in_system_header)
16179         {
16180           if (storage == ridpointers[(int) RID_EXTERN])
16181             {
16182               if (cxx_dialect == cxx98)
16183                 pedwarn (input_location, OPT_pedantic, 
16184                          "ISO C++ 1998 forbids the use of %<extern%> on "
16185                          "explicit instantiations");
16186             }
16187           else
16188             pedwarn (input_location, OPT_pedantic, 
16189                      "ISO C++ forbids the use of %qE"
16190                      " on explicit instantiations", storage);
16191         }
16192
16193       if (storage == ridpointers[(int) RID_INLINE])
16194         nomem_p = 1;
16195       else if (storage == ridpointers[(int) RID_EXTERN])
16196         extern_p = 1;
16197       else if (storage == ridpointers[(int) RID_STATIC])
16198         static_p = 1;
16199       else
16200         {
16201           error ("storage class %qD applied to template instantiation",
16202                  storage);
16203           extern_p = 0;
16204         }
16205     }
16206
16207   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
16208     {
16209       /* DR 259 [temp.spec].
16210
16211          Both an explicit instantiation and a declaration of an explicit
16212          specialization shall not appear in a program unless the explicit
16213          instantiation follows a declaration of the explicit specialization.
16214
16215          For a given set of template parameters, if an explicit
16216          instantiation of a template appears after a declaration of an
16217          explicit specialization for that template, the explicit
16218          instantiation has no effect.  */
16219       return;
16220     }
16221   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
16222     {
16223       /* [temp.spec]
16224
16225          No program shall explicitly instantiate any template more
16226          than once.
16227
16228          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
16229          instantiation was `extern'.  If EXTERN_P then the second is.
16230          These cases are OK.  */
16231       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
16232
16233       if (!previous_instantiation_extern_p && !extern_p
16234           && (complain & tf_error))
16235         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
16236
16237       /* If we've already instantiated the template, just return now.  */
16238       if (!CLASSTYPE_INTERFACE_ONLY (t))
16239         return;
16240     }
16241
16242   check_explicit_instantiation_namespace (TYPE_NAME (t));
16243   mark_class_instantiated (t, extern_p);
16244
16245   if (nomem_p)
16246     return;
16247
16248   {
16249     tree tmp;
16250
16251     /* In contrast to implicit instantiation, where only the
16252        declarations, and not the definitions, of members are
16253        instantiated, we have here:
16254
16255          [temp.explicit]
16256
16257          The explicit instantiation of a class template specialization
16258          implies the instantiation of all of its members not
16259          previously explicitly specialized in the translation unit
16260          containing the explicit instantiation.
16261
16262        Of course, we can't instantiate member template classes, since
16263        we don't have any arguments for them.  Note that the standard
16264        is unclear on whether the instantiation of the members are
16265        *explicit* instantiations or not.  However, the most natural
16266        interpretation is that it should be an explicit instantiation.  */
16267
16268     if (! static_p)
16269       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
16270         if (TREE_CODE (tmp) == FUNCTION_DECL
16271             && DECL_TEMPLATE_INSTANTIATION (tmp))
16272           instantiate_class_member (tmp, extern_p);
16273
16274     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
16275       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
16276         instantiate_class_member (tmp, extern_p);
16277
16278     if (CLASSTYPE_NESTED_UTDS (t))
16279       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
16280                              bt_instantiate_type_proc, &storage);
16281   }
16282 }
16283
16284 /* Given a function DECL, which is a specialization of TMPL, modify
16285    DECL to be a re-instantiation of TMPL with the same template
16286    arguments.  TMPL should be the template into which tsubst'ing
16287    should occur for DECL, not the most general template.
16288
16289    One reason for doing this is a scenario like this:
16290
16291      template <class T>
16292      void f(const T&, int i);
16293
16294      void g() { f(3, 7); }
16295
16296      template <class T>
16297      void f(const T& t, const int i) { }
16298
16299    Note that when the template is first instantiated, with
16300    instantiate_template, the resulting DECL will have no name for the
16301    first parameter, and the wrong type for the second.  So, when we go
16302    to instantiate the DECL, we regenerate it.  */
16303
16304 static void
16305 regenerate_decl_from_template (tree decl, tree tmpl)
16306 {
16307   /* The arguments used to instantiate DECL, from the most general
16308      template.  */
16309   tree args;
16310   tree code_pattern;
16311
16312   args = DECL_TI_ARGS (decl);
16313   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
16314
16315   /* Make sure that we can see identifiers, and compute access
16316      correctly.  */
16317   push_access_scope (decl);
16318
16319   if (TREE_CODE (decl) == FUNCTION_DECL)
16320     {
16321       tree decl_parm;
16322       tree pattern_parm;
16323       tree specs;
16324       int args_depth;
16325       int parms_depth;
16326
16327       args_depth = TMPL_ARGS_DEPTH (args);
16328       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
16329       if (args_depth > parms_depth)
16330         args = get_innermost_template_args (args, parms_depth);
16331
16332       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
16333                                               args, tf_error, NULL_TREE);
16334       if (specs)
16335         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
16336                                                     specs);
16337
16338       /* Merge parameter declarations.  */
16339       decl_parm = skip_artificial_parms_for (decl,
16340                                              DECL_ARGUMENTS (decl));
16341       pattern_parm
16342         = skip_artificial_parms_for (code_pattern,
16343                                      DECL_ARGUMENTS (code_pattern));
16344       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
16345         {
16346           tree parm_type;
16347           tree attributes;
16348           
16349           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16350             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
16351           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
16352                               NULL_TREE);
16353           parm_type = type_decays_to (parm_type);
16354           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16355             TREE_TYPE (decl_parm) = parm_type;
16356           attributes = DECL_ATTRIBUTES (pattern_parm);
16357           if (DECL_ATTRIBUTES (decl_parm) != attributes)
16358             {
16359               DECL_ATTRIBUTES (decl_parm) = attributes;
16360               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16361             }
16362           decl_parm = TREE_CHAIN (decl_parm);
16363           pattern_parm = TREE_CHAIN (pattern_parm);
16364         }
16365       /* Merge any parameters that match with the function parameter
16366          pack.  */
16367       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
16368         {
16369           int i, len;
16370           tree expanded_types;
16371           /* Expand the TYPE_PACK_EXPANSION that provides the types for
16372              the parameters in this function parameter pack.  */
16373           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
16374                                                  args, tf_error, NULL_TREE);
16375           len = TREE_VEC_LENGTH (expanded_types);
16376           for (i = 0; i < len; i++)
16377             {
16378               tree parm_type;
16379               tree attributes;
16380           
16381               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16382                 /* Rename the parameter to include the index.  */
16383                 DECL_NAME (decl_parm) = 
16384                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
16385               parm_type = TREE_VEC_ELT (expanded_types, i);
16386               parm_type = type_decays_to (parm_type);
16387               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16388                 TREE_TYPE (decl_parm) = parm_type;
16389               attributes = DECL_ATTRIBUTES (pattern_parm);
16390               if (DECL_ATTRIBUTES (decl_parm) != attributes)
16391                 {
16392                   DECL_ATTRIBUTES (decl_parm) = attributes;
16393                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16394                 }
16395               decl_parm = TREE_CHAIN (decl_parm);
16396             }
16397         }
16398       /* Merge additional specifiers from the CODE_PATTERN.  */
16399       if (DECL_DECLARED_INLINE_P (code_pattern)
16400           && !DECL_DECLARED_INLINE_P (decl))
16401         DECL_DECLARED_INLINE_P (decl) = 1;
16402     }
16403   else if (TREE_CODE (decl) == VAR_DECL)
16404     DECL_INITIAL (decl) =
16405       tsubst_expr (DECL_INITIAL (code_pattern), args,
16406                    tf_error, DECL_TI_TEMPLATE (decl),
16407                    /*integral_constant_expression_p=*/false);
16408   else
16409     gcc_unreachable ();
16410
16411   pop_access_scope (decl);
16412 }
16413
16414 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
16415    substituted to get DECL.  */
16416
16417 tree
16418 template_for_substitution (tree decl)
16419 {
16420   tree tmpl = DECL_TI_TEMPLATE (decl);
16421
16422   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
16423      for the instantiation.  This is not always the most general
16424      template.  Consider, for example:
16425
16426         template <class T>
16427         struct S { template <class U> void f();
16428                    template <> void f<int>(); };
16429
16430      and an instantiation of S<double>::f<int>.  We want TD to be the
16431      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
16432   while (/* An instantiation cannot have a definition, so we need a
16433             more general template.  */
16434          DECL_TEMPLATE_INSTANTIATION (tmpl)
16435            /* We must also deal with friend templates.  Given:
16436
16437                 template <class T> struct S {
16438                   template <class U> friend void f() {};
16439                 };
16440
16441               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
16442               so far as the language is concerned, but that's still
16443               where we get the pattern for the instantiation from.  On
16444               other hand, if the definition comes outside the class, say:
16445
16446                 template <class T> struct S {
16447                   template <class U> friend void f();
16448                 };
16449                 template <class U> friend void f() {}
16450
16451               we don't need to look any further.  That's what the check for
16452               DECL_INITIAL is for.  */
16453           || (TREE_CODE (decl) == FUNCTION_DECL
16454               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
16455               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
16456     {
16457       /* The present template, TD, should not be a definition.  If it
16458          were a definition, we should be using it!  Note that we
16459          cannot restructure the loop to just keep going until we find
16460          a template with a definition, since that might go too far if
16461          a specialization was declared, but not defined.  */
16462       gcc_assert (TREE_CODE (decl) != VAR_DECL
16463                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
16464
16465       /* Fetch the more general template.  */
16466       tmpl = DECL_TI_TEMPLATE (tmpl);
16467     }
16468
16469   return tmpl;
16470 }
16471
16472 /* Returns true if we need to instantiate this template instance even if we
16473    know we aren't going to emit it..  */
16474
16475 bool
16476 always_instantiate_p (tree decl)
16477 {
16478   /* We always instantiate inline functions so that we can inline them.  An
16479      explicit instantiation declaration prohibits implicit instantiation of
16480      non-inline functions.  With high levels of optimization, we would
16481      normally inline non-inline functions -- but we're not allowed to do
16482      that for "extern template" functions.  Therefore, we check
16483      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
16484   return ((TREE_CODE (decl) == FUNCTION_DECL
16485            && DECL_DECLARED_INLINE_P (decl))
16486           /* And we need to instantiate static data members so that
16487              their initializers are available in integral constant
16488              expressions.  */
16489           || (TREE_CODE (decl) == VAR_DECL
16490               && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl)));
16491 }
16492
16493 /* Produce the definition of D, a _DECL generated from a template.  If
16494    DEFER_OK is nonzero, then we don't have to actually do the
16495    instantiation now; we just have to do it sometime.  Normally it is
16496    an error if this is an explicit instantiation but D is undefined.
16497    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
16498    explicitly instantiated class template.  */
16499
16500 tree
16501 instantiate_decl (tree d, int defer_ok,
16502                   bool expl_inst_class_mem_p)
16503 {
16504   tree tmpl = DECL_TI_TEMPLATE (d);
16505   tree gen_args;
16506   tree args;
16507   tree td;
16508   tree code_pattern;
16509   tree spec;
16510   tree gen_tmpl;
16511   bool pattern_defined;
16512   int need_push;
16513   location_t saved_loc = input_location;
16514   bool external_p;
16515
16516   /* This function should only be used to instantiate templates for
16517      functions and static member variables.  */
16518   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
16519               || TREE_CODE (d) == VAR_DECL);
16520
16521   /* Variables are never deferred; if instantiation is required, they
16522      are instantiated right away.  That allows for better code in the
16523      case that an expression refers to the value of the variable --
16524      if the variable has a constant value the referring expression can
16525      take advantage of that fact.  */
16526   if (TREE_CODE (d) == VAR_DECL)
16527     defer_ok = 0;
16528
16529   /* Don't instantiate cloned functions.  Instead, instantiate the
16530      functions they cloned.  */
16531   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
16532     d = DECL_CLONED_FUNCTION (d);
16533
16534   if (DECL_TEMPLATE_INSTANTIATED (d)
16535       || DECL_TEMPLATE_SPECIALIZATION (d))
16536     /* D has already been instantiated or explicitly specialized, so
16537        there's nothing for us to do here.
16538
16539        It might seem reasonable to check whether or not D is an explicit
16540        instantiation, and, if so, stop here.  But when an explicit
16541        instantiation is deferred until the end of the compilation,
16542        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
16543        the instantiation.  */
16544     return d;
16545
16546   /* Check to see whether we know that this template will be
16547      instantiated in some other file, as with "extern template"
16548      extension.  */
16549   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
16550
16551   /* In general, we do not instantiate such templates.  */
16552   if (external_p && !always_instantiate_p (d))
16553     return d;
16554
16555   gen_tmpl = most_general_template (tmpl);
16556   gen_args = DECL_TI_ARGS (d);
16557
16558   if (tmpl != gen_tmpl)
16559     /* We should already have the extra args.  */
16560     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
16561                 == TMPL_ARGS_DEPTH (gen_args));
16562   /* And what's in the hash table should match D.  */
16563   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
16564               || spec == NULL_TREE);
16565
16566   /* This needs to happen before any tsubsting.  */
16567   if (! push_tinst_level (d))
16568     return d;
16569
16570   timevar_push (TV_PARSE);
16571
16572   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
16573      for the instantiation.  */
16574   td = template_for_substitution (d);
16575   code_pattern = DECL_TEMPLATE_RESULT (td);
16576
16577   /* We should never be trying to instantiate a member of a class
16578      template or partial specialization.  */
16579   gcc_assert (d != code_pattern);
16580
16581   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
16582       || DECL_TEMPLATE_SPECIALIZATION (td))
16583     /* In the case of a friend template whose definition is provided
16584        outside the class, we may have too many arguments.  Drop the
16585        ones we don't need.  The same is true for specializations.  */
16586     args = get_innermost_template_args
16587       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
16588   else
16589     args = gen_args;
16590
16591   if (TREE_CODE (d) == FUNCTION_DECL)
16592     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
16593   else
16594     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
16595
16596   /* We may be in the middle of deferred access check.  Disable it now.  */
16597   push_deferring_access_checks (dk_no_deferred);
16598
16599   /* Unless an explicit instantiation directive has already determined
16600      the linkage of D, remember that a definition is available for
16601      this entity.  */
16602   if (pattern_defined
16603       && !DECL_INTERFACE_KNOWN (d)
16604       && !DECL_NOT_REALLY_EXTERN (d))
16605     mark_definable (d);
16606
16607   input_location = DECL_SOURCE_LOCATION (d);
16608
16609   /* If D is a member of an explicitly instantiated class template,
16610      and no definition is available, treat it like an implicit
16611      instantiation.  */
16612   if (!pattern_defined && expl_inst_class_mem_p
16613       && DECL_EXPLICIT_INSTANTIATION (d))
16614     {
16615       DECL_NOT_REALLY_EXTERN (d) = 0;
16616       DECL_INTERFACE_KNOWN (d) = 0;
16617       SET_DECL_IMPLICIT_INSTANTIATION (d);
16618     }
16619
16620   /* Recheck the substitutions to obtain any warning messages
16621      about ignoring cv qualifiers.  Don't do this for artificial decls,
16622      as it breaks the context-sensitive substitution for lambda op(). */
16623   if (!defer_ok && !DECL_ARTIFICIAL (d))
16624     {
16625       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
16626       tree type = TREE_TYPE (gen);
16627
16628       /* Make sure that we can see identifiers, and compute access
16629          correctly.  D is already the target FUNCTION_DECL with the
16630          right context.  */
16631       push_access_scope (d);
16632
16633       if (TREE_CODE (gen) == FUNCTION_DECL)
16634         {
16635           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
16636           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
16637                                           d);
16638           /* Don't simply tsubst the function type, as that will give
16639              duplicate warnings about poor parameter qualifications.
16640              The function arguments are the same as the decl_arguments
16641              without the top level cv qualifiers.  */
16642           type = TREE_TYPE (type);
16643         }
16644       tsubst (type, gen_args, tf_warning_or_error, d);
16645
16646       pop_access_scope (d);
16647     }
16648
16649   /* Defer all other templates, unless we have been explicitly
16650      forbidden from doing so.  */
16651   if (/* If there is no definition, we cannot instantiate the
16652          template.  */
16653       ! pattern_defined
16654       /* If it's OK to postpone instantiation, do so.  */
16655       || defer_ok
16656       /* If this is a static data member that will be defined
16657          elsewhere, we don't want to instantiate the entire data
16658          member, but we do want to instantiate the initializer so that
16659          we can substitute that elsewhere.  */
16660       || (external_p && TREE_CODE (d) == VAR_DECL))
16661     {
16662       /* The definition of the static data member is now required so
16663          we must substitute the initializer.  */
16664       if (TREE_CODE (d) == VAR_DECL
16665           && !DECL_INITIAL (d)
16666           && DECL_INITIAL (code_pattern))
16667         {
16668           tree ns;
16669           tree init;
16670
16671           ns = decl_namespace_context (d);
16672           push_nested_namespace (ns);
16673           push_nested_class (DECL_CONTEXT (d));
16674           init = tsubst_expr (DECL_INITIAL (code_pattern),
16675                               args,
16676                               tf_warning_or_error, NULL_TREE,
16677                               /*integral_constant_expression_p=*/false);
16678           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
16679                           /*asmspec_tree=*/NULL_TREE,
16680                           LOOKUP_ONLYCONVERTING);
16681           pop_nested_class ();
16682           pop_nested_namespace (ns);
16683         }
16684
16685       /* We restore the source position here because it's used by
16686          add_pending_template.  */
16687       input_location = saved_loc;
16688
16689       if (at_eof && !pattern_defined
16690           && DECL_EXPLICIT_INSTANTIATION (d)
16691           && DECL_NOT_REALLY_EXTERN (d))
16692         /* [temp.explicit]
16693
16694            The definition of a non-exported function template, a
16695            non-exported member function template, or a non-exported
16696            member function or static data member of a class template
16697            shall be present in every translation unit in which it is
16698            explicitly instantiated.  */
16699         permerror (input_location,  "explicit instantiation of %qD "
16700                    "but no definition available", d);
16701
16702       /* ??? Historically, we have instantiated inline functions, even
16703          when marked as "extern template".  */
16704       if (!(external_p && TREE_CODE (d) == VAR_DECL))
16705         add_pending_template (d);
16706       goto out;
16707     }
16708   /* Tell the repository that D is available in this translation unit
16709      -- and see if it is supposed to be instantiated here.  */
16710   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
16711     {
16712       /* In a PCH file, despite the fact that the repository hasn't
16713          requested instantiation in the PCH it is still possible that
16714          an instantiation will be required in a file that includes the
16715          PCH.  */
16716       if (pch_file)
16717         add_pending_template (d);
16718       /* Instantiate inline functions so that the inliner can do its
16719          job, even though we'll not be emitting a copy of this
16720          function.  */
16721       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
16722         goto out;
16723     }
16724
16725   need_push = !cfun || !global_bindings_p ();
16726   if (need_push)
16727     push_to_top_level ();
16728
16729   /* Mark D as instantiated so that recursive calls to
16730      instantiate_decl do not try to instantiate it again.  */
16731   DECL_TEMPLATE_INSTANTIATED (d) = 1;
16732
16733   /* Regenerate the declaration in case the template has been modified
16734      by a subsequent redeclaration.  */
16735   regenerate_decl_from_template (d, td);
16736
16737   /* We already set the file and line above.  Reset them now in case
16738      they changed as a result of calling regenerate_decl_from_template.  */
16739   input_location = DECL_SOURCE_LOCATION (d);
16740
16741   if (TREE_CODE (d) == VAR_DECL)
16742     {
16743       tree init;
16744
16745       /* Clear out DECL_RTL; whatever was there before may not be right
16746          since we've reset the type of the declaration.  */
16747       SET_DECL_RTL (d, NULL_RTX);
16748       DECL_IN_AGGR_P (d) = 0;
16749
16750       /* The initializer is placed in DECL_INITIAL by
16751          regenerate_decl_from_template.  Pull it out so that
16752          cp_finish_decl can process it.  */
16753       init = DECL_INITIAL (d);
16754       DECL_INITIAL (d) = NULL_TREE;
16755       DECL_INITIALIZED_P (d) = 0;
16756
16757       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
16758          initializer.  That function will defer actual emission until
16759          we have a chance to determine linkage.  */
16760       DECL_EXTERNAL (d) = 0;
16761
16762       /* Enter the scope of D so that access-checking works correctly.  */
16763       push_nested_class (DECL_CONTEXT (d));
16764       cp_finish_decl (d, init, false, NULL_TREE, 0);
16765       pop_nested_class ();
16766     }
16767   else if (TREE_CODE (d) == FUNCTION_DECL)
16768     {
16769       htab_t saved_local_specializations;
16770       tree subst_decl;
16771       tree tmpl_parm;
16772       tree spec_parm;
16773
16774       /* Save away the current list, in case we are instantiating one
16775          template from within the body of another.  */
16776       saved_local_specializations = local_specializations;
16777
16778       /* Set up the list of local specializations.  */
16779       local_specializations = htab_create (37,
16780                                            hash_local_specialization,
16781                                            eq_local_specializations,
16782                                            NULL);
16783
16784       /* Set up context.  */
16785       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
16786
16787       /* Create substitution entries for the parameters.  */
16788       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
16789       tmpl_parm = DECL_ARGUMENTS (subst_decl);
16790       spec_parm = DECL_ARGUMENTS (d);
16791       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
16792         {
16793           register_local_specialization (spec_parm, tmpl_parm);
16794           spec_parm = skip_artificial_parms_for (d, spec_parm);
16795           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
16796         }
16797       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16798         {
16799           register_local_specialization (spec_parm, tmpl_parm);
16800           tmpl_parm = TREE_CHAIN (tmpl_parm);
16801           spec_parm = TREE_CHAIN (spec_parm);
16802         }
16803       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16804         {
16805           /* Register the (value) argument pack as a specialization of
16806              TMPL_PARM, then move on.  */
16807           tree argpack = make_fnparm_pack (spec_parm);
16808           register_local_specialization (argpack, tmpl_parm);
16809           tmpl_parm = TREE_CHAIN (tmpl_parm);
16810           spec_parm = NULL_TREE;
16811         }
16812       gcc_assert (!spec_parm);
16813
16814       /* Substitute into the body of the function.  */
16815       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
16816                    tf_warning_or_error, tmpl,
16817                    /*integral_constant_expression_p=*/false);
16818
16819       /* Set the current input_location to the end of the function
16820          so that finish_function knows where we are.  */
16821       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
16822
16823       /* We don't need the local specializations any more.  */
16824       htab_delete (local_specializations);
16825       local_specializations = saved_local_specializations;
16826
16827       /* Finish the function.  */
16828       d = finish_function (0);
16829       expand_or_defer_fn (d);
16830     }
16831
16832   /* We're not deferring instantiation any more.  */
16833   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
16834
16835   if (need_push)
16836     pop_from_top_level ();
16837
16838 out:
16839   input_location = saved_loc;
16840   pop_deferring_access_checks ();
16841   pop_tinst_level ();
16842
16843   timevar_pop (TV_PARSE);
16844
16845   return d;
16846 }
16847
16848 /* Run through the list of templates that we wish we could
16849    instantiate, and instantiate any we can.  RETRIES is the
16850    number of times we retry pending template instantiation.  */
16851
16852 void
16853 instantiate_pending_templates (int retries)
16854 {
16855   int reconsider;
16856   location_t saved_loc = input_location;
16857
16858   /* Instantiating templates may trigger vtable generation.  This in turn
16859      may require further template instantiations.  We place a limit here
16860      to avoid infinite loop.  */
16861   if (pending_templates && retries >= max_tinst_depth)
16862     {
16863       tree decl = pending_templates->tinst->decl;
16864
16865       error ("template instantiation depth exceeds maximum of %d"
16866              " instantiating %q+D, possibly from virtual table generation"
16867              " (use -ftemplate-depth= to increase the maximum)",
16868              max_tinst_depth, decl);
16869       if (TREE_CODE (decl) == FUNCTION_DECL)
16870         /* Pretend that we defined it.  */
16871         DECL_INITIAL (decl) = error_mark_node;
16872       return;
16873     }
16874
16875   do
16876     {
16877       struct pending_template **t = &pending_templates;
16878       struct pending_template *last = NULL;
16879       reconsider = 0;
16880       while (*t)
16881         {
16882           tree instantiation = reopen_tinst_level ((*t)->tinst);
16883           bool complete = false;
16884
16885           if (TYPE_P (instantiation))
16886             {
16887               tree fn;
16888
16889               if (!COMPLETE_TYPE_P (instantiation))
16890                 {
16891                   instantiate_class_template (instantiation);
16892                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
16893                     for (fn = TYPE_METHODS (instantiation);
16894                          fn;
16895                          fn = TREE_CHAIN (fn))
16896                       if (! DECL_ARTIFICIAL (fn))
16897                         instantiate_decl (fn,
16898                                           /*defer_ok=*/0,
16899                                           /*expl_inst_class_mem_p=*/false);
16900                   if (COMPLETE_TYPE_P (instantiation))
16901                     reconsider = 1;
16902                 }
16903
16904               complete = COMPLETE_TYPE_P (instantiation);
16905             }
16906           else
16907             {
16908               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
16909                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
16910                 {
16911                   instantiation
16912                     = instantiate_decl (instantiation,
16913                                         /*defer_ok=*/0,
16914                                         /*expl_inst_class_mem_p=*/false);
16915                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
16916                     reconsider = 1;
16917                 }
16918
16919               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
16920                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
16921             }
16922
16923           if (complete)
16924             /* If INSTANTIATION has been instantiated, then we don't
16925                need to consider it again in the future.  */
16926             *t = (*t)->next;
16927           else
16928             {
16929               last = *t;
16930               t = &(*t)->next;
16931             }
16932           tinst_depth = 0;
16933           current_tinst_level = NULL;
16934         }
16935       last_pending_template = last;
16936     }
16937   while (reconsider);
16938
16939   input_location = saved_loc;
16940 }
16941
16942 /* Substitute ARGVEC into T, which is a list of initializers for
16943    either base class or a non-static data member.  The TREE_PURPOSEs
16944    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
16945    instantiate_decl.  */
16946
16947 static tree
16948 tsubst_initializer_list (tree t, tree argvec)
16949 {
16950   tree inits = NULL_TREE;
16951
16952   for (; t; t = TREE_CHAIN (t))
16953     {
16954       tree decl;
16955       tree init;
16956       tree expanded_bases = NULL_TREE;
16957       tree expanded_arguments = NULL_TREE;
16958       int i, len = 1;
16959
16960       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
16961         {
16962           tree expr;
16963           tree arg;
16964
16965           /* Expand the base class expansion type into separate base
16966              classes.  */
16967           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
16968                                                  tf_warning_or_error,
16969                                                  NULL_TREE);
16970           if (expanded_bases == error_mark_node)
16971             continue;
16972           
16973           /* We'll be building separate TREE_LISTs of arguments for
16974              each base.  */
16975           len = TREE_VEC_LENGTH (expanded_bases);
16976           expanded_arguments = make_tree_vec (len);
16977           for (i = 0; i < len; i++)
16978             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
16979
16980           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
16981              expand each argument in the TREE_VALUE of t.  */
16982           expr = make_node (EXPR_PACK_EXPANSION);
16983           PACK_EXPANSION_PARAMETER_PACKS (expr) =
16984             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
16985
16986           if (TREE_VALUE (t) == void_type_node)
16987             /* VOID_TYPE_NODE is used to indicate
16988                value-initialization.  */
16989             {
16990               for (i = 0; i < len; i++)
16991                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
16992             }
16993           else
16994             {
16995               /* Substitute parameter packs into each argument in the
16996                  TREE_LIST.  */
16997               in_base_initializer = 1;
16998               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
16999                 {
17000                   tree expanded_exprs;
17001
17002                   /* Expand the argument.  */
17003                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
17004                   expanded_exprs 
17005                     = tsubst_pack_expansion (expr, argvec,
17006                                              tf_warning_or_error,
17007                                              NULL_TREE);
17008                   if (expanded_exprs == error_mark_node)
17009                     continue;
17010
17011                   /* Prepend each of the expanded expressions to the
17012                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
17013                   for (i = 0; i < len; i++)
17014                     {
17015                       TREE_VEC_ELT (expanded_arguments, i) = 
17016                         tree_cons (NULL_TREE, 
17017                                    TREE_VEC_ELT (expanded_exprs, i),
17018                                    TREE_VEC_ELT (expanded_arguments, i));
17019                     }
17020                 }
17021               in_base_initializer = 0;
17022
17023               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
17024                  since we built them backwards.  */
17025               for (i = 0; i < len; i++)
17026                 {
17027                   TREE_VEC_ELT (expanded_arguments, i) = 
17028                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
17029                 }
17030             }
17031         }
17032
17033       for (i = 0; i < len; ++i)
17034         {
17035           if (expanded_bases)
17036             {
17037               decl = TREE_VEC_ELT (expanded_bases, i);
17038               decl = expand_member_init (decl);
17039               init = TREE_VEC_ELT (expanded_arguments, i);
17040             }
17041           else
17042             {
17043               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
17044                                   tf_warning_or_error, NULL_TREE);
17045
17046               decl = expand_member_init (decl);
17047               if (decl && !DECL_P (decl))
17048                 in_base_initializer = 1;
17049
17050               init = tsubst_expr (TREE_VALUE (t), argvec, 
17051                                   tf_warning_or_error, NULL_TREE,
17052                                   /*integral_constant_expression_p=*/false);
17053               in_base_initializer = 0;
17054             }
17055
17056           if (decl)
17057             {
17058               init = build_tree_list (decl, init);
17059               TREE_CHAIN (init) = inits;
17060               inits = init;
17061             }
17062         }
17063     }
17064   return inits;
17065 }
17066
17067 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
17068
17069 static void
17070 set_current_access_from_decl (tree decl)
17071 {
17072   if (TREE_PRIVATE (decl))
17073     current_access_specifier = access_private_node;
17074   else if (TREE_PROTECTED (decl))
17075     current_access_specifier = access_protected_node;
17076   else
17077     current_access_specifier = access_public_node;
17078 }
17079
17080 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
17081    is the instantiation (which should have been created with
17082    start_enum) and ARGS are the template arguments to use.  */
17083
17084 static void
17085 tsubst_enum (tree tag, tree newtag, tree args)
17086 {
17087   tree e;
17088
17089   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
17090     {
17091       tree value;
17092       tree decl;
17093
17094       decl = TREE_VALUE (e);
17095       /* Note that in a template enum, the TREE_VALUE is the
17096          CONST_DECL, not the corresponding INTEGER_CST.  */
17097       value = tsubst_expr (DECL_INITIAL (decl),
17098                            args, tf_warning_or_error, NULL_TREE,
17099                            /*integral_constant_expression_p=*/true);
17100
17101       /* Give this enumeration constant the correct access.  */
17102       set_current_access_from_decl (decl);
17103
17104       /* Actually build the enumerator itself.  */
17105       build_enumerator (DECL_NAME (decl), value, newtag);
17106     }
17107
17108   finish_enum (newtag);
17109   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
17110     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
17111 }
17112
17113 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
17114    its type -- but without substituting the innermost set of template
17115    arguments.  So, innermost set of template parameters will appear in
17116    the type.  */
17117
17118 tree
17119 get_mostly_instantiated_function_type (tree decl)
17120 {
17121   tree fn_type;
17122   tree tmpl;
17123   tree targs;
17124   tree tparms;
17125   int parm_depth;
17126
17127   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
17128   targs = DECL_TI_ARGS (decl);
17129   tparms = DECL_TEMPLATE_PARMS (tmpl);
17130   parm_depth = TMPL_PARMS_DEPTH (tparms);
17131
17132   /* There should be as many levels of arguments as there are levels
17133      of parameters.  */
17134   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
17135
17136   fn_type = TREE_TYPE (tmpl);
17137
17138   if (parm_depth == 1)
17139     /* No substitution is necessary.  */
17140     ;
17141   else
17142     {
17143       int i, save_access_control;
17144       tree partial_args;
17145
17146       /* Replace the innermost level of the TARGS with NULL_TREEs to
17147          let tsubst know not to substitute for those parameters.  */
17148       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
17149       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
17150         SET_TMPL_ARGS_LEVEL (partial_args, i,
17151                              TMPL_ARGS_LEVEL (targs, i));
17152       SET_TMPL_ARGS_LEVEL (partial_args,
17153                            TMPL_ARGS_DEPTH (targs),
17154                            make_tree_vec (DECL_NTPARMS (tmpl)));
17155
17156       /* Disable access control as this function is used only during
17157          name-mangling.  */
17158       save_access_control = flag_access_control;
17159       flag_access_control = 0;
17160
17161       ++processing_template_decl;
17162       /* Now, do the (partial) substitution to figure out the
17163          appropriate function type.  */
17164       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
17165       --processing_template_decl;
17166
17167       /* Substitute into the template parameters to obtain the real
17168          innermost set of parameters.  This step is important if the
17169          innermost set of template parameters contains value
17170          parameters whose types depend on outer template parameters.  */
17171       TREE_VEC_LENGTH (partial_args)--;
17172       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
17173
17174       flag_access_control = save_access_control;
17175     }
17176
17177   return fn_type;
17178 }
17179
17180 /* Return truthvalue if we're processing a template different from
17181    the last one involved in diagnostics.  */
17182 int
17183 problematic_instantiation_changed (void)
17184 {
17185   return last_template_error_tick != tinst_level_tick;
17186 }
17187
17188 /* Remember current template involved in diagnostics.  */
17189 void
17190 record_last_problematic_instantiation (void)
17191 {
17192   last_template_error_tick = tinst_level_tick;
17193 }
17194
17195 struct tinst_level *
17196 current_instantiation (void)
17197 {
17198   return current_tinst_level;
17199 }
17200
17201 /* [temp.param] Check that template non-type parm TYPE is of an allowable
17202    type. Return zero for ok, nonzero for disallowed. Issue error and
17203    warning messages under control of COMPLAIN.  */
17204
17205 static int
17206 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
17207 {
17208   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
17209     return 0;
17210   else if (POINTER_TYPE_P (type))
17211     return 0;
17212   else if (TYPE_PTR_TO_MEMBER_P (type))
17213     return 0;
17214   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
17215     return 0;
17216   else if (TREE_CODE (type) == TYPENAME_TYPE)
17217     return 0;
17218
17219   if (complain & tf_error)
17220     error ("%q#T is not a valid type for a template constant parameter", type);
17221   return 1;
17222 }
17223
17224 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
17225    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
17226
17227 static bool
17228 dependent_type_p_r (tree type)
17229 {
17230   tree scope;
17231
17232   /* [temp.dep.type]
17233
17234      A type is dependent if it is:
17235
17236      -- a template parameter. Template template parameters are types
17237         for us (since TYPE_P holds true for them) so we handle
17238         them here.  */
17239   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17240       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
17241     return true;
17242   /* -- a qualified-id with a nested-name-specifier which contains a
17243         class-name that names a dependent type or whose unqualified-id
17244         names a dependent type.  */
17245   if (TREE_CODE (type) == TYPENAME_TYPE)
17246     return true;
17247   /* -- a cv-qualified type where the cv-unqualified type is
17248         dependent.  */
17249   type = TYPE_MAIN_VARIANT (type);
17250   /* -- a compound type constructed from any dependent type.  */
17251   if (TYPE_PTR_TO_MEMBER_P (type))
17252     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
17253             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
17254                                            (type)));
17255   else if (TREE_CODE (type) == POINTER_TYPE
17256            || TREE_CODE (type) == REFERENCE_TYPE)
17257     return dependent_type_p (TREE_TYPE (type));
17258   else if (TREE_CODE (type) == FUNCTION_TYPE
17259            || TREE_CODE (type) == METHOD_TYPE)
17260     {
17261       tree arg_type;
17262
17263       if (dependent_type_p (TREE_TYPE (type)))
17264         return true;
17265       for (arg_type = TYPE_ARG_TYPES (type);
17266            arg_type;
17267            arg_type = TREE_CHAIN (arg_type))
17268         if (dependent_type_p (TREE_VALUE (arg_type)))
17269           return true;
17270       return false;
17271     }
17272   /* -- an array type constructed from any dependent type or whose
17273         size is specified by a constant expression that is
17274         value-dependent.  */
17275   if (TREE_CODE (type) == ARRAY_TYPE)
17276     {
17277       if (TYPE_DOMAIN (type)
17278           && dependent_type_p (TYPE_DOMAIN (type)))
17279         return true;
17280       return dependent_type_p (TREE_TYPE (type));
17281     }
17282   else if (TREE_CODE (type) == INTEGER_TYPE
17283            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
17284     {
17285       /* If this is the TYPE_DOMAIN of an array type, consider it
17286          dependent.  We already checked for value-dependence in
17287          compute_array_index_type.  */
17288       return type_dependent_expression_p (TYPE_MAX_VALUE (type));
17289     }
17290
17291   /* -- a template-id in which either the template name is a template
17292      parameter ...  */
17293   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
17294     return true;
17295   /* ... or any of the template arguments is a dependent type or
17296         an expression that is type-dependent or value-dependent.  */
17297   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
17298            && (any_dependent_template_arguments_p
17299                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
17300     return true;
17301
17302   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
17303      argument of the `typeof' expression is not type-dependent, then
17304      it should already been have resolved.  */
17305   if (TREE_CODE (type) == TYPEOF_TYPE
17306       || TREE_CODE (type) == DECLTYPE_TYPE)
17307     return true;
17308
17309   /* A template argument pack is dependent if any of its packed
17310      arguments are.  */
17311   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
17312     {
17313       tree args = ARGUMENT_PACK_ARGS (type);
17314       int i, len = TREE_VEC_LENGTH (args);
17315       for (i = 0; i < len; ++i)
17316         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17317           return true;
17318     }
17319
17320   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
17321      be template parameters.  */
17322   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
17323     return true;
17324
17325   /* The standard does not specifically mention types that are local
17326      to template functions or local classes, but they should be
17327      considered dependent too.  For example:
17328
17329        template <int I> void f() {
17330          enum E { a = I };
17331          S<sizeof (E)> s;
17332        }
17333
17334      The size of `E' cannot be known until the value of `I' has been
17335      determined.  Therefore, `E' must be considered dependent.  */
17336   scope = TYPE_CONTEXT (type);
17337   if (scope && TYPE_P (scope))
17338     return dependent_type_p (scope);
17339   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
17340     return type_dependent_expression_p (scope);
17341
17342   /* Other types are non-dependent.  */
17343   return false;
17344 }
17345
17346 /* Returns TRUE if TYPE is dependent, in the sense of
17347    [temp.dep.type].  */
17348
17349 bool
17350 dependent_type_p (tree type)
17351 {
17352   /* If there are no template parameters in scope, then there can't be
17353      any dependent types.  */
17354   if (!processing_template_decl)
17355     {
17356       /* If we are not processing a template, then nobody should be
17357          providing us with a dependent type.  */
17358       gcc_assert (type);
17359       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
17360       return false;
17361     }
17362
17363   /* If the type is NULL, we have not computed a type for the entity
17364      in question; in that case, the type is dependent.  */
17365   if (!type)
17366     return true;
17367
17368   /* Erroneous types can be considered non-dependent.  */
17369   if (type == error_mark_node)
17370     return false;
17371
17372   /* If we have not already computed the appropriate value for TYPE,
17373      do so now.  */
17374   if (!TYPE_DEPENDENT_P_VALID (type))
17375     {
17376       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
17377       TYPE_DEPENDENT_P_VALID (type) = 1;
17378     }
17379
17380   return TYPE_DEPENDENT_P (type);
17381 }
17382
17383 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
17384    lookup.  In other words, a dependent type that is not the current
17385    instantiation.  */
17386
17387 bool
17388 dependent_scope_p (tree scope)
17389 {
17390   return (scope && TYPE_P (scope) && dependent_type_p (scope)
17391           && !currently_open_class (scope));
17392 }
17393
17394 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
17395
17396 static bool
17397 dependent_scope_ref_p (tree expression, bool criterion (tree))
17398 {
17399   tree scope;
17400   tree name;
17401
17402   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
17403
17404   if (!TYPE_P (TREE_OPERAND (expression, 0)))
17405     return true;
17406
17407   scope = TREE_OPERAND (expression, 0);
17408   name = TREE_OPERAND (expression, 1);
17409
17410   /* [temp.dep.expr]
17411
17412      An id-expression is type-dependent if it contains a
17413      nested-name-specifier that contains a class-name that names a
17414      dependent type.  */
17415   /* The suggested resolution to Core Issue 224 implies that if the
17416      qualifying type is the current class, then we must peek
17417      inside it.  */
17418   if (DECL_P (name)
17419       && currently_open_class (scope)
17420       && !criterion (name))
17421     return false;
17422   if (dependent_type_p (scope))
17423     return true;
17424
17425   return false;
17426 }
17427
17428 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
17429    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
17430    expression.  */
17431
17432 bool
17433 value_dependent_expression_p (tree expression)
17434 {
17435   if (!processing_template_decl)
17436     return false;
17437
17438   /* A name declared with a dependent type.  */
17439   if (DECL_P (expression) && type_dependent_expression_p (expression))
17440     return true;
17441
17442   switch (TREE_CODE (expression))
17443     {
17444     case IDENTIFIER_NODE:
17445       /* A name that has not been looked up -- must be dependent.  */
17446       return true;
17447
17448     case TEMPLATE_PARM_INDEX:
17449       /* A non-type template parm.  */
17450       return true;
17451
17452     case CONST_DECL:
17453       /* A non-type template parm.  */
17454       if (DECL_TEMPLATE_PARM_P (expression))
17455         return true;
17456       return value_dependent_expression_p (DECL_INITIAL (expression));
17457
17458     case VAR_DECL:
17459        /* A constant with integral or enumeration type and is initialized
17460           with an expression that is value-dependent.  */
17461       if (DECL_INITIAL (expression)
17462           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
17463           && value_dependent_expression_p (DECL_INITIAL (expression)))
17464         return true;
17465       return false;
17466
17467     case DYNAMIC_CAST_EXPR:
17468     case STATIC_CAST_EXPR:
17469     case CONST_CAST_EXPR:
17470     case REINTERPRET_CAST_EXPR:
17471     case CAST_EXPR:
17472       /* These expressions are value-dependent if the type to which
17473          the cast occurs is dependent or the expression being casted
17474          is value-dependent.  */
17475       {
17476         tree type = TREE_TYPE (expression);
17477
17478         if (dependent_type_p (type))
17479           return true;
17480
17481         /* A functional cast has a list of operands.  */
17482         expression = TREE_OPERAND (expression, 0);
17483         if (!expression)
17484           {
17485             /* If there are no operands, it must be an expression such
17486                as "int()". This should not happen for aggregate types
17487                because it would form non-constant expressions.  */
17488             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
17489
17490             return false;
17491           }
17492
17493         if (TREE_CODE (expression) == TREE_LIST)
17494           return any_value_dependent_elements_p (expression);
17495
17496         return value_dependent_expression_p (expression);
17497       }
17498
17499     case SIZEOF_EXPR:
17500     case ALIGNOF_EXPR:
17501       /* A `sizeof' expression is value-dependent if the operand is
17502          type-dependent or is a pack expansion.  */
17503       expression = TREE_OPERAND (expression, 0);
17504       if (PACK_EXPANSION_P (expression))
17505         return true;
17506       else if (TYPE_P (expression))
17507         return dependent_type_p (expression);
17508       return type_dependent_expression_p (expression);
17509
17510     case SCOPE_REF:
17511       return dependent_scope_ref_p (expression, value_dependent_expression_p);
17512
17513     case COMPONENT_REF:
17514       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
17515               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
17516
17517     case CALL_EXPR:
17518       /* A CALL_EXPR may appear in a constant expression if it is a
17519          call to a builtin function, e.g., __builtin_constant_p.  All
17520          such calls are value-dependent.  */
17521       return true;
17522
17523     case NONTYPE_ARGUMENT_PACK:
17524       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
17525          is value-dependent.  */
17526       {
17527         tree values = ARGUMENT_PACK_ARGS (expression);
17528         int i, len = TREE_VEC_LENGTH (values);
17529         
17530         for (i = 0; i < len; ++i)
17531           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
17532             return true;
17533         
17534         return false;
17535       }
17536
17537     case TRAIT_EXPR:
17538       {
17539         tree type2 = TRAIT_EXPR_TYPE2 (expression);
17540         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
17541                 || (type2 ? dependent_type_p (type2) : false));
17542       }
17543
17544     case MODOP_EXPR:
17545       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
17546               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
17547
17548     default:
17549       /* A constant expression is value-dependent if any subexpression is
17550          value-dependent.  */
17551       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
17552         {
17553         case tcc_reference:
17554         case tcc_unary:
17555           return (value_dependent_expression_p
17556                   (TREE_OPERAND (expression, 0)));
17557
17558         case tcc_comparison:
17559         case tcc_binary:
17560           return ((value_dependent_expression_p
17561                    (TREE_OPERAND (expression, 0)))
17562                   || (value_dependent_expression_p
17563                       (TREE_OPERAND (expression, 1))));
17564
17565         case tcc_expression:
17566         case tcc_vl_exp:
17567           {
17568             int i;
17569             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
17570               /* In some cases, some of the operands may be missing.
17571                  (For example, in the case of PREDECREMENT_EXPR, the
17572                  amount to increment by may be missing.)  That doesn't
17573                  make the expression dependent.  */
17574               if (TREE_OPERAND (expression, i)
17575                   && (value_dependent_expression_p
17576                       (TREE_OPERAND (expression, i))))
17577                 return true;
17578             return false;
17579           }
17580
17581         default:
17582           break;
17583         }
17584     }
17585
17586   /* The expression is not value-dependent.  */
17587   return false;
17588 }
17589
17590 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
17591    [temp.dep.expr].  */
17592
17593 bool
17594 type_dependent_expression_p (tree expression)
17595 {
17596   if (!processing_template_decl)
17597     return false;
17598
17599   if (expression == error_mark_node)
17600     return false;
17601
17602   /* An unresolved name is always dependent.  */
17603   if (TREE_CODE (expression) == IDENTIFIER_NODE
17604       || TREE_CODE (expression) == USING_DECL)
17605     return true;
17606
17607   /* Some expression forms are never type-dependent.  */
17608   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
17609       || TREE_CODE (expression) == SIZEOF_EXPR
17610       || TREE_CODE (expression) == ALIGNOF_EXPR
17611       || TREE_CODE (expression) == TRAIT_EXPR
17612       || TREE_CODE (expression) == TYPEID_EXPR
17613       || TREE_CODE (expression) == DELETE_EXPR
17614       || TREE_CODE (expression) == VEC_DELETE_EXPR
17615       || TREE_CODE (expression) == THROW_EXPR)
17616     return false;
17617
17618   /* The types of these expressions depends only on the type to which
17619      the cast occurs.  */
17620   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
17621       || TREE_CODE (expression) == STATIC_CAST_EXPR
17622       || TREE_CODE (expression) == CONST_CAST_EXPR
17623       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
17624       || TREE_CODE (expression) == CAST_EXPR)
17625     return dependent_type_p (TREE_TYPE (expression));
17626
17627   /* The types of these expressions depends only on the type created
17628      by the expression.  */
17629   if (TREE_CODE (expression) == NEW_EXPR
17630       || TREE_CODE (expression) == VEC_NEW_EXPR)
17631     {
17632       /* For NEW_EXPR tree nodes created inside a template, either
17633          the object type itself or a TREE_LIST may appear as the
17634          operand 1.  */
17635       tree type = TREE_OPERAND (expression, 1);
17636       if (TREE_CODE (type) == TREE_LIST)
17637         /* This is an array type.  We need to check array dimensions
17638            as well.  */
17639         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
17640                || value_dependent_expression_p
17641                     (TREE_OPERAND (TREE_VALUE (type), 1));
17642       else
17643         return dependent_type_p (type);
17644     }
17645
17646   if (TREE_CODE (expression) == SCOPE_REF
17647       && dependent_scope_ref_p (expression,
17648                                 type_dependent_expression_p))
17649     return true;
17650
17651   if (TREE_CODE (expression) == FUNCTION_DECL
17652       && DECL_LANG_SPECIFIC (expression)
17653       && DECL_TEMPLATE_INFO (expression)
17654       && (any_dependent_template_arguments_p
17655           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
17656     return true;
17657
17658   if (TREE_CODE (expression) == TEMPLATE_DECL
17659       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
17660     return false;
17661
17662   if (TREE_CODE (expression) == STMT_EXPR)
17663     expression = stmt_expr_value_expr (expression);
17664
17665   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
17666     {
17667       tree elt;
17668       unsigned i;
17669
17670       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
17671         {
17672           if (type_dependent_expression_p (elt))
17673             return true;
17674         }
17675       return false;
17676     }
17677
17678   if (TREE_TYPE (expression) == unknown_type_node)
17679     {
17680       if (TREE_CODE (expression) == ADDR_EXPR)
17681         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
17682       if (TREE_CODE (expression) == COMPONENT_REF
17683           || TREE_CODE (expression) == OFFSET_REF)
17684         {
17685           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
17686             return true;
17687           expression = TREE_OPERAND (expression, 1);
17688           if (TREE_CODE (expression) == IDENTIFIER_NODE)
17689             return false;
17690         }
17691       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
17692       if (TREE_CODE (expression) == SCOPE_REF)
17693         return false;
17694
17695       if (TREE_CODE (expression) == BASELINK)
17696         expression = BASELINK_FUNCTIONS (expression);
17697
17698       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
17699         {
17700           if (any_dependent_template_arguments_p
17701               (TREE_OPERAND (expression, 1)))
17702             return true;
17703           expression = TREE_OPERAND (expression, 0);
17704         }
17705       gcc_assert (TREE_CODE (expression) == OVERLOAD
17706                   || TREE_CODE (expression) == FUNCTION_DECL);
17707
17708       while (expression)
17709         {
17710           if (type_dependent_expression_p (OVL_CURRENT (expression)))
17711             return true;
17712           expression = OVL_NEXT (expression);
17713         }
17714       return false;
17715     }
17716
17717   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
17718
17719   return (dependent_type_p (TREE_TYPE (expression)));
17720 }
17721
17722 /* Like type_dependent_expression_p, but it also works while not processing
17723    a template definition, i.e. during substitution or mangling.  */
17724
17725 bool
17726 type_dependent_expression_p_push (tree expr)
17727 {
17728   bool b;
17729   ++processing_template_decl;
17730   b = type_dependent_expression_p (expr);
17731   --processing_template_decl;
17732   return b;
17733 }
17734
17735 /* Returns TRUE if ARGS contains a type-dependent expression.  */
17736
17737 bool
17738 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
17739 {
17740   unsigned int i;
17741   tree arg;
17742
17743   for (i = 0; VEC_iterate (tree, args, i, arg); ++i)
17744     {
17745       if (type_dependent_expression_p (arg))
17746         return true;
17747     }
17748   return false;
17749 }
17750
17751 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
17752    expressions) contains any value-dependent expressions.  */
17753
17754 bool
17755 any_value_dependent_elements_p (const_tree list)
17756 {
17757   for (; list; list = TREE_CHAIN (list))
17758     if (value_dependent_expression_p (TREE_VALUE (list)))
17759       return true;
17760
17761   return false;
17762 }
17763
17764 /* Returns TRUE if the ARG (a template argument) is dependent.  */
17765
17766 bool
17767 dependent_template_arg_p (tree arg)
17768 {
17769   if (!processing_template_decl)
17770     return false;
17771
17772   if (TREE_CODE (arg) == TEMPLATE_DECL
17773       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17774     return dependent_template_p (arg);
17775   else if (ARGUMENT_PACK_P (arg))
17776     {
17777       tree args = ARGUMENT_PACK_ARGS (arg);
17778       int i, len = TREE_VEC_LENGTH (args);
17779       for (i = 0; i < len; ++i)
17780         {
17781           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17782             return true;
17783         }
17784
17785       return false;
17786     }
17787   else if (TYPE_P (arg))
17788     return dependent_type_p (arg);
17789   else
17790     return (type_dependent_expression_p (arg)
17791             || value_dependent_expression_p (arg));
17792 }
17793
17794 /* Returns true if ARGS (a collection of template arguments) contains
17795    any types that require structural equality testing.  */
17796
17797 bool
17798 any_template_arguments_need_structural_equality_p (tree args)
17799 {
17800   int i;
17801   int j;
17802
17803   if (!args)
17804     return false;
17805   if (args == error_mark_node)
17806     return true;
17807
17808   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17809     {
17810       tree level = TMPL_ARGS_LEVEL (args, i + 1);
17811       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17812         {
17813           tree arg = TREE_VEC_ELT (level, j);
17814           tree packed_args = NULL_TREE;
17815           int k, len = 1;
17816
17817           if (ARGUMENT_PACK_P (arg))
17818             {
17819               /* Look inside the argument pack.  */
17820               packed_args = ARGUMENT_PACK_ARGS (arg);
17821               len = TREE_VEC_LENGTH (packed_args);
17822             }
17823
17824           for (k = 0; k < len; ++k)
17825             {
17826               if (packed_args)
17827                 arg = TREE_VEC_ELT (packed_args, k);
17828
17829               if (error_operand_p (arg))
17830                 return true;
17831               else if (TREE_CODE (arg) == TEMPLATE_DECL
17832                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17833                 continue;
17834               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
17835                 return true;
17836               else if (!TYPE_P (arg) && TREE_TYPE (arg)
17837                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
17838                 return true;
17839             }
17840         }
17841     }
17842
17843   return false;
17844 }
17845
17846 /* Returns true if ARGS (a collection of template arguments) contains
17847    any dependent arguments.  */
17848
17849 bool
17850 any_dependent_template_arguments_p (const_tree args)
17851 {
17852   int i;
17853   int j;
17854
17855   if (!args)
17856     return false;
17857   if (args == error_mark_node)
17858     return true;
17859
17860   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17861     {
17862       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
17863       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17864         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
17865           return true;
17866     }
17867
17868   return false;
17869 }
17870
17871 /* Returns TRUE if the template TMPL is dependent.  */
17872
17873 bool
17874 dependent_template_p (tree tmpl)
17875 {
17876   if (TREE_CODE (tmpl) == OVERLOAD)
17877     {
17878       while (tmpl)
17879         {
17880           if (dependent_template_p (OVL_FUNCTION (tmpl)))
17881             return true;
17882           tmpl = OVL_CHAIN (tmpl);
17883         }
17884       return false;
17885     }
17886
17887   /* Template template parameters are dependent.  */
17888   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
17889       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
17890     return true;
17891   /* So are names that have not been looked up.  */
17892   if (TREE_CODE (tmpl) == SCOPE_REF
17893       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
17894     return true;
17895   /* So are member templates of dependent classes.  */
17896   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
17897     return dependent_type_p (DECL_CONTEXT (tmpl));
17898   return false;
17899 }
17900
17901 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
17902
17903 bool
17904 dependent_template_id_p (tree tmpl, tree args)
17905 {
17906   return (dependent_template_p (tmpl)
17907           || any_dependent_template_arguments_p (args));
17908 }
17909
17910 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
17911    is dependent.  */
17912
17913 bool
17914 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
17915 {
17916   int i;
17917
17918   if (!processing_template_decl)
17919     return false;
17920
17921   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
17922     {
17923       tree decl = TREE_VEC_ELT (declv, i);
17924       tree init = TREE_VEC_ELT (initv, i);
17925       tree cond = TREE_VEC_ELT (condv, i);
17926       tree incr = TREE_VEC_ELT (incrv, i);
17927
17928       if (type_dependent_expression_p (decl))
17929         return true;
17930
17931       if (init && type_dependent_expression_p (init))
17932         return true;
17933
17934       if (type_dependent_expression_p (cond))
17935         return true;
17936
17937       if (COMPARISON_CLASS_P (cond)
17938           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
17939               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
17940         return true;
17941
17942       if (TREE_CODE (incr) == MODOP_EXPR)
17943         {
17944           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
17945               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
17946             return true;
17947         }
17948       else if (type_dependent_expression_p (incr))
17949         return true;
17950       else if (TREE_CODE (incr) == MODIFY_EXPR)
17951         {
17952           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
17953             return true;
17954           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
17955             {
17956               tree t = TREE_OPERAND (incr, 1);
17957               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
17958                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
17959                 return true;
17960             }
17961         }
17962     }
17963
17964   return false;
17965 }
17966
17967 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
17968    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
17969    no such TYPE can be found.  Note that this function peers inside
17970    uninstantiated templates and therefore should be used only in
17971    extremely limited situations.  ONLY_CURRENT_P restricts this
17972    peering to the currently open classes hierarchy (which is required
17973    when comparing types).  */
17974
17975 tree
17976 resolve_typename_type (tree type, bool only_current_p)
17977 {
17978   tree scope;
17979   tree name;
17980   tree decl;
17981   int quals;
17982   tree pushed_scope;
17983   tree result;
17984
17985   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
17986
17987   scope = TYPE_CONTEXT (type);
17988   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
17989      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
17990      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
17991      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
17992      identifier  of the TYPENAME_TYPE anymore.
17993      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
17994      TYPENAME_TYPE instead, we avoid messing up with a possible
17995      typedef variant case.  */
17996   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
17997
17998   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
17999      it first before we can figure out what NAME refers to.  */
18000   if (TREE_CODE (scope) == TYPENAME_TYPE)
18001     scope = resolve_typename_type (scope, only_current_p);
18002   /* If we don't know what SCOPE refers to, then we cannot resolve the
18003      TYPENAME_TYPE.  */
18004   if (TREE_CODE (scope) == TYPENAME_TYPE)
18005     return type;
18006   /* If the SCOPE is a template type parameter, we have no way of
18007      resolving the name.  */
18008   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
18009     return type;
18010   /* If the SCOPE is not the current instantiation, there's no reason
18011      to look inside it.  */
18012   if (only_current_p && !currently_open_class (scope))
18013     return type;
18014   /* If this is a typedef, we don't want to look inside (c++/11987).  */
18015   if (typedef_variant_p (type))
18016     return type;
18017   /* If SCOPE isn't the template itself, it will not have a valid
18018      TYPE_FIELDS list.  */
18019   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
18020     /* scope is either the template itself or a compatible instantiation
18021        like X<T>, so look up the name in the original template.  */
18022     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
18023   else
18024     /* scope is a partial instantiation, so we can't do the lookup or we
18025        will lose the template arguments.  */
18026     return type;
18027   /* Enter the SCOPE so that name lookup will be resolved as if we
18028      were in the class definition.  In particular, SCOPE will no
18029      longer be considered a dependent type.  */
18030   pushed_scope = push_scope (scope);
18031   /* Look up the declaration.  */
18032   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
18033
18034   result = NULL_TREE;
18035   
18036   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
18037      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
18038   if (!decl)
18039     /*nop*/;
18040   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
18041            && TREE_CODE (decl) == TYPE_DECL)
18042     {
18043       result = TREE_TYPE (decl);
18044       if (result == error_mark_node)
18045         result = NULL_TREE;
18046     }
18047   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
18048            && DECL_CLASS_TEMPLATE_P (decl))
18049     {
18050       tree tmpl;
18051       tree args;
18052       /* Obtain the template and the arguments.  */
18053       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
18054       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
18055       /* Instantiate the template.  */
18056       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
18057                                       /*entering_scope=*/0,
18058                                       tf_error | tf_user);
18059       if (result == error_mark_node)
18060         result = NULL_TREE;
18061     }
18062   
18063   /* Leave the SCOPE.  */
18064   if (pushed_scope)
18065     pop_scope (pushed_scope);
18066
18067   /* If we failed to resolve it, return the original typename.  */
18068   if (!result)
18069     return type;
18070   
18071   /* If lookup found a typename type, resolve that too.  */
18072   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
18073     {
18074       /* Ill-formed programs can cause infinite recursion here, so we
18075          must catch that.  */
18076       TYPENAME_IS_RESOLVING_P (type) = 1;
18077       result = resolve_typename_type (result, only_current_p);
18078       TYPENAME_IS_RESOLVING_P (type) = 0;
18079     }
18080   
18081   /* Qualify the resulting type.  */
18082   quals = cp_type_quals (type);
18083   if (quals)
18084     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
18085
18086   return result;
18087 }
18088
18089 /* EXPR is an expression which is not type-dependent.  Return a proxy
18090    for EXPR that can be used to compute the types of larger
18091    expressions containing EXPR.  */
18092
18093 tree
18094 build_non_dependent_expr (tree expr)
18095 {
18096   tree inner_expr;
18097
18098   /* Preserve null pointer constants so that the type of things like
18099      "p == 0" where "p" is a pointer can be determined.  */
18100   if (null_ptr_cst_p (expr))
18101     return expr;
18102   /* Preserve OVERLOADs; the functions must be available to resolve
18103      types.  */
18104   inner_expr = expr;
18105   if (TREE_CODE (inner_expr) == STMT_EXPR)
18106     inner_expr = stmt_expr_value_expr (inner_expr);
18107   if (TREE_CODE (inner_expr) == ADDR_EXPR)
18108     inner_expr = TREE_OPERAND (inner_expr, 0);
18109   if (TREE_CODE (inner_expr) == COMPONENT_REF)
18110     inner_expr = TREE_OPERAND (inner_expr, 1);
18111   if (is_overloaded_fn (inner_expr)
18112       || TREE_CODE (inner_expr) == OFFSET_REF)
18113     return expr;
18114   /* There is no need to return a proxy for a variable.  */
18115   if (TREE_CODE (expr) == VAR_DECL)
18116     return expr;
18117   /* Preserve string constants; conversions from string constants to
18118      "char *" are allowed, even though normally a "const char *"
18119      cannot be used to initialize a "char *".  */
18120   if (TREE_CODE (expr) == STRING_CST)
18121     return expr;
18122   /* Preserve arithmetic constants, as an optimization -- there is no
18123      reason to create a new node.  */
18124   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
18125     return expr;
18126   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
18127      There is at least one place where we want to know that a
18128      particular expression is a throw-expression: when checking a ?:
18129      expression, there are special rules if the second or third
18130      argument is a throw-expression.  */
18131   if (TREE_CODE (expr) == THROW_EXPR)
18132     return expr;
18133
18134   if (TREE_CODE (expr) == COND_EXPR)
18135     return build3 (COND_EXPR,
18136                    TREE_TYPE (expr),
18137                    TREE_OPERAND (expr, 0),
18138                    (TREE_OPERAND (expr, 1)
18139                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
18140                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
18141                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
18142   if (TREE_CODE (expr) == COMPOUND_EXPR
18143       && !COMPOUND_EXPR_OVERLOADED (expr))
18144     return build2 (COMPOUND_EXPR,
18145                    TREE_TYPE (expr),
18146                    TREE_OPERAND (expr, 0),
18147                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
18148
18149   /* If the type is unknown, it can't really be non-dependent */
18150   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
18151
18152   /* Otherwise, build a NON_DEPENDENT_EXPR.
18153
18154      REFERENCE_TYPEs are not stripped for expressions in templates
18155      because doing so would play havoc with mangling.  Consider, for
18156      example:
18157
18158        template <typename T> void f<T& g>() { g(); }
18159
18160      In the body of "f", the expression for "g" will have
18161      REFERENCE_TYPE, even though the standard says that it should
18162      not.  The reason is that we must preserve the syntactic form of
18163      the expression so that mangling (say) "f<g>" inside the body of
18164      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
18165      stripped here.  */
18166   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
18167 }
18168
18169 /* ARGS is a vector of expressions as arguments to a function call.
18170    Replace the arguments with equivalent non-dependent expressions.
18171    This modifies ARGS in place.  */
18172
18173 void
18174 make_args_non_dependent (VEC(tree,gc) *args)
18175 {
18176   unsigned int ix;
18177   tree arg;
18178
18179   for (ix = 0; VEC_iterate (tree, args, ix, arg); ++ix)
18180     {
18181       tree newarg = build_non_dependent_expr (arg);
18182       if (newarg != arg)
18183         VEC_replace (tree, args, ix, newarg);
18184     }
18185 }
18186
18187 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
18188    with a level one deeper than the actual template parms.  */
18189
18190 tree
18191 make_auto (void)
18192 {
18193   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
18194   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
18195                                TYPE_DECL, get_identifier ("auto"), au);
18196   TYPE_STUB_DECL (au) = TYPE_NAME (au);
18197   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
18198     (0, processing_template_decl + 1, processing_template_decl + 1,
18199      TYPE_NAME (au), NULL_TREE);
18200   TYPE_CANONICAL (au) = canonical_type_parameter (au);
18201   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
18202   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
18203
18204   return au;
18205 }
18206
18207 /* Given type ARG, return std::initializer_list<ARG>.  */
18208
18209 static tree
18210 listify (tree arg)
18211 {
18212   tree std_init_list = namespace_binding
18213     (get_identifier ("initializer_list"), std_node);
18214   tree argvec;
18215   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
18216     {    
18217       error ("deducing from brace-enclosed initializer list requires "
18218              "#include <initializer_list>");
18219       return error_mark_node;
18220     }
18221   argvec = make_tree_vec (1);
18222   TREE_VEC_ELT (argvec, 0) = arg;
18223   return lookup_template_class (std_init_list, argvec, NULL_TREE,
18224                                 NULL_TREE, 0, tf_warning_or_error);
18225 }
18226
18227 /* Replace auto in TYPE with std::initializer_list<auto>.  */
18228
18229 static tree
18230 listify_autos (tree type, tree auto_node)
18231 {
18232   tree init_auto = listify (auto_node);
18233   tree argvec = make_tree_vec (1);
18234   TREE_VEC_ELT (argvec, 0) = init_auto;
18235   if (processing_template_decl)
18236     argvec = add_to_template_args (current_template_args (), argvec);
18237   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18238 }
18239
18240 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
18241    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
18242
18243 tree
18244 do_auto_deduction (tree type, tree init, tree auto_node)
18245 {
18246   tree parms, tparms, targs;
18247   tree args[1];
18248   int val;
18249
18250   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
18251      with either a new invented type template parameter U or, if the
18252      initializer is a braced-init-list (8.5.4), with
18253      std::initializer_list<U>.  */
18254   if (BRACE_ENCLOSED_INITIALIZER_P (init))
18255     type = listify_autos (type, auto_node);
18256
18257   parms = build_tree_list (NULL_TREE, type);
18258   args[0] = init;
18259   tparms = make_tree_vec (1);
18260   targs = make_tree_vec (1);
18261   TREE_VEC_ELT (tparms, 0)
18262     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
18263   val = type_unification_real (tparms, targs, parms, args, 1, 0,
18264                                DEDUCE_CALL, LOOKUP_NORMAL);
18265   if (val > 0)
18266     {
18267       error ("unable to deduce %qT from %qE", type, init);
18268       return error_mark_node;
18269     }
18270
18271   /* If the list of declarators contains more than one declarator, the type
18272      of each declared variable is determined as described above. If the
18273      type deduced for the template parameter U is not the same in each
18274      deduction, the program is ill-formed.  */
18275   if (TREE_TYPE (auto_node)
18276       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
18277     {
18278       error ("inconsistent deduction for %qT: %qT and then %qT",
18279              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
18280       return error_mark_node;
18281     }
18282   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
18283
18284   if (processing_template_decl)
18285     targs = add_to_template_args (current_template_args (), targs);
18286   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
18287 }
18288
18289 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
18290    result.  */
18291
18292 tree
18293 splice_late_return_type (tree type, tree late_return_type)
18294 {
18295   tree argvec;
18296
18297   if (late_return_type == NULL_TREE)
18298     return type;
18299   argvec = make_tree_vec (1);
18300   TREE_VEC_ELT (argvec, 0) = late_return_type;
18301   if (processing_template_decl)
18302     argvec = add_to_template_args (current_template_args (), argvec);
18303   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18304 }
18305
18306 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
18307
18308 bool
18309 is_auto (const_tree type)
18310 {
18311   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18312       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
18313     return true;
18314   else
18315     return false;
18316 }
18317
18318 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
18319    appear as a type-specifier for the declaration in question, we don't
18320    have to look through the whole type.  */
18321
18322 tree
18323 type_uses_auto (tree type)
18324 {
18325   enum tree_code code;
18326   if (is_auto (type))
18327     return type;
18328
18329   code = TREE_CODE (type);
18330
18331   if (code == POINTER_TYPE || code == REFERENCE_TYPE
18332       || code == OFFSET_TYPE || code == FUNCTION_TYPE
18333       || code == METHOD_TYPE || code == ARRAY_TYPE)
18334     return type_uses_auto (TREE_TYPE (type));
18335
18336   if (TYPE_PTRMEMFUNC_P (type))
18337     return type_uses_auto (TREE_TYPE (TREE_TYPE
18338                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
18339
18340   return NULL_TREE;
18341 }
18342
18343 /* For a given template T, return the vector of typedefs referenced
18344    in T for which access check is needed at T instantiation time.
18345    T is either  a FUNCTION_DECL or a RECORD_TYPE.
18346    Those typedefs were added to T by the function
18347    append_type_to_template_for_access_check.  */
18348
18349 VEC(qualified_typedef_usage_t,gc)*
18350 get_types_needing_access_check (tree t)
18351 {
18352   tree ti;
18353   VEC(qualified_typedef_usage_t,gc) *result = NULL;
18354
18355   if (!t || t == error_mark_node)
18356     return NULL;
18357
18358   if (!(ti = get_template_info (t)))
18359     return NULL;
18360
18361   if (CLASS_TYPE_P (t)
18362       || TREE_CODE (t) == FUNCTION_DECL)
18363     {
18364       if (!TI_TEMPLATE (ti))
18365         return NULL;
18366
18367       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
18368     }
18369
18370   return result;
18371 }
18372
18373 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
18374    tied to T. That list of typedefs will be access checked at
18375    T instantiation time.
18376    T is either a FUNCTION_DECL or a RECORD_TYPE.
18377    TYPE_DECL is a TYPE_DECL node representing a typedef.
18378    SCOPE is the scope through which TYPE_DECL is accessed.
18379    LOCATION is the location of the usage point of TYPE_DECL.
18380
18381    This function is a subroutine of
18382    append_type_to_template_for_access_check.  */
18383
18384 static void
18385 append_type_to_template_for_access_check_1 (tree t,
18386                                             tree type_decl,
18387                                             tree scope,
18388                                             location_t location)
18389 {
18390   qualified_typedef_usage_t typedef_usage;
18391   tree ti;
18392
18393   if (!t || t == error_mark_node)
18394     return;
18395
18396   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
18397                || CLASS_TYPE_P (t))
18398               && type_decl
18399               && TREE_CODE (type_decl) == TYPE_DECL
18400               && scope);
18401
18402   if (!(ti = get_template_info (t)))
18403     return;
18404
18405   gcc_assert (TI_TEMPLATE (ti));
18406
18407   typedef_usage.typedef_decl = type_decl;
18408   typedef_usage.context = scope;
18409   typedef_usage.locus = location;
18410
18411   VEC_safe_push (qualified_typedef_usage_t, gc,
18412                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
18413                  &typedef_usage);
18414 }
18415
18416 /* Append TYPE_DECL to the template TEMPL.
18417    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
18418    At TEMPL instanciation time, TYPE_DECL will be checked to see
18419    if it can be accessed through SCOPE.
18420    LOCATION is the location of the usage point of TYPE_DECL.
18421
18422    e.g. consider the following code snippet:
18423
18424      class C
18425      {
18426        typedef int myint;
18427      };
18428
18429      template<class U> struct S
18430      {
18431        C::myint mi; // <-- usage point of the typedef C::myint
18432      };
18433
18434      S<char> s;
18435
18436    At S<char> instantiation time, we need to check the access of C::myint
18437    In other words, we need to check the access of the myint typedef through
18438    the C scope. For that purpose, this function will add the myint typedef
18439    and the scope C through which its being accessed to a list of typedefs
18440    tied to the template S. That list will be walked at template instantiation
18441    time and access check performed on each typedefs it contains.
18442    Note that this particular code snippet should yield an error because
18443    myint is private to C.  */
18444
18445 void
18446 append_type_to_template_for_access_check (tree templ,
18447                                           tree type_decl,
18448                                           tree scope,
18449                                           location_t location)
18450 {
18451   qualified_typedef_usage_t *iter;
18452   int i;
18453
18454   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
18455
18456   /* Make sure we don't append the type to the template twice.  */
18457   for (i = 0;
18458        VEC_iterate (qualified_typedef_usage_t,
18459                     get_types_needing_access_check (templ),
18460                     i, iter);
18461        ++i)
18462     if (iter->typedef_decl == type_decl && scope == iter->context)
18463       return;
18464
18465   append_type_to_template_for_access_check_1 (templ, type_decl,
18466                                               scope, location);
18467 }
18468
18469 /* Set up the hash tables for template instantiations.  */
18470
18471 void
18472 init_template_processing (void)
18473 {
18474   decl_specializations = htab_create_ggc (37,
18475                                           hash_specialization,
18476                                           eq_specializations,
18477                                           ggc_free);
18478   type_specializations = htab_create_ggc (37,
18479                                           hash_specialization,
18480                                           eq_specializations,
18481                                           ggc_free);
18482 }
18483
18484 #include "gt-cp-pt.h"