OSDN Git Service

ef765738f7490994bacb9fe33a57eba949224144
[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 ("redeclared with %d template parameter(s)", 
4665              TREE_VEC_LENGTH (parms));
4666       inform (input_location, "previous declaration %q+D used %d template parameter(s)", 
4667              tmpl, TREE_VEC_LENGTH (tmpl_parms));
4668       return false;
4669     }
4670
4671   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4672     {
4673       tree tmpl_parm;
4674       tree parm;
4675       tree tmpl_default;
4676       tree parm_default;
4677
4678       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4679           || TREE_VEC_ELT (parms, i) == error_mark_node)
4680         continue;
4681
4682       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4683       if (tmpl_parm == error_mark_node)
4684         return false;
4685
4686       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4687       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4688       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4689
4690       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4691          TEMPLATE_DECL.  */
4692       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4693           || (TREE_CODE (tmpl_parm) != TYPE_DECL
4694               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4695           || (TREE_CODE (tmpl_parm) != PARM_DECL
4696               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4697                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4698           || (TREE_CODE (tmpl_parm) == PARM_DECL
4699               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4700                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
4701         {
4702           error ("template parameter %q+#D", tmpl_parm);
4703           error ("redeclared here as %q#D", parm);
4704           return false;
4705         }
4706
4707       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4708         {
4709           /* We have in [temp.param]:
4710
4711              A template-parameter may not be given default arguments
4712              by two different declarations in the same scope.  */
4713           error_at (input_location, "redefinition of default argument for %q#D", parm);
4714           inform (DECL_SOURCE_LOCATION (tmpl_parm),
4715                   "original definition appeared here");
4716           return false;
4717         }
4718
4719       if (parm_default != NULL_TREE)
4720         /* Update the previous template parameters (which are the ones
4721            that will really count) with the new default value.  */
4722         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4723       else if (tmpl_default != NULL_TREE)
4724         /* Update the new parameters, too; they'll be used as the
4725            parameters for any members.  */
4726         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4727     }
4728
4729     return true;
4730 }
4731
4732 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4733    (possibly simplified) expression.  */
4734
4735 tree
4736 fold_non_dependent_expr (tree expr)
4737 {
4738   if (expr == NULL_TREE)
4739     return NULL_TREE;
4740
4741   /* If we're in a template, but EXPR isn't value dependent, simplify
4742      it.  We're supposed to treat:
4743
4744        template <typename T> void f(T[1 + 1]);
4745        template <typename T> void f(T[2]);
4746
4747      as two declarations of the same function, for example.  */
4748   if (processing_template_decl
4749       && !type_dependent_expression_p (expr)
4750       && !value_dependent_expression_p (expr))
4751     {
4752       HOST_WIDE_INT saved_processing_template_decl;
4753
4754       saved_processing_template_decl = processing_template_decl;
4755       processing_template_decl = 0;
4756       expr = tsubst_copy_and_build (expr,
4757                                     /*args=*/NULL_TREE,
4758                                     tf_error,
4759                                     /*in_decl=*/NULL_TREE,
4760                                     /*function_p=*/false,
4761                                     /*integral_constant_expression_p=*/true);
4762       processing_template_decl = saved_processing_template_decl;
4763     }
4764   return expr;
4765 }
4766
4767 /* EXPR is an expression which is used in a constant-expression context.
4768    For instance, it could be a VAR_DECL with a constant initializer.
4769    Extract the innermost constant expression.
4770
4771    This is basically a more powerful version of
4772    integral_constant_value, which can be used also in templates where
4773    initializers can maintain a syntactic rather than semantic form
4774    (even if they are non-dependent, for access-checking purposes).  */
4775
4776 static tree
4777 fold_decl_constant_value (tree expr)
4778 {
4779   tree const_expr = expr;
4780   do
4781     {
4782       expr = fold_non_dependent_expr (const_expr);
4783       const_expr = integral_constant_value (expr);
4784     }
4785   while (expr != const_expr);
4786
4787   return expr;
4788 }
4789
4790 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4791    must be a function or a pointer-to-function type, as specified
4792    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4793    and check that the resulting function has external linkage.  */
4794
4795 static tree
4796 convert_nontype_argument_function (tree type, tree expr)
4797 {
4798   tree fns = expr;
4799   tree fn, fn_no_ptr;
4800
4801   fn = instantiate_type (type, fns, tf_none);
4802   if (fn == error_mark_node)
4803     return error_mark_node;
4804
4805   fn_no_ptr = fn;
4806   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4807     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4808   if (TREE_CODE (fn_no_ptr) == BASELINK)
4809     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4810  
4811   /* [temp.arg.nontype]/1
4812
4813      A template-argument for a non-type, non-template template-parameter
4814      shall be one of:
4815      [...]
4816      -- the address of an object or function with external linkage.  */
4817   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4818     {
4819       error ("%qE is not a valid template argument for type %qT "
4820              "because function %qD has not external linkage",
4821              expr, type, fn_no_ptr);
4822       return NULL_TREE;
4823     }
4824
4825   return fn;
4826 }
4827
4828 /* Subroutine of convert_nontype_argument.
4829    Check if EXPR of type TYPE is a valid pointer-to-member constant.
4830    Emit an error otherwise.  */
4831
4832 static bool
4833 check_valid_ptrmem_cst_expr (tree type, tree expr)
4834 {
4835   STRIP_NOPS (expr);
4836   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
4837     return true;
4838   error ("%qE is not a valid template argument for type %qT",
4839          expr, type);
4840   error ("it must be a pointer-to-member of the form `&X::Y'");
4841   return false;
4842 }
4843
4844 /* Attempt to convert the non-type template parameter EXPR to the
4845    indicated TYPE.  If the conversion is successful, return the
4846    converted value.  If the conversion is unsuccessful, return
4847    NULL_TREE if we issued an error message, or error_mark_node if we
4848    did not.  We issue error messages for out-and-out bad template
4849    parameters, but not simply because the conversion failed, since we
4850    might be just trying to do argument deduction.  Both TYPE and EXPR
4851    must be non-dependent.
4852
4853    The conversion follows the special rules described in
4854    [temp.arg.nontype], and it is much more strict than an implicit
4855    conversion.
4856
4857    This function is called twice for each template argument (see
4858    lookup_template_class for a more accurate description of this
4859    problem). This means that we need to handle expressions which
4860    are not valid in a C++ source, but can be created from the
4861    first call (for instance, casts to perform conversions). These
4862    hacks can go away after we fix the double coercion problem.  */
4863
4864 static tree
4865 convert_nontype_argument (tree type, tree expr)
4866 {
4867   tree expr_type;
4868
4869   /* Detect immediately string literals as invalid non-type argument.
4870      This special-case is not needed for correctness (we would easily
4871      catch this later), but only to provide better diagnostic for this
4872      common user mistake. As suggested by DR 100, we do not mention
4873      linkage issues in the diagnostic as this is not the point.  */
4874   if (TREE_CODE (expr) == STRING_CST)
4875     {
4876       error ("%qE is not a valid template argument for type %qT "
4877              "because string literals can never be used in this context",
4878              expr, type);
4879       return NULL_TREE;
4880     }
4881
4882   /* If we are in a template, EXPR may be non-dependent, but still
4883      have a syntactic, rather than semantic, form.  For example, EXPR
4884      might be a SCOPE_REF, rather than the VAR_DECL to which the
4885      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4886      so that access checking can be performed when the template is
4887      instantiated -- but here we need the resolved form so that we can
4888      convert the argument.  */
4889   expr = fold_non_dependent_expr (expr);
4890   if (error_operand_p (expr))
4891     return error_mark_node;
4892   expr_type = TREE_TYPE (expr);
4893
4894   /* HACK: Due to double coercion, we can get a
4895      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4896      which is the tree that we built on the first call (see
4897      below when coercing to reference to object or to reference to
4898      function). We just strip everything and get to the arg.
4899      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4900      for examples.  */
4901   if (TREE_CODE (expr) == NOP_EXPR)
4902     {
4903       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4904         {
4905           /* ??? Maybe we could use convert_from_reference here, but we
4906              would need to relax its constraints because the NOP_EXPR
4907              could actually change the type to something more cv-qualified,
4908              and this is not folded by convert_from_reference.  */
4909           tree addr = TREE_OPERAND (expr, 0);
4910           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4911           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4912           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4913           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4914                       (TREE_TYPE (expr_type),
4915                        TREE_TYPE (TREE_TYPE (addr))));
4916
4917           expr = TREE_OPERAND (addr, 0);
4918           expr_type = TREE_TYPE (expr);
4919         }
4920
4921       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4922          parameter is a pointer to object, through decay and
4923          qualification conversion. Let's strip everything.  */
4924       else if (TYPE_PTROBV_P (type))
4925         {
4926           STRIP_NOPS (expr);
4927           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4928           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4929           /* Skip the ADDR_EXPR only if it is part of the decay for
4930              an array. Otherwise, it is part of the original argument
4931              in the source code.  */
4932           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4933             expr = TREE_OPERAND (expr, 0);
4934           expr_type = TREE_TYPE (expr);
4935         }
4936     }
4937
4938   /* [temp.arg.nontype]/5, bullet 1
4939
4940      For a non-type template-parameter of integral or enumeration type,
4941      integral promotions (_conv.prom_) and integral conversions
4942      (_conv.integral_) are applied.  */
4943   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4944     {
4945       if (!INTEGRAL_OR_ENUMERATION_TYPE_P (expr_type))
4946         return error_mark_node;
4947
4948       expr = fold_decl_constant_value (expr);
4949       /* Notice that there are constant expressions like '4 % 0' which
4950          do not fold into integer constants.  */
4951       if (TREE_CODE (expr) != INTEGER_CST)
4952         {
4953           error ("%qE is not a valid template argument for type %qT "
4954                  "because it is a non-constant expression", expr, type);
4955           return NULL_TREE;
4956         }
4957
4958       /* At this point, an implicit conversion does what we want,
4959          because we already know that the expression is of integral
4960          type.  */
4961       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4962       if (expr == error_mark_node)
4963         return error_mark_node;
4964
4965       /* Conversion was allowed: fold it to a bare integer constant.  */
4966       expr = fold (expr);
4967     }
4968   /* [temp.arg.nontype]/5, bullet 2
4969
4970      For a non-type template-parameter of type pointer to object,
4971      qualification conversions (_conv.qual_) and the array-to-pointer
4972      conversion (_conv.array_) are applied.  */
4973   else if (TYPE_PTROBV_P (type))
4974     {
4975       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
4976
4977          A template-argument for a non-type, non-template template-parameter
4978          shall be one of: [...]
4979
4980          -- the name of a non-type template-parameter;
4981          -- the address of an object or function with external linkage, [...]
4982             expressed as "& id-expression" where the & is optional if the name
4983             refers to a function or array, or if the corresponding
4984             template-parameter is a reference.
4985
4986         Here, we do not care about functions, as they are invalid anyway
4987         for a parameter of type pointer-to-object.  */
4988
4989       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
4990         /* Non-type template parameters are OK.  */
4991         ;
4992       else if (TREE_CODE (expr) != ADDR_EXPR
4993                && TREE_CODE (expr_type) != ARRAY_TYPE)
4994         {
4995           if (TREE_CODE (expr) == VAR_DECL)
4996             {
4997               error ("%qD is not a valid template argument "
4998                      "because %qD is a variable, not the address of "
4999                      "a variable",
5000                      expr, expr);
5001               return NULL_TREE;
5002             }
5003           /* Other values, like integer constants, might be valid
5004              non-type arguments of some other type.  */
5005           return error_mark_node;
5006         }
5007       else
5008         {
5009           tree decl;
5010
5011           decl = ((TREE_CODE (expr) == ADDR_EXPR)
5012                   ? TREE_OPERAND (expr, 0) : expr);
5013           if (TREE_CODE (decl) != VAR_DECL)
5014             {
5015               error ("%qE is not a valid template argument of type %qT "
5016                      "because %qE is not a variable",
5017                      expr, type, decl);
5018               return NULL_TREE;
5019             }
5020           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
5021             {
5022               error ("%qE is not a valid template argument of type %qT "
5023                      "because %qD does not have external linkage",
5024                      expr, type, decl);
5025               return NULL_TREE;
5026             }
5027         }
5028
5029       expr = decay_conversion (expr);
5030       if (expr == error_mark_node)
5031         return error_mark_node;
5032
5033       expr = perform_qualification_conversions (type, expr);
5034       if (expr == error_mark_node)
5035         return error_mark_node;
5036     }
5037   /* [temp.arg.nontype]/5, bullet 3
5038
5039      For a non-type template-parameter of type reference to object, no
5040      conversions apply. The type referred to by the reference may be more
5041      cv-qualified than the (otherwise identical) type of the
5042      template-argument. The template-parameter is bound directly to the
5043      template-argument, which must be an lvalue.  */
5044   else if (TYPE_REF_OBJ_P (type))
5045     {
5046       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5047                                                       expr_type))
5048         return error_mark_node;
5049
5050       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5051         {
5052           error ("%qE is not a valid template argument for type %qT "
5053                  "because of conflicts in cv-qualification", expr, type);
5054           return NULL_TREE;
5055         }
5056
5057       if (!real_lvalue_p (expr))
5058         {
5059           error ("%qE is not a valid template argument for type %qT "
5060                  "because it is not an lvalue", expr, type);
5061           return NULL_TREE;
5062         }
5063
5064       /* [temp.arg.nontype]/1
5065
5066          A template-argument for a non-type, non-template template-parameter
5067          shall be one of: [...]
5068
5069          -- the address of an object or function with external linkage.  */
5070       if (TREE_CODE (expr) == INDIRECT_REF
5071           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5072         {
5073           expr = TREE_OPERAND (expr, 0);
5074           if (DECL_P (expr))
5075             {
5076               error ("%q#D is not a valid template argument for type %qT "
5077                      "because a reference variable does not have a constant "
5078                      "address", expr, type);
5079               return NULL_TREE;
5080             }
5081         }
5082
5083       if (!DECL_P (expr))
5084         {
5085           error ("%qE is not a valid template argument for type %qT "
5086                  "because it is not an object with external linkage",
5087                  expr, type);
5088           return NULL_TREE;
5089         }
5090
5091       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5092         {
5093           error ("%qE is not a valid template argument for type %qT "
5094                  "because object %qD has not external linkage",
5095                  expr, type, expr);
5096           return NULL_TREE;
5097         }
5098
5099       expr = build_nop (type, build_address (expr));
5100     }
5101   /* [temp.arg.nontype]/5, bullet 4
5102
5103      For a non-type template-parameter of type pointer to function, only
5104      the function-to-pointer conversion (_conv.func_) is applied. If the
5105      template-argument represents a set of overloaded functions (or a
5106      pointer to such), the matching function is selected from the set
5107      (_over.over_).  */
5108   else if (TYPE_PTRFN_P (type))
5109     {
5110       /* If the argument is a template-id, we might not have enough
5111          context information to decay the pointer.  */
5112       if (!type_unknown_p (expr_type))
5113         {
5114           expr = decay_conversion (expr);
5115           if (expr == error_mark_node)
5116             return error_mark_node;
5117         }
5118
5119       expr = convert_nontype_argument_function (type, expr);
5120       if (!expr || expr == error_mark_node)
5121         return expr;
5122
5123       if (TREE_CODE (expr) != ADDR_EXPR)
5124         {
5125           error ("%qE is not a valid template argument for type %qT", expr, type);
5126           error ("it must be the address of a function with external linkage");
5127           return NULL_TREE;
5128         }
5129     }
5130   /* [temp.arg.nontype]/5, bullet 5
5131
5132      For a non-type template-parameter of type reference to function, no
5133      conversions apply. If the template-argument represents a set of
5134      overloaded functions, the matching function is selected from the set
5135      (_over.over_).  */
5136   else if (TYPE_REFFN_P (type))
5137     {
5138       if (TREE_CODE (expr) == ADDR_EXPR)
5139         {
5140           error ("%qE is not a valid template argument for type %qT "
5141                  "because it is a pointer", expr, type);
5142           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5143           return NULL_TREE;
5144         }
5145
5146       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5147       if (!expr || expr == error_mark_node)
5148         return expr;
5149
5150       expr = build_nop (type, build_address (expr));
5151     }
5152   /* [temp.arg.nontype]/5, bullet 6
5153
5154      For a non-type template-parameter of type pointer to member function,
5155      no conversions apply. If the template-argument represents a set of
5156      overloaded member functions, the matching member function is selected
5157      from the set (_over.over_).  */
5158   else if (TYPE_PTRMEMFUNC_P (type))
5159     {
5160       expr = instantiate_type (type, expr, tf_none);
5161       if (expr == error_mark_node)
5162         return error_mark_node;
5163
5164       /* [temp.arg.nontype] bullet 1 says the pointer to member
5165          expression must be a pointer-to-member constant.  */
5166       if (!check_valid_ptrmem_cst_expr (type, expr))
5167         return error_mark_node;
5168
5169       /* There is no way to disable standard conversions in
5170          resolve_address_of_overloaded_function (called by
5171          instantiate_type). It is possible that the call succeeded by
5172          converting &B::I to &D::I (where B is a base of D), so we need
5173          to reject this conversion here.
5174
5175          Actually, even if there was a way to disable standard conversions,
5176          it would still be better to reject them here so that we can
5177          provide a superior diagnostic.  */
5178       if (!same_type_p (TREE_TYPE (expr), type))
5179         {
5180           error ("%qE is not a valid template argument for type %qT "
5181                  "because it is of type %qT", expr, type,
5182                  TREE_TYPE (expr));
5183           /* If we are just one standard conversion off, explain.  */
5184           if (can_convert (type, TREE_TYPE (expr)))
5185             inform (input_location,
5186                     "standard conversions are not allowed in this context");
5187           return NULL_TREE;
5188         }
5189     }
5190   /* [temp.arg.nontype]/5, bullet 7
5191
5192      For a non-type template-parameter of type pointer to data member,
5193      qualification conversions (_conv.qual_) are applied.  */
5194   else if (TYPE_PTRMEM_P (type))
5195     {
5196       /* [temp.arg.nontype] bullet 1 says the pointer to member
5197          expression must be a pointer-to-member constant.  */
5198       if (!check_valid_ptrmem_cst_expr (type, expr))
5199         return error_mark_node;
5200
5201       expr = perform_qualification_conversions (type, expr);
5202       if (expr == error_mark_node)
5203         return expr;
5204     }
5205   /* A template non-type parameter must be one of the above.  */
5206   else
5207     gcc_unreachable ();
5208
5209   /* Sanity check: did we actually convert the argument to the
5210      right type?  */
5211   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
5212   return expr;
5213 }
5214
5215 /* Subroutine of coerce_template_template_parms, which returns 1 if
5216    PARM_PARM and ARG_PARM match using the rule for the template
5217    parameters of template template parameters. Both PARM and ARG are
5218    template parameters; the rest of the arguments are the same as for
5219    coerce_template_template_parms.
5220  */
5221 static int
5222 coerce_template_template_parm (tree parm,
5223                               tree arg,
5224                               tsubst_flags_t complain,
5225                               tree in_decl,
5226                               tree outer_args)
5227 {
5228   if (arg == NULL_TREE || arg == error_mark_node
5229       || parm == NULL_TREE || parm == error_mark_node)
5230     return 0;
5231   
5232   if (TREE_CODE (arg) != TREE_CODE (parm))
5233     return 0;
5234   
5235   switch (TREE_CODE (parm))
5236     {
5237     case TEMPLATE_DECL:
5238       /* We encounter instantiations of templates like
5239          template <template <template <class> class> class TT>
5240          class C;  */
5241       {
5242         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5243         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5244         
5245         if (!coerce_template_template_parms
5246             (parmparm, argparm, complain, in_decl, outer_args))
5247           return 0;
5248       }
5249       /* Fall through.  */
5250       
5251     case TYPE_DECL:
5252       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5253           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5254         /* Argument is a parameter pack but parameter is not.  */
5255         return 0;
5256       break;
5257       
5258     case PARM_DECL:
5259       /* The tsubst call is used to handle cases such as
5260          
5261            template <int> class C {};
5262            template <class T, template <T> class TT> class D {};
5263            D<int, C> d;
5264
5265          i.e. the parameter list of TT depends on earlier parameters.  */
5266       if (!uses_template_parms (TREE_TYPE (arg))
5267           && !same_type_p
5268                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5269                  TREE_TYPE (arg)))
5270         return 0;
5271       
5272       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5273           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5274         /* Argument is a parameter pack but parameter is not.  */
5275         return 0;
5276       
5277       break;
5278
5279     default:
5280       gcc_unreachable ();
5281     }
5282
5283   return 1;
5284 }
5285
5286
5287 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5288    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5289    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5290    or PARM_DECL.
5291
5292    Consider the example:
5293      template <class T> class A;
5294      template<template <class U> class TT> class B;
5295
5296    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5297    the parameters to A, and OUTER_ARGS contains A.  */
5298
5299 static int
5300 coerce_template_template_parms (tree parm_parms,
5301                                 tree arg_parms,
5302                                 tsubst_flags_t complain,
5303                                 tree in_decl,
5304                                 tree outer_args)
5305 {
5306   int nparms, nargs, i;
5307   tree parm, arg;
5308   int variadic_p = 0;
5309
5310   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5311   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5312
5313   nparms = TREE_VEC_LENGTH (parm_parms);
5314   nargs = TREE_VEC_LENGTH (arg_parms);
5315
5316   /* Determine whether we have a parameter pack at the end of the
5317      template template parameter's template parameter list.  */
5318   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5319     {
5320       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5321       
5322       if (parm == error_mark_node)
5323         return 0;
5324
5325       switch (TREE_CODE (parm))
5326         {
5327         case TEMPLATE_DECL:
5328         case TYPE_DECL:
5329           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5330             variadic_p = 1;
5331           break;
5332           
5333         case PARM_DECL:
5334           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5335             variadic_p = 1;
5336           break;
5337           
5338         default:
5339           gcc_unreachable ();
5340         }
5341     }
5342  
5343   if (nargs != nparms
5344       && !(variadic_p && nargs >= nparms - 1))
5345     return 0;
5346
5347   /* Check all of the template parameters except the parameter pack at
5348      the end (if any).  */
5349   for (i = 0; i < nparms - variadic_p; ++i)
5350     {
5351       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5352           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5353         continue;
5354
5355       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5356       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5357
5358       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5359                                           outer_args))
5360         return 0;
5361
5362     }
5363
5364   if (variadic_p)
5365     {
5366       /* Check each of the template parameters in the template
5367          argument against the template parameter pack at the end of
5368          the template template parameter.  */
5369       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5370         return 0;
5371
5372       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5373
5374       for (; i < nargs; ++i)
5375         {
5376           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5377             continue;
5378  
5379           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5380  
5381           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5382                                               outer_args))
5383             return 0;
5384         }
5385     }
5386
5387   return 1;
5388 }
5389
5390 /* Verifies that the deduced template arguments (in TARGS) for the
5391    template template parameters (in TPARMS) represent valid bindings,
5392    by comparing the template parameter list of each template argument
5393    to the template parameter list of its corresponding template
5394    template parameter, in accordance with DR150. This
5395    routine can only be called after all template arguments have been
5396    deduced. It will return TRUE if all of the template template
5397    parameter bindings are okay, FALSE otherwise.  */
5398 bool 
5399 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5400 {
5401   int i, ntparms = TREE_VEC_LENGTH (tparms);
5402   bool ret = true;
5403
5404   /* We're dealing with template parms in this process.  */
5405   ++processing_template_decl;
5406
5407   targs = INNERMOST_TEMPLATE_ARGS (targs);
5408
5409   for (i = 0; i < ntparms; ++i)
5410     {
5411       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5412       tree targ = TREE_VEC_ELT (targs, i);
5413
5414       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5415         {
5416           tree packed_args = NULL_TREE;
5417           int idx, len = 1;
5418
5419           if (ARGUMENT_PACK_P (targ))
5420             {
5421               /* Look inside the argument pack.  */
5422               packed_args = ARGUMENT_PACK_ARGS (targ);
5423               len = TREE_VEC_LENGTH (packed_args);
5424             }
5425
5426           for (idx = 0; idx < len; ++idx)
5427             {
5428               tree targ_parms = NULL_TREE;
5429
5430               if (packed_args)
5431                 /* Extract the next argument from the argument
5432                    pack.  */
5433                 targ = TREE_VEC_ELT (packed_args, idx);
5434
5435               if (PACK_EXPANSION_P (targ))
5436                 /* Look at the pattern of the pack expansion.  */
5437                 targ = PACK_EXPANSION_PATTERN (targ);
5438
5439               /* Extract the template parameters from the template
5440                  argument.  */
5441               if (TREE_CODE (targ) == TEMPLATE_DECL)
5442                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5443               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5444                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5445
5446               /* Verify that we can coerce the template template
5447                  parameters from the template argument to the template
5448                  parameter.  This requires an exact match.  */
5449               if (targ_parms
5450                   && !coerce_template_template_parms
5451                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5452                         targ_parms,
5453                         tf_none,
5454                         tparm,
5455                         targs))
5456                 {
5457                   ret = false;
5458                   goto out;
5459                 }
5460             }
5461         }
5462     }
5463
5464  out:
5465
5466   --processing_template_decl;
5467   return ret;
5468 }
5469
5470 /* Convert the indicated template ARG as necessary to match the
5471    indicated template PARM.  Returns the converted ARG, or
5472    error_mark_node if the conversion was unsuccessful.  Error and
5473    warning messages are issued under control of COMPLAIN.  This
5474    conversion is for the Ith parameter in the parameter list.  ARGS is
5475    the full set of template arguments deduced so far.  */
5476
5477 static tree
5478 convert_template_argument (tree parm,
5479                            tree arg,
5480                            tree args,
5481                            tsubst_flags_t complain,
5482                            int i,
5483                            tree in_decl)
5484 {
5485   tree orig_arg;
5486   tree val;
5487   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5488
5489   if (TREE_CODE (arg) == TREE_LIST
5490       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5491     {
5492       /* The template argument was the name of some
5493          member function.  That's usually
5494          invalid, but static members are OK.  In any
5495          case, grab the underlying fields/functions
5496          and issue an error later if required.  */
5497       orig_arg = TREE_VALUE (arg);
5498       TREE_TYPE (arg) = unknown_type_node;
5499     }
5500
5501   orig_arg = arg;
5502
5503   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5504   requires_type = (TREE_CODE (parm) == TYPE_DECL
5505                    || requires_tmpl_type);
5506
5507   /* When determining whether an argument pack expansion is a template,
5508      look at the pattern.  */
5509   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5510     arg = PACK_EXPANSION_PATTERN (arg);
5511
5512   /* Deal with an injected-class-name used as a template template arg.  */
5513   if (requires_tmpl_type && CLASS_TYPE_P (arg))
5514     {
5515       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
5516       if (TREE_CODE (t) == TEMPLATE_DECL)
5517         {
5518           if (complain & tf_warning_or_error)
5519             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
5520                      " used as template template argument", TYPE_NAME (arg));
5521           else if (flag_pedantic_errors)
5522             t = arg;
5523
5524           arg = t;
5525         }
5526     }
5527
5528   is_tmpl_type = 
5529     ((TREE_CODE (arg) == TEMPLATE_DECL
5530       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5531      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5532      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5533
5534   if (is_tmpl_type
5535       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5536           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5537     arg = TYPE_STUB_DECL (arg);
5538
5539   is_type = TYPE_P (arg) || is_tmpl_type;
5540
5541   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
5542       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
5543     {
5544       permerror (input_location, "to refer to a type member of a template parameter, "
5545                  "use %<typename %E%>", orig_arg);
5546
5547       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
5548                                      TREE_OPERAND (arg, 1),
5549                                      typename_type,
5550                                      complain & tf_error);
5551       arg = orig_arg;
5552       is_type = 1;
5553     }
5554   if (is_type != requires_type)
5555     {
5556       if (in_decl)
5557         {
5558           if (complain & tf_error)
5559             {
5560               error ("type/value mismatch at argument %d in template "
5561                      "parameter list for %qD",
5562                      i + 1, in_decl);
5563               if (is_type)
5564                 error ("  expected a constant of type %qT, got %qT",
5565                        TREE_TYPE (parm),
5566                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
5567               else if (requires_tmpl_type)
5568                 error ("  expected a class template, got %qE", orig_arg);
5569               else
5570                 error ("  expected a type, got %qE", orig_arg);
5571             }
5572         }
5573       return error_mark_node;
5574     }
5575   if (is_tmpl_type ^ requires_tmpl_type)
5576     {
5577       if (in_decl && (complain & tf_error))
5578         {
5579           error ("type/value mismatch at argument %d in template "
5580                  "parameter list for %qD",
5581                  i + 1, in_decl);
5582           if (is_tmpl_type)
5583             error ("  expected a type, got %qT", DECL_NAME (arg));
5584           else
5585             error ("  expected a class template, got %qT", orig_arg);
5586         }
5587       return error_mark_node;
5588     }
5589
5590   if (is_type)
5591     {
5592       if (requires_tmpl_type)
5593         {
5594           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5595             /* The number of argument required is not known yet.
5596                Just accept it for now.  */
5597             val = TREE_TYPE (arg);
5598           else
5599             {
5600               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5601               tree argparm;
5602
5603               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5604
5605               if (coerce_template_template_parms (parmparm, argparm,
5606                                                   complain, in_decl,
5607                                                   args))
5608                 {
5609                   val = arg;
5610
5611                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5612                      TEMPLATE_DECL.  */
5613                   if (val != error_mark_node)
5614                     {
5615                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5616                         val = TREE_TYPE (val);
5617                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
5618                         val = make_pack_expansion (val);
5619                     }
5620                 }
5621               else
5622                 {
5623                   if (in_decl && (complain & tf_error))
5624                     {
5625                       error ("type/value mismatch at argument %d in "
5626                              "template parameter list for %qD",
5627                              i + 1, in_decl);
5628                       error ("  expected a template of type %qD, got %qT",
5629                              parm, orig_arg);
5630                     }
5631
5632                   val = error_mark_node;
5633                 }
5634             }
5635         }
5636       else
5637         val = orig_arg;
5638       /* We only form one instance of each template specialization.
5639          Therefore, if we use a non-canonical variant (i.e., a
5640          typedef), any future messages referring to the type will use
5641          the typedef, which is confusing if those future uses do not
5642          themselves also use the typedef.  */
5643       if (TYPE_P (val))
5644         val = strip_typedefs (val);
5645     }
5646   else
5647     {
5648       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5649
5650       if (invalid_nontype_parm_type_p (t, complain))
5651         return error_mark_node;
5652
5653       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5654         {
5655           if (same_type_p (t, TREE_TYPE (orig_arg)))
5656             val = orig_arg;
5657           else
5658             {
5659               /* Not sure if this is reachable, but it doesn't hurt
5660                  to be robust.  */
5661               error ("type mismatch in nontype parameter pack");
5662               val = error_mark_node;
5663             }
5664         }
5665       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5666         /* We used to call digest_init here.  However, digest_init
5667            will report errors, which we don't want when complain
5668            is zero.  More importantly, digest_init will try too
5669            hard to convert things: for example, `0' should not be
5670            converted to pointer type at this point according to
5671            the standard.  Accepting this is not merely an
5672            extension, since deciding whether or not these
5673            conversions can occur is part of determining which
5674            function template to call, or whether a given explicit
5675            argument specification is valid.  */
5676         val = convert_nontype_argument (t, orig_arg);
5677       else
5678         val = orig_arg;
5679
5680       if (val == NULL_TREE)
5681         val = error_mark_node;
5682       else if (val == error_mark_node && (complain & tf_error))
5683         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5684
5685       if (TREE_CODE (val) == SCOPE_REF)
5686         {
5687           /* Strip typedefs from the SCOPE_REF.  */
5688           tree type = strip_typedefs (TREE_TYPE (val));
5689           tree scope = strip_typedefs (TREE_OPERAND (val, 0));
5690           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
5691                                       QUALIFIED_NAME_IS_TEMPLATE (val));
5692         }
5693     }
5694
5695   return val;
5696 }
5697
5698 /* Coerces the remaining template arguments in INNER_ARGS (from
5699    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5700    Returns the coerced argument pack. PARM_IDX is the position of this
5701    parameter in the template parameter list. ARGS is the original
5702    template argument list.  */
5703 static tree
5704 coerce_template_parameter_pack (tree parms,
5705                                 int parm_idx,
5706                                 tree args,
5707                                 tree inner_args,
5708                                 int arg_idx,
5709                                 tree new_args,
5710                                 int* lost,
5711                                 tree in_decl,
5712                                 tsubst_flags_t complain)
5713 {
5714   tree parm = TREE_VEC_ELT (parms, parm_idx);
5715   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5716   tree packed_args;
5717   tree argument_pack;
5718   tree packed_types = NULL_TREE;
5719
5720   if (arg_idx > nargs)
5721     arg_idx = nargs;
5722
5723   packed_args = make_tree_vec (nargs - arg_idx);
5724
5725   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5726       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5727     {
5728       /* When the template parameter is a non-type template
5729          parameter pack whose type uses parameter packs, we need
5730          to look at each of the template arguments
5731          separately. Build a vector of the types for these
5732          non-type template parameters in PACKED_TYPES.  */
5733       tree expansion 
5734         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5735       packed_types = tsubst_pack_expansion (expansion, args,
5736                                             complain, in_decl);
5737
5738       if (packed_types == error_mark_node)
5739         return error_mark_node;
5740
5741       /* Check that we have the right number of arguments.  */
5742       if (arg_idx < nargs
5743           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5744           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5745         {
5746           int needed_parms 
5747             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5748           error ("wrong number of template arguments (%d, should be %d)",
5749                  nargs, needed_parms);
5750           return error_mark_node;
5751         }
5752
5753       /* If we aren't able to check the actual arguments now
5754          (because they haven't been expanded yet), we can at least
5755          verify that all of the types used for the non-type
5756          template parameter pack are, in fact, valid for non-type
5757          template parameters.  */
5758       if (arg_idx < nargs 
5759           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5760         {
5761           int j, len = TREE_VEC_LENGTH (packed_types);
5762           for (j = 0; j < len; ++j)
5763             {
5764               tree t = TREE_VEC_ELT (packed_types, j);
5765               if (invalid_nontype_parm_type_p (t, complain))
5766                 return error_mark_node;
5767             }
5768         }
5769     }
5770
5771   /* Convert the remaining arguments, which will be a part of the
5772      parameter pack "parm".  */
5773   for (; arg_idx < nargs; ++arg_idx)
5774     {
5775       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5776       tree actual_parm = TREE_VALUE (parm);
5777
5778       if (packed_types && !PACK_EXPANSION_P (arg))
5779         {
5780           /* When we have a vector of types (corresponding to the
5781              non-type template parameter pack that uses parameter
5782              packs in its type, as mention above), and the
5783              argument is not an expansion (which expands to a
5784              currently unknown number of arguments), clone the
5785              parm and give it the next type in PACKED_TYPES.  */
5786           actual_parm = copy_node (actual_parm);
5787           TREE_TYPE (actual_parm) = 
5788             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5789         }
5790
5791       if (arg != error_mark_node)
5792         arg = convert_template_argument (actual_parm, 
5793                                          arg, new_args, complain, parm_idx,
5794                                          in_decl);
5795       if (arg == error_mark_node)
5796         (*lost)++;
5797       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5798     }
5799
5800   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5801       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5802     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
5803   else
5804     {
5805       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5806       TREE_TYPE (argument_pack) 
5807         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5808       TREE_CONSTANT (argument_pack) = 1;
5809     }
5810
5811   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5812 #ifdef ENABLE_CHECKING
5813   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
5814                                        TREE_VEC_LENGTH (packed_args));
5815 #endif
5816   return argument_pack;
5817 }
5818
5819 /* Convert all template arguments to their appropriate types, and
5820    return a vector containing the innermost resulting template
5821    arguments.  If any error occurs, return error_mark_node. Error and
5822    warning messages are issued under control of COMPLAIN.
5823
5824    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5825    for arguments not specified in ARGS.  Otherwise, if
5826    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5827    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5828    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5829    ARGS.  */
5830
5831 static tree
5832 coerce_template_parms (tree parms,
5833                        tree args,
5834                        tree in_decl,
5835                        tsubst_flags_t complain,
5836                        bool require_all_args,
5837                        bool use_default_args)
5838 {
5839   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5840   tree inner_args;
5841   tree new_args;
5842   tree new_inner_args;
5843   int saved_unevaluated_operand;
5844   int saved_inhibit_evaluation_warnings;
5845
5846   /* When used as a boolean value, indicates whether this is a
5847      variadic template parameter list. Since it's an int, we can also
5848      subtract it from nparms to get the number of non-variadic
5849      parameters.  */
5850   int variadic_p = 0;
5851
5852   nparms = TREE_VEC_LENGTH (parms);
5853
5854   /* Determine if there are any parameter packs.  */
5855   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5856     {
5857       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5858       if (template_parameter_pack_p (tparm))
5859         ++variadic_p;
5860     }
5861
5862   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5863   /* If there are 0 or 1 parameter packs, we need to expand any argument
5864      packs so that we can deduce a parameter pack from some non-packed args
5865      followed by an argument pack, as in variadic85.C.  If there are more
5866      than that, we need to leave argument packs intact so the arguments are
5867      assigned to the right parameter packs.  This should only happen when
5868      dealing with a nested class inside a partial specialization of a class
5869      template, as in variadic92.C.  */
5870   if (variadic_p <= 1)
5871     inner_args = expand_template_argument_pack (inner_args);
5872
5873   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5874   if ((nargs > nparms && !variadic_p)
5875       || (nargs < nparms - variadic_p
5876           && require_all_args
5877           && (!use_default_args
5878               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5879                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5880     {
5881       if (complain & tf_error)
5882         {
5883           const char *or_more = "";
5884           if (variadic_p)
5885             {
5886               or_more = " or more";
5887               --nparms;
5888             }
5889
5890           error ("wrong number of template arguments (%d, should be %d%s)",
5891                  nargs, nparms, or_more);
5892
5893           if (in_decl)
5894             error ("provided for %q+D", in_decl);
5895         }
5896
5897       return error_mark_node;
5898     }
5899
5900   /* We need to evaluate the template arguments, even though this
5901      template-id may be nested within a "sizeof".  */
5902   saved_unevaluated_operand = cp_unevaluated_operand;
5903   cp_unevaluated_operand = 0;
5904   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
5905   c_inhibit_evaluation_warnings = 0;
5906   new_inner_args = make_tree_vec (nparms);
5907   new_args = add_outermost_template_args (args, new_inner_args);
5908   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5909     {
5910       tree arg;
5911       tree parm;
5912
5913       /* Get the Ith template parameter.  */
5914       parm = TREE_VEC_ELT (parms, parm_idx);
5915  
5916       if (parm == error_mark_node)
5917       {
5918         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5919         continue;
5920       }
5921
5922       /* Calculate the next argument.  */
5923       if (arg_idx < nargs)
5924         arg = TREE_VEC_ELT (inner_args, arg_idx);
5925       else
5926         arg = NULL_TREE;
5927
5928       if (template_parameter_pack_p (TREE_VALUE (parm))
5929           && !(arg && ARGUMENT_PACK_P (arg)))
5930         {
5931           /* All remaining arguments will be placed in the
5932              template parameter pack PARM.  */
5933           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5934                                                 inner_args, arg_idx,
5935                                                 new_args, &lost,
5936                                                 in_decl, complain);
5937
5938           /* Store this argument.  */
5939           if (arg == error_mark_node)
5940             lost++;
5941           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5942
5943           /* We are done with all of the arguments.  */
5944           arg_idx = nargs;
5945           
5946           continue;
5947         }
5948       else if (arg)
5949         {
5950           if (PACK_EXPANSION_P (arg))
5951             {
5952               if (complain & tf_error)
5953                 {
5954                   /* FIXME this restriction was removed by N2555; see
5955                      bug 35722.  */
5956                   /* If ARG is a pack expansion, but PARM is not a
5957                      template parameter pack (if it were, we would have
5958                      handled it above), we're trying to expand into a
5959                      fixed-length argument list.  */
5960                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5961                     sorry ("cannot expand %<%E%> into a fixed-length "
5962                            "argument list", arg);
5963                   else
5964                     sorry ("cannot expand %<%T%> into a fixed-length "
5965                            "argument list", arg);
5966                 }
5967               return error_mark_node;
5968             }
5969         }
5970       else if (require_all_args)
5971         {
5972           /* There must be a default arg in this case.  */
5973           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
5974                                      complain, in_decl);
5975           /* The position of the first default template argument,
5976              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
5977              Record that.  */
5978           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
5979             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
5980         }
5981       else
5982         break;
5983
5984       if (arg == error_mark_node)
5985         {
5986           if (complain & tf_error)
5987             error ("template argument %d is invalid", arg_idx + 1);
5988         }
5989       else if (!arg)
5990         /* This only occurs if there was an error in the template
5991            parameter list itself (which we would already have
5992            reported) that we are trying to recover from, e.g., a class
5993            template with a parameter list such as
5994            template<typename..., typename>.  */
5995         return error_mark_node;
5996       else
5997         arg = convert_template_argument (TREE_VALUE (parm),
5998                                          arg, new_args, complain, 
5999                                          parm_idx, in_decl);
6000
6001       if (arg == error_mark_node)
6002         lost++;
6003       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6004     }
6005   cp_unevaluated_operand = saved_unevaluated_operand;
6006   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6007
6008   if (lost)
6009     return error_mark_node;
6010
6011 #ifdef ENABLE_CHECKING
6012   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6013     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6014                                          TREE_VEC_LENGTH (new_inner_args));
6015 #endif
6016
6017   return new_inner_args;
6018 }
6019
6020 /* Returns 1 if template args OT and NT are equivalent.  */
6021
6022 static int
6023 template_args_equal (tree ot, tree nt)
6024 {
6025   if (nt == ot)
6026     return 1;
6027
6028   if (TREE_CODE (nt) == TREE_VEC)
6029     /* For member templates */
6030     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6031   else if (PACK_EXPANSION_P (ot))
6032     return PACK_EXPANSION_P (nt) 
6033       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6034                               PACK_EXPANSION_PATTERN (nt));
6035   else if (ARGUMENT_PACK_P (ot))
6036     {
6037       int i, len;
6038       tree opack, npack;
6039
6040       if (!ARGUMENT_PACK_P (nt))
6041         return 0;
6042
6043       opack = ARGUMENT_PACK_ARGS (ot);
6044       npack = ARGUMENT_PACK_ARGS (nt);
6045       len = TREE_VEC_LENGTH (opack);
6046       if (TREE_VEC_LENGTH (npack) != len)
6047         return 0;
6048       for (i = 0; i < len; ++i)
6049         if (!template_args_equal (TREE_VEC_ELT (opack, i),
6050                                   TREE_VEC_ELT (npack, i)))
6051           return 0;
6052       return 1;
6053     }
6054   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6055     {
6056       /* We get here probably because we are in the middle of substituting
6057          into the pattern of a pack expansion. In that case the
6058          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6059          interested in. So we want to use the initial pack argument for
6060          the comparison.  */
6061       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6062       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6063         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6064       return template_args_equal (ot, nt);
6065     }
6066   else if (TYPE_P (nt))
6067     return TYPE_P (ot) && same_type_p (ot, nt);
6068   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6069     return 0;
6070   else
6071     return cp_tree_equal (ot, nt);
6072 }
6073
6074 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6075    of template arguments.  Returns 0 otherwise.  */
6076
6077 int
6078 comp_template_args (tree oldargs, tree newargs)
6079 {
6080   int i;
6081
6082   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6083     return 0;
6084
6085   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6086     {
6087       tree nt = TREE_VEC_ELT (newargs, i);
6088       tree ot = TREE_VEC_ELT (oldargs, i);
6089
6090       if (! template_args_equal (ot, nt))
6091         return 0;
6092     }
6093   return 1;
6094 }
6095
6096 static void
6097 add_pending_template (tree d)
6098 {
6099   tree ti = (TYPE_P (d)
6100              ? CLASSTYPE_TEMPLATE_INFO (d)
6101              : DECL_TEMPLATE_INFO (d));
6102   struct pending_template *pt;
6103   int level;
6104
6105   if (TI_PENDING_TEMPLATE_FLAG (ti))
6106     return;
6107
6108   /* We are called both from instantiate_decl, where we've already had a
6109      tinst_level pushed, and instantiate_template, where we haven't.
6110      Compensate.  */
6111   level = !current_tinst_level || current_tinst_level->decl != d;
6112
6113   if (level)
6114     push_tinst_level (d);
6115
6116   pt = GGC_NEW (struct pending_template);
6117   pt->next = NULL;
6118   pt->tinst = current_tinst_level;
6119   if (last_pending_template)
6120     last_pending_template->next = pt;
6121   else
6122     pending_templates = pt;
6123
6124   last_pending_template = pt;
6125
6126   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6127
6128   if (level)
6129     pop_tinst_level ();
6130 }
6131
6132
6133 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6134    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6135    documentation for TEMPLATE_ID_EXPR.  */
6136
6137 tree
6138 lookup_template_function (tree fns, tree arglist)
6139 {
6140   tree type;
6141
6142   if (fns == error_mark_node || arglist == error_mark_node)
6143     return error_mark_node;
6144
6145   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6146   gcc_assert (fns && (is_overloaded_fn (fns)
6147                       || TREE_CODE (fns) == IDENTIFIER_NODE));
6148
6149   if (BASELINK_P (fns))
6150     {
6151       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6152                                          unknown_type_node,
6153                                          BASELINK_FUNCTIONS (fns),
6154                                          arglist);
6155       return fns;
6156     }
6157
6158   type = TREE_TYPE (fns);
6159   if (TREE_CODE (fns) == OVERLOAD || !type)
6160     type = unknown_type_node;
6161
6162   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6163 }
6164
6165 /* Within the scope of a template class S<T>, the name S gets bound
6166    (in build_self_reference) to a TYPE_DECL for the class, not a
6167    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6168    or one of its enclosing classes, and that type is a template,
6169    return the associated TEMPLATE_DECL.  Otherwise, the original
6170    DECL is returned.
6171
6172    Also handle the case when DECL is a TREE_LIST of ambiguous
6173    injected-class-names from different bases.  */
6174
6175 tree
6176 maybe_get_template_decl_from_type_decl (tree decl)
6177 {
6178   if (decl == NULL_TREE)
6179     return decl;
6180
6181   /* DR 176: A lookup that finds an injected-class-name (10.2
6182      [class.member.lookup]) can result in an ambiguity in certain cases
6183      (for example, if it is found in more than one base class). If all of
6184      the injected-class-names that are found refer to specializations of
6185      the same class template, and if the name is followed by a
6186      template-argument-list, the reference refers to the class template
6187      itself and not a specialization thereof, and is not ambiguous.  */
6188   if (TREE_CODE (decl) == TREE_LIST)
6189     {
6190       tree t, tmpl = NULL_TREE;
6191       for (t = decl; t; t = TREE_CHAIN (t))
6192         {
6193           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6194           if (!tmpl)
6195             tmpl = elt;
6196           else if (tmpl != elt)
6197             break;
6198         }
6199       if (tmpl && t == NULL_TREE)
6200         return tmpl;
6201       else
6202         return decl;
6203     }
6204
6205   return (decl != NULL_TREE
6206           && DECL_SELF_REFERENCE_P (decl)
6207           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
6208     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
6209 }
6210
6211 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
6212    parameters, find the desired type.
6213
6214    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
6215
6216    IN_DECL, if non-NULL, is the template declaration we are trying to
6217    instantiate.
6218
6219    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
6220    the class we are looking up.
6221
6222    Issue error and warning messages under control of COMPLAIN.
6223
6224    If the template class is really a local class in a template
6225    function, then the FUNCTION_CONTEXT is the function in which it is
6226    being instantiated.
6227
6228    ??? Note that this function is currently called *twice* for each
6229    template-id: the first time from the parser, while creating the
6230    incomplete type (finish_template_type), and the second type during the
6231    real instantiation (instantiate_template_class). This is surely something
6232    that we want to avoid. It also causes some problems with argument
6233    coercion (see convert_nontype_argument for more information on this).  */
6234
6235 tree
6236 lookup_template_class (tree d1,
6237                        tree arglist,
6238                        tree in_decl,
6239                        tree context,
6240                        int entering_scope,
6241                        tsubst_flags_t complain)
6242 {
6243   tree templ = NULL_TREE, parmlist;
6244   tree t;
6245   spec_entry **slot;
6246   spec_entry *entry;
6247   spec_entry elt;
6248   hashval_t hash;
6249
6250   timevar_push (TV_NAME_LOOKUP);
6251
6252   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6253     {
6254       tree value = innermost_non_namespace_value (d1);
6255       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6256         templ = value;
6257       else
6258         {
6259           if (context)
6260             push_decl_namespace (context);
6261           templ = lookup_name (d1);
6262           templ = maybe_get_template_decl_from_type_decl (templ);
6263           if (context)
6264             pop_decl_namespace ();
6265         }
6266       if (templ)
6267         context = DECL_CONTEXT (templ);
6268     }
6269   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6270     {
6271       tree type = TREE_TYPE (d1);
6272
6273       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6274          an implicit typename for the second A.  Deal with it.  */
6275       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6276         type = TREE_TYPE (type);
6277
6278       if (CLASSTYPE_TEMPLATE_INFO (type))
6279         {
6280           templ = CLASSTYPE_TI_TEMPLATE (type);
6281           d1 = DECL_NAME (templ);
6282         }
6283     }
6284   else if (TREE_CODE (d1) == ENUMERAL_TYPE
6285            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6286     {
6287       templ = TYPE_TI_TEMPLATE (d1);
6288       d1 = DECL_NAME (templ);
6289     }
6290   else if (TREE_CODE (d1) == TEMPLATE_DECL
6291            && DECL_TEMPLATE_RESULT (d1)
6292            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6293     {
6294       templ = d1;
6295       d1 = DECL_NAME (templ);
6296       context = DECL_CONTEXT (templ);
6297     }
6298
6299   /* Issue an error message if we didn't find a template.  */
6300   if (! templ)
6301     {
6302       if (complain & tf_error)
6303         error ("%qT is not a template", d1);
6304       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6305     }
6306
6307   if (TREE_CODE (templ) != TEMPLATE_DECL
6308          /* Make sure it's a user visible template, if it was named by
6309             the user.  */
6310       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6311           && !PRIMARY_TEMPLATE_P (templ)))
6312     {
6313       if (complain & tf_error)
6314         {
6315           error ("non-template type %qT used as a template", d1);
6316           if (in_decl)
6317             error ("for template declaration %q+D", in_decl);
6318         }
6319       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6320     }
6321
6322   complain &= ~tf_user;
6323
6324   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6325     {
6326       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6327          template arguments */
6328
6329       tree parm;
6330       tree arglist2;
6331       tree outer;
6332
6333       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6334
6335       /* Consider an example where a template template parameter declared as
6336
6337            template <class T, class U = std::allocator<T> > class TT
6338
6339          The template parameter level of T and U are one level larger than
6340          of TT.  To proper process the default argument of U, say when an
6341          instantiation `TT<int>' is seen, we need to build the full
6342          arguments containing {int} as the innermost level.  Outer levels,
6343          available when not appearing as default template argument, can be
6344          obtained from the arguments of the enclosing template.
6345
6346          Suppose that TT is later substituted with std::vector.  The above
6347          instantiation is `TT<int, std::allocator<T> >' with TT at
6348          level 1, and T at level 2, while the template arguments at level 1
6349          becomes {std::vector} and the inner level 2 is {int}.  */
6350
6351       outer = DECL_CONTEXT (templ);
6352       if (outer)
6353         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
6354       else if (current_template_parms)
6355         /* This is an argument of the current template, so we haven't set
6356            DECL_CONTEXT yet.  */
6357         outer = current_template_args ();
6358
6359       if (outer)
6360         arglist = add_to_template_args (outer, arglist);
6361
6362       arglist2 = coerce_template_parms (parmlist, arglist, templ,
6363                                         complain,
6364                                         /*require_all_args=*/true,
6365                                         /*use_default_args=*/true);
6366       if (arglist2 == error_mark_node
6367           || (!uses_template_parms (arglist2)
6368               && check_instantiated_args (templ, arglist2, complain)))
6369         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6370
6371       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
6372       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
6373     }
6374   else
6375     {
6376       tree template_type = TREE_TYPE (templ);
6377       tree gen_tmpl;
6378       tree type_decl;
6379       tree found = NULL_TREE;
6380       int arg_depth;
6381       int parm_depth;
6382       int is_dependent_type;
6383       int use_partial_inst_tmpl = false;
6384
6385       gen_tmpl = most_general_template (templ);
6386       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
6387       parm_depth = TMPL_PARMS_DEPTH (parmlist);
6388       arg_depth = TMPL_ARGS_DEPTH (arglist);
6389
6390       if (arg_depth == 1 && parm_depth > 1)
6391         {
6392           /* We've been given an incomplete set of template arguments.
6393              For example, given:
6394
6395                template <class T> struct S1 {
6396                  template <class U> struct S2 {};
6397                  template <class U> struct S2<U*> {};
6398                 };
6399
6400              we will be called with an ARGLIST of `U*', but the
6401              TEMPLATE will be `template <class T> template
6402              <class U> struct S1<T>::S2'.  We must fill in the missing
6403              arguments.  */
6404           arglist
6405             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
6406                                            arglist);
6407           arg_depth = TMPL_ARGS_DEPTH (arglist);
6408         }
6409
6410       /* Now we should have enough arguments.  */
6411       gcc_assert (parm_depth == arg_depth);
6412
6413       /* From here on, we're only interested in the most general
6414          template.  */
6415
6416       /* Calculate the BOUND_ARGS.  These will be the args that are
6417          actually tsubst'd into the definition to create the
6418          instantiation.  */
6419       if (parm_depth > 1)
6420         {
6421           /* We have multiple levels of arguments to coerce, at once.  */
6422           int i;
6423           int saved_depth = TMPL_ARGS_DEPTH (arglist);
6424
6425           tree bound_args = make_tree_vec (parm_depth);
6426
6427           for (i = saved_depth,
6428                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
6429                i > 0 && t != NULL_TREE;
6430                --i, t = TREE_CHAIN (t))
6431             {
6432               tree a = coerce_template_parms (TREE_VALUE (t),
6433                                               arglist, gen_tmpl,
6434                                               complain,
6435                                               /*require_all_args=*/true,
6436                                               /*use_default_args=*/true);
6437
6438               /* Don't process further if one of the levels fails.  */
6439               if (a == error_mark_node)
6440                 {
6441                   /* Restore the ARGLIST to its full size.  */
6442                   TREE_VEC_LENGTH (arglist) = saved_depth;
6443                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6444                 }
6445
6446               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6447
6448               /* We temporarily reduce the length of the ARGLIST so
6449                  that coerce_template_parms will see only the arguments
6450                  corresponding to the template parameters it is
6451                  examining.  */
6452               TREE_VEC_LENGTH (arglist)--;
6453             }
6454
6455           /* Restore the ARGLIST to its full size.  */
6456           TREE_VEC_LENGTH (arglist) = saved_depth;
6457
6458           arglist = bound_args;
6459         }
6460       else
6461         arglist
6462           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6463                                    INNERMOST_TEMPLATE_ARGS (arglist),
6464                                    gen_tmpl,
6465                                    complain,
6466                                    /*require_all_args=*/true,
6467                                    /*use_default_args=*/true);
6468
6469       if (arglist == error_mark_node)
6470         /* We were unable to bind the arguments.  */
6471         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6472
6473       /* In the scope of a template class, explicit references to the
6474          template class refer to the type of the template, not any
6475          instantiation of it.  For example, in:
6476
6477            template <class T> class C { void f(C<T>); }
6478
6479          the `C<T>' is just the same as `C'.  Outside of the
6480          class, however, such a reference is an instantiation.  */
6481       if ((entering_scope
6482            || !PRIMARY_TEMPLATE_P (gen_tmpl)
6483            || currently_open_class (template_type))
6484           /* comp_template_args is expensive, check it last.  */
6485           && comp_template_args (TYPE_TI_ARGS (template_type),
6486                                  arglist))
6487         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, template_type);
6488
6489       /* If we already have this specialization, return it.  */
6490       elt.tmpl = gen_tmpl;
6491       elt.args = arglist;
6492       hash = hash_specialization (&elt);
6493       entry = (spec_entry *) htab_find_with_hash (type_specializations,
6494                                                   &elt, hash);
6495
6496       if (entry)
6497         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->spec);
6498
6499       is_dependent_type = uses_template_parms (arglist);
6500
6501       /* If the deduced arguments are invalid, then the binding
6502          failed.  */
6503       if (!is_dependent_type
6504           && check_instantiated_args (gen_tmpl,
6505                                       INNERMOST_TEMPLATE_ARGS (arglist),
6506                                       complain))
6507         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6508
6509       if (!is_dependent_type
6510           && !PRIMARY_TEMPLATE_P (gen_tmpl)
6511           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
6512           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6513         {
6514           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6515                                       DECL_NAME (gen_tmpl),
6516                                       /*tag_scope=*/ts_global);
6517           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
6518         }
6519
6520       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
6521                         complain, in_decl);
6522       if (!context)
6523         context = global_namespace;
6524
6525       /* Create the type.  */
6526       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
6527         {
6528           if (!is_dependent_type)
6529             {
6530               set_current_access_from_decl (TYPE_NAME (template_type));
6531               t = start_enum (TYPE_IDENTIFIER (template_type),
6532                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
6533                                       arglist, complain, in_decl),
6534                               SCOPED_ENUM_P (template_type));
6535             }
6536           else
6537             {
6538               /* We don't want to call start_enum for this type, since
6539                  the values for the enumeration constants may involve
6540                  template parameters.  And, no one should be interested
6541                  in the enumeration constants for such a type.  */
6542               t = cxx_make_type (ENUMERAL_TYPE);
6543               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
6544             }
6545         }
6546       else
6547         {
6548           t = make_class_type (TREE_CODE (template_type));
6549           CLASSTYPE_DECLARED_CLASS (t)
6550             = CLASSTYPE_DECLARED_CLASS (template_type);
6551           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
6552           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
6553
6554           /* A local class.  Make sure the decl gets registered properly.  */
6555           if (context == current_function_decl)
6556             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
6557
6558           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
6559             /* This instantiation is another name for the primary
6560                template type. Set the TYPE_CANONICAL field
6561                appropriately. */
6562             TYPE_CANONICAL (t) = template_type;
6563           else if (any_template_arguments_need_structural_equality_p (arglist))
6564             /* Some of the template arguments require structural
6565                equality testing, so this template class requires
6566                structural equality testing. */
6567             SET_TYPE_STRUCTURAL_EQUALITY (t);
6568         }
6569
6570       /* If we called start_enum or pushtag above, this information
6571          will already be set up.  */
6572       if (!TYPE_NAME (t))
6573         {
6574           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
6575
6576           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
6577           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
6578           DECL_SOURCE_LOCATION (type_decl)
6579             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
6580         }
6581       else
6582         type_decl = TYPE_NAME (t);
6583
6584       TREE_PRIVATE (type_decl)
6585         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
6586       TREE_PROTECTED (type_decl)
6587         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
6588       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
6589         {
6590           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
6591           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
6592         }
6593
6594       /* Let's consider the explicit specialization of a member
6595          of a class template specialization that is implicitely instantiated,
6596          e.g.:
6597              template<class T>
6598              struct S
6599              {
6600                template<class U> struct M {}; //#0
6601              };
6602
6603              template<>
6604              template<>
6605              struct S<int>::M<char> //#1
6606              {
6607                int i;
6608              };
6609         [temp.expl.spec]/4 says this is valid.
6610
6611         In this case, when we write:
6612         S<int>::M<char> m;
6613
6614         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
6615         the one of #0.
6616
6617         When we encounter #1, we want to store the partial instantiation
6618         of M (template<class T> S<int>::M<T>) in it's CLASSTYPE_TI_TEMPLATE.
6619
6620         For all cases other than this "explicit specialization of member of a
6621         class template", we just want to store the most general template into
6622         the CLASSTYPE_TI_TEMPLATE of M.
6623
6624         This case of "explicit specialization of member of a class template"
6625         only happens when:
6626         1/ the enclosing class is an instantiation of, and therefore not
6627         the same as, the context of the most general template, and
6628         2/ we aren't looking at the partial instantiation itself, i.e.
6629         the innermost arguments are not the same as the innermost parms of
6630         the most general template.
6631
6632         So it's only when 1/ and 2/ happens that we want to use the partial
6633         instantiation of the member template in lieu of its most general
6634         template.  */
6635
6636       if (PRIMARY_TEMPLATE_P (gen_tmpl)
6637           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
6638           /* the enclosing class must be an instantiation...  */
6639           && CLASS_TYPE_P (context)
6640           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
6641         {
6642           tree partial_inst_args;
6643           TREE_VEC_LENGTH (arglist)--;
6644           ++processing_template_decl;
6645           partial_inst_args =
6646             tsubst (INNERMOST_TEMPLATE_ARGS
6647                         (CLASSTYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
6648                     arglist, complain, NULL_TREE);
6649           --processing_template_decl;
6650           TREE_VEC_LENGTH (arglist)++;
6651           use_partial_inst_tmpl =
6652             /*...and we must not be looking at the partial instantiation
6653              itself. */
6654             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
6655                                  partial_inst_args);
6656         }
6657
6658       if (!use_partial_inst_tmpl)
6659         /* This case is easy; there are no member templates involved.  */
6660         found = gen_tmpl;
6661       else
6662         {
6663           /* This is a full instantiation of a member template.  Find
6664              the partial instantiation of which this is an instance.  */
6665
6666           /* Temporarily reduce by one the number of levels in the ARGLIST
6667              so as to avoid comparing the last set of arguments.  */
6668           TREE_VEC_LENGTH (arglist)--;
6669           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
6670           TREE_VEC_LENGTH (arglist)++;
6671           found = CLASSTYPE_TI_TEMPLATE (found);
6672         }
6673
6674       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
6675
6676       elt.spec = t;
6677       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
6678                                                        &elt, hash, INSERT);
6679       *slot = GGC_NEW (spec_entry);
6680       **slot = elt;
6681
6682       /* Note this use of the partial instantiation so we can check it
6683          later in maybe_process_partial_specialization.  */
6684       DECL_TEMPLATE_INSTANTIATIONS (templ)
6685         = tree_cons (arglist, t,
6686                      DECL_TEMPLATE_INSTANTIATIONS (templ));
6687
6688       if (TREE_CODE (t) == ENUMERAL_TYPE && !is_dependent_type)
6689         /* Now that the type has been registered on the instantiations
6690            list, we set up the enumerators.  Because the enumeration
6691            constants may involve the enumeration type itself, we make
6692            sure to register the type first, and then create the
6693            constants.  That way, doing tsubst_expr for the enumeration
6694            constants won't result in recursive calls here; we'll find
6695            the instantiation and exit above.  */
6696         tsubst_enum (template_type, t, arglist);
6697
6698       if (is_dependent_type)
6699         /* If the type makes use of template parameters, the
6700            code that generates debugging information will crash.  */
6701         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6702
6703       /* Possibly limit visibility based on template args.  */
6704       TREE_PUBLIC (type_decl) = 1;
6705       determine_visibility (type_decl);
6706
6707       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6708     }
6709   timevar_pop (TV_NAME_LOOKUP);
6710 }
6711 \f
6712 struct pair_fn_data
6713 {
6714   tree_fn_t fn;
6715   void *data;
6716   /* True when we should also visit template parameters that occur in
6717      non-deduced contexts.  */
6718   bool include_nondeduced_p;
6719   struct pointer_set_t *visited;
6720 };
6721
6722 /* Called from for_each_template_parm via walk_tree.  */
6723
6724 static tree
6725 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6726 {
6727   tree t = *tp;
6728   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6729   tree_fn_t fn = pfd->fn;
6730   void *data = pfd->data;
6731
6732   if (TYPE_P (t)
6733       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6734       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6735                                  pfd->include_nondeduced_p))
6736     return error_mark_node;
6737
6738   switch (TREE_CODE (t))
6739     {
6740     case RECORD_TYPE:
6741       if (TYPE_PTRMEMFUNC_P (t))
6742         break;
6743       /* Fall through.  */
6744
6745     case UNION_TYPE:
6746     case ENUMERAL_TYPE:
6747       if (!TYPE_TEMPLATE_INFO (t))
6748         *walk_subtrees = 0;
6749       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
6750                                        fn, data, pfd->visited, 
6751                                        pfd->include_nondeduced_p))
6752         return error_mark_node;
6753       break;
6754
6755     case INTEGER_TYPE:
6756       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6757                                   fn, data, pfd->visited, 
6758                                   pfd->include_nondeduced_p)
6759           || for_each_template_parm (TYPE_MAX_VALUE (t),
6760                                      fn, data, pfd->visited,
6761                                      pfd->include_nondeduced_p))
6762         return error_mark_node;
6763       break;
6764
6765     case METHOD_TYPE:
6766       /* Since we're not going to walk subtrees, we have to do this
6767          explicitly here.  */
6768       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6769                                   pfd->visited, pfd->include_nondeduced_p))
6770         return error_mark_node;
6771       /* Fall through.  */
6772
6773     case FUNCTION_TYPE:
6774       /* Check the return type.  */
6775       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6776                                   pfd->include_nondeduced_p))
6777         return error_mark_node;
6778
6779       /* Check the parameter types.  Since default arguments are not
6780          instantiated until they are needed, the TYPE_ARG_TYPES may
6781          contain expressions that involve template parameters.  But,
6782          no-one should be looking at them yet.  And, once they're
6783          instantiated, they don't contain template parameters, so
6784          there's no point in looking at them then, either.  */
6785       {
6786         tree parm;
6787
6788         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6789           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6790                                       pfd->visited, pfd->include_nondeduced_p))
6791             return error_mark_node;
6792
6793         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6794            want walk_tree walking into them itself.  */
6795         *walk_subtrees = 0;
6796       }
6797       break;
6798
6799     case TYPEOF_TYPE:
6800       if (pfd->include_nondeduced_p
6801           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6802                                      pfd->visited, 
6803                                      pfd->include_nondeduced_p))
6804         return error_mark_node;
6805       break;
6806
6807     case FUNCTION_DECL:
6808     case VAR_DECL:
6809       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6810           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6811                                      pfd->visited, pfd->include_nondeduced_p))
6812         return error_mark_node;
6813       /* Fall through.  */
6814
6815     case PARM_DECL:
6816     case CONST_DECL:
6817       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6818           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6819                                      pfd->visited, pfd->include_nondeduced_p))
6820         return error_mark_node;
6821       if (DECL_CONTEXT (t)
6822           && pfd->include_nondeduced_p
6823           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6824                                      pfd->visited, pfd->include_nondeduced_p))
6825         return error_mark_node;
6826       break;
6827
6828     case BOUND_TEMPLATE_TEMPLATE_PARM:
6829       /* Record template parameters such as `T' inside `TT<T>'.  */
6830       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6831                                   pfd->include_nondeduced_p))
6832         return error_mark_node;
6833       /* Fall through.  */
6834
6835     case TEMPLATE_TEMPLATE_PARM:
6836     case TEMPLATE_TYPE_PARM:
6837     case TEMPLATE_PARM_INDEX:
6838       if (fn && (*fn)(t, data))
6839         return error_mark_node;
6840       else if (!fn)
6841         return error_mark_node;
6842       break;
6843
6844     case TEMPLATE_DECL:
6845       /* A template template parameter is encountered.  */
6846       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6847           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6848                                      pfd->include_nondeduced_p))
6849         return error_mark_node;
6850
6851       /* Already substituted template template parameter */
6852       *walk_subtrees = 0;
6853       break;
6854
6855     case TYPENAME_TYPE:
6856       if (!fn
6857           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6858                                      data, pfd->visited, 
6859                                      pfd->include_nondeduced_p))
6860         return error_mark_node;
6861       break;
6862
6863     case CONSTRUCTOR:
6864       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6865           && pfd->include_nondeduced_p
6866           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6867                                      (TREE_TYPE (t)), fn, data,
6868                                      pfd->visited, pfd->include_nondeduced_p))
6869         return error_mark_node;
6870       break;
6871
6872     case INDIRECT_REF:
6873     case COMPONENT_REF:
6874       /* If there's no type, then this thing must be some expression
6875          involving template parameters.  */
6876       if (!fn && !TREE_TYPE (t))
6877         return error_mark_node;
6878       break;
6879
6880     case MODOP_EXPR:
6881     case CAST_EXPR:
6882     case REINTERPRET_CAST_EXPR:
6883     case CONST_CAST_EXPR:
6884     case STATIC_CAST_EXPR:
6885     case DYNAMIC_CAST_EXPR:
6886     case ARROW_EXPR:
6887     case DOTSTAR_EXPR:
6888     case TYPEID_EXPR:
6889     case PSEUDO_DTOR_EXPR:
6890       if (!fn)
6891         return error_mark_node;
6892       break;
6893
6894     default:
6895       break;
6896     }
6897
6898   /* We didn't find any template parameters we liked.  */
6899   return NULL_TREE;
6900 }
6901
6902 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6903    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6904    call FN with the parameter and the DATA.
6905    If FN returns nonzero, the iteration is terminated, and
6906    for_each_template_parm returns 1.  Otherwise, the iteration
6907    continues.  If FN never returns a nonzero value, the value
6908    returned by for_each_template_parm is 0.  If FN is NULL, it is
6909    considered to be the function which always returns 1.
6910
6911    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6912    parameters that occur in non-deduced contexts.  When false, only
6913    visits those template parameters that can be deduced.  */
6914
6915 static int
6916 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6917                         struct pointer_set_t *visited,
6918                         bool include_nondeduced_p)
6919 {
6920   struct pair_fn_data pfd;
6921   int result;
6922
6923   /* Set up.  */
6924   pfd.fn = fn;
6925   pfd.data = data;
6926   pfd.include_nondeduced_p = include_nondeduced_p;
6927
6928   /* Walk the tree.  (Conceptually, we would like to walk without
6929      duplicates, but for_each_template_parm_r recursively calls
6930      for_each_template_parm, so we would need to reorganize a fair
6931      bit to use walk_tree_without_duplicates, so we keep our own
6932      visited list.)  */
6933   if (visited)
6934     pfd.visited = visited;
6935   else
6936     pfd.visited = pointer_set_create ();
6937   result = cp_walk_tree (&t,
6938                          for_each_template_parm_r,
6939                          &pfd,
6940                          pfd.visited) != NULL_TREE;
6941
6942   /* Clean up.  */
6943   if (!visited)
6944     {
6945       pointer_set_destroy (pfd.visited);
6946       pfd.visited = 0;
6947     }
6948
6949   return result;
6950 }
6951
6952 /* Returns true if T depends on any template parameter.  */
6953
6954 int
6955 uses_template_parms (tree t)
6956 {
6957   bool dependent_p;
6958   int saved_processing_template_decl;
6959
6960   saved_processing_template_decl = processing_template_decl;
6961   if (!saved_processing_template_decl)
6962     processing_template_decl = 1;
6963   if (TYPE_P (t))
6964     dependent_p = dependent_type_p (t);
6965   else if (TREE_CODE (t) == TREE_VEC)
6966     dependent_p = any_dependent_template_arguments_p (t);
6967   else if (TREE_CODE (t) == TREE_LIST)
6968     dependent_p = (uses_template_parms (TREE_VALUE (t))
6969                    || uses_template_parms (TREE_CHAIN (t)));
6970   else if (TREE_CODE (t) == TYPE_DECL)
6971     dependent_p = dependent_type_p (TREE_TYPE (t));
6972   else if (DECL_P (t)
6973            || EXPR_P (t)
6974            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
6975            || TREE_CODE (t) == OVERLOAD
6976            || TREE_CODE (t) == BASELINK
6977            || TREE_CODE (t) == IDENTIFIER_NODE
6978            || TREE_CODE (t) == TRAIT_EXPR
6979            || TREE_CODE (t) == CONSTRUCTOR
6980            || CONSTANT_CLASS_P (t))
6981     dependent_p = (type_dependent_expression_p (t)
6982                    || value_dependent_expression_p (t));
6983   else
6984     {
6985       gcc_assert (t == error_mark_node);
6986       dependent_p = false;
6987     }
6988
6989   processing_template_decl = saved_processing_template_decl;
6990
6991   return dependent_p;
6992 }
6993
6994 /* Returns true if T depends on any template parameter with level LEVEL.  */
6995
6996 int
6997 uses_template_parms_level (tree t, int level)
6998 {
6999   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
7000                                  /*include_nondeduced_p=*/true);
7001 }
7002
7003 static int tinst_depth;
7004 extern int max_tinst_depth;
7005 #ifdef GATHER_STATISTICS
7006 int depth_reached;
7007 #endif
7008 static int tinst_level_tick;
7009 static int last_template_error_tick;
7010
7011 /* We're starting to instantiate D; record the template instantiation context
7012    for diagnostics and to restore it later.  */
7013
7014 int
7015 push_tinst_level (tree d)
7016 {
7017   struct tinst_level *new_level;
7018
7019   if (tinst_depth >= max_tinst_depth)
7020     {
7021       /* If the instantiation in question still has unbound template parms,
7022          we don't really care if we can't instantiate it, so just return.
7023          This happens with base instantiation for implicit `typename'.  */
7024       if (uses_template_parms (d))
7025         return 0;
7026
7027       last_template_error_tick = tinst_level_tick;
7028       error ("template instantiation depth exceeds maximum of %d (use "
7029              "-ftemplate-depth= to increase the maximum) instantiating %qD",
7030              max_tinst_depth, d);
7031
7032       print_instantiation_context ();
7033
7034       return 0;
7035     }
7036
7037   new_level = GGC_NEW (struct tinst_level);
7038   new_level->decl = d;
7039   new_level->locus = input_location;
7040   new_level->in_system_header_p = in_system_header;
7041   new_level->next = current_tinst_level;
7042   current_tinst_level = new_level;
7043
7044   ++tinst_depth;
7045 #ifdef GATHER_STATISTICS
7046   if (tinst_depth > depth_reached)
7047     depth_reached = tinst_depth;
7048 #endif
7049
7050   ++tinst_level_tick;
7051   return 1;
7052 }
7053
7054 /* We're done instantiating this template; return to the instantiation
7055    context.  */
7056
7057 void
7058 pop_tinst_level (void)
7059 {
7060   /* Restore the filename and line number stashed away when we started
7061      this instantiation.  */
7062   input_location = current_tinst_level->locus;
7063   current_tinst_level = current_tinst_level->next;
7064   --tinst_depth;
7065   ++tinst_level_tick;
7066 }
7067
7068 /* We're instantiating a deferred template; restore the template
7069    instantiation context in which the instantiation was requested, which
7070    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
7071
7072 static tree
7073 reopen_tinst_level (struct tinst_level *level)
7074 {
7075   struct tinst_level *t;
7076
7077   tinst_depth = 0;
7078   for (t = level; t; t = t->next)
7079     ++tinst_depth;
7080
7081   current_tinst_level = level;
7082   pop_tinst_level ();
7083   return level->decl;
7084 }
7085
7086 /* Returns the TINST_LEVEL which gives the original instantiation
7087    context.  */
7088
7089 struct tinst_level *
7090 outermost_tinst_level (void)
7091 {
7092   struct tinst_level *level = current_tinst_level;
7093   if (level)
7094     while (level->next)
7095       level = level->next;
7096   return level;
7097 }
7098
7099 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
7100
7101 bool
7102 parameter_of_template_p (tree parm, tree templ)
7103 {
7104   tree parms;
7105   int i;
7106
7107   if (!parm || !templ)
7108     return false;
7109
7110   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
7111   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7112
7113   parms = DECL_TEMPLATE_PARMS (templ);
7114   parms = INNERMOST_TEMPLATE_PARMS (parms);
7115
7116   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
7117     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
7118       return true;
7119
7120   return false;
7121 }
7122
7123 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
7124    vector of template arguments, as for tsubst.
7125
7126    Returns an appropriate tsubst'd friend declaration.  */
7127
7128 static tree
7129 tsubst_friend_function (tree decl, tree args)
7130 {
7131   tree new_friend;
7132
7133   if (TREE_CODE (decl) == FUNCTION_DECL
7134       && DECL_TEMPLATE_INSTANTIATION (decl)
7135       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
7136     /* This was a friend declared with an explicit template
7137        argument list, e.g.:
7138
7139        friend void f<>(T);
7140
7141        to indicate that f was a template instantiation, not a new
7142        function declaration.  Now, we have to figure out what
7143        instantiation of what template.  */
7144     {
7145       tree template_id, arglist, fns;
7146       tree new_args;
7147       tree tmpl;
7148       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
7149
7150       /* Friend functions are looked up in the containing namespace scope.
7151          We must enter that scope, to avoid finding member functions of the
7152          current class with same name.  */
7153       push_nested_namespace (ns);
7154       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
7155                          tf_warning_or_error, NULL_TREE,
7156                          /*integral_constant_expression_p=*/false);
7157       pop_nested_namespace (ns);
7158       arglist = tsubst (DECL_TI_ARGS (decl), args,
7159                         tf_warning_or_error, NULL_TREE);
7160       template_id = lookup_template_function (fns, arglist);
7161
7162       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7163       tmpl = determine_specialization (template_id, new_friend,
7164                                        &new_args,
7165                                        /*need_member_template=*/0,
7166                                        TREE_VEC_LENGTH (args),
7167                                        tsk_none);
7168       return instantiate_template (tmpl, new_args, tf_error);
7169     }
7170
7171   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7172
7173   /* The NEW_FRIEND will look like an instantiation, to the
7174      compiler, but is not an instantiation from the point of view of
7175      the language.  For example, we might have had:
7176
7177      template <class T> struct S {
7178        template <class U> friend void f(T, U);
7179      };
7180
7181      Then, in S<int>, template <class U> void f(int, U) is not an
7182      instantiation of anything.  */
7183   if (new_friend == error_mark_node)
7184     return error_mark_node;
7185
7186   DECL_USE_TEMPLATE (new_friend) = 0;
7187   if (TREE_CODE (decl) == TEMPLATE_DECL)
7188     {
7189       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
7190       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
7191         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
7192     }
7193
7194   /* The mangled name for the NEW_FRIEND is incorrect.  The function
7195      is not a template instantiation and should not be mangled like
7196      one.  Therefore, we forget the mangling here; we'll recompute it
7197      later if we need it.  */
7198   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
7199     {
7200       SET_DECL_RTL (new_friend, NULL_RTX);
7201       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
7202     }
7203
7204   if (DECL_NAMESPACE_SCOPE_P (new_friend))
7205     {
7206       tree old_decl;
7207       tree new_friend_template_info;
7208       tree new_friend_result_template_info;
7209       tree ns;
7210       int  new_friend_is_defn;
7211
7212       /* We must save some information from NEW_FRIEND before calling
7213          duplicate decls since that function will free NEW_FRIEND if
7214          possible.  */
7215       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
7216       new_friend_is_defn =
7217             (DECL_INITIAL (DECL_TEMPLATE_RESULT
7218                            (template_for_substitution (new_friend)))
7219              != NULL_TREE);
7220       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
7221         {
7222           /* This declaration is a `primary' template.  */
7223           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
7224
7225           new_friend_result_template_info
7226             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
7227         }
7228       else
7229         new_friend_result_template_info = NULL_TREE;
7230
7231       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
7232       if (new_friend_is_defn)
7233         DECL_INITIAL (new_friend) = error_mark_node;
7234
7235       /* Inside pushdecl_namespace_level, we will push into the
7236          current namespace. However, the friend function should go
7237          into the namespace of the template.  */
7238       ns = decl_namespace_context (new_friend);
7239       push_nested_namespace (ns);
7240       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
7241       pop_nested_namespace (ns);
7242
7243       if (old_decl == error_mark_node)
7244         return error_mark_node;
7245
7246       if (old_decl != new_friend)
7247         {
7248           /* This new friend declaration matched an existing
7249              declaration.  For example, given:
7250
7251                template <class T> void f(T);
7252                template <class U> class C {
7253                  template <class T> friend void f(T) {}
7254                };
7255
7256              the friend declaration actually provides the definition
7257              of `f', once C has been instantiated for some type.  So,
7258              old_decl will be the out-of-class template declaration,
7259              while new_friend is the in-class definition.
7260
7261              But, if `f' was called before this point, the
7262              instantiation of `f' will have DECL_TI_ARGS corresponding
7263              to `T' but not to `U', references to which might appear
7264              in the definition of `f'.  Previously, the most general
7265              template for an instantiation of `f' was the out-of-class
7266              version; now it is the in-class version.  Therefore, we
7267              run through all specialization of `f', adding to their
7268              DECL_TI_ARGS appropriately.  In particular, they need a
7269              new set of outer arguments, corresponding to the
7270              arguments for this class instantiation.
7271
7272              The same situation can arise with something like this:
7273
7274                friend void f(int);
7275                template <class T> class C {
7276                  friend void f(T) {}
7277                };
7278
7279              when `C<int>' is instantiated.  Now, `f(int)' is defined
7280              in the class.  */
7281
7282           if (!new_friend_is_defn)
7283             /* On the other hand, if the in-class declaration does
7284                *not* provide a definition, then we don't want to alter
7285                existing definitions.  We can just leave everything
7286                alone.  */
7287             ;
7288           else
7289             {
7290               tree new_template = TI_TEMPLATE (new_friend_template_info);
7291               tree new_args = TI_ARGS (new_friend_template_info);
7292
7293               /* Overwrite whatever template info was there before, if
7294                  any, with the new template information pertaining to
7295                  the declaration.  */
7296               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
7297
7298               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
7299                 /* We should have called reregister_specialization in
7300                    duplicate_decls.  */
7301                 gcc_assert (retrieve_specialization (new_template,
7302                                                      new_args, 0)
7303                             == old_decl);
7304               else
7305                 {
7306                   tree t;
7307
7308                   /* Indicate that the old function template is a partial
7309                      instantiation.  */
7310                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
7311                     = new_friend_result_template_info;
7312
7313                   gcc_assert (new_template
7314                               == most_general_template (new_template));
7315                   gcc_assert (new_template != old_decl);
7316
7317                   /* Reassign any specializations already in the hash table
7318                      to the new more general template, and add the
7319                      additional template args.  */
7320                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
7321                        t != NULL_TREE;
7322                        t = TREE_CHAIN (t))
7323                     {
7324                       tree spec = TREE_VALUE (t);
7325                       spec_entry elt;
7326
7327                       elt.tmpl = old_decl;
7328                       elt.args = DECL_TI_ARGS (spec);
7329                       elt.spec = NULL_TREE;
7330
7331                       htab_remove_elt (decl_specializations, &elt);
7332
7333                       DECL_TI_ARGS (spec)
7334                         = add_outermost_template_args (new_args,
7335                                                        DECL_TI_ARGS (spec));
7336
7337                       register_specialization
7338                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
7339
7340                     }
7341                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
7342                 }
7343             }
7344
7345           /* The information from NEW_FRIEND has been merged into OLD_DECL
7346              by duplicate_decls.  */
7347           new_friend = old_decl;
7348         }
7349     }
7350   else
7351     {
7352       tree context = DECL_CONTEXT (new_friend);
7353       bool dependent_p;
7354
7355       /* In the code
7356            template <class T> class C {
7357              template <class U> friend void C1<U>::f (); // case 1
7358              friend void C2<T>::f ();                    // case 2
7359            };
7360          we only need to make sure CONTEXT is a complete type for
7361          case 2.  To distinguish between the two cases, we note that
7362          CONTEXT of case 1 remains dependent type after tsubst while
7363          this isn't true for case 2.  */
7364       ++processing_template_decl;
7365       dependent_p = dependent_type_p (context);
7366       --processing_template_decl;
7367
7368       if (!dependent_p
7369           && !complete_type_or_else (context, NULL_TREE))
7370         return error_mark_node;
7371
7372       if (COMPLETE_TYPE_P (context))
7373         {
7374           /* Check to see that the declaration is really present, and,
7375              possibly obtain an improved declaration.  */
7376           tree fn = check_classfn (context,
7377                                    new_friend, NULL_TREE);
7378
7379           if (fn)
7380             new_friend = fn;
7381         }
7382     }
7383
7384   return new_friend;
7385 }
7386
7387 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
7388    template arguments, as for tsubst.
7389
7390    Returns an appropriate tsubst'd friend type or error_mark_node on
7391    failure.  */
7392
7393 static tree
7394 tsubst_friend_class (tree friend_tmpl, tree args)
7395 {
7396   tree friend_type;
7397   tree tmpl;
7398   tree context;
7399
7400   context = DECL_CONTEXT (friend_tmpl);
7401
7402   if (context)
7403     {
7404       if (TREE_CODE (context) == NAMESPACE_DECL)
7405         push_nested_namespace (context);
7406       else
7407         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
7408     }
7409
7410   /* Look for a class template declaration.  We look for hidden names
7411      because two friend declarations of the same template are the
7412      same.  For example, in:
7413
7414        struct A { 
7415          template <typename> friend class F;
7416        };
7417        template <typename> struct B { 
7418          template <typename> friend class F;
7419        };
7420
7421      both F templates are the same.  */
7422   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
7423                            /*block_p=*/true, 0, 
7424                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
7425
7426   /* But, if we don't find one, it might be because we're in a
7427      situation like this:
7428
7429        template <class T>
7430        struct S {
7431          template <class U>
7432          friend struct S;
7433        };
7434
7435      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
7436      for `S<int>', not the TEMPLATE_DECL.  */
7437   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
7438     {
7439       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
7440       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
7441     }
7442
7443   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
7444     {
7445       /* The friend template has already been declared.  Just
7446          check to see that the declarations match, and install any new
7447          default parameters.  We must tsubst the default parameters,
7448          of course.  We only need the innermost template parameters
7449          because that is all that redeclare_class_template will look
7450          at.  */
7451       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
7452           > TMPL_ARGS_DEPTH (args))
7453         {
7454           tree parms;
7455           location_t saved_input_location;
7456           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
7457                                          args, tf_warning_or_error);
7458
7459           saved_input_location = input_location;
7460           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
7461           redeclare_class_template (TREE_TYPE (tmpl), parms);
7462           input_location = saved_input_location;
7463           
7464         }
7465
7466       friend_type = TREE_TYPE (tmpl);
7467     }
7468   else
7469     {
7470       /* The friend template has not already been declared.  In this
7471          case, the instantiation of the template class will cause the
7472          injection of this template into the global scope.  */
7473       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7474       if (tmpl == error_mark_node)
7475         return error_mark_node;
7476
7477       /* The new TMPL is not an instantiation of anything, so we
7478          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7479          the new type because that is supposed to be the corresponding
7480          template decl, i.e., TMPL.  */
7481       DECL_USE_TEMPLATE (tmpl) = 0;
7482       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7483       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7484       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7485         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7486
7487       /* Inject this template into the global scope.  */
7488       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7489     }
7490
7491   if (context)
7492     {
7493       if (TREE_CODE (context) == NAMESPACE_DECL)
7494         pop_nested_namespace (context);
7495       else
7496         pop_nested_class ();
7497     }
7498
7499   return friend_type;
7500 }
7501
7502 /* Returns zero if TYPE cannot be completed later due to circularity.
7503    Otherwise returns one.  */
7504
7505 static int
7506 can_complete_type_without_circularity (tree type)
7507 {
7508   if (type == NULL_TREE || type == error_mark_node)
7509     return 0;
7510   else if (COMPLETE_TYPE_P (type))
7511     return 1;
7512   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
7513     return can_complete_type_without_circularity (TREE_TYPE (type));
7514   else if (CLASS_TYPE_P (type)
7515            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
7516     return 0;
7517   else
7518     return 1;
7519 }
7520
7521 /* Apply any attributes which had to be deferred until instantiation
7522    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
7523    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
7524
7525 static void
7526 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
7527                                 tree args, tsubst_flags_t complain, tree in_decl)
7528 {
7529   tree last_dep = NULL_TREE;
7530   tree t;
7531   tree *p;
7532
7533   for (t = attributes; t; t = TREE_CHAIN (t))
7534     if (ATTR_IS_DEPENDENT (t))
7535       {
7536         last_dep = t;
7537         attributes = copy_list (attributes);
7538         break;
7539       }
7540
7541   if (DECL_P (*decl_p))
7542     {
7543       if (TREE_TYPE (*decl_p) == error_mark_node)
7544         return;
7545       p = &DECL_ATTRIBUTES (*decl_p);
7546     }
7547   else
7548     p = &TYPE_ATTRIBUTES (*decl_p);
7549
7550   if (last_dep)
7551     {
7552       tree late_attrs = NULL_TREE;
7553       tree *q = &late_attrs;
7554
7555       for (*p = attributes; *p; )
7556         {
7557           t = *p;
7558           if (ATTR_IS_DEPENDENT (t))
7559             {
7560               *p = TREE_CHAIN (t);
7561               TREE_CHAIN (t) = NULL_TREE;
7562               /* If the first attribute argument is an identifier, don't
7563                  pass it through tsubst.  Attributes like mode, format,
7564                  cleanup and several target specific attributes expect it
7565                  unmodified.  */
7566               if (TREE_VALUE (t)
7567                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
7568                   && TREE_VALUE (TREE_VALUE (t))
7569                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
7570                       == IDENTIFIER_NODE))
7571                 {
7572                   tree chain
7573                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
7574                                    in_decl,
7575                                    /*integral_constant_expression_p=*/false);
7576                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
7577                     TREE_VALUE (t)
7578                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
7579                                    chain);
7580                 }
7581               else
7582                 TREE_VALUE (t)
7583                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
7584                                  /*integral_constant_expression_p=*/false);
7585               *q = t;
7586               q = &TREE_CHAIN (t);
7587             }
7588           else
7589             p = &TREE_CHAIN (t);
7590         }
7591
7592       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
7593     }
7594 }
7595
7596 /* Perform (or defer) access check for typedefs that were referenced
7597    from within the template TMPL code.
7598    This is a subroutine of instantiate_template and instantiate_class_template.
7599    TMPL is the template to consider and TARGS is the list of arguments of
7600    that template.  */
7601
7602 static void
7603 perform_typedefs_access_check (tree tmpl, tree targs)
7604 {
7605   location_t saved_location;
7606   int i;
7607   qualified_typedef_usage_t *iter;
7608
7609   if (!tmpl
7610       || (!CLASS_TYPE_P (tmpl)
7611           && TREE_CODE (tmpl) != FUNCTION_DECL))
7612     return;
7613
7614   saved_location = input_location;
7615   for (i = 0;
7616        VEC_iterate (qualified_typedef_usage_t,
7617                     get_types_needing_access_check (tmpl),
7618                     i, iter);
7619         ++i)
7620     {
7621       tree type_decl = iter->typedef_decl;
7622       tree type_scope = iter->context;
7623
7624       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
7625         continue;
7626
7627       if (uses_template_parms (type_decl))
7628         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
7629       if (uses_template_parms (type_scope))
7630         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
7631
7632       /* Make access check error messages point to the location
7633          of the use of the typedef.  */
7634       input_location = iter->locus;
7635       perform_or_defer_access_check (TYPE_BINFO (type_scope),
7636                                      type_decl, type_decl);
7637     }
7638     input_location = saved_location;
7639 }
7640
7641 tree
7642 instantiate_class_template (tree type)
7643 {
7644   tree templ, args, pattern, t, member;
7645   tree typedecl;
7646   tree pbinfo;
7647   tree base_list;
7648   unsigned int saved_maximum_field_alignment;
7649
7650   if (type == error_mark_node)
7651     return error_mark_node;
7652
7653   if (TYPE_BEING_DEFINED (type)
7654       || COMPLETE_TYPE_P (type)
7655       || uses_template_parms (type))
7656     return type;
7657
7658   /* Figure out which template is being instantiated.  */
7659   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
7660   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7661
7662   /* Determine what specialization of the original template to
7663      instantiate.  */
7664   t = most_specialized_class (type, templ);
7665   if (t == error_mark_node)
7666     {
7667       TYPE_BEING_DEFINED (type) = 1;
7668       return error_mark_node;
7669     }
7670   else if (t)
7671     {
7672       /* This TYPE is actually an instantiation of a partial
7673          specialization.  We replace the innermost set of ARGS with
7674          the arguments appropriate for substitution.  For example,
7675          given:
7676
7677            template <class T> struct S {};
7678            template <class T> struct S<T*> {};
7679
7680          and supposing that we are instantiating S<int*>, ARGS will
7681          presently be {int*} -- but we need {int}.  */
7682       pattern = TREE_TYPE (t);
7683       args = TREE_PURPOSE (t);
7684     }
7685   else
7686     {
7687       pattern = TREE_TYPE (templ);
7688       args = CLASSTYPE_TI_ARGS (type);
7689     }
7690
7691   /* If the template we're instantiating is incomplete, then clearly
7692      there's nothing we can do.  */
7693   if (!COMPLETE_TYPE_P (pattern))
7694     return type;
7695
7696   /* If we've recursively instantiated too many templates, stop.  */
7697   if (! push_tinst_level (type))
7698     return type;
7699
7700   /* Now we're really doing the instantiation.  Mark the type as in
7701      the process of being defined.  */
7702   TYPE_BEING_DEFINED (type) = 1;
7703
7704   /* We may be in the middle of deferred access check.  Disable
7705      it now.  */
7706   push_deferring_access_checks (dk_no_deferred);
7707
7708   push_to_top_level ();
7709   /* Use #pragma pack from the template context.  */
7710   saved_maximum_field_alignment = maximum_field_alignment;
7711   maximum_field_alignment = TYPE_PRECISION (pattern);
7712
7713   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
7714
7715   /* Set the input location to the most specialized template definition.
7716      This is needed if tsubsting causes an error.  */
7717   typedecl = TYPE_MAIN_DECL (pattern);
7718   input_location = DECL_SOURCE_LOCATION (typedecl);
7719
7720   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7721   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7722   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7723   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7724   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
7725   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
7726   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
7727   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
7728   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7729   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7730   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7731   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7732   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7733   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7734   if (ANON_AGGR_TYPE_P (pattern))
7735     SET_ANON_AGGR_TYPE_P (type);
7736   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7737     {
7738       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7739       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7740     }
7741
7742   pbinfo = TYPE_BINFO (pattern);
7743
7744   /* We should never instantiate a nested class before its enclosing
7745      class; we need to look up the nested class by name before we can
7746      instantiate it, and that lookup should instantiate the enclosing
7747      class.  */
7748   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7749               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
7750               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
7751
7752   base_list = NULL_TREE;
7753   if (BINFO_N_BASE_BINFOS (pbinfo))
7754     {
7755       tree pbase_binfo;
7756       tree context = TYPE_CONTEXT (type);
7757       tree pushed_scope;
7758       int i;
7759
7760       /* We must enter the scope containing the type, as that is where
7761          the accessibility of types named in dependent bases are
7762          looked up from.  */
7763       pushed_scope = push_scope (context ? context : global_namespace);
7764
7765       /* Substitute into each of the bases to determine the actual
7766          basetypes.  */
7767       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7768         {
7769           tree base;
7770           tree access = BINFO_BASE_ACCESS (pbinfo, i);
7771           tree expanded_bases = NULL_TREE;
7772           int idx, len = 1;
7773
7774           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7775             {
7776               expanded_bases = 
7777                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7778                                        args, tf_error, NULL_TREE);
7779               if (expanded_bases == error_mark_node)
7780                 continue;
7781
7782               len = TREE_VEC_LENGTH (expanded_bases);
7783             }
7784
7785           for (idx = 0; idx < len; idx++)
7786             {
7787               if (expanded_bases)
7788                 /* Extract the already-expanded base class.  */
7789                 base = TREE_VEC_ELT (expanded_bases, idx);
7790               else
7791                 /* Substitute to figure out the base class.  */
7792                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
7793                                NULL_TREE);
7794
7795               if (base == error_mark_node)
7796                 continue;
7797
7798               base_list = tree_cons (access, base, base_list);
7799               if (BINFO_VIRTUAL_P (pbase_binfo))
7800                 TREE_TYPE (base_list) = integer_type_node;
7801             }
7802         }
7803
7804       /* The list is now in reverse order; correct that.  */
7805       base_list = nreverse (base_list);
7806
7807       if (pushed_scope)
7808         pop_scope (pushed_scope);
7809     }
7810   /* Now call xref_basetypes to set up all the base-class
7811      information.  */
7812   xref_basetypes (type, base_list);
7813
7814   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7815                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7816                                   args, tf_error, NULL_TREE);
7817
7818   /* Now that our base classes are set up, enter the scope of the
7819      class, so that name lookups into base classes, etc. will work
7820      correctly.  This is precisely analogous to what we do in
7821      begin_class_definition when defining an ordinary non-template
7822      class, except we also need to push the enclosing classes.  */
7823   push_nested_class (type);
7824
7825   /* Now members are processed in the order of declaration.  */
7826   for (member = CLASSTYPE_DECL_LIST (pattern);
7827        member; member = TREE_CHAIN (member))
7828     {
7829       tree t = TREE_VALUE (member);
7830
7831       if (TREE_PURPOSE (member))
7832         {
7833           if (TYPE_P (t))
7834             {
7835               /* Build new CLASSTYPE_NESTED_UTDS.  */
7836
7837               tree newtag;
7838               bool class_template_p;
7839
7840               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7841                                   && TYPE_LANG_SPECIFIC (t)
7842                                   && CLASSTYPE_IS_TEMPLATE (t));
7843               /* If the member is a class template, then -- even after
7844                  substitution -- there may be dependent types in the
7845                  template argument list for the class.  We increment
7846                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7847                  that function will assume that no types are dependent
7848                  when outside of a template.  */
7849               if (class_template_p)
7850                 ++processing_template_decl;
7851               newtag = tsubst (t, args, tf_error, NULL_TREE);
7852               if (class_template_p)
7853                 --processing_template_decl;
7854               if (newtag == error_mark_node)
7855                 continue;
7856
7857               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7858                 {
7859                   tree name = TYPE_IDENTIFIER (t);
7860
7861                   if (class_template_p)
7862                     /* Unfortunately, lookup_template_class sets
7863                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7864                        instantiation (i.e., for the type of a member
7865                        template class nested within a template class.)
7866                        This behavior is required for
7867                        maybe_process_partial_specialization to work
7868                        correctly, but is not accurate in this case;
7869                        the TAG is not an instantiation of anything.
7870                        (The corresponding TEMPLATE_DECL is an
7871                        instantiation, but the TYPE is not.) */
7872                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7873
7874                   /* Now, we call pushtag to put this NEWTAG into the scope of
7875                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7876                      pushtag calling push_template_decl.  We don't have to do
7877                      this for enums because it will already have been done in
7878                      tsubst_enum.  */
7879                   if (name)
7880                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7881                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7882                 }
7883             }
7884           else if (TREE_CODE (t) == FUNCTION_DECL
7885                    || DECL_FUNCTION_TEMPLATE_P (t))
7886             {
7887               /* Build new TYPE_METHODS.  */
7888               tree r;
7889
7890               if (TREE_CODE (t) == TEMPLATE_DECL)
7891                 ++processing_template_decl;
7892               r = tsubst (t, args, tf_error, NULL_TREE);
7893               if (TREE_CODE (t) == TEMPLATE_DECL)
7894                 --processing_template_decl;
7895               set_current_access_from_decl (r);
7896               finish_member_declaration (r);
7897             }
7898           else
7899             {
7900               /* Build new TYPE_FIELDS.  */
7901               if (TREE_CODE (t) == STATIC_ASSERT)
7902                 {
7903                   tree condition = 
7904                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7905                                  tf_warning_or_error, NULL_TREE,
7906                                  /*integral_constant_expression_p=*/true);
7907                   finish_static_assert (condition,
7908                                         STATIC_ASSERT_MESSAGE (t), 
7909                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7910                                         /*member_p=*/true);
7911                 }
7912               else if (TREE_CODE (t) != CONST_DECL)
7913                 {
7914                   tree r;
7915
7916                   /* The file and line for this declaration, to
7917                      assist in error message reporting.  Since we
7918                      called push_tinst_level above, we don't need to
7919                      restore these.  */
7920                   input_location = DECL_SOURCE_LOCATION (t);
7921
7922                   if (TREE_CODE (t) == TEMPLATE_DECL)
7923                     ++processing_template_decl;
7924                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7925                   if (TREE_CODE (t) == TEMPLATE_DECL)
7926                     --processing_template_decl;
7927                   if (TREE_CODE (r) == VAR_DECL)
7928                     {
7929                       /* In [temp.inst]:
7930
7931                            [t]he initialization (and any associated
7932                            side-effects) of a static data member does
7933                            not occur unless the static data member is
7934                            itself used in a way that requires the
7935                            definition of the static data member to
7936                            exist.
7937
7938                          Therefore, we do not substitute into the
7939                          initialized for the static data member here.  */
7940                       finish_static_data_member_decl
7941                         (r,
7942                          /*init=*/NULL_TREE,
7943                          /*init_const_expr_p=*/false,
7944                          /*asmspec_tree=*/NULL_TREE,
7945                          /*flags=*/0);
7946                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7947                         check_static_variable_definition (r, TREE_TYPE (r));
7948                     }
7949                   else if (TREE_CODE (r) == FIELD_DECL)
7950                     {
7951                       /* Determine whether R has a valid type and can be
7952                          completed later.  If R is invalid, then it is
7953                          replaced by error_mark_node so that it will not be
7954                          added to TYPE_FIELDS.  */
7955                       tree rtype = TREE_TYPE (r);
7956                       if (can_complete_type_without_circularity (rtype))
7957                         complete_type (rtype);
7958
7959                       if (!COMPLETE_TYPE_P (rtype))
7960                         {
7961                           cxx_incomplete_type_error (r, rtype);
7962                           r = error_mark_node;
7963                         }
7964                     }
7965
7966                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
7967                      such a thing will already have been added to the field
7968                      list by tsubst_enum in finish_member_declaration in the
7969                      CLASSTYPE_NESTED_UTDS case above.  */
7970                   if (!(TREE_CODE (r) == TYPE_DECL
7971                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
7972                         && DECL_ARTIFICIAL (r)))
7973                     {
7974                       set_current_access_from_decl (r);
7975                       finish_member_declaration (r);
7976                     }
7977                 }
7978             }
7979         }
7980       else
7981         {
7982           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
7983             {
7984               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
7985
7986               tree friend_type = t;
7987               bool adjust_processing_template_decl = false;
7988
7989               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7990                 {
7991                   /* template <class T> friend class C;  */
7992                   friend_type = tsubst_friend_class (friend_type, args);
7993                   adjust_processing_template_decl = true;
7994                 }
7995               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
7996                 {
7997                   /* template <class T> friend class C::D;  */
7998                   friend_type = tsubst (friend_type, args,
7999                                         tf_warning_or_error, NULL_TREE);
8000                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8001                     friend_type = TREE_TYPE (friend_type);
8002                   adjust_processing_template_decl = true;
8003                 }
8004               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
8005                 {
8006                   /* This could be either
8007
8008                        friend class T::C;
8009
8010                      when dependent_type_p is false or
8011
8012                        template <class U> friend class T::C;
8013
8014                      otherwise.  */
8015                   friend_type = tsubst (friend_type, args,
8016                                         tf_warning_or_error, NULL_TREE);
8017                   /* Bump processing_template_decl for correct
8018                      dependent_type_p calculation.  */
8019                   ++processing_template_decl;
8020                   if (dependent_type_p (friend_type))
8021                     adjust_processing_template_decl = true;
8022                   --processing_template_decl;
8023                 }
8024               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
8025                        && hidden_name_p (TYPE_NAME (friend_type)))
8026                 {
8027                   /* friend class C;
8028
8029                      where C hasn't been declared yet.  Let's lookup name
8030                      from namespace scope directly, bypassing any name that
8031                      come from dependent base class.  */
8032                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
8033
8034                   /* The call to xref_tag_from_type does injection for friend
8035                      classes.  */
8036                   push_nested_namespace (ns);
8037                   friend_type =
8038                     xref_tag_from_type (friend_type, NULL_TREE,
8039                                         /*tag_scope=*/ts_current);
8040                   pop_nested_namespace (ns);
8041                 }
8042               else if (uses_template_parms (friend_type))
8043                 /* friend class C<T>;  */
8044                 friend_type = tsubst (friend_type, args,
8045                                       tf_warning_or_error, NULL_TREE);
8046               /* Otherwise it's
8047
8048                    friend class C;
8049
8050                  where C is already declared or
8051
8052                    friend class C<int>;
8053
8054                  We don't have to do anything in these cases.  */
8055
8056               if (adjust_processing_template_decl)
8057                 /* Trick make_friend_class into realizing that the friend
8058                    we're adding is a template, not an ordinary class.  It's
8059                    important that we use make_friend_class since it will
8060                    perform some error-checking and output cross-reference
8061                    information.  */
8062                 ++processing_template_decl;
8063
8064               if (friend_type != error_mark_node)
8065                 make_friend_class (type, friend_type, /*complain=*/false);
8066
8067               if (adjust_processing_template_decl)
8068                 --processing_template_decl;
8069             }
8070           else
8071             {
8072               /* Build new DECL_FRIENDLIST.  */
8073               tree r;
8074
8075               /* The file and line for this declaration, to
8076                  assist in error message reporting.  Since we
8077                  called push_tinst_level above, we don't need to
8078                  restore these.  */
8079               input_location = DECL_SOURCE_LOCATION (t);
8080
8081               if (TREE_CODE (t) == TEMPLATE_DECL)
8082                 {
8083                   ++processing_template_decl;
8084                   push_deferring_access_checks (dk_no_check);
8085                 }
8086
8087               r = tsubst_friend_function (t, args);
8088               add_friend (type, r, /*complain=*/false);
8089               if (TREE_CODE (t) == TEMPLATE_DECL)
8090                 {
8091                   pop_deferring_access_checks ();
8092                   --processing_template_decl;
8093                 }
8094             }
8095         }
8096     }
8097
8098   /* Set the file and line number information to whatever is given for
8099      the class itself.  This puts error messages involving generated
8100      implicit functions at a predictable point, and the same point
8101      that would be used for non-template classes.  */
8102   input_location = DECL_SOURCE_LOCATION (typedecl);
8103
8104   unreverse_member_declarations (type);
8105   finish_struct_1 (type);
8106   TYPE_BEING_DEFINED (type) = 0;
8107
8108   /* Now that the class is complete, instantiate default arguments for
8109      any member functions.  We don't do this earlier because the
8110      default arguments may reference members of the class.  */
8111   if (!PRIMARY_TEMPLATE_P (templ))
8112     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
8113       if (TREE_CODE (t) == FUNCTION_DECL
8114           /* Implicitly generated member functions will not have template
8115              information; they are not instantiations, but instead are
8116              created "fresh" for each instantiation.  */
8117           && DECL_TEMPLATE_INFO (t))
8118         tsubst_default_arguments (t);
8119
8120   /* Some typedefs referenced from within the template code need to be access
8121      checked at template instantiation time, i.e now. These types were
8122      added to the template at parsing time. Let's get those and perform
8123      the access checks then.  */
8124   perform_typedefs_access_check (pattern, args);
8125   perform_deferred_access_checks ();
8126   pop_nested_class ();
8127   maximum_field_alignment = saved_maximum_field_alignment;
8128   pop_from_top_level ();
8129   pop_deferring_access_checks ();
8130   pop_tinst_level ();
8131
8132   /* The vtable for a template class can be emitted in any translation
8133      unit in which the class is instantiated.  When there is no key
8134      method, however, finish_struct_1 will already have added TYPE to
8135      the keyed_classes list.  */
8136   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
8137     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
8138
8139   return type;
8140 }
8141
8142 static tree
8143 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8144 {
8145   tree r;
8146
8147   if (!t)
8148     r = t;
8149   else if (TYPE_P (t))
8150     r = tsubst (t, args, complain, in_decl);
8151   else
8152     {
8153       r = tsubst_expr (t, args, complain, in_decl,
8154                        /*integral_constant_expression_p=*/true);
8155       r = fold_non_dependent_expr (r);
8156     }
8157   return r;
8158 }
8159
8160 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
8161    NONTYPE_ARGUMENT_PACK.  */
8162
8163 static tree
8164 make_fnparm_pack (tree spec_parm)
8165 {
8166   /* Collect all of the extra "packed" parameters into an
8167      argument pack.  */
8168   tree parmvec;
8169   tree parmtypevec;
8170   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
8171   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
8172   int i, len = list_length (spec_parm);
8173
8174   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
8175   parmvec = make_tree_vec (len);
8176   parmtypevec = make_tree_vec (len);
8177   for (i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
8178     {
8179       TREE_VEC_ELT (parmvec, i) = spec_parm;
8180       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
8181     }
8182
8183   /* Build the argument packs.  */
8184   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
8185   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
8186   TREE_TYPE (argpack) = argtypepack;
8187
8188   return argpack;
8189 }        
8190
8191 /* Substitute ARGS into T, which is an pack expansion
8192    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
8193    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
8194    (if only a partial substitution could be performed) or
8195    ERROR_MARK_NODE if there was an error.  */
8196 tree
8197 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
8198                        tree in_decl)
8199 {
8200   tree pattern;
8201   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
8202   int i, len = -1;
8203   tree result;
8204   int incomplete = 0;
8205   bool very_local_specializations = false;
8206
8207   gcc_assert (PACK_EXPANSION_P (t));
8208   pattern = PACK_EXPANSION_PATTERN (t);
8209
8210   /* Determine the argument packs that will instantiate the parameter
8211      packs used in the expansion expression. While we're at it,
8212      compute the number of arguments to be expanded and make sure it
8213      is consistent.  */
8214   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
8215        pack = TREE_CHAIN (pack))
8216     {
8217       tree parm_pack = TREE_VALUE (pack);
8218       tree arg_pack = NULL_TREE;
8219       tree orig_arg = NULL_TREE;
8220
8221       if (TREE_CODE (parm_pack) == PARM_DECL)
8222         {
8223           arg_pack = retrieve_local_specialization (parm_pack);
8224           if (arg_pack == NULL_TREE)
8225             {
8226               /* This can happen for a parameter name used later in a function
8227                  declaration (such as in a late-specified return type).  Just
8228                  make a dummy decl, since it's only used for its type.  */
8229               gcc_assert (cp_unevaluated_operand != 0);
8230               arg_pack = tsubst_decl (parm_pack, args, complain);
8231               arg_pack = make_fnparm_pack (arg_pack);
8232             }
8233         }
8234       else
8235         {
8236           int level, idx, levels;
8237           template_parm_level_and_index (parm_pack, &level, &idx);
8238
8239           levels = TMPL_ARGS_DEPTH (args);
8240           if (level <= levels)
8241             arg_pack = TMPL_ARG (args, level, idx);
8242         }
8243
8244       orig_arg = arg_pack;
8245       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
8246         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
8247       
8248       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
8249         /* This can only happen if we forget to expand an argument
8250            pack somewhere else. Just return an error, silently.  */
8251         {
8252           result = make_tree_vec (1);
8253           TREE_VEC_ELT (result, 0) = error_mark_node;
8254           return result;
8255         }
8256
8257       if (arg_pack
8258           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
8259           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
8260         {
8261           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
8262           tree pattern = PACK_EXPANSION_PATTERN (expansion);
8263           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
8264               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
8265             /* The argument pack that the parameter maps to is just an
8266                expansion of the parameter itself, such as one would
8267                find in the implicit typedef of a class inside the
8268                class itself.  Consider this parameter "unsubstituted",
8269                so that we will maintain the outer pack expansion.  */
8270             arg_pack = NULL_TREE;
8271         }
8272           
8273       if (arg_pack)
8274         {
8275           int my_len = 
8276             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
8277
8278           /* It's all-or-nothing with incomplete argument packs.  */
8279           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8280             return error_mark_node;
8281           
8282           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8283             incomplete = 1;
8284
8285           if (len < 0)
8286             len = my_len;
8287           else if (len != my_len)
8288             {
8289               if (incomplete)
8290                 /* We got explicit args for some packs but not others;
8291                    do nothing now and try again after deduction.  */
8292                 return t;
8293               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
8294                 error ("mismatched argument pack lengths while expanding "
8295                        "%<%T%>",
8296                        pattern);
8297               else
8298                 error ("mismatched argument pack lengths while expanding "
8299                        "%<%E%>",
8300                        pattern);
8301               return error_mark_node;
8302             }
8303
8304           /* Keep track of the parameter packs and their corresponding
8305              argument packs.  */
8306           packs = tree_cons (parm_pack, arg_pack, packs);
8307           TREE_TYPE (packs) = orig_arg;
8308         }
8309       else
8310         /* We can't substitute for this parameter pack.  */
8311         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
8312                                          TREE_VALUE (pack),
8313                                          unsubstituted_packs);
8314     }
8315
8316   /* We cannot expand this expansion expression, because we don't have
8317      all of the argument packs we need. Substitute into the pattern
8318      and return a PACK_EXPANSION_*. The caller will need to deal with
8319      that.  */
8320   if (unsubstituted_packs)
8321     {
8322       tree new_pat;
8323       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8324         new_pat = tsubst_expr (pattern, args, complain, in_decl,
8325                                /*integral_constant_expression_p=*/false);
8326       else
8327         new_pat = tsubst (pattern, args, complain, in_decl);
8328       return make_pack_expansion (new_pat);
8329     }
8330
8331   /* We could not find any argument packs that work.  */
8332   if (len < 0)
8333     return error_mark_node;
8334
8335   if (!local_specializations)
8336     {
8337       /* We're in a late-specified return type, so we don't have a local
8338          specializations table.  Create one for doing this expansion.  */
8339       very_local_specializations = true;
8340       local_specializations = htab_create (37,
8341                                            hash_local_specialization,
8342                                            eq_local_specializations,
8343                                            NULL);
8344     }
8345
8346   /* For each argument in each argument pack, substitute into the
8347      pattern.  */
8348   result = make_tree_vec (len + incomplete);
8349   for (i = 0; i < len + incomplete; ++i)
8350     {
8351       /* For parameter pack, change the substitution of the parameter
8352          pack to the ith argument in its argument pack, then expand
8353          the pattern.  */
8354       for (pack = packs; pack; pack = TREE_CHAIN (pack))
8355         {
8356           tree parm = TREE_PURPOSE (pack);
8357
8358           if (TREE_CODE (parm) == PARM_DECL)
8359             {
8360               /* Select the Ith argument from the pack.  */
8361               tree arg = make_node (ARGUMENT_PACK_SELECT);
8362               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
8363               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
8364               mark_used (parm);
8365               register_local_specialization (arg, parm);
8366             }
8367           else
8368             {
8369               tree value = parm;
8370               int idx, level;
8371               template_parm_level_and_index (parm, &level, &idx);
8372               
8373               if (i < len) 
8374                 {
8375                   /* Select the Ith argument from the pack. */
8376                   value = make_node (ARGUMENT_PACK_SELECT);
8377                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
8378                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
8379                 }
8380
8381               /* Update the corresponding argument.  */
8382               TMPL_ARG (args, level, idx) = value;
8383             }
8384         }
8385
8386       /* Substitute into the PATTERN with the altered arguments.  */
8387       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8388         TREE_VEC_ELT (result, i) = 
8389           tsubst_expr (pattern, args, complain, in_decl,
8390                        /*integral_constant_expression_p=*/false);
8391       else
8392         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
8393
8394       if (i == len)
8395         /* When we have incomplete argument packs, the last "expanded"
8396            result is itself a pack expansion, which allows us
8397            to deduce more arguments.  */
8398         TREE_VEC_ELT (result, i) = 
8399           make_pack_expansion (TREE_VEC_ELT (result, i));
8400
8401       if (TREE_VEC_ELT (result, i) == error_mark_node)
8402         {
8403           result = error_mark_node;
8404           break;
8405         }
8406     }
8407
8408   /* Update ARGS to restore the substitution from parameter packs to
8409      their argument packs.  */
8410   for (pack = packs; pack; pack = TREE_CHAIN (pack))
8411     {
8412       tree parm = TREE_PURPOSE (pack);
8413
8414       if (TREE_CODE (parm) == PARM_DECL)
8415         register_local_specialization (TREE_TYPE (pack), parm);
8416       else
8417         {
8418           int idx, level;
8419           template_parm_level_and_index (parm, &level, &idx);
8420           
8421           /* Update the corresponding argument.  */
8422           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
8423             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
8424               TREE_TYPE (pack);
8425           else
8426             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
8427         }
8428     }
8429
8430   if (very_local_specializations)
8431     {
8432       htab_delete (local_specializations);
8433       local_specializations = NULL;
8434     }
8435   
8436   return result;
8437 }
8438
8439 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
8440    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
8441    parameter packs; all parms generated from a function parameter pack will
8442    have the same DECL_PARM_INDEX.  */
8443
8444 tree
8445 get_pattern_parm (tree parm, tree tmpl)
8446 {
8447   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
8448   tree patparm;
8449
8450   if (DECL_ARTIFICIAL (parm))
8451     {
8452       for (patparm = DECL_ARGUMENTS (pattern);
8453            patparm; patparm = TREE_CHAIN (patparm))
8454         if (DECL_ARTIFICIAL (patparm)
8455             && DECL_NAME (parm) == DECL_NAME (patparm))
8456           break;
8457     }
8458   else
8459     {
8460       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
8461       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
8462       gcc_assert (DECL_PARM_INDEX (patparm)
8463                   == DECL_PARM_INDEX (parm));
8464     }
8465
8466   return patparm;
8467 }
8468
8469 /* Substitute ARGS into the vector or list of template arguments T.  */
8470
8471 static tree
8472 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8473 {
8474   tree orig_t = t;
8475   int len = TREE_VEC_LENGTH (t);
8476   int need_new = 0, i, expanded_len_adjust = 0, out;
8477   tree *elts = (tree *) alloca (len * sizeof (tree));
8478
8479   for (i = 0; i < len; i++)
8480     {
8481       tree orig_arg = TREE_VEC_ELT (t, i);
8482       tree new_arg;
8483
8484       if (TREE_CODE (orig_arg) == TREE_VEC)
8485         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
8486       else if (PACK_EXPANSION_P (orig_arg))
8487         {
8488           /* Substitute into an expansion expression.  */
8489           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
8490
8491           if (TREE_CODE (new_arg) == TREE_VEC)
8492             /* Add to the expanded length adjustment the number of
8493                expanded arguments. We subtract one from this
8494                measurement, because the argument pack expression
8495                itself is already counted as 1 in
8496                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
8497                the argument pack is empty.  */
8498             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
8499         }
8500       else if (ARGUMENT_PACK_P (orig_arg))
8501         {
8502           /* Substitute into each of the arguments.  */
8503           new_arg = TYPE_P (orig_arg)
8504             ? cxx_make_type (TREE_CODE (orig_arg))
8505             : make_node (TREE_CODE (orig_arg));
8506           
8507           SET_ARGUMENT_PACK_ARGS (
8508             new_arg,
8509             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
8510                                   args, complain, in_decl));
8511
8512           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
8513             new_arg = error_mark_node;
8514
8515           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
8516             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
8517                                           complain, in_decl);
8518             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
8519
8520             if (TREE_TYPE (new_arg) == error_mark_node)
8521               new_arg = error_mark_node;
8522           }
8523         }
8524       else
8525         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
8526
8527       if (new_arg == error_mark_node)
8528         return error_mark_node;
8529
8530       elts[i] = new_arg;
8531       if (new_arg != orig_arg)
8532         need_new = 1;
8533     }
8534
8535   if (!need_new)
8536     return t;
8537
8538   /* Make space for the expanded arguments coming from template
8539      argument packs.  */
8540   t = make_tree_vec (len + expanded_len_adjust);
8541   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
8542      arguments for a member template.
8543      In that case each TREE_VEC in ORIG_T represents a level of template
8544      arguments, and ORIG_T won't carry any non defaulted argument count.
8545      It will rather be the nested TREE_VECs that will carry one.
8546      In other words, ORIG_T carries a non defaulted argument count only
8547      if it doesn't contain any nested TREE_VEC.  */
8548   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
8549     {
8550       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
8551       count += expanded_len_adjust;
8552       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
8553     }
8554   for (i = 0, out = 0; i < len; i++)
8555     {
8556       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
8557            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
8558           && TREE_CODE (elts[i]) == TREE_VEC)
8559         {
8560           int idx;
8561
8562           /* Now expand the template argument pack "in place".  */
8563           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
8564             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
8565         }
8566       else
8567         {
8568           TREE_VEC_ELT (t, out) = elts[i];
8569           out++;
8570         }
8571     }
8572
8573   return t;
8574 }
8575
8576 /* Return the result of substituting ARGS into the template parameters
8577    given by PARMS.  If there are m levels of ARGS and m + n levels of
8578    PARMS, then the result will contain n levels of PARMS.  For
8579    example, if PARMS is `template <class T> template <class U>
8580    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
8581    result will be `template <int*, double, class V>'.  */
8582
8583 static tree
8584 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
8585 {
8586   tree r = NULL_TREE;
8587   tree* new_parms;
8588
8589   /* When substituting into a template, we must set
8590      PROCESSING_TEMPLATE_DECL as the template parameters may be
8591      dependent if they are based on one-another, and the dependency
8592      predicates are short-circuit outside of templates.  */
8593   ++processing_template_decl;
8594
8595   for (new_parms = &r;
8596        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
8597        new_parms = &(TREE_CHAIN (*new_parms)),
8598          parms = TREE_CHAIN (parms))
8599     {
8600       tree new_vec =
8601         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
8602       int i;
8603
8604       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
8605         {
8606           tree tuple;
8607           tree default_value;
8608           tree parm_decl;
8609
8610           if (parms == error_mark_node)
8611             continue;
8612
8613           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
8614
8615           if (tuple == error_mark_node)
8616             continue;
8617
8618           default_value = TREE_PURPOSE (tuple);
8619           parm_decl = TREE_VALUE (tuple);
8620
8621           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
8622           if (TREE_CODE (parm_decl) == PARM_DECL
8623               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
8624             parm_decl = error_mark_node;
8625           default_value = tsubst_template_arg (default_value, args,
8626                                                complain, NULL_TREE);
8627
8628           tuple = build_tree_list (default_value, parm_decl);
8629           TREE_VEC_ELT (new_vec, i) = tuple;
8630         }
8631
8632       *new_parms =
8633         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
8634                              - TMPL_ARGS_DEPTH (args)),
8635                    new_vec, NULL_TREE);
8636     }
8637
8638   --processing_template_decl;
8639
8640   return r;
8641 }
8642
8643 /* Substitute the ARGS into the indicated aggregate (or enumeration)
8644    type T.  If T is not an aggregate or enumeration type, it is
8645    handled as if by tsubst.  IN_DECL is as for tsubst.  If
8646    ENTERING_SCOPE is nonzero, T is the context for a template which
8647    we are presently tsubst'ing.  Return the substituted value.  */
8648
8649 static tree
8650 tsubst_aggr_type (tree t,
8651                   tree args,
8652                   tsubst_flags_t complain,
8653                   tree in_decl,
8654                   int entering_scope)
8655 {
8656   if (t == NULL_TREE)
8657     return NULL_TREE;
8658
8659   switch (TREE_CODE (t))
8660     {
8661     case RECORD_TYPE:
8662       if (TYPE_PTRMEMFUNC_P (t))
8663         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
8664
8665       /* Else fall through.  */
8666     case ENUMERAL_TYPE:
8667     case UNION_TYPE:
8668       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
8669         {
8670           tree argvec;
8671           tree context;
8672           tree r;
8673           int saved_unevaluated_operand;
8674           int saved_inhibit_evaluation_warnings;
8675
8676           /* In "sizeof(X<I>)" we need to evaluate "I".  */
8677           saved_unevaluated_operand = cp_unevaluated_operand;
8678           cp_unevaluated_operand = 0;
8679           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
8680           c_inhibit_evaluation_warnings = 0;
8681
8682           /* First, determine the context for the type we are looking
8683              up.  */
8684           context = TYPE_CONTEXT (t);
8685           if (context)
8686             {
8687               context = tsubst_aggr_type (context, args, complain,
8688                                           in_decl, /*entering_scope=*/1);
8689               /* If context is a nested class inside a class template,
8690                  it may still need to be instantiated (c++/33959).  */
8691               if (TYPE_P (context))
8692                 context = complete_type (context);
8693             }
8694
8695           /* Then, figure out what arguments are appropriate for the
8696              type we are trying to find.  For example, given:
8697
8698                template <class T> struct S;
8699                template <class T, class U> void f(T, U) { S<U> su; }
8700
8701              and supposing that we are instantiating f<int, double>,
8702              then our ARGS will be {int, double}, but, when looking up
8703              S we only want {double}.  */
8704           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
8705                                          complain, in_decl);
8706           if (argvec == error_mark_node)
8707             r = error_mark_node;
8708           else
8709             {
8710               r = lookup_template_class (t, argvec, in_decl, context,
8711                                          entering_scope, complain);
8712               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
8713             }
8714
8715           cp_unevaluated_operand = saved_unevaluated_operand;
8716           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
8717
8718           return r;
8719         }
8720       else
8721         /* This is not a template type, so there's nothing to do.  */
8722         return t;
8723
8724     default:
8725       return tsubst (t, args, complain, in_decl);
8726     }
8727 }
8728
8729 /* Substitute into the default argument ARG (a default argument for
8730    FN), which has the indicated TYPE.  */
8731
8732 tree
8733 tsubst_default_argument (tree fn, tree type, tree arg)
8734 {
8735   tree saved_class_ptr = NULL_TREE;
8736   tree saved_class_ref = NULL_TREE;
8737
8738   /* This default argument came from a template.  Instantiate the
8739      default argument here, not in tsubst.  In the case of
8740      something like:
8741
8742        template <class T>
8743        struct S {
8744          static T t();
8745          void f(T = t());
8746        };
8747
8748      we must be careful to do name lookup in the scope of S<T>,
8749      rather than in the current class.  */
8750   push_access_scope (fn);
8751   /* The "this" pointer is not valid in a default argument.  */
8752   if (cfun)
8753     {
8754       saved_class_ptr = current_class_ptr;
8755       cp_function_chain->x_current_class_ptr = NULL_TREE;
8756       saved_class_ref = current_class_ref;
8757       cp_function_chain->x_current_class_ref = NULL_TREE;
8758     }
8759
8760   push_deferring_access_checks(dk_no_deferred);
8761   /* The default argument expression may cause implicitly defined
8762      member functions to be synthesized, which will result in garbage
8763      collection.  We must treat this situation as if we were within
8764      the body of function so as to avoid collecting live data on the
8765      stack.  */
8766   ++function_depth;
8767   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
8768                      tf_warning_or_error, NULL_TREE,
8769                      /*integral_constant_expression_p=*/false);
8770   --function_depth;
8771   pop_deferring_access_checks();
8772
8773   /* Restore the "this" pointer.  */
8774   if (cfun)
8775     {
8776       cp_function_chain->x_current_class_ptr = saved_class_ptr;
8777       cp_function_chain->x_current_class_ref = saved_class_ref;
8778     }
8779
8780   /* Make sure the default argument is reasonable.  */
8781   arg = check_default_argument (type, arg);
8782
8783   pop_access_scope (fn);
8784
8785   return arg;
8786 }
8787
8788 /* Substitute into all the default arguments for FN.  */
8789
8790 static void
8791 tsubst_default_arguments (tree fn)
8792 {
8793   tree arg;
8794   tree tmpl_args;
8795
8796   tmpl_args = DECL_TI_ARGS (fn);
8797
8798   /* If this function is not yet instantiated, we certainly don't need
8799      its default arguments.  */
8800   if (uses_template_parms (tmpl_args))
8801     return;
8802
8803   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
8804        arg;
8805        arg = TREE_CHAIN (arg))
8806     if (TREE_PURPOSE (arg))
8807       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
8808                                                     TREE_VALUE (arg),
8809                                                     TREE_PURPOSE (arg));
8810 }
8811
8812 /* Substitute the ARGS into the T, which is a _DECL.  Return the
8813    result of the substitution.  Issue error and warning messages under
8814    control of COMPLAIN.  */
8815
8816 static tree
8817 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
8818 {
8819 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
8820   location_t saved_loc;
8821   tree r = NULL_TREE;
8822   tree in_decl = t;
8823   hashval_t hash = 0;
8824
8825   /* Set the filename and linenumber to improve error-reporting.  */
8826   saved_loc = input_location;
8827   input_location = DECL_SOURCE_LOCATION (t);
8828
8829   switch (TREE_CODE (t))
8830     {
8831     case TEMPLATE_DECL:
8832       {
8833         /* We can get here when processing a member function template,
8834            member class template, or template template parameter.  */
8835         tree decl = DECL_TEMPLATE_RESULT (t);
8836         tree spec;
8837         tree tmpl_args;
8838         tree full_args;
8839
8840         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8841           {
8842             /* Template template parameter is treated here.  */
8843             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8844             if (new_type == error_mark_node)
8845               RETURN (error_mark_node);
8846
8847             r = copy_decl (t);
8848             TREE_CHAIN (r) = NULL_TREE;
8849             TREE_TYPE (r) = new_type;
8850             DECL_TEMPLATE_RESULT (r)
8851               = build_decl (DECL_SOURCE_LOCATION (decl),
8852                             TYPE_DECL, DECL_NAME (decl), new_type);
8853             DECL_TEMPLATE_PARMS (r)
8854               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8855                                        complain);
8856             TYPE_NAME (new_type) = r;
8857             break;
8858           }
8859
8860         /* We might already have an instance of this template.
8861            The ARGS are for the surrounding class type, so the
8862            full args contain the tsubst'd args for the context,
8863            plus the innermost args from the template decl.  */
8864         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8865           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8866           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8867         /* Because this is a template, the arguments will still be
8868            dependent, even after substitution.  If
8869            PROCESSING_TEMPLATE_DECL is not set, the dependency
8870            predicates will short-circuit.  */
8871         ++processing_template_decl;
8872         full_args = tsubst_template_args (tmpl_args, args,
8873                                           complain, in_decl);
8874         --processing_template_decl;
8875         if (full_args == error_mark_node)
8876           RETURN (error_mark_node);
8877
8878         /* If this is a default template template argument,
8879            tsubst might not have changed anything.  */
8880         if (full_args == tmpl_args)
8881           RETURN (t);
8882
8883         hash = hash_tmpl_and_args (t, full_args);
8884         spec = retrieve_specialization (t, full_args, hash);
8885         if (spec != NULL_TREE)
8886           {
8887             r = spec;
8888             break;
8889           }
8890
8891         /* Make a new template decl.  It will be similar to the
8892            original, but will record the current template arguments.
8893            We also create a new function declaration, which is just
8894            like the old one, but points to this new template, rather
8895            than the old one.  */
8896         r = copy_decl (t);
8897         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
8898         TREE_CHAIN (r) = NULL_TREE;
8899
8900         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
8901
8902         if (TREE_CODE (decl) == TYPE_DECL)
8903           {
8904             tree new_type;
8905             ++processing_template_decl;
8906             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8907             --processing_template_decl;
8908             if (new_type == error_mark_node)
8909               RETURN (error_mark_node);
8910
8911             TREE_TYPE (r) = new_type;
8912             CLASSTYPE_TI_TEMPLATE (new_type) = r;
8913             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
8914             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
8915             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
8916           }
8917         else
8918           {
8919             tree new_decl;
8920             ++processing_template_decl;
8921             new_decl = tsubst (decl, args, complain, in_decl);
8922             --processing_template_decl;
8923             if (new_decl == error_mark_node)
8924               RETURN (error_mark_node);
8925
8926             DECL_TEMPLATE_RESULT (r) = new_decl;
8927             DECL_TI_TEMPLATE (new_decl) = r;
8928             TREE_TYPE (r) = TREE_TYPE (new_decl);
8929             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
8930             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
8931           }
8932
8933         SET_DECL_IMPLICIT_INSTANTIATION (r);
8934         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
8935         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
8936
8937         /* The template parameters for this new template are all the
8938            template parameters for the old template, except the
8939            outermost level of parameters.  */
8940         DECL_TEMPLATE_PARMS (r)
8941           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8942                                    complain);
8943
8944         if (PRIMARY_TEMPLATE_P (t))
8945           DECL_PRIMARY_TEMPLATE (r) = r;
8946
8947         if (TREE_CODE (decl) != TYPE_DECL)
8948           /* Record this non-type partial instantiation.  */
8949           register_specialization (r, t,
8950                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
8951                                    false, hash);
8952       }
8953       break;
8954
8955     case FUNCTION_DECL:
8956       {
8957         tree ctx;
8958         tree argvec = NULL_TREE;
8959         tree *friends;
8960         tree gen_tmpl;
8961         tree type;
8962         int member;
8963         int args_depth;
8964         int parms_depth;
8965
8966         /* Nobody should be tsubst'ing into non-template functions.  */
8967         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
8968
8969         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
8970           {
8971             tree spec;
8972             bool dependent_p;
8973
8974             /* If T is not dependent, just return it.  We have to
8975                increment PROCESSING_TEMPLATE_DECL because
8976                value_dependent_expression_p assumes that nothing is
8977                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
8978             ++processing_template_decl;
8979             dependent_p = value_dependent_expression_p (t);
8980             --processing_template_decl;
8981             if (!dependent_p)
8982               RETURN (t);
8983
8984             /* Calculate the most general template of which R is a
8985                specialization, and the complete set of arguments used to
8986                specialize R.  */
8987             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
8988             argvec = tsubst_template_args (DECL_TI_ARGS
8989                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
8990                                            args, complain, in_decl);
8991
8992             /* Check to see if we already have this specialization.  */
8993             hash = hash_tmpl_and_args (gen_tmpl, argvec);
8994             spec = retrieve_specialization (gen_tmpl, argvec, hash);
8995
8996             if (spec)
8997               {
8998                 r = spec;
8999                 break;
9000               }
9001
9002             /* We can see more levels of arguments than parameters if
9003                there was a specialization of a member template, like
9004                this:
9005
9006                  template <class T> struct S { template <class U> void f(); }
9007                  template <> template <class U> void S<int>::f(U);
9008
9009                Here, we'll be substituting into the specialization,
9010                because that's where we can find the code we actually
9011                want to generate, but we'll have enough arguments for
9012                the most general template.
9013
9014                We also deal with the peculiar case:
9015
9016                  template <class T> struct S {
9017                    template <class U> friend void f();
9018                  };
9019                  template <class U> void f() {}
9020                  template S<int>;
9021                  template void f<double>();
9022
9023                Here, the ARGS for the instantiation of will be {int,
9024                double}.  But, we only need as many ARGS as there are
9025                levels of template parameters in CODE_PATTERN.  We are
9026                careful not to get fooled into reducing the ARGS in
9027                situations like:
9028
9029                  template <class T> struct S { template <class U> void f(U); }
9030                  template <class T> template <> void S<T>::f(int) {}
9031
9032                which we can spot because the pattern will be a
9033                specialization in this case.  */
9034             args_depth = TMPL_ARGS_DEPTH (args);
9035             parms_depth =
9036               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
9037             if (args_depth > parms_depth
9038                 && !DECL_TEMPLATE_SPECIALIZATION (t))
9039               args = get_innermost_template_args (args, parms_depth);
9040           }
9041         else
9042           {
9043             /* This special case arises when we have something like this:
9044
9045                  template <class T> struct S {
9046                    friend void f<int>(int, double);
9047                  };
9048
9049                Here, the DECL_TI_TEMPLATE for the friend declaration
9050                will be an IDENTIFIER_NODE.  We are being called from
9051                tsubst_friend_function, and we want only to create a
9052                new decl (R) with appropriate types so that we can call
9053                determine_specialization.  */
9054             gen_tmpl = NULL_TREE;
9055           }
9056
9057         if (DECL_CLASS_SCOPE_P (t))
9058           {
9059             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
9060               member = 2;
9061             else
9062               member = 1;
9063             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
9064                                     complain, t, /*entering_scope=*/1);
9065           }
9066         else
9067           {
9068             member = 0;
9069             ctx = DECL_CONTEXT (t);
9070           }
9071         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9072         if (type == error_mark_node)
9073           RETURN (error_mark_node);
9074
9075         /* We do NOT check for matching decls pushed separately at this
9076            point, as they may not represent instantiations of this
9077            template, and in any case are considered separate under the
9078            discrete model.  */
9079         r = copy_decl (t);
9080         DECL_USE_TEMPLATE (r) = 0;
9081         TREE_TYPE (r) = type;
9082         /* Clear out the mangled name and RTL for the instantiation.  */
9083         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9084         SET_DECL_RTL (r, NULL_RTX);
9085         /* Leave DECL_INITIAL set on deleted instantiations.  */
9086         if (!DECL_DELETED_FN (r))
9087           DECL_INITIAL (r) = NULL_TREE;
9088         DECL_CONTEXT (r) = ctx;
9089
9090         if (member && DECL_CONV_FN_P (r))
9091           /* Type-conversion operator.  Reconstruct the name, in
9092              case it's the name of one of the template's parameters.  */
9093           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
9094
9095         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
9096                                      complain, t);
9097         DECL_RESULT (r) = NULL_TREE;
9098
9099         TREE_STATIC (r) = 0;
9100         TREE_PUBLIC (r) = TREE_PUBLIC (t);
9101         DECL_EXTERNAL (r) = 1;
9102         /* If this is an instantiation of a function with internal
9103            linkage, we already know what object file linkage will be
9104            assigned to the instantiation.  */
9105         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
9106         DECL_DEFER_OUTPUT (r) = 0;
9107         TREE_CHAIN (r) = NULL_TREE;
9108         DECL_PENDING_INLINE_INFO (r) = 0;
9109         DECL_PENDING_INLINE_P (r) = 0;
9110         DECL_SAVED_TREE (r) = NULL_TREE;
9111         DECL_STRUCT_FUNCTION (r) = NULL;
9112         TREE_USED (r) = 0;
9113         /* We'll re-clone as appropriate in instantiate_template.  */
9114         DECL_CLONED_FUNCTION (r) = NULL_TREE;
9115
9116         /* If we aren't complaining now, return on error before we register
9117            the specialization so that we'll complain eventually.  */
9118         if ((complain & tf_error) == 0
9119             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9120             && !grok_op_properties (r, /*complain=*/false))
9121           RETURN (error_mark_node);
9122
9123         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
9124            this in the special friend case mentioned above where
9125            GEN_TMPL is NULL.  */
9126         if (gen_tmpl)
9127           {
9128             DECL_TEMPLATE_INFO (r)
9129               = build_template_info (gen_tmpl, argvec);
9130             SET_DECL_IMPLICIT_INSTANTIATION (r);
9131             register_specialization (r, gen_tmpl, argvec, false, hash);
9132
9133             /* We're not supposed to instantiate default arguments
9134                until they are called, for a template.  But, for a
9135                declaration like:
9136
9137                  template <class T> void f ()
9138                  { extern void g(int i = T()); }
9139
9140                we should do the substitution when the template is
9141                instantiated.  We handle the member function case in
9142                instantiate_class_template since the default arguments
9143                might refer to other members of the class.  */
9144             if (!member
9145                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
9146                 && !uses_template_parms (argvec))
9147               tsubst_default_arguments (r);
9148           }
9149         else
9150           DECL_TEMPLATE_INFO (r) = NULL_TREE;
9151
9152         /* Copy the list of befriending classes.  */
9153         for (friends = &DECL_BEFRIENDING_CLASSES (r);
9154              *friends;
9155              friends = &TREE_CHAIN (*friends))
9156           {
9157             *friends = copy_node (*friends);
9158             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
9159                                             args, complain,
9160                                             in_decl);
9161           }
9162
9163         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
9164           {
9165             maybe_retrofit_in_chrg (r);
9166             if (DECL_CONSTRUCTOR_P (r))
9167               grok_ctor_properties (ctx, r);
9168             /* If this is an instantiation of a member template, clone it.
9169                If it isn't, that'll be handled by
9170                clone_constructors_and_destructors.  */
9171             if (PRIMARY_TEMPLATE_P (gen_tmpl))
9172               clone_function_decl (r, /*update_method_vec_p=*/0);
9173           }
9174         else if ((complain & tf_error) != 0
9175                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9176                  && !grok_op_properties (r, /*complain=*/true))
9177           RETURN (error_mark_node);
9178
9179         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
9180           SET_DECL_FRIEND_CONTEXT (r,
9181                                    tsubst (DECL_FRIEND_CONTEXT (t),
9182                                             args, complain, in_decl));
9183
9184         /* Possibly limit visibility based on template args.  */
9185         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9186         if (DECL_VISIBILITY_SPECIFIED (t))
9187           {
9188             DECL_VISIBILITY_SPECIFIED (r) = 0;
9189             DECL_ATTRIBUTES (r)
9190               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9191           }
9192         determine_visibility (r);
9193         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
9194             && !processing_template_decl)
9195           defaulted_late_check (r);
9196
9197         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9198                                         args, complain, in_decl);
9199       }
9200       break;
9201
9202     case PARM_DECL:
9203       {
9204         tree type = NULL_TREE;
9205         int i, len = 1;
9206         tree expanded_types = NULL_TREE;
9207         tree prev_r = NULL_TREE;
9208         tree first_r = NULL_TREE;
9209
9210         if (FUNCTION_PARAMETER_PACK_P (t))
9211           {
9212             /* If there is a local specialization that isn't a
9213                parameter pack, it means that we're doing a "simple"
9214                substitution from inside tsubst_pack_expansion. Just
9215                return the local specialization (which will be a single
9216                parm).  */
9217             tree spec = retrieve_local_specialization (t);
9218             if (spec 
9219                 && TREE_CODE (spec) == PARM_DECL
9220                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
9221               RETURN (spec);
9222
9223             /* Expand the TYPE_PACK_EXPANSION that provides the types for
9224                the parameters in this function parameter pack.  */
9225             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
9226                                                     complain, in_decl);
9227             if (TREE_CODE (expanded_types) == TREE_VEC)
9228               {
9229                 len = TREE_VEC_LENGTH (expanded_types);
9230
9231                 /* Zero-length parameter packs are boring. Just substitute
9232                    into the chain.  */
9233                 if (len == 0)
9234                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
9235                                   TREE_CHAIN (t)));
9236               }
9237             else
9238               {
9239                 /* All we did was update the type. Make a note of that.  */
9240                 type = expanded_types;
9241                 expanded_types = NULL_TREE;
9242               }
9243           }
9244
9245         /* Loop through all of the parameter's we'll build. When T is
9246            a function parameter pack, LEN is the number of expanded
9247            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
9248         r = NULL_TREE;
9249         for (i = 0; i < len; ++i)
9250           {
9251             prev_r = r;
9252             r = copy_node (t);
9253             if (DECL_TEMPLATE_PARM_P (t))
9254               SET_DECL_TEMPLATE_PARM_P (r);
9255
9256             /* An argument of a function parameter pack is not a parameter
9257                pack.  */
9258             FUNCTION_PARAMETER_PACK_P (r) = false;
9259
9260             if (expanded_types)
9261               /* We're on the Ith parameter of the function parameter
9262                  pack.  */
9263               {
9264                 /* Get the Ith type.  */
9265                 type = TREE_VEC_ELT (expanded_types, i);
9266
9267                 if (DECL_NAME (r))
9268                   /* Rename the parameter to include the index.  */
9269                   DECL_NAME (r) =
9270                     make_ith_pack_parameter_name (DECL_NAME (r), i);
9271               }
9272             else if (!type)
9273               /* We're dealing with a normal parameter.  */
9274               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9275
9276             type = type_decays_to (type);
9277             TREE_TYPE (r) = type;
9278             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9279
9280             if (DECL_INITIAL (r))
9281               {
9282                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
9283                   DECL_INITIAL (r) = TREE_TYPE (r);
9284                 else
9285                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
9286                                              complain, in_decl);
9287               }
9288
9289             DECL_CONTEXT (r) = NULL_TREE;
9290
9291             if (!DECL_TEMPLATE_PARM_P (r))
9292               DECL_ARG_TYPE (r) = type_passed_as (type);
9293
9294             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9295                                             args, complain, in_decl);
9296
9297             /* Keep track of the first new parameter we
9298                generate. That's what will be returned to the
9299                caller.  */
9300             if (!first_r)
9301               first_r = r;
9302
9303             /* Build a proper chain of parameters when substituting
9304                into a function parameter pack.  */
9305             if (prev_r)
9306               TREE_CHAIN (prev_r) = r;
9307           }
9308
9309         if (TREE_CHAIN (t))
9310           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
9311                                    complain, TREE_CHAIN (t));
9312
9313         /* FIRST_R contains the start of the chain we've built.  */
9314         r = first_r;
9315       }
9316       break;
9317
9318     case FIELD_DECL:
9319       {
9320         tree type;
9321
9322         r = copy_decl (t);
9323         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9324         if (type == error_mark_node)
9325           RETURN (error_mark_node);
9326         TREE_TYPE (r) = type;
9327         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9328
9329         /* DECL_INITIAL gives the number of bits in a bit-field.  */
9330         DECL_INITIAL (r)
9331           = tsubst_expr (DECL_INITIAL (t), args,
9332                          complain, in_decl,
9333                          /*integral_constant_expression_p=*/true);
9334         /* We don't have to set DECL_CONTEXT here; it is set by
9335            finish_member_declaration.  */
9336         TREE_CHAIN (r) = NULL_TREE;
9337         if (VOID_TYPE_P (type))
9338           error ("instantiation of %q+D as type %qT", r, type);
9339
9340         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9341                                         args, complain, in_decl);
9342       }
9343       break;
9344
9345     case USING_DECL:
9346       /* We reach here only for member using decls.  */
9347       if (DECL_DEPENDENT_P (t))
9348         {
9349           r = do_class_using_decl
9350             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
9351              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
9352           if (!r)
9353             r = error_mark_node;
9354           else
9355             {
9356               TREE_PROTECTED (r) = TREE_PROTECTED (t);
9357               TREE_PRIVATE (r) = TREE_PRIVATE (t);
9358             }
9359         }
9360       else
9361         {
9362           r = copy_node (t);
9363           TREE_CHAIN (r) = NULL_TREE;
9364         }
9365       break;
9366
9367     case TYPE_DECL:
9368     case VAR_DECL:
9369       {
9370         tree argvec = NULL_TREE;
9371         tree gen_tmpl = NULL_TREE;
9372         tree spec;
9373         tree tmpl = NULL_TREE;
9374         tree ctx;
9375         tree type = NULL_TREE;
9376         bool local_p;
9377
9378         if (TREE_CODE (t) == TYPE_DECL
9379             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
9380           {
9381             /* If this is the canonical decl, we don't have to
9382                mess with instantiations, and often we can't (for
9383                typename, template type parms and such).  Note that
9384                TYPE_NAME is not correct for the above test if
9385                we've copied the type for a typedef.  */
9386             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9387             if (type == error_mark_node)
9388               RETURN (error_mark_node);
9389             r = TYPE_NAME (type);
9390             break;
9391           }
9392
9393         /* Check to see if we already have the specialization we
9394            need.  */
9395         spec = NULL_TREE;
9396         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
9397           {
9398             /* T is a static data member or namespace-scope entity.
9399                We have to substitute into namespace-scope variables
9400                (even though such entities are never templates) because
9401                of cases like:
9402                
9403                  template <class T> void f() { extern T t; }
9404
9405                where the entity referenced is not known until
9406                instantiation time.  */
9407             local_p = false;
9408             ctx = DECL_CONTEXT (t);
9409             if (DECL_CLASS_SCOPE_P (t))
9410               {
9411                 ctx = tsubst_aggr_type (ctx, args,
9412                                         complain,
9413                                         in_decl, /*entering_scope=*/1);
9414                 /* If CTX is unchanged, then T is in fact the
9415                    specialization we want.  That situation occurs when
9416                    referencing a static data member within in its own
9417                    class.  We can use pointer equality, rather than
9418                    same_type_p, because DECL_CONTEXT is always
9419                    canonical.  */
9420                 if (ctx == DECL_CONTEXT (t))
9421                   spec = t;
9422               }
9423
9424             if (!spec)
9425               {
9426                 tmpl = DECL_TI_TEMPLATE (t);
9427                 gen_tmpl = most_general_template (tmpl);
9428                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
9429                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
9430                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
9431               }
9432           }
9433         else
9434           {
9435             /* A local variable.  */
9436             local_p = true;
9437             /* Subsequent calls to pushdecl will fill this in.  */
9438             ctx = NULL_TREE;
9439             spec = retrieve_local_specialization (t);
9440           }
9441         /* If we already have the specialization we need, there is
9442            nothing more to do.  */ 
9443         if (spec)
9444           {
9445             r = spec;
9446             break;
9447           }
9448
9449         /* Create a new node for the specialization we need.  */
9450         r = copy_decl (t);
9451         if (type == NULL_TREE)
9452           {
9453             if (is_typedef_decl (t))
9454               type = DECL_ORIGINAL_TYPE (t);
9455             else
9456               type = TREE_TYPE (t);
9457             type = tsubst (type, args, complain, in_decl);
9458           }
9459         if (TREE_CODE (r) == VAR_DECL)
9460           {
9461             /* Even if the original location is out of scope, the
9462                newly substituted one is not.  */
9463             DECL_DEAD_FOR_LOCAL (r) = 0;
9464             DECL_INITIALIZED_P (r) = 0;
9465             DECL_TEMPLATE_INSTANTIATED (r) = 0;
9466             if (type == error_mark_node)
9467               RETURN (error_mark_node);
9468             if (TREE_CODE (type) == FUNCTION_TYPE)
9469               {
9470                 /* It may seem that this case cannot occur, since:
9471
9472                      typedef void f();
9473                      void g() { f x; }
9474
9475                    declares a function, not a variable.  However:
9476       
9477                      typedef void f();
9478                      template <typename T> void g() { T t; }
9479                      template void g<f>();
9480
9481                    is an attempt to declare a variable with function
9482                    type.  */
9483                 error ("variable %qD has function type",
9484                        /* R is not yet sufficiently initialized, so we
9485                           just use its name.  */
9486                        DECL_NAME (r));
9487                 RETURN (error_mark_node);
9488               }
9489             type = complete_type (type);
9490             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
9491               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
9492             type = check_var_type (DECL_NAME (r), type);
9493
9494             if (DECL_HAS_VALUE_EXPR_P (t))
9495               {
9496                 tree ve = DECL_VALUE_EXPR (t);
9497                 ve = tsubst_expr (ve, args, complain, in_decl,
9498                                   /*constant_expression_p=*/false);
9499                 SET_DECL_VALUE_EXPR (r, ve);
9500               }
9501           }
9502         else if (DECL_SELF_REFERENCE_P (t))
9503           SET_DECL_SELF_REFERENCE_P (r);
9504         TREE_TYPE (r) = type;
9505         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9506         DECL_CONTEXT (r) = ctx;
9507         /* Clear out the mangled name and RTL for the instantiation.  */
9508         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9509         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9510           SET_DECL_RTL (r, NULL_RTX);
9511         /* The initializer must not be expanded until it is required;
9512            see [temp.inst].  */
9513         DECL_INITIAL (r) = NULL_TREE;
9514         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9515           SET_DECL_RTL (r, NULL_RTX);
9516         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
9517         if (TREE_CODE (r) == VAR_DECL)
9518           {
9519             /* Possibly limit visibility based on template args.  */
9520             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9521             if (DECL_VISIBILITY_SPECIFIED (t))
9522               {
9523                 DECL_VISIBILITY_SPECIFIED (r) = 0;
9524                 DECL_ATTRIBUTES (r)
9525                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9526               }
9527             determine_visibility (r);
9528           }
9529
9530         if (!local_p)
9531           {
9532             /* A static data member declaration is always marked
9533                external when it is declared in-class, even if an
9534                initializer is present.  We mimic the non-template
9535                processing here.  */
9536             DECL_EXTERNAL (r) = 1;
9537
9538             register_specialization (r, gen_tmpl, argvec, false, hash);
9539             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
9540             SET_DECL_IMPLICIT_INSTANTIATION (r);
9541           }
9542         else if (cp_unevaluated_operand)
9543           {
9544             /* We're substituting this var in a decltype outside of its
9545                scope, such as for a lambda return type.  Don't add it to
9546                local_specializations, do perform auto deduction.  */
9547             tree auto_node = type_uses_auto (type);
9548             tree init
9549               = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
9550                              /*constant_expression_p=*/false);
9551
9552             if (auto_node && init && describable_type (init))
9553               {
9554                 type = do_auto_deduction (type, init, auto_node);
9555                 TREE_TYPE (r) = type;
9556               }
9557           }
9558         else
9559           register_local_specialization (r, t);
9560
9561         TREE_CHAIN (r) = NULL_TREE;
9562
9563         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
9564                                         /*flags=*/0,
9565                                         args, complain, in_decl);
9566
9567         /* Preserve a typedef that names a type.  */
9568         if (is_typedef_decl (r))
9569           {
9570             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
9571             set_underlying_type (r);
9572           }
9573
9574         layout_decl (r, 0);
9575       }
9576       break;
9577
9578     default:
9579       gcc_unreachable ();
9580     }
9581 #undef RETURN
9582
9583  out:
9584   /* Restore the file and line information.  */
9585   input_location = saved_loc;
9586
9587   return r;
9588 }
9589
9590 /* Substitute into the ARG_TYPES of a function type.  */
9591
9592 static tree
9593 tsubst_arg_types (tree arg_types,
9594                   tree args,
9595                   tsubst_flags_t complain,
9596                   tree in_decl)
9597 {
9598   tree remaining_arg_types;
9599   tree type = NULL_TREE;
9600   int i = 1;
9601   tree expanded_args = NULL_TREE;
9602   tree default_arg;
9603
9604   if (!arg_types || arg_types == void_list_node)
9605     return arg_types;
9606
9607   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
9608                                           args, complain, in_decl);
9609   if (remaining_arg_types == error_mark_node)
9610     return error_mark_node;
9611
9612   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
9613     {
9614       /* For a pack expansion, perform substitution on the
9615          entire expression. Later on, we'll handle the arguments
9616          one-by-one.  */
9617       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
9618                                             args, complain, in_decl);
9619
9620       if (TREE_CODE (expanded_args) == TREE_VEC)
9621         /* So that we'll spin through the parameters, one by one.  */
9622         i = TREE_VEC_LENGTH (expanded_args);
9623       else
9624         {
9625           /* We only partially substituted into the parameter
9626              pack. Our type is TYPE_PACK_EXPANSION.  */
9627           type = expanded_args;
9628           expanded_args = NULL_TREE;
9629         }
9630     }
9631
9632   while (i > 0) {
9633     --i;
9634     
9635     if (expanded_args)
9636       type = TREE_VEC_ELT (expanded_args, i);
9637     else if (!type)
9638       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
9639
9640     if (type == error_mark_node)
9641       return error_mark_node;
9642     if (VOID_TYPE_P (type))
9643       {
9644         if (complain & tf_error)
9645           {
9646             error ("invalid parameter type %qT", type);
9647             if (in_decl)
9648               error ("in declaration %q+D", in_decl);
9649           }
9650         return error_mark_node;
9651     }
9652     
9653     /* Do array-to-pointer, function-to-pointer conversion, and ignore
9654        top-level qualifiers as required.  */
9655     type = TYPE_MAIN_VARIANT (type_decays_to (type));
9656
9657     /* We do not substitute into default arguments here.  The standard
9658        mandates that they be instantiated only when needed, which is
9659        done in build_over_call.  */
9660     default_arg = TREE_PURPOSE (arg_types);
9661
9662     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
9663       {
9664         /* We've instantiated a template before its default arguments
9665            have been parsed.  This can happen for a nested template
9666            class, and is not an error unless we require the default
9667            argument in a call of this function.  */
9668         remaining_arg_types = 
9669           tree_cons (default_arg, type, remaining_arg_types);
9670         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
9671                        remaining_arg_types);
9672       }
9673     else
9674       remaining_arg_types = 
9675         hash_tree_cons (default_arg, type, remaining_arg_types);
9676   }
9677         
9678   return remaining_arg_types;
9679 }
9680
9681 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
9682    *not* handle the exception-specification for FNTYPE, because the
9683    initial substitution of explicitly provided template parameters
9684    during argument deduction forbids substitution into the
9685    exception-specification:
9686
9687      [temp.deduct]
9688
9689      All references in the function type of the function template to  the
9690      corresponding template parameters are replaced by the specified tem-
9691      plate argument values.  If a substitution in a template parameter or
9692      in  the function type of the function template results in an invalid
9693      type, type deduction fails.  [Note: The equivalent  substitution  in
9694      exception specifications is done only when the function is instanti-
9695      ated, at which point a program is  ill-formed  if  the  substitution
9696      results in an invalid type.]  */
9697
9698 static tree
9699 tsubst_function_type (tree t,
9700                       tree args,
9701                       tsubst_flags_t complain,
9702                       tree in_decl)
9703 {
9704   tree return_type;
9705   tree arg_types;
9706   tree fntype;
9707
9708   /* The TYPE_CONTEXT is not used for function/method types.  */
9709   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
9710
9711   /* Substitute the return type.  */
9712   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9713   if (return_type == error_mark_node)
9714     return error_mark_node;
9715   /* The standard does not presently indicate that creation of a
9716      function type with an invalid return type is a deduction failure.
9717      However, that is clearly analogous to creating an array of "void"
9718      or a reference to a reference.  This is core issue #486.  */
9719   if (TREE_CODE (return_type) == ARRAY_TYPE
9720       || TREE_CODE (return_type) == FUNCTION_TYPE)
9721     {
9722       if (complain & tf_error)
9723         {
9724           if (TREE_CODE (return_type) == ARRAY_TYPE)
9725             error ("function returning an array");
9726           else
9727             error ("function returning a function");
9728         }
9729       return error_mark_node;
9730     }
9731
9732   /* Substitute the argument types.  */
9733   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
9734                                 complain, in_decl);
9735   if (arg_types == error_mark_node)
9736     return error_mark_node;
9737
9738   /* Construct a new type node and return it.  */
9739   if (TREE_CODE (t) == FUNCTION_TYPE)
9740     fntype = build_function_type (return_type, arg_types);
9741   else
9742     {
9743       tree r = TREE_TYPE (TREE_VALUE (arg_types));
9744       if (! MAYBE_CLASS_TYPE_P (r))
9745         {
9746           /* [temp.deduct]
9747
9748              Type deduction may fail for any of the following
9749              reasons:
9750
9751              -- Attempting to create "pointer to member of T" when T
9752              is not a class type.  */
9753           if (complain & tf_error)
9754             error ("creating pointer to member function of non-class type %qT",
9755                       r);
9756           return error_mark_node;
9757         }
9758
9759       fntype = build_method_type_directly (r, return_type,
9760                                            TREE_CHAIN (arg_types));
9761     }
9762   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
9763   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
9764
9765   return fntype;
9766 }
9767
9768 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
9769    ARGS into that specification, and return the substituted
9770    specification.  If there is no specification, return NULL_TREE.  */
9771
9772 static tree
9773 tsubst_exception_specification (tree fntype,
9774                                 tree args,
9775                                 tsubst_flags_t complain,
9776                                 tree in_decl)
9777 {
9778   tree specs;
9779   tree new_specs;
9780
9781   specs = TYPE_RAISES_EXCEPTIONS (fntype);
9782   new_specs = NULL_TREE;
9783   if (specs)
9784     {
9785       if (! TREE_VALUE (specs))
9786         new_specs = specs;
9787       else
9788         while (specs)
9789           {
9790             tree spec;
9791             int i, len = 1;
9792             tree expanded_specs = NULL_TREE;
9793
9794             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
9795               {
9796                 /* Expand the pack expansion type.  */
9797                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
9798                                                        args, complain,
9799                                                        in_decl);
9800
9801                 if (expanded_specs == error_mark_node)
9802                   return error_mark_node;
9803                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
9804                   len = TREE_VEC_LENGTH (expanded_specs);
9805                 else
9806                   {
9807                     /* We're substituting into a member template, so
9808                        we got a TYPE_PACK_EXPANSION back.  Add that
9809                        expansion and move on.  */
9810                     gcc_assert (TREE_CODE (expanded_specs) 
9811                                 == TYPE_PACK_EXPANSION);
9812                     new_specs = add_exception_specifier (new_specs,
9813                                                          expanded_specs,
9814                                                          complain);
9815                     specs = TREE_CHAIN (specs);
9816                     continue;
9817                   }
9818               }
9819
9820             for (i = 0; i < len; ++i)
9821               {
9822                 if (expanded_specs)
9823                   spec = TREE_VEC_ELT (expanded_specs, i);
9824                 else
9825                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
9826                 if (spec == error_mark_node)
9827                   return spec;
9828                 new_specs = add_exception_specifier (new_specs, spec, 
9829                                                      complain);
9830               }
9831
9832             specs = TREE_CHAIN (specs);
9833           }
9834     }
9835   return new_specs;
9836 }
9837
9838 /* Take the tree structure T and replace template parameters used
9839    therein with the argument vector ARGS.  IN_DECL is an associated
9840    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
9841    Issue error and warning messages under control of COMPLAIN.  Note
9842    that we must be relatively non-tolerant of extensions here, in
9843    order to preserve conformance; if we allow substitutions that
9844    should not be allowed, we may allow argument deductions that should
9845    not succeed, and therefore report ambiguous overload situations
9846    where there are none.  In theory, we could allow the substitution,
9847    but indicate that it should have failed, and allow our caller to
9848    make sure that the right thing happens, but we don't try to do this
9849    yet.
9850
9851    This function is used for dealing with types, decls and the like;
9852    for expressions, use tsubst_expr or tsubst_copy.  */
9853
9854 tree
9855 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9856 {
9857   tree type, r;
9858
9859   if (t == NULL_TREE || t == error_mark_node
9860       || t == integer_type_node
9861       || t == void_type_node
9862       || t == char_type_node
9863       || t == unknown_type_node
9864       || TREE_CODE (t) == NAMESPACE_DECL)
9865     return t;
9866
9867   if (DECL_P (t))
9868     return tsubst_decl (t, args, complain);
9869
9870   if (args == NULL_TREE)
9871     return t;
9872
9873   if (TREE_CODE (t) == IDENTIFIER_NODE)
9874     type = IDENTIFIER_TYPE_VALUE (t);
9875   else
9876     type = TREE_TYPE (t);
9877
9878   gcc_assert (type != unknown_type_node);
9879
9880   /* Reuse typedefs.  We need to do this to handle dependent attributes,
9881      such as attribute aligned.  */
9882   if (TYPE_P (t)
9883       && TYPE_NAME (t)
9884       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
9885     {
9886       tree decl = TYPE_NAME (t);
9887       
9888       if (DECL_CLASS_SCOPE_P (decl)
9889           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
9890           && uses_template_parms (DECL_CONTEXT (decl)))
9891         {
9892           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
9893           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
9894           r = retrieve_specialization (tmpl, gen_args, 0);
9895         }
9896       else if (DECL_FUNCTION_SCOPE_P (decl)
9897                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
9898                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
9899         r = retrieve_local_specialization (decl);
9900       else
9901         /* The typedef is from a non-template context.  */
9902         return t;
9903
9904       if (r)
9905         {
9906           r = TREE_TYPE (r);
9907           r = cp_build_qualified_type_real
9908             (r, cp_type_quals (t) | cp_type_quals (r),
9909              complain | tf_ignore_bad_quals);
9910           return r;
9911         }
9912       /* Else we must be instantiating the typedef, so fall through.  */
9913     }
9914
9915   if (type
9916       && TREE_CODE (t) != TYPENAME_TYPE
9917       && TREE_CODE (t) != IDENTIFIER_NODE
9918       && TREE_CODE (t) != FUNCTION_TYPE
9919       && TREE_CODE (t) != METHOD_TYPE)
9920     type = tsubst (type, args, complain, in_decl);
9921   if (type == error_mark_node)
9922     return error_mark_node;
9923
9924   switch (TREE_CODE (t))
9925     {
9926     case RECORD_TYPE:
9927     case UNION_TYPE:
9928     case ENUMERAL_TYPE:
9929       return tsubst_aggr_type (t, args, complain, in_decl,
9930                                /*entering_scope=*/0);
9931
9932     case ERROR_MARK:
9933     case IDENTIFIER_NODE:
9934     case VOID_TYPE:
9935     case REAL_TYPE:
9936     case COMPLEX_TYPE:
9937     case VECTOR_TYPE:
9938     case BOOLEAN_TYPE:
9939     case INTEGER_CST:
9940     case REAL_CST:
9941     case STRING_CST:
9942       return t;
9943
9944     case INTEGER_TYPE:
9945       if (t == integer_type_node)
9946         return t;
9947
9948       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
9949           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
9950         return t;
9951
9952       {
9953         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
9954
9955         max = tsubst_expr (omax, args, complain, in_decl,
9956                            /*integral_constant_expression_p=*/false);
9957
9958         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
9959            needed.  */
9960         if (TREE_CODE (max) == NOP_EXPR
9961             && TREE_SIDE_EFFECTS (omax)
9962             && !TREE_TYPE (max))
9963           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
9964
9965         max = fold_decl_constant_value (max);
9966
9967         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
9968            with TREE_SIDE_EFFECTS that indicates this is not an integral
9969            constant expression.  */
9970         if (processing_template_decl
9971             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
9972           {
9973             gcc_assert (TREE_CODE (max) == NOP_EXPR);
9974             TREE_SIDE_EFFECTS (max) = 1;
9975           }
9976
9977         if (TREE_CODE (max) != INTEGER_CST
9978             && !at_function_scope_p ()
9979             && !TREE_SIDE_EFFECTS (max)
9980             && !value_dependent_expression_p (max))
9981           {
9982             if (complain & tf_error)
9983               error ("array bound is not an integer constant");
9984             return error_mark_node;
9985           }
9986
9987         /* [temp.deduct]
9988
9989            Type deduction may fail for any of the following
9990            reasons:
9991
9992              Attempting to create an array with a size that is
9993              zero or negative.  */
9994         if (integer_zerop (max) && !(complain & tf_error))
9995           /* We must fail if performing argument deduction (as
9996              indicated by the state of complain), so that
9997              another substitution can be found.  */
9998           return error_mark_node;
9999         else if (TREE_CODE (max) == INTEGER_CST
10000                  && INT_CST_LT (max, integer_zero_node))
10001           {
10002             if (complain & tf_error)
10003               error ("creating array with negative size (%qE)", max);
10004
10005             return error_mark_node;
10006           }
10007
10008         return compute_array_index_type (NULL_TREE, max);
10009       }
10010
10011     case TEMPLATE_TYPE_PARM:
10012     case TEMPLATE_TEMPLATE_PARM:
10013     case BOUND_TEMPLATE_TEMPLATE_PARM:
10014     case TEMPLATE_PARM_INDEX:
10015       {
10016         int idx;
10017         int level;
10018         int levels;
10019         tree arg = NULL_TREE;
10020
10021         r = NULL_TREE;
10022
10023         gcc_assert (TREE_VEC_LENGTH (args) > 0);
10024         template_parm_level_and_index (t, &level, &idx); 
10025
10026         levels = TMPL_ARGS_DEPTH (args);
10027         if (level <= levels)
10028           {
10029             arg = TMPL_ARG (args, level, idx);
10030
10031             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
10032               /* See through ARGUMENT_PACK_SELECT arguments. */
10033               arg = ARGUMENT_PACK_SELECT_ARG (arg);
10034           }
10035
10036         if (arg == error_mark_node)
10037           return error_mark_node;
10038         else if (arg != NULL_TREE)
10039           {
10040             if (ARGUMENT_PACK_P (arg))
10041               /* If ARG is an argument pack, we don't actually want to
10042                  perform a substitution here, because substitutions
10043                  for argument packs are only done
10044                  element-by-element. We can get to this point when
10045                  substituting the type of a non-type template
10046                  parameter pack, when that type actually contains
10047                  template parameter packs from an outer template, e.g.,
10048
10049                  template<typename... Types> struct A {
10050                    template<Types... Values> struct B { };
10051                  };  */
10052               return t;
10053
10054             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
10055               {
10056                 int quals;
10057                 gcc_assert (TYPE_P (arg));
10058
10059                 /* cv-quals from the template are discarded when
10060                    substituting in a function or reference type.  */
10061                 if (TREE_CODE (arg) == FUNCTION_TYPE
10062                     || TREE_CODE (arg) == METHOD_TYPE
10063                     || TREE_CODE (arg) == REFERENCE_TYPE)
10064                   quals = cp_type_quals (arg);
10065                 else
10066                   quals = cp_type_quals (arg) | cp_type_quals (t);
10067                   
10068                 return cp_build_qualified_type_real
10069                   (arg, quals, complain | tf_ignore_bad_quals);
10070               }
10071             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10072               {
10073                 /* We are processing a type constructed from a
10074                    template template parameter.  */
10075                 tree argvec = tsubst (TYPE_TI_ARGS (t),
10076                                       args, complain, in_decl);
10077                 if (argvec == error_mark_node)
10078                   return error_mark_node;
10079
10080                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
10081                    are resolving nested-types in the signature of a
10082                    member function templates.  Otherwise ARG is a
10083                    TEMPLATE_DECL and is the real template to be
10084                    instantiated.  */
10085                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
10086                   arg = TYPE_NAME (arg);
10087
10088                 r = lookup_template_class (arg,
10089                                            argvec, in_decl,
10090                                            DECL_CONTEXT (arg),
10091                                             /*entering_scope=*/0,
10092                                            complain);
10093                 return cp_build_qualified_type_real
10094                   (r, TYPE_QUALS (t), complain);
10095               }
10096             else
10097               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
10098               return arg;
10099           }
10100
10101         if (level == 1)
10102           /* This can happen during the attempted tsubst'ing in
10103              unify.  This means that we don't yet have any information
10104              about the template parameter in question.  */
10105           return t;
10106
10107         /* If we get here, we must have been looking at a parm for a
10108            more deeply nested template.  Make a new version of this
10109            template parameter, but with a lower level.  */
10110         switch (TREE_CODE (t))
10111           {
10112           case TEMPLATE_TYPE_PARM:
10113           case TEMPLATE_TEMPLATE_PARM:
10114           case BOUND_TEMPLATE_TEMPLATE_PARM:
10115             if (cp_type_quals (t))
10116               {
10117                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
10118                 r = cp_build_qualified_type_real
10119                   (r, cp_type_quals (t),
10120                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
10121                                ? tf_ignore_bad_quals : 0));
10122               }
10123             else
10124               {
10125                 r = copy_type (t);
10126                 TEMPLATE_TYPE_PARM_INDEX (r)
10127                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
10128                                                 r, levels, args, complain);
10129                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
10130                 TYPE_MAIN_VARIANT (r) = r;
10131                 TYPE_POINTER_TO (r) = NULL_TREE;
10132                 TYPE_REFERENCE_TO (r) = NULL_TREE;
10133
10134                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
10135                   /* We have reduced the level of the template
10136                      template parameter, but not the levels of its
10137                      template parameters, so canonical_type_parameter
10138                      will not be able to find the canonical template
10139                      template parameter for this level. Thus, we
10140                      require structural equality checking to compare
10141                      TEMPLATE_TEMPLATE_PARMs. */
10142                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10143                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
10144                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10145                 else
10146                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
10147
10148                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10149                   {
10150                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
10151                                           complain, in_decl);
10152                     if (argvec == error_mark_node)
10153                       return error_mark_node;
10154
10155                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
10156                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
10157                   }
10158               }
10159             break;
10160
10161           case TEMPLATE_PARM_INDEX:
10162             r = reduce_template_parm_level (t, type, levels, args, complain);
10163             break;
10164
10165           default:
10166             gcc_unreachable ();
10167           }
10168
10169         return r;
10170       }
10171
10172     case TREE_LIST:
10173       {
10174         tree purpose, value, chain;
10175
10176         if (t == void_list_node)
10177           return t;
10178
10179         purpose = TREE_PURPOSE (t);
10180         if (purpose)
10181           {
10182             purpose = tsubst (purpose, args, complain, in_decl);
10183             if (purpose == error_mark_node)
10184               return error_mark_node;
10185           }
10186         value = TREE_VALUE (t);
10187         if (value)
10188           {
10189             value = tsubst (value, args, complain, in_decl);
10190             if (value == error_mark_node)
10191               return error_mark_node;
10192           }
10193         chain = TREE_CHAIN (t);
10194         if (chain && chain != void_type_node)
10195           {
10196             chain = tsubst (chain, args, complain, in_decl);
10197             if (chain == error_mark_node)
10198               return error_mark_node;
10199           }
10200         if (purpose == TREE_PURPOSE (t)
10201             && value == TREE_VALUE (t)
10202             && chain == TREE_CHAIN (t))
10203           return t;
10204         return hash_tree_cons (purpose, value, chain);
10205       }
10206
10207     case TREE_BINFO:
10208       /* We should never be tsubsting a binfo.  */
10209       gcc_unreachable ();
10210
10211     case TREE_VEC:
10212       /* A vector of template arguments.  */
10213       gcc_assert (!type);
10214       return tsubst_template_args (t, args, complain, in_decl);
10215
10216     case POINTER_TYPE:
10217     case REFERENCE_TYPE:
10218       {
10219         enum tree_code code;
10220
10221         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
10222           return t;
10223
10224         code = TREE_CODE (t);
10225
10226
10227         /* [temp.deduct]
10228
10229            Type deduction may fail for any of the following
10230            reasons:
10231
10232            -- Attempting to create a pointer to reference type.
10233            -- Attempting to create a reference to a reference type or
10234               a reference to void.
10235
10236           Core issue 106 says that creating a reference to a reference
10237           during instantiation is no longer a cause for failure. We
10238           only enforce this check in strict C++98 mode.  */
10239         if ((TREE_CODE (type) == REFERENCE_TYPE
10240              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
10241             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
10242           {
10243             static location_t last_loc;
10244
10245             /* We keep track of the last time we issued this error
10246                message to avoid spewing a ton of messages during a
10247                single bad template instantiation.  */
10248             if (complain & tf_error
10249                 && last_loc != input_location)
10250               {
10251                 if (TREE_CODE (type) == VOID_TYPE)
10252                   error ("forming reference to void");
10253                else if (code == POINTER_TYPE)
10254                  error ("forming pointer to reference type %qT", type);
10255                else
10256                   error ("forming reference to reference type %qT", type);
10257                 last_loc = input_location;
10258               }
10259
10260             return error_mark_node;
10261           }
10262         else if (code == POINTER_TYPE)
10263           {
10264             r = build_pointer_type (type);
10265             if (TREE_CODE (type) == METHOD_TYPE)
10266               r = build_ptrmemfunc_type (r);
10267           }
10268         else if (TREE_CODE (type) == REFERENCE_TYPE)
10269           /* In C++0x, during template argument substitution, when there is an
10270              attempt to create a reference to a reference type, reference
10271              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
10272
10273              "If a template-argument for a template-parameter T names a type
10274              that is a reference to a type A, an attempt to create the type
10275              'lvalue reference to cv T' creates the type 'lvalue reference to
10276              A,' while an attempt to create the type type rvalue reference to
10277              cv T' creates the type T"
10278           */
10279           r = cp_build_reference_type
10280               (TREE_TYPE (type),
10281                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
10282         else
10283           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
10284         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
10285
10286         if (r != error_mark_node)
10287           /* Will this ever be needed for TYPE_..._TO values?  */
10288           layout_type (r);
10289
10290         return r;
10291       }
10292     case OFFSET_TYPE:
10293       {
10294         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
10295         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
10296           {
10297             /* [temp.deduct]
10298
10299                Type deduction may fail for any of the following
10300                reasons:
10301
10302                -- Attempting to create "pointer to member of T" when T
10303                   is not a class type.  */
10304             if (complain & tf_error)
10305               error ("creating pointer to member of non-class type %qT", r);
10306             return error_mark_node;
10307           }
10308         if (TREE_CODE (type) == REFERENCE_TYPE)
10309           {
10310             if (complain & tf_error)
10311               error ("creating pointer to member reference type %qT", type);
10312             return error_mark_node;
10313           }
10314         if (TREE_CODE (type) == VOID_TYPE)
10315           {
10316             if (complain & tf_error)
10317               error ("creating pointer to member of type void");
10318             return error_mark_node;
10319           }
10320         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
10321         if (TREE_CODE (type) == FUNCTION_TYPE)
10322           {
10323             /* The type of the implicit object parameter gets its
10324                cv-qualifiers from the FUNCTION_TYPE. */
10325             tree memptr;
10326             tree method_type = build_memfn_type (type, r, cp_type_quals (type));
10327             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
10328             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
10329                                                  complain);
10330           }
10331         else
10332           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
10333                                                TYPE_QUALS (t),
10334                                                complain);
10335       }
10336     case FUNCTION_TYPE:
10337     case METHOD_TYPE:
10338       {
10339         tree fntype;
10340         tree specs;
10341         fntype = tsubst_function_type (t, args, complain, in_decl);
10342         if (fntype == error_mark_node)
10343           return error_mark_node;
10344
10345         /* Substitute the exception specification.  */
10346         specs = tsubst_exception_specification (t, args, complain,
10347                                                 in_decl);
10348         if (specs == error_mark_node)
10349           return error_mark_node;
10350         if (specs)
10351           fntype = build_exception_variant (fntype, specs);
10352         return fntype;
10353       }
10354     case ARRAY_TYPE:
10355       {
10356         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
10357         if (domain == error_mark_node)
10358           return error_mark_node;
10359
10360         /* As an optimization, we avoid regenerating the array type if
10361            it will obviously be the same as T.  */
10362         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
10363           return t;
10364
10365         /* These checks should match the ones in grokdeclarator.
10366
10367            [temp.deduct]
10368
10369            The deduction may fail for any of the following reasons:
10370
10371            -- Attempting to create an array with an element type that
10372               is void, a function type, or a reference type, or [DR337]
10373               an abstract class type.  */
10374         if (TREE_CODE (type) == VOID_TYPE
10375             || TREE_CODE (type) == FUNCTION_TYPE
10376             || TREE_CODE (type) == REFERENCE_TYPE)
10377           {
10378             if (complain & tf_error)
10379               error ("creating array of %qT", type);
10380             return error_mark_node;
10381           }
10382         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
10383           {
10384             if (complain & tf_error)
10385               error ("creating array of %qT, which is an abstract class type",
10386                      type);
10387             return error_mark_node;
10388           }
10389
10390         r = build_cplus_array_type (type, domain);
10391
10392         if (TYPE_USER_ALIGN (t))
10393           {
10394             TYPE_ALIGN (r) = TYPE_ALIGN (t);
10395             TYPE_USER_ALIGN (r) = 1;
10396           }
10397
10398         return r;
10399       }
10400
10401     case PLUS_EXPR:
10402     case MINUS_EXPR:
10403       {
10404         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10405         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10406
10407         if (e1 == error_mark_node || e2 == error_mark_node)
10408           return error_mark_node;
10409
10410         return fold_build2_loc (input_location,
10411                             TREE_CODE (t), TREE_TYPE (t), e1, e2);
10412       }
10413
10414     case NEGATE_EXPR:
10415     case NOP_EXPR:
10416       {
10417         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10418         if (e == error_mark_node)
10419           return error_mark_node;
10420
10421         return fold_build1_loc (input_location, TREE_CODE (t), TREE_TYPE (t), e);
10422       }
10423
10424     case TYPENAME_TYPE:
10425       {
10426         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10427                                      in_decl, /*entering_scope=*/1);
10428         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
10429                               complain, in_decl);
10430
10431         if (ctx == error_mark_node || f == error_mark_node)
10432           return error_mark_node;
10433
10434         if (!MAYBE_CLASS_TYPE_P (ctx))
10435           {
10436             if (complain & tf_error)
10437               error ("%qT is not a class, struct, or union type", ctx);
10438             return error_mark_node;
10439           }
10440         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
10441           {
10442             /* Normally, make_typename_type does not require that the CTX
10443                have complete type in order to allow things like:
10444
10445                  template <class T> struct S { typename S<T>::X Y; };
10446
10447                But, such constructs have already been resolved by this
10448                point, so here CTX really should have complete type, unless
10449                it's a partial instantiation.  */
10450             if (!(complain & tf_no_class_instantiations))
10451               ctx = complete_type (ctx);
10452             if (!COMPLETE_TYPE_P (ctx))
10453               {
10454                 if (complain & tf_error)
10455                   cxx_incomplete_type_error (NULL_TREE, ctx);
10456                 return error_mark_node;
10457               }
10458           }
10459
10460         f = make_typename_type (ctx, f, typename_type,
10461                                 (complain & tf_error) | tf_keep_type_decl);
10462         if (f == error_mark_node)
10463           return f;
10464         if (TREE_CODE (f) == TYPE_DECL)
10465           {
10466             complain |= tf_ignore_bad_quals;
10467             f = TREE_TYPE (f);
10468           }
10469
10470         if (TREE_CODE (f) != TYPENAME_TYPE)
10471           {
10472             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
10473               error ("%qT resolves to %qT, which is not an enumeration type",
10474                      t, f);
10475             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
10476               error ("%qT resolves to %qT, which is is not a class type",
10477                      t, f);
10478           }
10479
10480         return cp_build_qualified_type_real
10481           (f, cp_type_quals (f) | cp_type_quals (t), complain);
10482       }
10483
10484     case UNBOUND_CLASS_TEMPLATE:
10485       {
10486         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10487                                      in_decl, /*entering_scope=*/1);
10488         tree name = TYPE_IDENTIFIER (t);
10489         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
10490
10491         if (ctx == error_mark_node || name == error_mark_node)
10492           return error_mark_node;
10493
10494         if (parm_list)
10495           parm_list = tsubst_template_parms (parm_list, args, complain);
10496         return make_unbound_class_template (ctx, name, parm_list, complain);
10497       }
10498
10499     case INDIRECT_REF:
10500     case ADDR_EXPR:
10501     case CALL_EXPR:
10502       gcc_unreachable ();
10503
10504     case ARRAY_REF:
10505       {
10506         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10507         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
10508                                /*integral_constant_expression_p=*/false);
10509         if (e1 == error_mark_node || e2 == error_mark_node)
10510           return error_mark_node;
10511
10512         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
10513       }
10514
10515     case SCOPE_REF:
10516       {
10517         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10518         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10519         if (e1 == error_mark_node || e2 == error_mark_node)
10520           return error_mark_node;
10521
10522         return build_qualified_name (/*type=*/NULL_TREE,
10523                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
10524       }
10525
10526     case TYPEOF_TYPE:
10527       {
10528         tree type;
10529
10530         ++cp_unevaluated_operand;
10531         ++c_inhibit_evaluation_warnings;
10532
10533         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
10534                             complain, in_decl,
10535                             /*integral_constant_expression_p=*/false);
10536
10537         --cp_unevaluated_operand;
10538         --c_inhibit_evaluation_warnings;
10539
10540         type = finish_typeof (type);
10541         return cp_build_qualified_type_real (type,
10542                                              cp_type_quals (t)
10543                                              | cp_type_quals (type),
10544                                              complain);
10545       }
10546
10547     case DECLTYPE_TYPE:
10548       {
10549         tree type;
10550
10551         ++cp_unevaluated_operand;
10552         ++c_inhibit_evaluation_warnings;
10553
10554         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
10555                             complain, in_decl,
10556                             /*integral_constant_expression_p=*/false);
10557
10558         --cp_unevaluated_operand;
10559         --c_inhibit_evaluation_warnings;
10560
10561         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
10562           type = lambda_capture_field_type (type);
10563         else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
10564           type = lambda_return_type (type);
10565         else
10566           type = finish_decltype_type
10567             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
10568         return cp_build_qualified_type_real (type,
10569                                              cp_type_quals (t)
10570                                              | cp_type_quals (type),
10571                                              complain);
10572       }
10573
10574     case TYPE_ARGUMENT_PACK:
10575     case NONTYPE_ARGUMENT_PACK:
10576       {
10577         tree r = TYPE_P (t)
10578           ? cxx_make_type (TREE_CODE (t))
10579           : make_node (TREE_CODE (t));
10580         tree packed_out = 
10581           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
10582                                 args,
10583                                 complain,
10584                                 in_decl);
10585         SET_ARGUMENT_PACK_ARGS (r, packed_out);
10586
10587         /* For template nontype argument packs, also substitute into
10588            the type.  */
10589         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
10590           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
10591
10592         return r;
10593       }
10594       break;
10595
10596     default:
10597       sorry ("use of %qs in template",
10598              tree_code_name [(int) TREE_CODE (t)]);
10599       return error_mark_node;
10600     }
10601 }
10602
10603 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
10604    type of the expression on the left-hand side of the "." or "->"
10605    operator.  */
10606
10607 static tree
10608 tsubst_baselink (tree baselink, tree object_type,
10609                  tree args, tsubst_flags_t complain, tree in_decl)
10610 {
10611     tree name;
10612     tree qualifying_scope;
10613     tree fns;
10614     tree optype;
10615     tree template_args = 0;
10616     bool template_id_p = false;
10617
10618     /* A baselink indicates a function from a base class.  Both the
10619        BASELINK_ACCESS_BINFO and the base class referenced may
10620        indicate bases of the template class, rather than the
10621        instantiated class.  In addition, lookups that were not
10622        ambiguous before may be ambiguous now.  Therefore, we perform
10623        the lookup again.  */
10624     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
10625     qualifying_scope = tsubst (qualifying_scope, args,
10626                                complain, in_decl);
10627     fns = BASELINK_FUNCTIONS (baselink);
10628     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
10629     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
10630       {
10631         template_id_p = true;
10632         template_args = TREE_OPERAND (fns, 1);
10633         fns = TREE_OPERAND (fns, 0);
10634         if (template_args)
10635           template_args = tsubst_template_args (template_args, args,
10636                                                 complain, in_decl);
10637       }
10638     name = DECL_NAME (get_first_fn (fns));
10639     if (IDENTIFIER_TYPENAME_P (name))
10640       name = mangle_conv_op_name_for_type (optype);
10641     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
10642
10643     /* If lookup found a single function, mark it as used at this
10644        point.  (If it lookup found multiple functions the one selected
10645        later by overload resolution will be marked as used at that
10646        point.)  */
10647     if (BASELINK_P (baselink))
10648       fns = BASELINK_FUNCTIONS (baselink);
10649     if (!template_id_p && !really_overloaded_fn (fns))
10650       mark_used (OVL_CURRENT (fns));
10651
10652     /* Add back the template arguments, if present.  */
10653     if (BASELINK_P (baselink) && template_id_p)
10654       BASELINK_FUNCTIONS (baselink)
10655         = build_nt (TEMPLATE_ID_EXPR,
10656                     BASELINK_FUNCTIONS (baselink),
10657                     template_args);
10658     /* Update the conversion operator type.  */
10659     BASELINK_OPTYPE (baselink) = optype;
10660
10661     if (!object_type)
10662       object_type = current_class_type;
10663     return adjust_result_of_qualified_name_lookup (baselink,
10664                                                    qualifying_scope,
10665                                                    object_type);
10666 }
10667
10668 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
10669    true if the qualified-id will be a postfix-expression in-and-of
10670    itself; false if more of the postfix-expression follows the
10671    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
10672    of "&".  */
10673
10674 static tree
10675 tsubst_qualified_id (tree qualified_id, tree args,
10676                      tsubst_flags_t complain, tree in_decl,
10677                      bool done, bool address_p)
10678 {
10679   tree expr;
10680   tree scope;
10681   tree name;
10682   bool is_template;
10683   tree template_args;
10684
10685   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
10686
10687   /* Figure out what name to look up.  */
10688   name = TREE_OPERAND (qualified_id, 1);
10689   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
10690     {
10691       is_template = true;
10692       template_args = TREE_OPERAND (name, 1);
10693       if (template_args)
10694         template_args = tsubst_template_args (template_args, args,
10695                                               complain, in_decl);
10696       name = TREE_OPERAND (name, 0);
10697     }
10698   else
10699     {
10700       is_template = false;
10701       template_args = NULL_TREE;
10702     }
10703
10704   /* Substitute into the qualifying scope.  When there are no ARGS, we
10705      are just trying to simplify a non-dependent expression.  In that
10706      case the qualifying scope may be dependent, and, in any case,
10707      substituting will not help.  */
10708   scope = TREE_OPERAND (qualified_id, 0);
10709   if (args)
10710     {
10711       scope = tsubst (scope, args, complain, in_decl);
10712       expr = tsubst_copy (name, args, complain, in_decl);
10713     }
10714   else
10715     expr = name;
10716
10717   if (dependent_scope_p (scope))
10718     return build_qualified_name (NULL_TREE, scope, expr,
10719                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
10720
10721   if (!BASELINK_P (name) && !DECL_P (expr))
10722     {
10723       if (TREE_CODE (expr) == BIT_NOT_EXPR)
10724         {
10725           /* A BIT_NOT_EXPR is used to represent a destructor.  */
10726           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
10727             {
10728               error ("qualifying type %qT does not match destructor name ~%qT",
10729                      scope, TREE_OPERAND (expr, 0));
10730               expr = error_mark_node;
10731             }
10732           else
10733             expr = lookup_qualified_name (scope, complete_dtor_identifier,
10734                                           /*is_type_p=*/0, false);
10735         }
10736       else
10737         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
10738       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
10739                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
10740         {
10741           if (complain & tf_error)
10742             {
10743               error ("dependent-name %qE is parsed as a non-type, but "
10744                      "instantiation yields a type", qualified_id);
10745               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
10746             }
10747           return error_mark_node;
10748         }
10749     }
10750
10751   if (DECL_P (expr))
10752     {
10753       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
10754                                            scope);
10755       /* Remember that there was a reference to this entity.  */
10756       mark_used (expr);
10757     }
10758
10759   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
10760     {
10761       if (complain & tf_error)
10762         qualified_name_lookup_error (scope,
10763                                      TREE_OPERAND (qualified_id, 1),
10764                                      expr, input_location);
10765       return error_mark_node;
10766     }
10767
10768   if (is_template)
10769     expr = lookup_template_function (expr, template_args);
10770
10771   if (expr == error_mark_node && complain & tf_error)
10772     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
10773                                  expr, input_location);
10774   else if (TYPE_P (scope))
10775     {
10776       expr = (adjust_result_of_qualified_name_lookup
10777               (expr, scope, current_class_type));
10778       expr = (finish_qualified_id_expr
10779               (scope, expr, done, address_p,
10780                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
10781                /*template_arg_p=*/false));
10782     }
10783
10784   /* Expressions do not generally have reference type.  */
10785   if (TREE_CODE (expr) != SCOPE_REF
10786       /* However, if we're about to form a pointer-to-member, we just
10787          want the referenced member referenced.  */
10788       && TREE_CODE (expr) != OFFSET_REF)
10789     expr = convert_from_reference (expr);
10790
10791   return expr;
10792 }
10793
10794 /* Like tsubst, but deals with expressions.  This function just replaces
10795    template parms; to finish processing the resultant expression, use
10796    tsubst_expr.  */
10797
10798 static tree
10799 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10800 {
10801   enum tree_code code;
10802   tree r;
10803
10804   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
10805     return t;
10806
10807   code = TREE_CODE (t);
10808
10809   switch (code)
10810     {
10811     case PARM_DECL:
10812       r = retrieve_local_specialization (t);
10813
10814       if (r == NULL)
10815         {
10816           tree c;
10817           /* This can happen for a parameter name used later in a function
10818              declaration (such as in a late-specified return type).  Just
10819              make a dummy decl, since it's only used for its type.  */
10820           gcc_assert (cp_unevaluated_operand != 0);
10821           /* We copy T because want to tsubst the PARM_DECL only,
10822              not the following PARM_DECLs that are chained to T.  */
10823           c = copy_node (t);
10824           r = tsubst_decl (c, args, complain);
10825           /* Give it the template pattern as its context; its true context
10826              hasn't been instantiated yet and this is good enough for
10827              mangling.  */
10828           DECL_CONTEXT (r) = DECL_CONTEXT (t);
10829         }
10830       
10831       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10832         r = ARGUMENT_PACK_SELECT_ARG (r);
10833       mark_used (r);
10834       return r;
10835
10836     case CONST_DECL:
10837       {
10838         tree enum_type;
10839         tree v;
10840
10841         if (DECL_TEMPLATE_PARM_P (t))
10842           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10843         /* There is no need to substitute into namespace-scope
10844            enumerators.  */
10845         if (DECL_NAMESPACE_SCOPE_P (t))
10846           return t;
10847         /* If ARGS is NULL, then T is known to be non-dependent.  */
10848         if (args == NULL_TREE)
10849           return integral_constant_value (t);
10850
10851         /* Unfortunately, we cannot just call lookup_name here.
10852            Consider:
10853
10854              template <int I> int f() {
10855              enum E { a = I };
10856              struct S { void g() { E e = a; } };
10857              };
10858
10859            When we instantiate f<7>::S::g(), say, lookup_name is not
10860            clever enough to find f<7>::a.  */
10861         enum_type
10862           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10863                               /*entering_scope=*/0);
10864
10865         for (v = TYPE_VALUES (enum_type);
10866              v != NULL_TREE;
10867              v = TREE_CHAIN (v))
10868           if (TREE_PURPOSE (v) == DECL_NAME (t))
10869             return TREE_VALUE (v);
10870
10871           /* We didn't find the name.  That should never happen; if
10872              name-lookup found it during preliminary parsing, we
10873              should find it again here during instantiation.  */
10874         gcc_unreachable ();
10875       }
10876       return t;
10877
10878     case FIELD_DECL:
10879       if (DECL_CONTEXT (t))
10880         {
10881           tree ctx;
10882
10883           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
10884                                   /*entering_scope=*/1);
10885           if (ctx != DECL_CONTEXT (t))
10886             {
10887               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
10888               if (!r)
10889                 {
10890                   if (complain & tf_error)
10891                     error ("using invalid field %qD", t);
10892                   return error_mark_node;
10893                 }
10894               return r;
10895             }
10896         }
10897
10898       return t;
10899
10900     case VAR_DECL:
10901     case FUNCTION_DECL:
10902       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10903           || local_variable_p (t))
10904         t = tsubst (t, args, complain, in_decl);
10905       mark_used (t);
10906       return t;
10907
10908     case BASELINK:
10909       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
10910
10911     case TEMPLATE_DECL:
10912       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10913         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
10914                        args, complain, in_decl);
10915       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
10916         return tsubst (t, args, complain, in_decl);
10917       else if (DECL_CLASS_SCOPE_P (t)
10918                && uses_template_parms (DECL_CONTEXT (t)))
10919         {
10920           /* Template template argument like the following example need
10921              special treatment:
10922
10923                template <template <class> class TT> struct C {};
10924                template <class T> struct D {
10925                  template <class U> struct E {};
10926                  C<E> c;                                // #1
10927                };
10928                D<int> d;                                // #2
10929
10930              We are processing the template argument `E' in #1 for
10931              the template instantiation #2.  Originally, `E' is a
10932              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
10933              have to substitute this with one having context `D<int>'.  */
10934
10935           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
10936           return lookup_field (context, DECL_NAME(t), 0, false);
10937         }
10938       else
10939         /* Ordinary template template argument.  */
10940         return t;
10941
10942     case CAST_EXPR:
10943     case REINTERPRET_CAST_EXPR:
10944     case CONST_CAST_EXPR:
10945     case STATIC_CAST_EXPR:
10946     case DYNAMIC_CAST_EXPR:
10947     case NOP_EXPR:
10948       return build1
10949         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10950          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10951
10952     case SIZEOF_EXPR:
10953       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10954         {
10955           /* We only want to compute the number of arguments.  */
10956           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
10957                                                 complain, in_decl);
10958           int len = 0;
10959
10960           if (TREE_CODE (expanded) == TREE_VEC)
10961             len = TREE_VEC_LENGTH (expanded);
10962
10963           if (expanded == error_mark_node)
10964             return error_mark_node;
10965           else if (PACK_EXPANSION_P (expanded)
10966                    || (TREE_CODE (expanded) == TREE_VEC
10967                        && len > 0
10968                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
10969             {
10970               if (TREE_CODE (expanded) == TREE_VEC)
10971                 expanded = TREE_VEC_ELT (expanded, len - 1);
10972
10973               if (TYPE_P (expanded))
10974                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
10975                                                    complain & tf_error);
10976               else
10977                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
10978                                                    complain & tf_error);
10979             }
10980           else
10981             return build_int_cst (size_type_node, len);
10982         }
10983       /* Fall through */
10984
10985     case INDIRECT_REF:
10986     case NEGATE_EXPR:
10987     case TRUTH_NOT_EXPR:
10988     case BIT_NOT_EXPR:
10989     case ADDR_EXPR:
10990     case UNARY_PLUS_EXPR:      /* Unary + */
10991     case ALIGNOF_EXPR:
10992     case ARROW_EXPR:
10993     case THROW_EXPR:
10994     case TYPEID_EXPR:
10995     case REALPART_EXPR:
10996     case IMAGPART_EXPR:
10997       return build1
10998         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10999          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11000
11001     case COMPONENT_REF:
11002       {
11003         tree object;
11004         tree name;
11005
11006         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
11007         name = TREE_OPERAND (t, 1);
11008         if (TREE_CODE (name) == BIT_NOT_EXPR)
11009           {
11010             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11011                                 complain, in_decl);
11012             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11013           }
11014         else if (TREE_CODE (name) == SCOPE_REF
11015                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
11016           {
11017             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
11018                                      complain, in_decl);
11019             name = TREE_OPERAND (name, 1);
11020             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11021                                 complain, in_decl);
11022             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11023             name = build_qualified_name (/*type=*/NULL_TREE,
11024                                          base, name,
11025                                          /*template_p=*/false);
11026           }
11027         else if (TREE_CODE (name) == BASELINK)
11028           name = tsubst_baselink (name,
11029                                   non_reference (TREE_TYPE (object)),
11030                                   args, complain,
11031                                   in_decl);
11032         else
11033           name = tsubst_copy (name, args, complain, in_decl);
11034         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
11035       }
11036
11037     case PLUS_EXPR:
11038     case MINUS_EXPR:
11039     case MULT_EXPR:
11040     case TRUNC_DIV_EXPR:
11041     case CEIL_DIV_EXPR:
11042     case FLOOR_DIV_EXPR:
11043     case ROUND_DIV_EXPR:
11044     case EXACT_DIV_EXPR:
11045     case BIT_AND_EXPR:
11046     case BIT_IOR_EXPR:
11047     case BIT_XOR_EXPR:
11048     case TRUNC_MOD_EXPR:
11049     case FLOOR_MOD_EXPR:
11050     case TRUTH_ANDIF_EXPR:
11051     case TRUTH_ORIF_EXPR:
11052     case TRUTH_AND_EXPR:
11053     case TRUTH_OR_EXPR:
11054     case RSHIFT_EXPR:
11055     case LSHIFT_EXPR:
11056     case RROTATE_EXPR:
11057     case LROTATE_EXPR:
11058     case EQ_EXPR:
11059     case NE_EXPR:
11060     case MAX_EXPR:
11061     case MIN_EXPR:
11062     case LE_EXPR:
11063     case GE_EXPR:
11064     case LT_EXPR:
11065     case GT_EXPR:
11066     case COMPOUND_EXPR:
11067     case DOTSTAR_EXPR:
11068     case MEMBER_REF:
11069     case PREDECREMENT_EXPR:
11070     case PREINCREMENT_EXPR:
11071     case POSTDECREMENT_EXPR:
11072     case POSTINCREMENT_EXPR:
11073       return build_nt
11074         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11075          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11076
11077     case SCOPE_REF:
11078       return build_qualified_name (/*type=*/NULL_TREE,
11079                                    tsubst_copy (TREE_OPERAND (t, 0),
11080                                                 args, complain, in_decl),
11081                                    tsubst_copy (TREE_OPERAND (t, 1),
11082                                                 args, complain, in_decl),
11083                                    QUALIFIED_NAME_IS_TEMPLATE (t));
11084
11085     case ARRAY_REF:
11086       return build_nt
11087         (ARRAY_REF,
11088          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11089          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11090          NULL_TREE, NULL_TREE);
11091
11092     case CALL_EXPR:
11093       {
11094         int n = VL_EXP_OPERAND_LENGTH (t);
11095         tree result = build_vl_exp (CALL_EXPR, n);
11096         int i;
11097         for (i = 0; i < n; i++)
11098           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
11099                                              complain, in_decl);
11100         return result;
11101       }
11102
11103     case COND_EXPR:
11104     case MODOP_EXPR:
11105     case PSEUDO_DTOR_EXPR:
11106       {
11107         r = build_nt
11108           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11109            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11110            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11111         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11112         return r;
11113       }
11114
11115     case NEW_EXPR:
11116       {
11117         r = build_nt
11118         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11119          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11120          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11121         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
11122         return r;
11123       }
11124
11125     case DELETE_EXPR:
11126       {
11127         r = build_nt
11128         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11129          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11130         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
11131         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
11132         return r;
11133       }
11134
11135     case TEMPLATE_ID_EXPR:
11136       {
11137         /* Substituted template arguments */
11138         tree fn = TREE_OPERAND (t, 0);
11139         tree targs = TREE_OPERAND (t, 1);
11140
11141         fn = tsubst_copy (fn, args, complain, in_decl);
11142         if (targs)
11143           targs = tsubst_template_args (targs, args, complain, in_decl);
11144
11145         return lookup_template_function (fn, targs);
11146       }
11147
11148     case TREE_LIST:
11149       {
11150         tree purpose, value, chain;
11151
11152         if (t == void_list_node)
11153           return t;
11154
11155         purpose = TREE_PURPOSE (t);
11156         if (purpose)
11157           purpose = tsubst_copy (purpose, args, complain, in_decl);
11158         value = TREE_VALUE (t);
11159         if (value)
11160           value = tsubst_copy (value, args, complain, in_decl);
11161         chain = TREE_CHAIN (t);
11162         if (chain && chain != void_type_node)
11163           chain = tsubst_copy (chain, args, complain, in_decl);
11164         if (purpose == TREE_PURPOSE (t)
11165             && value == TREE_VALUE (t)
11166             && chain == TREE_CHAIN (t))
11167           return t;
11168         return tree_cons (purpose, value, chain);
11169       }
11170
11171     case RECORD_TYPE:
11172     case UNION_TYPE:
11173     case ENUMERAL_TYPE:
11174     case INTEGER_TYPE:
11175     case TEMPLATE_TYPE_PARM:
11176     case TEMPLATE_TEMPLATE_PARM:
11177     case BOUND_TEMPLATE_TEMPLATE_PARM:
11178     case TEMPLATE_PARM_INDEX:
11179     case POINTER_TYPE:
11180     case REFERENCE_TYPE:
11181     case OFFSET_TYPE:
11182     case FUNCTION_TYPE:
11183     case METHOD_TYPE:
11184     case ARRAY_TYPE:
11185     case TYPENAME_TYPE:
11186     case UNBOUND_CLASS_TEMPLATE:
11187     case TYPEOF_TYPE:
11188     case DECLTYPE_TYPE:
11189     case TYPE_DECL:
11190       return tsubst (t, args, complain, in_decl);
11191
11192     case IDENTIFIER_NODE:
11193       if (IDENTIFIER_TYPENAME_P (t))
11194         {
11195           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11196           return mangle_conv_op_name_for_type (new_type);
11197         }
11198       else
11199         return t;
11200
11201     case CONSTRUCTOR:
11202       /* This is handled by tsubst_copy_and_build.  */
11203       gcc_unreachable ();
11204
11205     case VA_ARG_EXPR:
11206       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
11207                                           in_decl),
11208                              tsubst (TREE_TYPE (t), args, complain, in_decl));
11209
11210     case CLEANUP_POINT_EXPR:
11211       /* We shouldn't have built any of these during initial template
11212          generation.  Instead, they should be built during instantiation
11213          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
11214       gcc_unreachable ();
11215
11216     case OFFSET_REF:
11217       mark_used (TREE_OPERAND (t, 1));
11218       return t;
11219
11220     case EXPR_PACK_EXPANSION:
11221       error ("invalid use of pack expansion expression");
11222       return error_mark_node;
11223
11224     case NONTYPE_ARGUMENT_PACK:
11225       error ("use %<...%> to expand argument pack");
11226       return error_mark_node;
11227
11228     default:
11229       return t;
11230     }
11231 }
11232
11233 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
11234
11235 static tree
11236 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
11237                     tree in_decl)
11238 {
11239   tree new_clauses = NULL, nc, oc;
11240
11241   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
11242     {
11243       nc = copy_node (oc);
11244       OMP_CLAUSE_CHAIN (nc) = new_clauses;
11245       new_clauses = nc;
11246
11247       switch (OMP_CLAUSE_CODE (nc))
11248         {
11249         case OMP_CLAUSE_LASTPRIVATE:
11250           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
11251             {
11252               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
11253               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
11254                            in_decl, /*integral_constant_expression_p=*/false);
11255               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
11256                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
11257             }
11258           /* FALLTHRU */
11259         case OMP_CLAUSE_PRIVATE:
11260         case OMP_CLAUSE_SHARED:
11261         case OMP_CLAUSE_FIRSTPRIVATE:
11262         case OMP_CLAUSE_REDUCTION:
11263         case OMP_CLAUSE_COPYIN:
11264         case OMP_CLAUSE_COPYPRIVATE:
11265         case OMP_CLAUSE_IF:
11266         case OMP_CLAUSE_NUM_THREADS:
11267         case OMP_CLAUSE_SCHEDULE:
11268         case OMP_CLAUSE_COLLAPSE:
11269           OMP_CLAUSE_OPERAND (nc, 0)
11270             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
11271                            in_decl, /*integral_constant_expression_p=*/false);
11272           break;
11273         case OMP_CLAUSE_NOWAIT:
11274         case OMP_CLAUSE_ORDERED:
11275         case OMP_CLAUSE_DEFAULT:
11276         case OMP_CLAUSE_UNTIED:
11277           break;
11278         default:
11279           gcc_unreachable ();
11280         }
11281     }
11282
11283   return finish_omp_clauses (nreverse (new_clauses));
11284 }
11285
11286 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
11287
11288 static tree
11289 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
11290                           tree in_decl)
11291 {
11292 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
11293
11294   tree purpose, value, chain;
11295
11296   if (t == NULL)
11297     return t;
11298
11299   if (TREE_CODE (t) != TREE_LIST)
11300     return tsubst_copy_and_build (t, args, complain, in_decl,
11301                                   /*function_p=*/false,
11302                                   /*integral_constant_expression_p=*/false);
11303
11304   if (t == void_list_node)
11305     return t;
11306
11307   purpose = TREE_PURPOSE (t);
11308   if (purpose)
11309     purpose = RECUR (purpose);
11310   value = TREE_VALUE (t);
11311   if (value && TREE_CODE (value) != LABEL_DECL)
11312     value = RECUR (value);
11313   chain = TREE_CHAIN (t);
11314   if (chain && chain != void_type_node)
11315     chain = RECUR (chain);
11316   return tree_cons (purpose, value, chain);
11317 #undef RECUR
11318 }
11319
11320 /* Substitute one OMP_FOR iterator.  */
11321
11322 static void
11323 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
11324                          tree condv, tree incrv, tree *clauses,
11325                          tree args, tsubst_flags_t complain, tree in_decl,
11326                          bool integral_constant_expression_p)
11327 {
11328 #define RECUR(NODE)                             \
11329   tsubst_expr ((NODE), args, complain, in_decl, \
11330                integral_constant_expression_p)
11331   tree decl, init, cond, incr, auto_node;
11332
11333   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
11334   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
11335   decl = RECUR (TREE_OPERAND (init, 0));
11336   init = TREE_OPERAND (init, 1);
11337   auto_node = type_uses_auto (TREE_TYPE (decl));
11338   if (auto_node && init)
11339     {
11340       tree init_expr = init;
11341       if (TREE_CODE (init_expr) == DECL_EXPR)
11342         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
11343       init_expr = RECUR (init_expr);
11344       TREE_TYPE (decl)
11345         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
11346     }
11347   gcc_assert (!type_dependent_expression_p (decl));
11348
11349   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
11350     {
11351       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
11352       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11353       if (TREE_CODE (incr) == MODIFY_EXPR)
11354         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
11355                                     RECUR (TREE_OPERAND (incr, 1)),
11356                                     complain);
11357       else
11358         incr = RECUR (incr);
11359       TREE_VEC_ELT (declv, i) = decl;
11360       TREE_VEC_ELT (initv, i) = init;
11361       TREE_VEC_ELT (condv, i) = cond;
11362       TREE_VEC_ELT (incrv, i) = incr;
11363       return;
11364     }
11365
11366   if (init && TREE_CODE (init) != DECL_EXPR)
11367     {
11368       tree c;
11369       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
11370         {
11371           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
11372                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
11373               && OMP_CLAUSE_DECL (c) == decl)
11374             break;
11375           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
11376                    && OMP_CLAUSE_DECL (c) == decl)
11377             error ("iteration variable %qD should not be firstprivate", decl);
11378           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
11379                    && OMP_CLAUSE_DECL (c) == decl)
11380             error ("iteration variable %qD should not be reduction", decl);
11381         }
11382       if (c == NULL)
11383         {
11384           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
11385           OMP_CLAUSE_DECL (c) = decl;
11386           c = finish_omp_clauses (c);
11387           if (c)
11388             {
11389               OMP_CLAUSE_CHAIN (c) = *clauses;
11390               *clauses = c;
11391             }
11392         }
11393     }
11394   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
11395   if (COMPARISON_CLASS_P (cond))
11396     cond = build2 (TREE_CODE (cond), boolean_type_node,
11397                    RECUR (TREE_OPERAND (cond, 0)),
11398                    RECUR (TREE_OPERAND (cond, 1)));
11399   else
11400     cond = RECUR (cond);
11401   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11402   switch (TREE_CODE (incr))
11403     {
11404     case PREINCREMENT_EXPR:
11405     case PREDECREMENT_EXPR:
11406     case POSTINCREMENT_EXPR:
11407     case POSTDECREMENT_EXPR:
11408       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
11409                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
11410       break;
11411     case MODIFY_EXPR:
11412       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11413           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11414         {
11415           tree rhs = TREE_OPERAND (incr, 1);
11416           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11417                          RECUR (TREE_OPERAND (incr, 0)),
11418                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11419                                  RECUR (TREE_OPERAND (rhs, 0)),
11420                                  RECUR (TREE_OPERAND (rhs, 1))));
11421         }
11422       else
11423         incr = RECUR (incr);
11424       break;
11425     case MODOP_EXPR:
11426       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11427           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11428         {
11429           tree lhs = RECUR (TREE_OPERAND (incr, 0));
11430           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
11431                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
11432                                  TREE_TYPE (decl), lhs,
11433                                  RECUR (TREE_OPERAND (incr, 2))));
11434         }
11435       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
11436                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
11437                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
11438         {
11439           tree rhs = TREE_OPERAND (incr, 2);
11440           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11441                          RECUR (TREE_OPERAND (incr, 0)),
11442                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11443                                  RECUR (TREE_OPERAND (rhs, 0)),
11444                                  RECUR (TREE_OPERAND (rhs, 1))));
11445         }
11446       else
11447         incr = RECUR (incr);
11448       break;
11449     default:
11450       incr = RECUR (incr);
11451       break;
11452     }
11453
11454   TREE_VEC_ELT (declv, i) = decl;
11455   TREE_VEC_ELT (initv, i) = init;
11456   TREE_VEC_ELT (condv, i) = cond;
11457   TREE_VEC_ELT (incrv, i) = incr;
11458 #undef RECUR
11459 }
11460
11461 /* Like tsubst_copy for expressions, etc. but also does semantic
11462    processing.  */
11463
11464 static tree
11465 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
11466              bool integral_constant_expression_p)
11467 {
11468 #define RECUR(NODE)                             \
11469   tsubst_expr ((NODE), args, complain, in_decl, \
11470                integral_constant_expression_p)
11471
11472   tree stmt, tmp;
11473
11474   if (t == NULL_TREE || t == error_mark_node)
11475     return t;
11476
11477   if (EXPR_HAS_LOCATION (t))
11478     input_location = EXPR_LOCATION (t);
11479   if (STATEMENT_CODE_P (TREE_CODE (t)))
11480     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
11481
11482   switch (TREE_CODE (t))
11483     {
11484     case STATEMENT_LIST:
11485       {
11486         tree_stmt_iterator i;
11487         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
11488           RECUR (tsi_stmt (i));
11489         break;
11490       }
11491
11492     case CTOR_INITIALIZER:
11493       finish_mem_initializers (tsubst_initializer_list
11494                                (TREE_OPERAND (t, 0), args));
11495       break;
11496
11497     case RETURN_EXPR:
11498       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
11499       break;
11500
11501     case EXPR_STMT:
11502       tmp = RECUR (EXPR_STMT_EXPR (t));
11503       if (EXPR_STMT_STMT_EXPR_RESULT (t))
11504         finish_stmt_expr_expr (tmp, cur_stmt_expr);
11505       else
11506         finish_expr_stmt (tmp);
11507       break;
11508
11509     case USING_STMT:
11510       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
11511       break;
11512
11513     case DECL_EXPR:
11514       {
11515         tree decl;
11516         tree init;
11517
11518         decl = DECL_EXPR_DECL (t);
11519         if (TREE_CODE (decl) == LABEL_DECL)
11520           finish_label_decl (DECL_NAME (decl));
11521         else if (TREE_CODE (decl) == USING_DECL)
11522           {
11523             tree scope = USING_DECL_SCOPE (decl);
11524             tree name = DECL_NAME (decl);
11525             tree decl;
11526
11527             scope = RECUR (scope);
11528             decl = lookup_qualified_name (scope, name,
11529                                           /*is_type_p=*/false,
11530                                           /*complain=*/false);
11531             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
11532               qualified_name_lookup_error (scope, name, decl, input_location);
11533             else
11534               do_local_using_decl (decl, scope, name);
11535           }
11536         else
11537           {
11538             init = DECL_INITIAL (decl);
11539             decl = tsubst (decl, args, complain, in_decl);
11540             if (decl != error_mark_node)
11541               {
11542                 /* By marking the declaration as instantiated, we avoid
11543                    trying to instantiate it.  Since instantiate_decl can't
11544                    handle local variables, and since we've already done
11545                    all that needs to be done, that's the right thing to
11546                    do.  */
11547                 if (TREE_CODE (decl) == VAR_DECL)
11548                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11549                 if (TREE_CODE (decl) == VAR_DECL
11550                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
11551                   /* Anonymous aggregates are a special case.  */
11552                   finish_anon_union (decl);
11553                 else
11554                   {
11555                     maybe_push_decl (decl);
11556                     if (TREE_CODE (decl) == VAR_DECL
11557                         && DECL_PRETTY_FUNCTION_P (decl))
11558                       {
11559                         /* For __PRETTY_FUNCTION__ we have to adjust the
11560                            initializer.  */
11561                         const char *const name
11562                           = cxx_printable_name (current_function_decl, 2);
11563                         init = cp_fname_init (name, &TREE_TYPE (decl));
11564                       }
11565                     else
11566                       {
11567                         tree t = RECUR (init);
11568
11569                         if (init && !t)
11570                           /* If we had an initializer but it
11571                              instantiated to nothing,
11572                              value-initialize the object.  This will
11573                              only occur when the initializer was a
11574                              pack expansion where the parameter packs
11575                              used in that expansion were of length
11576                              zero.  */
11577                           init = build_value_init (TREE_TYPE (decl));
11578                         else
11579                           init = t;
11580                       }
11581
11582                     cp_finish_decl (decl, init, false, NULL_TREE, 0);
11583                   }
11584               }
11585           }
11586
11587         /* A DECL_EXPR can also be used as an expression, in the condition
11588            clause of an if/for/while construct.  */
11589         return decl;
11590       }
11591
11592     case FOR_STMT:
11593       stmt = begin_for_stmt ();
11594                           RECUR (FOR_INIT_STMT (t));
11595       finish_for_init_stmt (stmt);
11596       tmp = RECUR (FOR_COND (t));
11597       finish_for_cond (tmp, stmt);
11598       tmp = RECUR (FOR_EXPR (t));
11599       finish_for_expr (tmp, stmt);
11600       RECUR (FOR_BODY (t));
11601       finish_for_stmt (stmt);
11602       break;
11603
11604     case WHILE_STMT:
11605       stmt = begin_while_stmt ();
11606       tmp = RECUR (WHILE_COND (t));
11607       finish_while_stmt_cond (tmp, stmt);
11608       RECUR (WHILE_BODY (t));
11609       finish_while_stmt (stmt);
11610       break;
11611
11612     case DO_STMT:
11613       stmt = begin_do_stmt ();
11614       RECUR (DO_BODY (t));
11615       finish_do_body (stmt);
11616       tmp = RECUR (DO_COND (t));
11617       finish_do_stmt (tmp, stmt);
11618       break;
11619
11620     case IF_STMT:
11621       stmt = begin_if_stmt ();
11622       tmp = RECUR (IF_COND (t));
11623       finish_if_stmt_cond (tmp, stmt);
11624       RECUR (THEN_CLAUSE (t));
11625       finish_then_clause (stmt);
11626
11627       if (ELSE_CLAUSE (t))
11628         {
11629           begin_else_clause (stmt);
11630           RECUR (ELSE_CLAUSE (t));
11631           finish_else_clause (stmt);
11632         }
11633
11634       finish_if_stmt (stmt);
11635       break;
11636
11637     case BIND_EXPR:
11638       if (BIND_EXPR_BODY_BLOCK (t))
11639         stmt = begin_function_body ();
11640       else
11641         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
11642                                     ? BCS_TRY_BLOCK : 0);
11643
11644       RECUR (BIND_EXPR_BODY (t));
11645
11646       if (BIND_EXPR_BODY_BLOCK (t))
11647         finish_function_body (stmt);
11648       else
11649         finish_compound_stmt (stmt);
11650       break;
11651
11652     case BREAK_STMT:
11653       finish_break_stmt ();
11654       break;
11655
11656     case CONTINUE_STMT:
11657       finish_continue_stmt ();
11658       break;
11659
11660     case SWITCH_STMT:
11661       stmt = begin_switch_stmt ();
11662       tmp = RECUR (SWITCH_STMT_COND (t));
11663       finish_switch_cond (tmp, stmt);
11664       RECUR (SWITCH_STMT_BODY (t));
11665       finish_switch_stmt (stmt);
11666       break;
11667
11668     case CASE_LABEL_EXPR:
11669       finish_case_label (EXPR_LOCATION (t),
11670                          RECUR (CASE_LOW (t)),
11671                          RECUR (CASE_HIGH (t)));
11672       break;
11673
11674     case LABEL_EXPR:
11675       {
11676         tree decl = LABEL_EXPR_LABEL (t);
11677         tree label;
11678
11679         label = finish_label_stmt (DECL_NAME (decl));
11680         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
11681           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
11682       }
11683       break;
11684
11685     case GOTO_EXPR:
11686       tmp = GOTO_DESTINATION (t);
11687       if (TREE_CODE (tmp) != LABEL_DECL)
11688         /* Computed goto's must be tsubst'd into.  On the other hand,
11689            non-computed gotos must not be; the identifier in question
11690            will have no binding.  */
11691         tmp = RECUR (tmp);
11692       else
11693         tmp = DECL_NAME (tmp);
11694       finish_goto_stmt (tmp);
11695       break;
11696
11697     case ASM_EXPR:
11698       tmp = finish_asm_stmt
11699         (ASM_VOLATILE_P (t),
11700          RECUR (ASM_STRING (t)),
11701          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
11702          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
11703          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
11704          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
11705       {
11706         tree asm_expr = tmp;
11707         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
11708           asm_expr = TREE_OPERAND (asm_expr, 0);
11709         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
11710       }
11711       break;
11712
11713     case TRY_BLOCK:
11714       if (CLEANUP_P (t))
11715         {
11716           stmt = begin_try_block ();
11717           RECUR (TRY_STMTS (t));
11718           finish_cleanup_try_block (stmt);
11719           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
11720         }
11721       else
11722         {
11723           tree compound_stmt = NULL_TREE;
11724
11725           if (FN_TRY_BLOCK_P (t))
11726             stmt = begin_function_try_block (&compound_stmt);
11727           else
11728             stmt = begin_try_block ();
11729
11730           RECUR (TRY_STMTS (t));
11731
11732           if (FN_TRY_BLOCK_P (t))
11733             finish_function_try_block (stmt);
11734           else
11735             finish_try_block (stmt);
11736
11737           RECUR (TRY_HANDLERS (t));
11738           if (FN_TRY_BLOCK_P (t))
11739             finish_function_handler_sequence (stmt, compound_stmt);
11740           else
11741             finish_handler_sequence (stmt);
11742         }
11743       break;
11744
11745     case HANDLER:
11746       {
11747         tree decl = HANDLER_PARMS (t);
11748
11749         if (decl)
11750           {
11751             decl = tsubst (decl, args, complain, in_decl);
11752             /* Prevent instantiate_decl from trying to instantiate
11753                this variable.  We've already done all that needs to be
11754                done.  */
11755             if (decl != error_mark_node)
11756               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11757           }
11758         stmt = begin_handler ();
11759         finish_handler_parms (decl, stmt);
11760         RECUR (HANDLER_BODY (t));
11761         finish_handler (stmt);
11762       }
11763       break;
11764
11765     case TAG_DEFN:
11766       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
11767       break;
11768
11769     case STATIC_ASSERT:
11770       {
11771         tree condition = 
11772           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
11773                        args,
11774                        complain, in_decl,
11775                        /*integral_constant_expression_p=*/true);
11776         finish_static_assert (condition,
11777                               STATIC_ASSERT_MESSAGE (t),
11778                               STATIC_ASSERT_SOURCE_LOCATION (t),
11779                               /*member_p=*/false);
11780       }
11781       break;
11782
11783     case OMP_PARALLEL:
11784       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
11785                                 args, complain, in_decl);
11786       stmt = begin_omp_parallel ();
11787       RECUR (OMP_PARALLEL_BODY (t));
11788       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
11789         = OMP_PARALLEL_COMBINED (t);
11790       break;
11791
11792     case OMP_TASK:
11793       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
11794                                 args, complain, in_decl);
11795       stmt = begin_omp_task ();
11796       RECUR (OMP_TASK_BODY (t));
11797       finish_omp_task (tmp, stmt);
11798       break;
11799
11800     case OMP_FOR:
11801       {
11802         tree clauses, body, pre_body;
11803         tree declv, initv, condv, incrv;
11804         int i;
11805
11806         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
11807                                       args, complain, in_decl);
11808         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11809         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11810         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11811         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11812
11813         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
11814           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
11815                                    &clauses, args, complain, in_decl,
11816                                    integral_constant_expression_p);
11817
11818         stmt = begin_omp_structured_block ();
11819
11820         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
11821           if (TREE_VEC_ELT (initv, i) == NULL
11822               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
11823             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
11824           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
11825             {
11826               tree init = RECUR (TREE_VEC_ELT (initv, i));
11827               gcc_assert (init == TREE_VEC_ELT (declv, i));
11828               TREE_VEC_ELT (initv, i) = NULL_TREE;
11829             }
11830           else
11831             {
11832               tree decl_expr = TREE_VEC_ELT (initv, i);
11833               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
11834               gcc_assert (init != NULL);
11835               TREE_VEC_ELT (initv, i) = RECUR (init);
11836               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
11837               RECUR (decl_expr);
11838               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
11839             }
11840
11841         pre_body = push_stmt_list ();
11842         RECUR (OMP_FOR_PRE_BODY (t));
11843         pre_body = pop_stmt_list (pre_body);
11844
11845         body = push_stmt_list ();
11846         RECUR (OMP_FOR_BODY (t));
11847         body = pop_stmt_list (body);
11848
11849         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
11850                             body, pre_body, clauses);
11851
11852         add_stmt (finish_omp_structured_block (stmt));
11853       }
11854       break;
11855
11856     case OMP_SECTIONS:
11857     case OMP_SINGLE:
11858       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
11859       stmt = push_stmt_list ();
11860       RECUR (OMP_BODY (t));
11861       stmt = pop_stmt_list (stmt);
11862
11863       t = copy_node (t);
11864       OMP_BODY (t) = stmt;
11865       OMP_CLAUSES (t) = tmp;
11866       add_stmt (t);
11867       break;
11868
11869     case OMP_SECTION:
11870     case OMP_CRITICAL:
11871     case OMP_MASTER:
11872     case OMP_ORDERED:
11873       stmt = push_stmt_list ();
11874       RECUR (OMP_BODY (t));
11875       stmt = pop_stmt_list (stmt);
11876
11877       t = copy_node (t);
11878       OMP_BODY (t) = stmt;
11879       add_stmt (t);
11880       break;
11881
11882     case OMP_ATOMIC:
11883       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
11884       {
11885         tree op1 = TREE_OPERAND (t, 1);
11886         tree lhs = RECUR (TREE_OPERAND (op1, 0));
11887         tree rhs = RECUR (TREE_OPERAND (op1, 1));
11888         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
11889       }
11890       break;
11891
11892     case EXPR_PACK_EXPANSION:
11893       error ("invalid use of pack expansion expression");
11894       return error_mark_node;
11895
11896     case NONTYPE_ARGUMENT_PACK:
11897       error ("use %<...%> to expand argument pack");
11898       return error_mark_node;
11899
11900     default:
11901       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
11902
11903       return tsubst_copy_and_build (t, args, complain, in_decl,
11904                                     /*function_p=*/false,
11905                                     integral_constant_expression_p);
11906     }
11907
11908   return NULL_TREE;
11909 #undef RECUR
11910 }
11911
11912 /* T is a postfix-expression that is not being used in a function
11913    call.  Return the substituted version of T.  */
11914
11915 static tree
11916 tsubst_non_call_postfix_expression (tree t, tree args,
11917                                     tsubst_flags_t complain,
11918                                     tree in_decl)
11919 {
11920   if (TREE_CODE (t) == SCOPE_REF)
11921     t = tsubst_qualified_id (t, args, complain, in_decl,
11922                              /*done=*/false, /*address_p=*/false);
11923   else
11924     t = tsubst_copy_and_build (t, args, complain, in_decl,
11925                                /*function_p=*/false,
11926                                /*integral_constant_expression_p=*/false);
11927
11928   return t;
11929 }
11930
11931 /* Like tsubst but deals with expressions and performs semantic
11932    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
11933
11934 tree
11935 tsubst_copy_and_build (tree t,
11936                        tree args,
11937                        tsubst_flags_t complain,
11938                        tree in_decl,
11939                        bool function_p,
11940                        bool integral_constant_expression_p)
11941 {
11942 #define RECUR(NODE)                                             \
11943   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
11944                          /*function_p=*/false,                  \
11945                          integral_constant_expression_p)
11946
11947   tree op1;
11948
11949   if (t == NULL_TREE || t == error_mark_node)
11950     return t;
11951
11952   switch (TREE_CODE (t))
11953     {
11954     case USING_DECL:
11955       t = DECL_NAME (t);
11956       /* Fall through.  */
11957     case IDENTIFIER_NODE:
11958       {
11959         tree decl;
11960         cp_id_kind idk;
11961         bool non_integral_constant_expression_p;
11962         const char *error_msg;
11963
11964         if (IDENTIFIER_TYPENAME_P (t))
11965           {
11966             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11967             t = mangle_conv_op_name_for_type (new_type);
11968           }
11969
11970         /* Look up the name.  */
11971         decl = lookup_name (t);
11972
11973         /* By convention, expressions use ERROR_MARK_NODE to indicate
11974            failure, not NULL_TREE.  */
11975         if (decl == NULL_TREE)
11976           decl = error_mark_node;
11977
11978         decl = finish_id_expression (t, decl, NULL_TREE,
11979                                      &idk,
11980                                      integral_constant_expression_p,
11981                                      /*allow_non_integral_constant_expression_p=*/false,
11982                                      &non_integral_constant_expression_p,
11983                                      /*template_p=*/false,
11984                                      /*done=*/true,
11985                                      /*address_p=*/false,
11986                                      /*template_arg_p=*/false,
11987                                      &error_msg,
11988                                      input_location);
11989         if (error_msg)
11990           error (error_msg);
11991         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
11992           decl = unqualified_name_lookup_error (decl);
11993         return decl;
11994       }
11995
11996     case TEMPLATE_ID_EXPR:
11997       {
11998         tree object;
11999         tree templ = RECUR (TREE_OPERAND (t, 0));
12000         tree targs = TREE_OPERAND (t, 1);
12001
12002         if (targs)
12003           targs = tsubst_template_args (targs, args, complain, in_decl);
12004
12005         if (TREE_CODE (templ) == COMPONENT_REF)
12006           {
12007             object = TREE_OPERAND (templ, 0);
12008             templ = TREE_OPERAND (templ, 1);
12009           }
12010         else
12011           object = NULL_TREE;
12012         templ = lookup_template_function (templ, targs);
12013
12014         if (object)
12015           return build3 (COMPONENT_REF, TREE_TYPE (templ),
12016                          object, templ, NULL_TREE);
12017         else
12018           return baselink_for_fns (templ);
12019       }
12020
12021     case INDIRECT_REF:
12022       {
12023         tree r = RECUR (TREE_OPERAND (t, 0));
12024
12025         if (REFERENCE_REF_P (t))
12026           {
12027             /* A type conversion to reference type will be enclosed in
12028                such an indirect ref, but the substitution of the cast
12029                will have also added such an indirect ref.  */
12030             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
12031               r = convert_from_reference (r);
12032           }
12033         else
12034           r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
12035         return r;
12036       }
12037
12038     case NOP_EXPR:
12039       return build_nop
12040         (tsubst (TREE_TYPE (t), args, complain, in_decl),
12041          RECUR (TREE_OPERAND (t, 0)));
12042
12043     case CAST_EXPR:
12044     case REINTERPRET_CAST_EXPR:
12045     case CONST_CAST_EXPR:
12046     case DYNAMIC_CAST_EXPR:
12047     case STATIC_CAST_EXPR:
12048       {
12049         tree type;
12050         tree op;
12051
12052         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12053         if (integral_constant_expression_p
12054             && !cast_valid_in_integral_constant_expression_p (type))
12055           {
12056             if (complain & tf_error)
12057               error ("a cast to a type other than an integral or "
12058                      "enumeration type cannot appear in a constant-expression");
12059             return error_mark_node; 
12060           }
12061
12062         op = RECUR (TREE_OPERAND (t, 0));
12063
12064         switch (TREE_CODE (t))
12065           {
12066           case CAST_EXPR:
12067             return build_functional_cast (type, op, complain);
12068           case REINTERPRET_CAST_EXPR:
12069             return build_reinterpret_cast (type, op, complain);
12070           case CONST_CAST_EXPR:
12071             return build_const_cast (type, op, complain);
12072           case DYNAMIC_CAST_EXPR:
12073             return build_dynamic_cast (type, op, complain);
12074           case STATIC_CAST_EXPR:
12075             return build_static_cast (type, op, complain);
12076           default:
12077             gcc_unreachable ();
12078           }
12079       }
12080
12081     case POSTDECREMENT_EXPR:
12082     case POSTINCREMENT_EXPR:
12083       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12084                                                 args, complain, in_decl);
12085       return build_x_unary_op (TREE_CODE (t), op1, complain);
12086
12087     case PREDECREMENT_EXPR:
12088     case PREINCREMENT_EXPR:
12089     case NEGATE_EXPR:
12090     case BIT_NOT_EXPR:
12091     case ABS_EXPR:
12092     case TRUTH_NOT_EXPR:
12093     case UNARY_PLUS_EXPR:  /* Unary + */
12094     case REALPART_EXPR:
12095     case IMAGPART_EXPR:
12096       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
12097                                complain);
12098
12099     case ADDR_EXPR:
12100       op1 = TREE_OPERAND (t, 0);
12101       if (TREE_CODE (op1) == SCOPE_REF)
12102         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
12103                                    /*done=*/true, /*address_p=*/true);
12104       else
12105         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
12106                                                   in_decl);
12107       if (TREE_CODE (op1) == LABEL_DECL)
12108         return finish_label_address_expr (DECL_NAME (op1),
12109                                           EXPR_LOCATION (op1));
12110       return build_x_unary_op (ADDR_EXPR, op1, complain);
12111
12112     case PLUS_EXPR:
12113     case MINUS_EXPR:
12114     case MULT_EXPR:
12115     case TRUNC_DIV_EXPR:
12116     case CEIL_DIV_EXPR:
12117     case FLOOR_DIV_EXPR:
12118     case ROUND_DIV_EXPR:
12119     case EXACT_DIV_EXPR:
12120     case BIT_AND_EXPR:
12121     case BIT_IOR_EXPR:
12122     case BIT_XOR_EXPR:
12123     case TRUNC_MOD_EXPR:
12124     case FLOOR_MOD_EXPR:
12125     case TRUTH_ANDIF_EXPR:
12126     case TRUTH_ORIF_EXPR:
12127     case TRUTH_AND_EXPR:
12128     case TRUTH_OR_EXPR:
12129     case RSHIFT_EXPR:
12130     case LSHIFT_EXPR:
12131     case RROTATE_EXPR:
12132     case LROTATE_EXPR:
12133     case EQ_EXPR:
12134     case NE_EXPR:
12135     case MAX_EXPR:
12136     case MIN_EXPR:
12137     case LE_EXPR:
12138     case GE_EXPR:
12139     case LT_EXPR:
12140     case GT_EXPR:
12141     case MEMBER_REF:
12142     case DOTSTAR_EXPR:
12143       return build_x_binary_op
12144         (TREE_CODE (t),
12145          RECUR (TREE_OPERAND (t, 0)),
12146          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
12147           ? ERROR_MARK
12148           : TREE_CODE (TREE_OPERAND (t, 0))),
12149          RECUR (TREE_OPERAND (t, 1)),
12150          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
12151           ? ERROR_MARK
12152           : TREE_CODE (TREE_OPERAND (t, 1))),
12153          /*overloaded_p=*/NULL,
12154          complain);
12155
12156     case SCOPE_REF:
12157       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
12158                                   /*address_p=*/false);
12159     case ARRAY_REF:
12160       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12161                                                 args, complain, in_decl);
12162       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
12163
12164     case SIZEOF_EXPR:
12165       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
12166         return tsubst_copy (t, args, complain, in_decl);
12167       /* Fall through */
12168       
12169     case ALIGNOF_EXPR:
12170       op1 = TREE_OPERAND (t, 0);
12171       if (!args)
12172         {
12173           /* When there are no ARGS, we are trying to evaluate a
12174              non-dependent expression from the parser.  Trying to do
12175              the substitutions may not work.  */
12176           if (!TYPE_P (op1))
12177             op1 = TREE_TYPE (op1);
12178         }
12179       else
12180         {
12181           ++cp_unevaluated_operand;
12182           ++c_inhibit_evaluation_warnings;
12183           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12184                                        /*function_p=*/false,
12185                                        /*integral_constant_expression_p=*/false);
12186           --cp_unevaluated_operand;
12187           --c_inhibit_evaluation_warnings;
12188         }
12189       if (TYPE_P (op1))
12190         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
12191                                            complain & tf_error);
12192       else
12193         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
12194                                            complain & tf_error);
12195
12196     case MODOP_EXPR:
12197       {
12198         tree r = build_x_modify_expr
12199           (RECUR (TREE_OPERAND (t, 0)),
12200            TREE_CODE (TREE_OPERAND (t, 1)),
12201            RECUR (TREE_OPERAND (t, 2)),
12202            complain);
12203         /* TREE_NO_WARNING must be set if either the expression was
12204            parenthesized or it uses an operator such as >>= rather
12205            than plain assignment.  In the former case, it was already
12206            set and must be copied.  In the latter case,
12207            build_x_modify_expr sets it and it must not be reset
12208            here.  */
12209         if (TREE_NO_WARNING (t))
12210           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12211         return r;
12212       }
12213
12214     case ARROW_EXPR:
12215       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12216                                                 args, complain, in_decl);
12217       /* Remember that there was a reference to this entity.  */
12218       if (DECL_P (op1))
12219         mark_used (op1);
12220       return build_x_arrow (op1);
12221
12222     case NEW_EXPR:
12223       {
12224         tree placement = RECUR (TREE_OPERAND (t, 0));
12225         tree init = RECUR (TREE_OPERAND (t, 3));
12226         VEC(tree,gc) *placement_vec;
12227         VEC(tree,gc) *init_vec;
12228         tree ret;
12229
12230         if (placement == NULL_TREE)
12231           placement_vec = NULL;
12232         else
12233           {
12234             placement_vec = make_tree_vector ();
12235             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
12236               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
12237           }
12238
12239         /* If there was an initializer in the original tree, but it
12240            instantiated to an empty list, then we should pass a
12241            non-NULL empty vector to tell build_new that it was an
12242            empty initializer() rather than no initializer.  This can
12243            only happen when the initializer is a pack expansion whose
12244            parameter packs are of length zero.  */
12245         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
12246           init_vec = NULL;
12247         else
12248           {
12249             init_vec = make_tree_vector ();
12250             if (init == void_zero_node)
12251               gcc_assert (init_vec != NULL);
12252             else
12253               {
12254                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
12255                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
12256               }
12257           }
12258
12259         ret = build_new (&placement_vec,
12260                          RECUR (TREE_OPERAND (t, 1)),
12261                          RECUR (TREE_OPERAND (t, 2)),
12262                          &init_vec,
12263                          NEW_EXPR_USE_GLOBAL (t),
12264                          complain);
12265
12266         if (placement_vec != NULL)
12267           release_tree_vector (placement_vec);
12268         if (init_vec != NULL)
12269           release_tree_vector (init_vec);
12270
12271         return ret;
12272       }
12273
12274     case DELETE_EXPR:
12275      return delete_sanity
12276        (RECUR (TREE_OPERAND (t, 0)),
12277         RECUR (TREE_OPERAND (t, 1)),
12278         DELETE_EXPR_USE_VEC (t),
12279         DELETE_EXPR_USE_GLOBAL (t));
12280
12281     case COMPOUND_EXPR:
12282       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
12283                                     RECUR (TREE_OPERAND (t, 1)),
12284                                     complain);
12285
12286     case CALL_EXPR:
12287       {
12288         tree function;
12289         VEC(tree,gc) *call_args;
12290         unsigned int nargs, i;
12291         bool qualified_p;
12292         bool koenig_p;
12293         tree ret;
12294
12295         function = CALL_EXPR_FN (t);
12296         /* When we parsed the expression,  we determined whether or
12297            not Koenig lookup should be performed.  */
12298         koenig_p = KOENIG_LOOKUP_P (t);
12299         if (TREE_CODE (function) == SCOPE_REF)
12300           {
12301             qualified_p = true;
12302             function = tsubst_qualified_id (function, args, complain, in_decl,
12303                                             /*done=*/false,
12304                                             /*address_p=*/false);
12305           }
12306         else
12307           {
12308             if (TREE_CODE (function) == COMPONENT_REF)
12309               {
12310                 tree op = TREE_OPERAND (function, 1);
12311
12312                 qualified_p = (TREE_CODE (op) == SCOPE_REF
12313                                || (BASELINK_P (op)
12314                                    && BASELINK_QUALIFIED_P (op)));
12315               }
12316             else
12317               qualified_p = false;
12318
12319             function = tsubst_copy_and_build (function, args, complain,
12320                                               in_decl,
12321                                               !qualified_p,
12322                                               integral_constant_expression_p);
12323
12324             if (BASELINK_P (function))
12325               qualified_p = true;
12326           }
12327
12328         nargs = call_expr_nargs (t);
12329         call_args = make_tree_vector ();
12330         for (i = 0; i < nargs; ++i)
12331           {
12332             tree arg = CALL_EXPR_ARG (t, i);
12333
12334             if (!PACK_EXPANSION_P (arg))
12335               VEC_safe_push (tree, gc, call_args,
12336                              RECUR (CALL_EXPR_ARG (t, i)));
12337             else
12338               {
12339                 /* Expand the pack expansion and push each entry onto
12340                    CALL_ARGS.  */
12341                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
12342                 if (TREE_CODE (arg) == TREE_VEC)
12343                   {
12344                     unsigned int len, j;
12345
12346                     len = TREE_VEC_LENGTH (arg);
12347                     for (j = 0; j < len; ++j)
12348                       {
12349                         tree value = TREE_VEC_ELT (arg, j);
12350                         if (value != NULL_TREE)
12351                           value = convert_from_reference (value);
12352                         VEC_safe_push (tree, gc, call_args, value);
12353                       }
12354                   }
12355                 else
12356                   {
12357                     /* A partial substitution.  Add one entry.  */
12358                     VEC_safe_push (tree, gc, call_args, arg);
12359                   }
12360               }
12361           }
12362
12363         /* We do not perform argument-dependent lookup if normal
12364            lookup finds a non-function, in accordance with the
12365            expected resolution of DR 218.  */
12366         if (koenig_p
12367             && ((is_overloaded_fn (function)
12368                  /* If lookup found a member function, the Koenig lookup is
12369                     not appropriate, even if an unqualified-name was used
12370                     to denote the function.  */
12371                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
12372                 || TREE_CODE (function) == IDENTIFIER_NODE)
12373             /* Only do this when substitution turns a dependent call
12374                into a non-dependent call.  */
12375             && type_dependent_expression_p_push (t)
12376             && !any_type_dependent_arguments_p (call_args))
12377           function = perform_koenig_lookup (function, call_args);
12378
12379         if (TREE_CODE (function) == IDENTIFIER_NODE)
12380           {
12381             unqualified_name_lookup_error (function);
12382             release_tree_vector (call_args);
12383             return error_mark_node;
12384           }
12385
12386         /* Remember that there was a reference to this entity.  */
12387         if (DECL_P (function))
12388           mark_used (function);
12389
12390         if (TREE_CODE (function) == OFFSET_REF)
12391           ret = build_offset_ref_call_from_tree (function, &call_args);
12392         else if (TREE_CODE (function) == COMPONENT_REF)
12393           {
12394             if (!BASELINK_P (TREE_OPERAND (function, 1)))
12395               ret = finish_call_expr (function, &call_args,
12396                                        /*disallow_virtual=*/false,
12397                                        /*koenig_p=*/false,
12398                                        complain);
12399             else
12400               ret = (build_new_method_call
12401                       (TREE_OPERAND (function, 0),
12402                        TREE_OPERAND (function, 1),
12403                        &call_args, NULL_TREE,
12404                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
12405                        /*fn_p=*/NULL,
12406                        complain));
12407           }
12408         else
12409           ret = finish_call_expr (function, &call_args,
12410                                   /*disallow_virtual=*/qualified_p,
12411                                   koenig_p,
12412                                   complain);
12413
12414         release_tree_vector (call_args);
12415
12416         return ret;
12417       }
12418
12419     case COND_EXPR:
12420       return build_x_conditional_expr
12421         (RECUR (TREE_OPERAND (t, 0)),
12422          RECUR (TREE_OPERAND (t, 1)),
12423          RECUR (TREE_OPERAND (t, 2)),
12424          complain);
12425
12426     case PSEUDO_DTOR_EXPR:
12427       return finish_pseudo_destructor_expr
12428         (RECUR (TREE_OPERAND (t, 0)),
12429          RECUR (TREE_OPERAND (t, 1)),
12430          RECUR (TREE_OPERAND (t, 2)));
12431
12432     case TREE_LIST:
12433       {
12434         tree purpose, value, chain;
12435
12436         if (t == void_list_node)
12437           return t;
12438
12439         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
12440             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
12441           {
12442             /* We have pack expansions, so expand those and
12443                create a new list out of it.  */
12444             tree purposevec = NULL_TREE;
12445             tree valuevec = NULL_TREE;
12446             tree chain;
12447             int i, len = -1;
12448
12449             /* Expand the argument expressions.  */
12450             if (TREE_PURPOSE (t))
12451               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
12452                                                  complain, in_decl);
12453             if (TREE_VALUE (t))
12454               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
12455                                                complain, in_decl);
12456
12457             /* Build the rest of the list.  */
12458             chain = TREE_CHAIN (t);
12459             if (chain && chain != void_type_node)
12460               chain = RECUR (chain);
12461
12462             /* Determine the number of arguments.  */
12463             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
12464               {
12465                 len = TREE_VEC_LENGTH (purposevec);
12466                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
12467               }
12468             else if (TREE_CODE (valuevec) == TREE_VEC)
12469               len = TREE_VEC_LENGTH (valuevec);
12470             else
12471               {
12472                 /* Since we only performed a partial substitution into
12473                    the argument pack, we only return a single list
12474                    node.  */
12475                 if (purposevec == TREE_PURPOSE (t)
12476                     && valuevec == TREE_VALUE (t)
12477                     && chain == TREE_CHAIN (t))
12478                   return t;
12479
12480                 return tree_cons (purposevec, valuevec, chain);
12481               }
12482             
12483             /* Convert the argument vectors into a TREE_LIST */
12484             i = len;
12485             while (i > 0)
12486               {
12487                 /* Grab the Ith values.  */
12488                 i--;
12489                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
12490                                      : NULL_TREE;
12491                 value 
12492                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
12493                              : NULL_TREE;
12494
12495                 /* Build the list (backwards).  */
12496                 chain = tree_cons (purpose, value, chain);
12497               }
12498
12499             return chain;
12500           }
12501
12502         purpose = TREE_PURPOSE (t);
12503         if (purpose)
12504           purpose = RECUR (purpose);
12505         value = TREE_VALUE (t);
12506         if (value)
12507           value = RECUR (value);
12508         chain = TREE_CHAIN (t);
12509         if (chain && chain != void_type_node)
12510           chain = RECUR (chain);
12511         if (purpose == TREE_PURPOSE (t)
12512             && value == TREE_VALUE (t)
12513             && chain == TREE_CHAIN (t))
12514           return t;
12515         return tree_cons (purpose, value, chain);
12516       }
12517
12518     case COMPONENT_REF:
12519       {
12520         tree object;
12521         tree object_type;
12522         tree member;
12523
12524         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12525                                                      args, complain, in_decl);
12526         /* Remember that there was a reference to this entity.  */
12527         if (DECL_P (object))
12528           mark_used (object);
12529         object_type = TREE_TYPE (object);
12530
12531         member = TREE_OPERAND (t, 1);
12532         if (BASELINK_P (member))
12533           member = tsubst_baselink (member,
12534                                     non_reference (TREE_TYPE (object)),
12535                                     args, complain, in_decl);
12536         else
12537           member = tsubst_copy (member, args, complain, in_decl);
12538         if (member == error_mark_node)
12539           return error_mark_node;
12540
12541         if (object_type && !CLASS_TYPE_P (object_type))
12542           {
12543             if (SCALAR_TYPE_P (object_type))
12544               {
12545                 tree s = NULL_TREE;
12546                 tree dtor = member;
12547
12548                 if (TREE_CODE (dtor) == SCOPE_REF)
12549                   {
12550                     s = TREE_OPERAND (dtor, 0);
12551                     dtor = TREE_OPERAND (dtor, 1);
12552                   }
12553                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
12554                   {
12555                     dtor = TREE_OPERAND (dtor, 0);
12556                     if (TYPE_P (dtor))
12557                       return finish_pseudo_destructor_expr (object, s, dtor);
12558                   }
12559               }
12560           }
12561         else if (TREE_CODE (member) == SCOPE_REF
12562                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
12563           {
12564             tree tmpl;
12565             tree args;
12566
12567             /* Lookup the template functions now that we know what the
12568                scope is.  */
12569             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
12570             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
12571             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
12572                                             /*is_type_p=*/false,
12573                                             /*complain=*/false);
12574             if (BASELINK_P (member))
12575               {
12576                 BASELINK_FUNCTIONS (member)
12577                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
12578                               args);
12579                 member = (adjust_result_of_qualified_name_lookup
12580                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
12581                            object_type));
12582               }
12583             else
12584               {
12585                 qualified_name_lookup_error (object_type, tmpl, member,
12586                                              input_location);
12587                 return error_mark_node;
12588               }
12589           }
12590         else if (TREE_CODE (member) == SCOPE_REF
12591                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
12592                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
12593           {
12594             if (complain & tf_error)
12595               {
12596                 if (TYPE_P (TREE_OPERAND (member, 0)))
12597                   error ("%qT is not a class or namespace",
12598                          TREE_OPERAND (member, 0));
12599                 else
12600                   error ("%qD is not a class or namespace",
12601                          TREE_OPERAND (member, 0));
12602               }
12603             return error_mark_node;
12604           }
12605         else if (TREE_CODE (member) == FIELD_DECL)
12606           return finish_non_static_data_member (member, object, NULL_TREE);
12607
12608         return finish_class_member_access_expr (object, member,
12609                                                 /*template_p=*/false,
12610                                                 complain);
12611       }
12612
12613     case THROW_EXPR:
12614       return build_throw
12615         (RECUR (TREE_OPERAND (t, 0)));
12616
12617     case CONSTRUCTOR:
12618       {
12619         VEC(constructor_elt,gc) *n;
12620         constructor_elt *ce;
12621         unsigned HOST_WIDE_INT idx;
12622         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12623         bool process_index_p;
12624         int newlen;
12625         bool need_copy_p = false;
12626         tree r;
12627
12628         if (type == error_mark_node)
12629           return error_mark_node;
12630
12631         /* digest_init will do the wrong thing if we let it.  */
12632         if (type && TYPE_PTRMEMFUNC_P (type))
12633           return t;
12634
12635         /* We do not want to process the index of aggregate
12636            initializers as they are identifier nodes which will be
12637            looked up by digest_init.  */
12638         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
12639
12640         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
12641         newlen = VEC_length (constructor_elt, n);
12642         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
12643           {
12644             if (ce->index && process_index_p)
12645               ce->index = RECUR (ce->index);
12646
12647             if (PACK_EXPANSION_P (ce->value))
12648               {
12649                 /* Substitute into the pack expansion.  */
12650                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
12651                                                   in_decl);
12652
12653                 if (ce->value == error_mark_node)
12654                   ;
12655                 else if (TREE_VEC_LENGTH (ce->value) == 1)
12656                   /* Just move the argument into place.  */
12657                   ce->value = TREE_VEC_ELT (ce->value, 0);
12658                 else
12659                   {
12660                     /* Update the length of the final CONSTRUCTOR
12661                        arguments vector, and note that we will need to
12662                        copy.*/
12663                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
12664                     need_copy_p = true;
12665                   }
12666               }
12667             else
12668               ce->value = RECUR (ce->value);
12669           }
12670
12671         if (need_copy_p)
12672           {
12673             VEC(constructor_elt,gc) *old_n = n;
12674
12675             n = VEC_alloc (constructor_elt, gc, newlen);
12676             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
12677                  idx++)
12678               {
12679                 if (TREE_CODE (ce->value) == TREE_VEC)
12680                   {
12681                     int i, len = TREE_VEC_LENGTH (ce->value);
12682                     for (i = 0; i < len; ++i)
12683                       CONSTRUCTOR_APPEND_ELT (n, 0,
12684                                               TREE_VEC_ELT (ce->value, i));
12685                   }
12686                 else
12687                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
12688               }
12689           }
12690
12691         r = build_constructor (init_list_type_node, n);
12692         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
12693
12694         if (TREE_HAS_CONSTRUCTOR (t))
12695           return finish_compound_literal (type, r);
12696
12697         return r;
12698       }
12699
12700     case TYPEID_EXPR:
12701       {
12702         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
12703         if (TYPE_P (operand_0))
12704           return get_typeid (operand_0);
12705         return build_typeid (operand_0);
12706       }
12707
12708     case VAR_DECL:
12709       if (!args)
12710         return t;
12711       /* Fall through */
12712
12713     case PARM_DECL:
12714       {
12715         tree r = tsubst_copy (t, args, complain, in_decl);
12716
12717         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
12718           /* If the original type was a reference, we'll be wrapped in
12719              the appropriate INDIRECT_REF.  */
12720           r = convert_from_reference (r);
12721         return r;
12722       }
12723
12724     case VA_ARG_EXPR:
12725       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
12726                              tsubst_copy (TREE_TYPE (t), args, complain,
12727                                           in_decl));
12728
12729     case OFFSETOF_EXPR:
12730       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
12731
12732     case TRAIT_EXPR:
12733       {
12734         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
12735                                   complain, in_decl);
12736
12737         tree type2 = TRAIT_EXPR_TYPE2 (t);
12738         if (type2)
12739           type2 = tsubst_copy (type2, args, complain, in_decl);
12740         
12741         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
12742       }
12743
12744     case STMT_EXPR:
12745       {
12746         tree old_stmt_expr = cur_stmt_expr;
12747         tree stmt_expr = begin_stmt_expr ();
12748
12749         cur_stmt_expr = stmt_expr;
12750         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
12751                      integral_constant_expression_p);
12752         stmt_expr = finish_stmt_expr (stmt_expr, false);
12753         cur_stmt_expr = old_stmt_expr;
12754
12755         /* If the resulting list of expression statement is empty,
12756            fold it further into void_zero_node.  */
12757         if (empty_expr_stmt_p (stmt_expr))
12758           stmt_expr = void_zero_node;
12759
12760         return stmt_expr;
12761       }
12762
12763     case CONST_DECL:
12764       t = tsubst_copy (t, args, complain, in_decl);
12765       /* As in finish_id_expression, we resolve enumeration constants
12766          to their underlying values.  */
12767       if (TREE_CODE (t) == CONST_DECL)
12768         {
12769           used_types_insert (TREE_TYPE (t));
12770           return DECL_INITIAL (t);
12771         }
12772       return t;
12773
12774     case LAMBDA_EXPR:
12775       {
12776         tree r = build_lambda_expr ();
12777
12778         tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12779         TREE_TYPE (r) = type;
12780         CLASSTYPE_LAMBDA_EXPR (type) = r;
12781
12782         LAMBDA_EXPR_LOCATION (r)
12783           = LAMBDA_EXPR_LOCATION (t);
12784         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
12785           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
12786         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
12787         LAMBDA_EXPR_DISCRIMINATOR (r)
12788           = (LAMBDA_EXPR_DISCRIMINATOR (t));
12789         LAMBDA_EXPR_CAPTURE_LIST (r)
12790           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
12791         LAMBDA_EXPR_THIS_CAPTURE (r)
12792           = RECUR (LAMBDA_EXPR_THIS_CAPTURE (t));
12793         LAMBDA_EXPR_EXTRA_SCOPE (r)
12794           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
12795
12796         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
12797         determine_visibility (TYPE_NAME (type));
12798         /* Now that we know visibility, instantiate the type so we have a
12799            declaration of the op() for later calls to lambda_function.  */
12800         complete_type (type);
12801
12802         type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
12803         if (type)
12804           apply_lambda_return_type (r, type);
12805
12806         return build_lambda_object (r);
12807       }
12808
12809     default:
12810       /* Handle Objective-C++ constructs, if appropriate.  */
12811       {
12812         tree subst
12813           = objcp_tsubst_copy_and_build (t, args, complain,
12814                                          in_decl, /*function_p=*/false);
12815         if (subst)
12816           return subst;
12817       }
12818       return tsubst_copy (t, args, complain, in_decl);
12819     }
12820
12821 #undef RECUR
12822 }
12823
12824 /* Verify that the instantiated ARGS are valid. For type arguments,
12825    make sure that the type's linkage is ok. For non-type arguments,
12826    make sure they are constants if they are integral or enumerations.
12827    Emit an error under control of COMPLAIN, and return TRUE on error.  */
12828
12829 static bool
12830 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
12831 {
12832   if (ARGUMENT_PACK_P (t))
12833     {
12834       tree vec = ARGUMENT_PACK_ARGS (t);
12835       int len = TREE_VEC_LENGTH (vec);
12836       bool result = false;
12837       int i;
12838
12839       for (i = 0; i < len; ++i)
12840         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
12841           result = true;
12842       return result;
12843     }
12844   else if (TYPE_P (t))
12845     {
12846       /* [basic.link]: A name with no linkage (notably, the name
12847          of a class or enumeration declared in a local scope)
12848          shall not be used to declare an entity with linkage.
12849          This implies that names with no linkage cannot be used as
12850          template arguments
12851
12852          DR 757 relaxes this restriction for C++0x.  */
12853       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
12854                  : no_linkage_check (t, /*relaxed_p=*/false));
12855
12856       if (nt)
12857         {
12858           /* DR 488 makes use of a type with no linkage cause
12859              type deduction to fail.  */
12860           if (complain & tf_error)
12861             {
12862               if (TYPE_ANONYMOUS_P (nt))
12863                 error ("%qT is/uses anonymous type", t);
12864               else
12865                 error ("template argument for %qD uses local type %qT",
12866                        tmpl, t);
12867             }
12868           return true;
12869         }
12870       /* In order to avoid all sorts of complications, we do not
12871          allow variably-modified types as template arguments.  */
12872       else if (variably_modified_type_p (t, NULL_TREE))
12873         {
12874           if (complain & tf_error)
12875             error ("%qT is a variably modified type", t);
12876           return true;
12877         }
12878     }
12879   /* A non-type argument of integral or enumerated type must be a
12880      constant.  */
12881   else if (TREE_TYPE (t)
12882            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
12883            && !TREE_CONSTANT (t))
12884     {
12885       if (complain & tf_error)
12886         error ("integral expression %qE is not constant", t);
12887       return true;
12888     }
12889   return false;
12890 }
12891
12892 static bool
12893 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
12894 {
12895   int ix, len = DECL_NTPARMS (tmpl);
12896   bool result = false;
12897
12898   for (ix = 0; ix != len; ix++)
12899     {
12900       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
12901         result = true;
12902     }
12903   if (result && (complain & tf_error))
12904     error ("  trying to instantiate %qD", tmpl);
12905   return result;
12906 }
12907
12908 /* Instantiate the indicated variable or function template TMPL with
12909    the template arguments in TARG_PTR.  */
12910
12911 tree
12912 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
12913 {
12914   tree targ_ptr = orig_args;
12915   tree fndecl;
12916   tree gen_tmpl;
12917   tree spec;
12918   HOST_WIDE_INT saved_processing_template_decl;
12919
12920   if (tmpl == error_mark_node)
12921     return error_mark_node;
12922
12923   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
12924
12925   /* If this function is a clone, handle it specially.  */
12926   if (DECL_CLONED_FUNCTION_P (tmpl))
12927     {
12928       tree spec;
12929       tree clone;
12930
12931       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
12932          DECL_CLONED_FUNCTION.  */
12933       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
12934                                    targ_ptr, complain);
12935       if (spec == error_mark_node)
12936         return error_mark_node;
12937
12938       /* Look for the clone.  */
12939       FOR_EACH_CLONE (clone, spec)
12940         if (DECL_NAME (clone) == DECL_NAME (tmpl))
12941           return clone;
12942       /* We should always have found the clone by now.  */
12943       gcc_unreachable ();
12944       return NULL_TREE;
12945     }
12946
12947   /* Check to see if we already have this specialization.  */
12948   gen_tmpl = most_general_template (tmpl);
12949   if (tmpl != gen_tmpl)
12950     /* The TMPL is a partial instantiation.  To get a full set of
12951        arguments we must add the arguments used to perform the
12952        partial instantiation.  */
12953     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
12954                                             targ_ptr);
12955
12956   /* It would be nice to avoid hashing here and then again in tsubst_decl,
12957      but it doesn't seem to be on the hot path.  */
12958   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
12959
12960   gcc_assert (tmpl == gen_tmpl
12961               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
12962                   == spec)
12963               || fndecl == NULL_TREE);
12964
12965   if (spec != NULL_TREE)
12966     return spec;
12967
12968   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
12969                                complain))
12970     return error_mark_node;
12971
12972   /* We are building a FUNCTION_DECL, during which the access of its
12973      parameters and return types have to be checked.  However this
12974      FUNCTION_DECL which is the desired context for access checking
12975      is not built yet.  We solve this chicken-and-egg problem by
12976      deferring all checks until we have the FUNCTION_DECL.  */
12977   push_deferring_access_checks (dk_deferred);
12978
12979   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
12980      (because, for example, we have encountered a non-dependent
12981      function call in the body of a template function and must now
12982      determine which of several overloaded functions will be called),
12983      within the instantiation itself we are not processing a
12984      template.  */  
12985   saved_processing_template_decl = processing_template_decl;
12986   processing_template_decl = 0;
12987   /* Substitute template parameters to obtain the specialization.  */
12988   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
12989                    targ_ptr, complain, gen_tmpl);
12990   processing_template_decl = saved_processing_template_decl;
12991   if (fndecl == error_mark_node)
12992     return error_mark_node;
12993
12994   /* Now we know the specialization, compute access previously
12995      deferred.  */
12996   push_access_scope (fndecl);
12997
12998   /* Some typedefs referenced from within the template code need to be access
12999      checked at template instantiation time, i.e now. These types were
13000      added to the template at parsing time. Let's get those and perfom
13001      the acces checks then.  */
13002   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
13003   perform_deferred_access_checks ();
13004   pop_access_scope (fndecl);
13005   pop_deferring_access_checks ();
13006
13007   /* The DECL_TI_TEMPLATE should always be the immediate parent
13008      template, not the most general template.  */
13009   DECL_TI_TEMPLATE (fndecl) = tmpl;
13010
13011   /* If we've just instantiated the main entry point for a function,
13012      instantiate all the alternate entry points as well.  We do this
13013      by cloning the instantiation of the main entry point, not by
13014      instantiating the template clones.  */
13015   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
13016     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
13017
13018   return fndecl;
13019 }
13020
13021 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
13022    NARGS elements of the arguments that are being used when calling
13023    it.  TARGS is a vector into which the deduced template arguments
13024    are placed.
13025
13026    Return zero for success, 2 for an incomplete match that doesn't resolve
13027    all the types, and 1 for complete failure.  An error message will be
13028    printed only for an incomplete match.
13029
13030    If FN is a conversion operator, or we are trying to produce a specific
13031    specialization, RETURN_TYPE is the return type desired.
13032
13033    The EXPLICIT_TARGS are explicit template arguments provided via a
13034    template-id.
13035
13036    The parameter STRICT is one of:
13037
13038    DEDUCE_CALL:
13039      We are deducing arguments for a function call, as in
13040      [temp.deduct.call].
13041
13042    DEDUCE_CONV:
13043      We are deducing arguments for a conversion function, as in
13044      [temp.deduct.conv].
13045
13046    DEDUCE_EXACT:
13047      We are deducing arguments when doing an explicit instantiation
13048      as in [temp.explicit], when determining an explicit specialization
13049      as in [temp.expl.spec], or when taking the address of a function
13050      template, as in [temp.deduct.funcaddr].  */
13051
13052 int
13053 fn_type_unification (tree fn,
13054                      tree explicit_targs,
13055                      tree targs,
13056                      const tree *args,
13057                      unsigned int nargs,
13058                      tree return_type,
13059                      unification_kind_t strict,
13060                      int flags)
13061 {
13062   tree parms;
13063   tree fntype;
13064   int result;
13065   bool incomplete_argument_packs_p = false;
13066
13067   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
13068
13069   fntype = TREE_TYPE (fn);
13070   if (explicit_targs)
13071     {
13072       /* [temp.deduct]
13073
13074          The specified template arguments must match the template
13075          parameters in kind (i.e., type, nontype, template), and there
13076          must not be more arguments than there are parameters;
13077          otherwise type deduction fails.
13078
13079          Nontype arguments must match the types of the corresponding
13080          nontype template parameters, or must be convertible to the
13081          types of the corresponding nontype parameters as specified in
13082          _temp.arg.nontype_, otherwise type deduction fails.
13083
13084          All references in the function type of the function template
13085          to the corresponding template parameters are replaced by the
13086          specified template argument values.  If a substitution in a
13087          template parameter or in the function type of the function
13088          template results in an invalid type, type deduction fails.  */
13089       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
13090       int i, len = TREE_VEC_LENGTH (tparms);
13091       tree converted_args;
13092       bool incomplete = false;
13093
13094       if (explicit_targs == error_mark_node)
13095         return 1;
13096
13097       converted_args
13098         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
13099                                   /*require_all_args=*/false,
13100                                   /*use_default_args=*/false));
13101       if (converted_args == error_mark_node)
13102         return 1;
13103
13104       /* Substitute the explicit args into the function type.  This is
13105          necessary so that, for instance, explicitly declared function
13106          arguments can match null pointed constants.  If we were given
13107          an incomplete set of explicit args, we must not do semantic
13108          processing during substitution as we could create partial
13109          instantiations.  */
13110       for (i = 0; i < len; i++)
13111         {
13112           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13113           bool parameter_pack = false;
13114
13115           /* Dig out the actual parm.  */
13116           if (TREE_CODE (parm) == TYPE_DECL
13117               || TREE_CODE (parm) == TEMPLATE_DECL)
13118             {
13119               parm = TREE_TYPE (parm);
13120               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
13121             }
13122           else if (TREE_CODE (parm) == PARM_DECL)
13123             {
13124               parm = DECL_INITIAL (parm);
13125               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
13126             }
13127
13128           if (parameter_pack)
13129             {
13130               int level, idx;
13131               tree targ;
13132               template_parm_level_and_index (parm, &level, &idx);
13133
13134               /* Mark the argument pack as "incomplete". We could
13135                  still deduce more arguments during unification.  */
13136               targ = TMPL_ARG (converted_args, level, idx);
13137               if (targ)
13138                 {
13139                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
13140                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
13141                     = ARGUMENT_PACK_ARGS (targ);
13142                 }
13143
13144               /* We have some incomplete argument packs.  */
13145               incomplete_argument_packs_p = true;
13146             }
13147         }
13148
13149       if (incomplete_argument_packs_p)
13150         /* Any substitution is guaranteed to be incomplete if there
13151            are incomplete argument packs, because we can still deduce
13152            more arguments.  */
13153         incomplete = 1;
13154       else
13155         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
13156
13157       processing_template_decl += incomplete;
13158       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
13159       processing_template_decl -= incomplete;
13160
13161       if (fntype == error_mark_node)
13162         return 1;
13163
13164       /* Place the explicitly specified arguments in TARGS.  */
13165       for (i = NUM_TMPL_ARGS (converted_args); i--;)
13166         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
13167     }
13168
13169   /* Never do unification on the 'this' parameter.  */
13170   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
13171
13172   if (return_type)
13173     {
13174       tree *new_args;
13175
13176       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
13177       new_args = XALLOCAVEC (tree, nargs + 1);
13178       new_args[0] = return_type;
13179       memcpy (new_args + 1, args, nargs * sizeof (tree));
13180       args = new_args;
13181       ++nargs;
13182     }
13183
13184   /* We allow incomplete unification without an error message here
13185      because the standard doesn't seem to explicitly prohibit it.  Our
13186      callers must be ready to deal with unification failures in any
13187      event.  */
13188   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
13189                                   targs, parms, args, nargs, /*subr=*/0,
13190                                   strict, flags);
13191
13192   if (result == 0 && incomplete_argument_packs_p)
13193     {
13194       int i, len = NUM_TMPL_ARGS (targs);
13195
13196       /* Clear the "incomplete" flags on all argument packs.  */
13197       for (i = 0; i < len; i++)
13198         {
13199           tree arg = TREE_VEC_ELT (targs, i);
13200           if (ARGUMENT_PACK_P (arg))
13201             {
13202               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
13203               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
13204             }
13205         }
13206     }
13207
13208   /* Now that we have bindings for all of the template arguments,
13209      ensure that the arguments deduced for the template template
13210      parameters have compatible template parameter lists.  We cannot
13211      check this property before we have deduced all template
13212      arguments, because the template parameter types of a template
13213      template parameter might depend on prior template parameters
13214      deduced after the template template parameter.  The following
13215      ill-formed example illustrates this issue:
13216
13217        template<typename T, template<T> class C> void f(C<5>, T);
13218
13219        template<int N> struct X {};
13220
13221        void g() {
13222          f(X<5>(), 5l); // error: template argument deduction fails
13223        }
13224
13225      The template parameter list of 'C' depends on the template type
13226      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
13227      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
13228      time that we deduce 'C'.  */
13229   if (result == 0
13230       && !template_template_parm_bindings_ok_p 
13231            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
13232     return 1;
13233
13234   if (result == 0)
13235     /* All is well so far.  Now, check:
13236
13237        [temp.deduct]
13238
13239        When all template arguments have been deduced, all uses of
13240        template parameters in nondeduced contexts are replaced with
13241        the corresponding deduced argument values.  If the
13242        substitution results in an invalid type, as described above,
13243        type deduction fails.  */
13244     {
13245       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
13246       if (substed == error_mark_node)
13247         return 1;
13248
13249       /* If we're looking for an exact match, check that what we got
13250          is indeed an exact match.  It might not be if some template
13251          parameters are used in non-deduced contexts.  */
13252       if (strict == DEDUCE_EXACT)
13253         {
13254           unsigned int i;
13255
13256           tree sarg
13257             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
13258           if (return_type)
13259             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
13260           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
13261             if (!same_type_p (args[i], TREE_VALUE (sarg)))
13262               return 1;
13263         }
13264     }
13265
13266   return result;
13267 }
13268
13269 /* Adjust types before performing type deduction, as described in
13270    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
13271    sections are symmetric.  PARM is the type of a function parameter
13272    or the return type of the conversion function.  ARG is the type of
13273    the argument passed to the call, or the type of the value
13274    initialized with the result of the conversion function.
13275    ARG_EXPR is the original argument expression, which may be null.  */
13276
13277 static int
13278 maybe_adjust_types_for_deduction (unification_kind_t strict,
13279                                   tree* parm,
13280                                   tree* arg,
13281                                   tree arg_expr)
13282 {
13283   int result = 0;
13284
13285   switch (strict)
13286     {
13287     case DEDUCE_CALL:
13288       break;
13289
13290     case DEDUCE_CONV:
13291       {
13292         /* Swap PARM and ARG throughout the remainder of this
13293            function; the handling is precisely symmetric since PARM
13294            will initialize ARG rather than vice versa.  */
13295         tree* temp = parm;
13296         parm = arg;
13297         arg = temp;
13298         break;
13299       }
13300
13301     case DEDUCE_EXACT:
13302       /* Core issue #873: Do the DR606 thing (see below) for these cases,
13303          too, but here handle it by stripping the reference from PARM
13304          rather than by adding it to ARG.  */
13305       if (TREE_CODE (*parm) == REFERENCE_TYPE
13306           && TYPE_REF_IS_RVALUE (*parm)
13307           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13308           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13309           && TREE_CODE (*arg) == REFERENCE_TYPE
13310           && !TYPE_REF_IS_RVALUE (*arg))
13311         *parm = TREE_TYPE (*parm);
13312       /* Nothing else to do in this case.  */
13313       return 0;
13314
13315     default:
13316       gcc_unreachable ();
13317     }
13318
13319   if (TREE_CODE (*parm) != REFERENCE_TYPE)
13320     {
13321       /* [temp.deduct.call]
13322
13323          If P is not a reference type:
13324
13325          --If A is an array type, the pointer type produced by the
13326          array-to-pointer standard conversion (_conv.array_) is
13327          used in place of A for type deduction; otherwise,
13328
13329          --If A is a function type, the pointer type produced by
13330          the function-to-pointer standard conversion
13331          (_conv.func_) is used in place of A for type deduction;
13332          otherwise,
13333
13334          --If A is a cv-qualified type, the top level
13335          cv-qualifiers of A's type are ignored for type
13336          deduction.  */
13337       if (TREE_CODE (*arg) == ARRAY_TYPE)
13338         *arg = build_pointer_type (TREE_TYPE (*arg));
13339       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
13340         *arg = build_pointer_type (*arg);
13341       else
13342         *arg = TYPE_MAIN_VARIANT (*arg);
13343     }
13344
13345   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
13346      of the form T&&, where T is a template parameter, and the argument
13347      is an lvalue, T is deduced as A& */
13348   if (TREE_CODE (*parm) == REFERENCE_TYPE
13349       && TYPE_REF_IS_RVALUE (*parm)
13350       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13351       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13352       && arg_expr && real_lvalue_p (arg_expr))
13353     *arg = build_reference_type (*arg);
13354
13355   /* [temp.deduct.call]
13356
13357      If P is a cv-qualified type, the top level cv-qualifiers
13358      of P's type are ignored for type deduction.  If P is a
13359      reference type, the type referred to by P is used for
13360      type deduction.  */
13361   *parm = TYPE_MAIN_VARIANT (*parm);
13362   if (TREE_CODE (*parm) == REFERENCE_TYPE)
13363     {
13364       *parm = TREE_TYPE (*parm);
13365       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13366     }
13367
13368   /* DR 322. For conversion deduction, remove a reference type on parm
13369      too (which has been swapped into ARG).  */
13370   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
13371     *arg = TREE_TYPE (*arg);
13372
13373   return result;
13374 }
13375
13376 /* Most parms like fn_type_unification.
13377
13378    If SUBR is 1, we're being called recursively (to unify the
13379    arguments of a function or method parameter of a function
13380    template). */
13381
13382 static int
13383 type_unification_real (tree tparms,
13384                        tree targs,
13385                        tree xparms,
13386                        const tree *xargs,
13387                        unsigned int xnargs,
13388                        int subr,
13389                        unification_kind_t strict,
13390                        int flags)
13391 {
13392   tree parm, arg, arg_expr;
13393   int i;
13394   int ntparms = TREE_VEC_LENGTH (tparms);
13395   int sub_strict;
13396   int saw_undeduced = 0;
13397   tree parms;
13398   const tree *args;
13399   unsigned int nargs;
13400   unsigned int ia;
13401
13402   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
13403   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
13404   gcc_assert (ntparms > 0);
13405
13406   /* Reset the number of non-defaulted template arguments contained
13407      in in TARGS.  */
13408   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
13409
13410   switch (strict)
13411     {
13412     case DEDUCE_CALL:
13413       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
13414                     | UNIFY_ALLOW_DERIVED);
13415       break;
13416
13417     case DEDUCE_CONV:
13418       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13419       break;
13420
13421     case DEDUCE_EXACT:
13422       sub_strict = UNIFY_ALLOW_NONE;
13423       break;
13424
13425     default:
13426       gcc_unreachable ();
13427     }
13428
13429  again:
13430   parms = xparms;
13431   args = xargs;
13432   nargs = xnargs;
13433
13434   ia = 0;
13435   while (parms && parms != void_list_node
13436          && ia < nargs)
13437     {
13438       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13439         break;
13440
13441       parm = TREE_VALUE (parms);
13442       parms = TREE_CHAIN (parms);
13443       arg = args[ia];
13444       ++ia;
13445       arg_expr = NULL;
13446
13447       if (arg == error_mark_node)
13448         return 1;
13449       if (arg == unknown_type_node)
13450         /* We can't deduce anything from this, but we might get all the
13451            template args from other function args.  */
13452         continue;
13453
13454       /* Conversions will be performed on a function argument that
13455          corresponds with a function parameter that contains only
13456          non-deducible template parameters and explicitly specified
13457          template parameters.  */
13458       if (!uses_template_parms (parm))
13459         {
13460           tree type;
13461
13462           if (!TYPE_P (arg))
13463             type = TREE_TYPE (arg);
13464           else
13465             type = arg;
13466
13467           if (same_type_p (parm, type))
13468             continue;
13469           if (strict != DEDUCE_EXACT
13470               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
13471                                   flags))
13472             continue;
13473
13474           return 1;
13475         }
13476
13477       if (!TYPE_P (arg))
13478         {
13479           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13480           if (type_unknown_p (arg))
13481             {
13482               /* [temp.deduct.type] 
13483
13484                  A template-argument can be deduced from a pointer to
13485                  function or pointer to member function argument if
13486                  the set of overloaded functions does not contain
13487                  function templates and at most one of a set of
13488                  overloaded functions provides a unique match.  */
13489               if (resolve_overloaded_unification
13490                   (tparms, targs, parm, arg, strict, sub_strict))
13491                 continue;
13492
13493               return 1;
13494             }
13495           arg_expr = arg;
13496           arg = unlowered_expr_type (arg);
13497           if (arg == error_mark_node)
13498             return 1;
13499         }
13500
13501       {
13502         int arg_strict = sub_strict;
13503
13504         if (!subr)
13505           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
13506                                                           arg_expr);
13507
13508         if (arg == init_list_type_node && arg_expr)
13509           arg = arg_expr;
13510         if (unify (tparms, targs, parm, arg, arg_strict))
13511           return 1;
13512       }
13513     }
13514
13515
13516   if (parms 
13517       && parms != void_list_node
13518       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13519     {
13520       /* Unify the remaining arguments with the pack expansion type.  */
13521       tree argvec;
13522       tree parmvec = make_tree_vec (1);
13523
13524       /* Allocate a TREE_VEC and copy in all of the arguments */ 
13525       argvec = make_tree_vec (nargs - ia);
13526       for (i = 0; ia < nargs; ++ia, ++i)
13527         TREE_VEC_ELT (argvec, i) = args[ia];
13528
13529       /* Copy the parameter into parmvec.  */
13530       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
13531       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
13532                                 /*call_args_p=*/true, /*subr=*/subr))
13533         return 1;
13534
13535       /* Advance to the end of the list of parameters.  */
13536       parms = TREE_CHAIN (parms);
13537     }
13538
13539   /* Fail if we've reached the end of the parm list, and more args
13540      are present, and the parm list isn't variadic.  */
13541   if (ia < nargs && parms == void_list_node)
13542     return 1;
13543   /* Fail if parms are left and they don't have default values.  */
13544   if (parms && parms != void_list_node
13545       && TREE_PURPOSE (parms) == NULL_TREE)
13546     return 1;
13547
13548   if (!subr)
13549     for (i = 0; i < ntparms; i++)
13550       if (!TREE_VEC_ELT (targs, i))
13551         {
13552           tree tparm;
13553
13554           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
13555             continue;
13556
13557           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13558
13559           /* If this is an undeduced nontype parameter that depends on
13560              a type parameter, try another pass; its type may have been
13561              deduced from a later argument than the one from which
13562              this parameter can be deduced.  */
13563           if (TREE_CODE (tparm) == PARM_DECL
13564               && uses_template_parms (TREE_TYPE (tparm))
13565               && !saw_undeduced++)
13566             goto again;
13567
13568           /* Core issue #226 (C++0x) [temp.deduct]:
13569
13570                If a template argument has not been deduced, its
13571                default template argument, if any, is used. 
13572
13573              When we are in C++98 mode, TREE_PURPOSE will either
13574              be NULL_TREE or ERROR_MARK_NODE, so we do not need
13575              to explicitly check cxx_dialect here.  */
13576           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
13577             {
13578               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13579               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
13580               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
13581               arg = convert_template_argument (parm, arg, targs, tf_none,
13582                                                i, NULL_TREE);
13583               if (arg == error_mark_node)
13584                 return 1;
13585               else
13586                 {
13587                   TREE_VEC_ELT (targs, i) = arg;
13588                   /* The position of the first default template argument,
13589                      is also the number of non-defaulted arguments in TARGS.
13590                      Record that.  */
13591                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
13592                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
13593                   continue;
13594                 }
13595             }
13596
13597           /* If the type parameter is a parameter pack, then it will
13598              be deduced to an empty parameter pack.  */
13599           if (template_parameter_pack_p (tparm))
13600             {
13601               tree arg;
13602
13603               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
13604                 {
13605                   arg = make_node (NONTYPE_ARGUMENT_PACK);
13606                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
13607                   TREE_CONSTANT (arg) = 1;
13608                 }
13609               else
13610                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
13611
13612               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
13613
13614               TREE_VEC_ELT (targs, i) = arg;
13615               continue;
13616             }
13617
13618           return 2;
13619         }
13620 #ifdef ENABLE_CHECKING
13621   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
13622     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
13623 #endif
13624
13625   return 0;
13626 }
13627
13628 /* Subroutine of type_unification_real.  Args are like the variables
13629    at the call site.  ARG is an overloaded function (or template-id);
13630    we try deducing template args from each of the overloads, and if
13631    only one succeeds, we go with that.  Modifies TARGS and returns
13632    true on success.  */
13633
13634 static bool
13635 resolve_overloaded_unification (tree tparms,
13636                                 tree targs,
13637                                 tree parm,
13638                                 tree arg,
13639                                 unification_kind_t strict,
13640                                 int sub_strict)
13641 {
13642   tree tempargs = copy_node (targs);
13643   int good = 0;
13644   tree goodfn = NULL_TREE;
13645   bool addr_p;
13646
13647   if (TREE_CODE (arg) == ADDR_EXPR)
13648     {
13649       arg = TREE_OPERAND (arg, 0);
13650       addr_p = true;
13651     }
13652   else
13653     addr_p = false;
13654
13655   if (TREE_CODE (arg) == COMPONENT_REF)
13656     /* Handle `&x' where `x' is some static or non-static member
13657        function name.  */
13658     arg = TREE_OPERAND (arg, 1);
13659
13660   if (TREE_CODE (arg) == OFFSET_REF)
13661     arg = TREE_OPERAND (arg, 1);
13662
13663   /* Strip baselink information.  */
13664   if (BASELINK_P (arg))
13665     arg = BASELINK_FUNCTIONS (arg);
13666
13667   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
13668     {
13669       /* If we got some explicit template args, we need to plug them into
13670          the affected templates before we try to unify, in case the
13671          explicit args will completely resolve the templates in question.  */
13672
13673       tree expl_subargs = TREE_OPERAND (arg, 1);
13674       arg = TREE_OPERAND (arg, 0);
13675
13676       for (; arg; arg = OVL_NEXT (arg))
13677         {
13678           tree fn = OVL_CURRENT (arg);
13679           tree subargs, elem;
13680
13681           if (TREE_CODE (fn) != TEMPLATE_DECL)
13682             continue;
13683
13684           ++processing_template_decl;
13685           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13686                                   expl_subargs, /*check_ret=*/false);
13687           if (subargs)
13688             {
13689               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
13690               if (try_one_overload (tparms, targs, tempargs, parm,
13691                                     elem, strict, sub_strict, addr_p)
13692                   && (!goodfn || !decls_match (goodfn, elem)))
13693                 {
13694                   goodfn = elem;
13695                   ++good;
13696                 }
13697             }
13698           --processing_template_decl;
13699         }
13700     }
13701   else if (TREE_CODE (arg) != OVERLOAD
13702            && TREE_CODE (arg) != FUNCTION_DECL)
13703     /* If ARG is, for example, "(0, &f)" then its type will be unknown
13704        -- but the deduction does not succeed because the expression is
13705        not just the function on its own.  */
13706     return false;
13707   else
13708     for (; arg; arg = OVL_NEXT (arg))
13709       if (try_one_overload (tparms, targs, tempargs, parm,
13710                             TREE_TYPE (OVL_CURRENT (arg)),
13711                             strict, sub_strict, addr_p)
13712           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
13713         {
13714           goodfn = OVL_CURRENT (arg);
13715           ++good;
13716         }
13717
13718   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13719      to function or pointer to member function argument if the set of
13720      overloaded functions does not contain function templates and at most
13721      one of a set of overloaded functions provides a unique match.
13722
13723      So if we found multiple possibilities, we return success but don't
13724      deduce anything.  */
13725
13726   if (good == 1)
13727     {
13728       int i = TREE_VEC_LENGTH (targs);
13729       for (; i--; )
13730         if (TREE_VEC_ELT (tempargs, i))
13731           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
13732     }
13733   if (good)
13734     return true;
13735
13736   return false;
13737 }
13738
13739 /* Core DR 115: In contexts where deduction is done and fails, or in
13740    contexts where deduction is not done, if a template argument list is
13741    specified and it, along with any default template arguments, identifies
13742    a single function template specialization, then the template-id is an
13743    lvalue for the function template specialization.  */
13744
13745 tree
13746 resolve_nondeduced_context (tree orig_expr)
13747 {
13748   tree expr, offset, baselink;
13749   bool addr;
13750
13751   if (!type_unknown_p (orig_expr))
13752     return orig_expr;
13753
13754   expr = orig_expr;
13755   addr = false;
13756   offset = NULL_TREE;
13757   baselink = NULL_TREE;
13758
13759   if (TREE_CODE (expr) == ADDR_EXPR)
13760     {
13761       expr = TREE_OPERAND (expr, 0);
13762       addr = true;
13763     }
13764   if (TREE_CODE (expr) == OFFSET_REF)
13765     {
13766       offset = expr;
13767       expr = TREE_OPERAND (expr, 1);
13768     }
13769   if (TREE_CODE (expr) == BASELINK)
13770     {
13771       baselink = expr;
13772       expr = BASELINK_FUNCTIONS (expr);
13773     }
13774
13775   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
13776     {
13777       int good = 0;
13778       tree goodfn = NULL_TREE;
13779
13780       /* If we got some explicit template args, we need to plug them into
13781          the affected templates before we try to unify, in case the
13782          explicit args will completely resolve the templates in question.  */
13783
13784       tree expl_subargs = TREE_OPERAND (expr, 1);
13785       tree arg = TREE_OPERAND (expr, 0);
13786       tree badfn = NULL_TREE;
13787       tree badargs = NULL_TREE;
13788
13789       for (; arg; arg = OVL_NEXT (arg))
13790         {
13791           tree fn = OVL_CURRENT (arg);
13792           tree subargs, elem;
13793
13794           if (TREE_CODE (fn) != TEMPLATE_DECL)
13795             continue;
13796
13797           ++processing_template_decl;
13798           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13799                                   expl_subargs, /*check_ret=*/false);
13800           if (subargs && !any_dependent_template_arguments_p (subargs))
13801             {
13802               elem = instantiate_template (fn, subargs, tf_none);
13803               if (elem == error_mark_node)
13804                 {
13805                   badfn = fn;
13806                   badargs = subargs;
13807                 }
13808               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
13809                 {
13810                   goodfn = elem;
13811                   ++good;
13812                 }
13813             }
13814           --processing_template_decl;
13815         }
13816       if (good == 1)
13817         {
13818           expr = goodfn;
13819           if (baselink)
13820             expr = build_baselink (BASELINK_BINFO (baselink),
13821                                    BASELINK_ACCESS_BINFO (baselink),
13822                                    expr, BASELINK_OPTYPE (baselink));
13823           if (offset)
13824             expr = build2 (OFFSET_REF, TREE_TYPE (expr),
13825                            TREE_OPERAND (offset, 0), expr);
13826           if (addr)
13827             expr = build_address (expr);
13828           return expr;
13829         }
13830       else if (good == 0 && badargs)
13831         /* There were no good options and at least one bad one, so let the
13832            user know what the problem is.  */
13833         instantiate_template (badfn, badargs, tf_warning_or_error);
13834     }
13835   return orig_expr;
13836 }
13837
13838 /* Subroutine of resolve_overloaded_unification; does deduction for a single
13839    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
13840    different overloads deduce different arguments for a given parm.
13841    ADDR_P is true if the expression for which deduction is being
13842    performed was of the form "& fn" rather than simply "fn".
13843
13844    Returns 1 on success.  */
13845
13846 static int
13847 try_one_overload (tree tparms,
13848                   tree orig_targs,
13849                   tree targs,
13850                   tree parm,
13851                   tree arg,
13852                   unification_kind_t strict,
13853                   int sub_strict,
13854                   bool addr_p)
13855 {
13856   int nargs;
13857   tree tempargs;
13858   int i;
13859
13860   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13861      to function or pointer to member function argument if the set of
13862      overloaded functions does not contain function templates and at most
13863      one of a set of overloaded functions provides a unique match.
13864
13865      So if this is a template, just return success.  */
13866
13867   if (uses_template_parms (arg))
13868     return 1;
13869
13870   if (TREE_CODE (arg) == METHOD_TYPE)
13871     arg = build_ptrmemfunc_type (build_pointer_type (arg));
13872   else if (addr_p)
13873     arg = build_pointer_type (arg);
13874
13875   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
13876
13877   /* We don't copy orig_targs for this because if we have already deduced
13878      some template args from previous args, unify would complain when we
13879      try to deduce a template parameter for the same argument, even though
13880      there isn't really a conflict.  */
13881   nargs = TREE_VEC_LENGTH (targs);
13882   tempargs = make_tree_vec (nargs);
13883
13884   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
13885     return 0;
13886
13887   /* First make sure we didn't deduce anything that conflicts with
13888      explicitly specified args.  */
13889   for (i = nargs; i--; )
13890     {
13891       tree elt = TREE_VEC_ELT (tempargs, i);
13892       tree oldelt = TREE_VEC_ELT (orig_targs, i);
13893
13894       if (!elt)
13895         /*NOP*/;
13896       else if (uses_template_parms (elt))
13897         /* Since we're unifying against ourselves, we will fill in
13898            template args used in the function parm list with our own
13899            template parms.  Discard them.  */
13900         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
13901       else if (oldelt && !template_args_equal (oldelt, elt))
13902         return 0;
13903     }
13904
13905   for (i = nargs; i--; )
13906     {
13907       tree elt = TREE_VEC_ELT (tempargs, i);
13908
13909       if (elt)
13910         TREE_VEC_ELT (targs, i) = elt;
13911     }
13912
13913   return 1;
13914 }
13915
13916 /* PARM is a template class (perhaps with unbound template
13917    parameters).  ARG is a fully instantiated type.  If ARG can be
13918    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
13919    TARGS are as for unify.  */
13920
13921 static tree
13922 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
13923 {
13924   tree copy_of_targs;
13925
13926   if (!CLASSTYPE_TEMPLATE_INFO (arg)
13927       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
13928           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
13929     return NULL_TREE;
13930
13931   /* We need to make a new template argument vector for the call to
13932      unify.  If we used TARGS, we'd clutter it up with the result of
13933      the attempted unification, even if this class didn't work out.
13934      We also don't want to commit ourselves to all the unifications
13935      we've already done, since unification is supposed to be done on
13936      an argument-by-argument basis.  In other words, consider the
13937      following pathological case:
13938
13939        template <int I, int J, int K>
13940        struct S {};
13941
13942        template <int I, int J>
13943        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
13944
13945        template <int I, int J, int K>
13946        void f(S<I, J, K>, S<I, I, I>);
13947
13948        void g() {
13949          S<0, 0, 0> s0;
13950          S<0, 1, 2> s2;
13951
13952          f(s0, s2);
13953        }
13954
13955      Now, by the time we consider the unification involving `s2', we
13956      already know that we must have `f<0, 0, 0>'.  But, even though
13957      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
13958      because there are two ways to unify base classes of S<0, 1, 2>
13959      with S<I, I, I>.  If we kept the already deduced knowledge, we
13960      would reject the possibility I=1.  */
13961   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
13962
13963   /* If unification failed, we're done.  */
13964   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
13965              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
13966     return NULL_TREE;
13967
13968   return arg;
13969 }
13970
13971 /* Given a template type PARM and a class type ARG, find the unique
13972    base type in ARG that is an instance of PARM.  We do not examine
13973    ARG itself; only its base-classes.  If there is not exactly one
13974    appropriate base class, return NULL_TREE.  PARM may be the type of
13975    a partial specialization, as well as a plain template type.  Used
13976    by unify.  */
13977
13978 static tree
13979 get_template_base (tree tparms, tree targs, tree parm, tree arg)
13980 {
13981   tree rval = NULL_TREE;
13982   tree binfo;
13983
13984   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
13985
13986   binfo = TYPE_BINFO (complete_type (arg));
13987   if (!binfo)
13988     /* The type could not be completed.  */
13989     return NULL_TREE;
13990
13991   /* Walk in inheritance graph order.  The search order is not
13992      important, and this avoids multiple walks of virtual bases.  */
13993   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
13994     {
13995       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
13996
13997       if (r)
13998         {
13999           /* If there is more than one satisfactory baseclass, then:
14000
14001                [temp.deduct.call]
14002
14003               If they yield more than one possible deduced A, the type
14004               deduction fails.
14005
14006              applies.  */
14007           if (rval && !same_type_p (r, rval))
14008             return NULL_TREE;
14009
14010           rval = r;
14011         }
14012     }
14013
14014   return rval;
14015 }
14016
14017 /* Returns the level of DECL, which declares a template parameter.  */
14018
14019 static int
14020 template_decl_level (tree decl)
14021 {
14022   switch (TREE_CODE (decl))
14023     {
14024     case TYPE_DECL:
14025     case TEMPLATE_DECL:
14026       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
14027
14028     case PARM_DECL:
14029       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
14030
14031     default:
14032       gcc_unreachable ();
14033     }
14034   return 0;
14035 }
14036
14037 /* Decide whether ARG can be unified with PARM, considering only the
14038    cv-qualifiers of each type, given STRICT as documented for unify.
14039    Returns nonzero iff the unification is OK on that basis.  */
14040
14041 static int
14042 check_cv_quals_for_unify (int strict, tree arg, tree parm)
14043 {
14044   int arg_quals = cp_type_quals (arg);
14045   int parm_quals = cp_type_quals (parm);
14046
14047   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14048       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14049     {
14050       /*  Although a CVR qualifier is ignored when being applied to a
14051           substituted template parameter ([8.3.2]/1 for example), that
14052           does not apply during deduction [14.8.2.4]/1, (even though
14053           that is not explicitly mentioned, [14.8.2.4]/9 indicates
14054           this).  Except when we're allowing additional CV qualifiers
14055           at the outer level [14.8.2.1]/3,1st bullet.  */
14056       if ((TREE_CODE (arg) == REFERENCE_TYPE
14057            || TREE_CODE (arg) == FUNCTION_TYPE
14058            || TREE_CODE (arg) == METHOD_TYPE)
14059           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
14060         return 0;
14061
14062       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
14063           && (parm_quals & TYPE_QUAL_RESTRICT))
14064         return 0;
14065     }
14066
14067   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14068       && (arg_quals & parm_quals) != parm_quals)
14069     return 0;
14070
14071   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
14072       && (parm_quals & arg_quals) != arg_quals)
14073     return 0;
14074
14075   return 1;
14076 }
14077
14078 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
14079 void 
14080 template_parm_level_and_index (tree parm, int* level, int* index)
14081 {
14082   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14083       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14084       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14085     {
14086       *index = TEMPLATE_TYPE_IDX (parm);
14087       *level = TEMPLATE_TYPE_LEVEL (parm);
14088     }
14089   else
14090     {
14091       *index = TEMPLATE_PARM_IDX (parm);
14092       *level = TEMPLATE_PARM_LEVEL (parm);
14093     }
14094 }
14095
14096 /* Unifies the remaining arguments in PACKED_ARGS with the pack
14097    expansion at the end of PACKED_PARMS. Returns 0 if the type
14098    deduction succeeds, 1 otherwise. STRICT is the same as in
14099    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
14100    call argument list. We'll need to adjust the arguments to make them
14101    types. SUBR tells us if this is from a recursive call to
14102    type_unification_real.  */
14103 int
14104 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
14105                       tree packed_args, int strict, bool call_args_p,
14106                       bool subr)
14107 {
14108   tree parm 
14109     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
14110   tree pattern = PACK_EXPANSION_PATTERN (parm);
14111   tree pack, packs = NULL_TREE;
14112   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
14113   int len = TREE_VEC_LENGTH (packed_args);
14114
14115   /* Determine the parameter packs we will be deducing from the
14116      pattern, and record their current deductions.  */
14117   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
14118        pack; pack = TREE_CHAIN (pack))
14119     {
14120       tree parm_pack = TREE_VALUE (pack);
14121       int idx, level;
14122
14123       /* Determine the index and level of this parameter pack.  */
14124       template_parm_level_and_index (parm_pack, &level, &idx);
14125
14126       /* Keep track of the parameter packs and their corresponding
14127          argument packs.  */
14128       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
14129       TREE_TYPE (packs) = make_tree_vec (len - start);
14130     }
14131   
14132   /* Loop through all of the arguments that have not yet been
14133      unified and unify each with the pattern.  */
14134   for (i = start; i < len; i++)
14135     {
14136       tree parm = pattern;
14137
14138       /* For each parameter pack, clear out the deduced value so that
14139          we can deduce it again.  */
14140       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14141         {
14142           int idx, level;
14143           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14144
14145           TMPL_ARG (targs, level, idx) = NULL_TREE;
14146         }
14147
14148       /* Unify the pattern with the current argument.  */
14149       {
14150         tree arg = TREE_VEC_ELT (packed_args, i);
14151         tree arg_expr = NULL_TREE;
14152         int arg_strict = strict;
14153         bool skip_arg_p = false;
14154
14155         if (call_args_p)
14156           {
14157             int sub_strict;
14158
14159             /* This mirrors what we do in type_unification_real.  */
14160             switch (strict)
14161               {
14162               case DEDUCE_CALL:
14163                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
14164                               | UNIFY_ALLOW_MORE_CV_QUAL
14165                               | UNIFY_ALLOW_DERIVED);
14166                 break;
14167                 
14168               case DEDUCE_CONV:
14169                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14170                 break;
14171                 
14172               case DEDUCE_EXACT:
14173                 sub_strict = UNIFY_ALLOW_NONE;
14174                 break;
14175                 
14176               default:
14177                 gcc_unreachable ();
14178               }
14179
14180             if (!TYPE_P (arg))
14181               {
14182                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14183                 if (type_unknown_p (arg))
14184                   {
14185                     /* [temp.deduct.type] A template-argument can be
14186                        deduced from a pointer to function or pointer
14187                        to member function argument if the set of
14188                        overloaded functions does not contain function
14189                        templates and at most one of a set of
14190                        overloaded functions provides a unique
14191                        match.  */
14192
14193                     if (resolve_overloaded_unification
14194                         (tparms, targs, parm, arg,
14195                          (unification_kind_t) strict,
14196                          sub_strict)
14197                         != 0)
14198                       return 1;
14199                     skip_arg_p = true;
14200                   }
14201
14202                 if (!skip_arg_p)
14203                   {
14204                     arg_expr = arg;
14205                     arg = unlowered_expr_type (arg);
14206                     if (arg == error_mark_node)
14207                       return 1;
14208                   }
14209               }
14210       
14211             arg_strict = sub_strict;
14212
14213             if (!subr)
14214               arg_strict |= 
14215                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
14216                                                   &parm, &arg, arg_expr);
14217           }
14218
14219         if (!skip_arg_p)
14220           {
14221             /* For deduction from an init-list we need the actual list.  */
14222             if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
14223               arg = arg_expr;
14224             if (unify (tparms, targs, parm, arg, arg_strict))
14225               return 1;
14226           }
14227       }
14228
14229       /* For each parameter pack, collect the deduced value.  */
14230       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14231         {
14232           int idx, level;
14233           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14234
14235           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
14236             TMPL_ARG (targs, level, idx);
14237         }
14238     }
14239
14240   /* Verify that the results of unification with the parameter packs
14241      produce results consistent with what we've seen before, and make
14242      the deduced argument packs available.  */
14243   for (pack = packs; pack; pack = TREE_CHAIN (pack))
14244     {
14245       tree old_pack = TREE_VALUE (pack);
14246       tree new_args = TREE_TYPE (pack);
14247       int i, len = TREE_VEC_LENGTH (new_args);
14248       int idx, level;
14249       bool nondeduced_p = false;
14250
14251       /* By default keep the original deduced argument pack.
14252          If necessary, more specific code is going to update the
14253          resulting deduced argument later down in this function.  */
14254       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14255       TMPL_ARG (targs, level, idx) = old_pack;
14256
14257       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
14258          actually deduce anything.  */
14259       for (i = 0; i < len && !nondeduced_p; ++i)
14260         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
14261           nondeduced_p = true;
14262       if (nondeduced_p)
14263         continue;
14264
14265       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
14266         {
14267           /* Prepend the explicit arguments onto NEW_ARGS.  */
14268           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14269           tree old_args = new_args;
14270           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
14271           int len = explicit_len + TREE_VEC_LENGTH (old_args);
14272
14273           /* Copy the explicit arguments.  */
14274           new_args = make_tree_vec (len);
14275           for (i = 0; i < explicit_len; i++)
14276             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
14277
14278           /* Copy the deduced arguments.  */
14279           for (; i < len; i++)
14280             TREE_VEC_ELT (new_args, i) =
14281               TREE_VEC_ELT (old_args, i - explicit_len);
14282         }
14283
14284       if (!old_pack)
14285         {
14286           tree result;
14287           /* Build the deduced *_ARGUMENT_PACK.  */
14288           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
14289             {
14290               result = make_node (NONTYPE_ARGUMENT_PACK);
14291               TREE_TYPE (result) = 
14292                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
14293               TREE_CONSTANT (result) = 1;
14294             }
14295           else
14296             result = cxx_make_type (TYPE_ARGUMENT_PACK);
14297
14298           SET_ARGUMENT_PACK_ARGS (result, new_args);
14299
14300           /* Note the deduced argument packs for this parameter
14301              pack.  */
14302           TMPL_ARG (targs, level, idx) = result;
14303         }
14304       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
14305                && (ARGUMENT_PACK_ARGS (old_pack) 
14306                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
14307         {
14308           /* We only had the explicitly-provided arguments before, but
14309              now we have a complete set of arguments.  */
14310           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14311
14312           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
14313           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
14314           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
14315         }
14316       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
14317                                     new_args))
14318         /* Inconsistent unification of this parameter pack.  */
14319         return 1;
14320     }
14321
14322   return 0;
14323 }
14324
14325 /* Deduce the value of template parameters.  TPARMS is the (innermost)
14326    set of template parameters to a template.  TARGS is the bindings
14327    for those template parameters, as determined thus far; TARGS may
14328    include template arguments for outer levels of template parameters
14329    as well.  PARM is a parameter to a template function, or a
14330    subcomponent of that parameter; ARG is the corresponding argument.
14331    This function attempts to match PARM with ARG in a manner
14332    consistent with the existing assignments in TARGS.  If more values
14333    are deduced, then TARGS is updated.
14334
14335    Returns 0 if the type deduction succeeds, 1 otherwise.  The
14336    parameter STRICT is a bitwise or of the following flags:
14337
14338      UNIFY_ALLOW_NONE:
14339        Require an exact match between PARM and ARG.
14340      UNIFY_ALLOW_MORE_CV_QUAL:
14341        Allow the deduced ARG to be more cv-qualified (by qualification
14342        conversion) than ARG.
14343      UNIFY_ALLOW_LESS_CV_QUAL:
14344        Allow the deduced ARG to be less cv-qualified than ARG.
14345      UNIFY_ALLOW_DERIVED:
14346        Allow the deduced ARG to be a template base class of ARG,
14347        or a pointer to a template base class of the type pointed to by
14348        ARG.
14349      UNIFY_ALLOW_INTEGER:
14350        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
14351        case for more information.
14352      UNIFY_ALLOW_OUTER_LEVEL:
14353        This is the outermost level of a deduction. Used to determine validity
14354        of qualification conversions. A valid qualification conversion must
14355        have const qualified pointers leading up to the inner type which
14356        requires additional CV quals, except at the outer level, where const
14357        is not required [conv.qual]. It would be normal to set this flag in
14358        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
14359      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
14360        This is the outermost level of a deduction, and PARM can be more CV
14361        qualified at this point.
14362      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
14363        This is the outermost level of a deduction, and PARM can be less CV
14364        qualified at this point.  */
14365
14366 static int
14367 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
14368 {
14369   int idx;
14370   tree targ;
14371   tree tparm;
14372   int strict_in = strict;
14373
14374   /* I don't think this will do the right thing with respect to types.
14375      But the only case I've seen it in so far has been array bounds, where
14376      signedness is the only information lost, and I think that will be
14377      okay.  */
14378   while (TREE_CODE (parm) == NOP_EXPR)
14379     parm = TREE_OPERAND (parm, 0);
14380
14381   if (arg == error_mark_node)
14382     return 1;
14383   if (arg == unknown_type_node
14384       || arg == init_list_type_node)
14385     /* We can't deduce anything from this, but we might get all the
14386        template args from other function args.  */
14387     return 0;
14388
14389   /* If PARM uses template parameters, then we can't bail out here,
14390      even if ARG == PARM, since we won't record unifications for the
14391      template parameters.  We might need them if we're trying to
14392      figure out which of two things is more specialized.  */
14393   if (arg == parm && !uses_template_parms (parm))
14394     return 0;
14395
14396   /* Handle init lists early, so the rest of the function can assume
14397      we're dealing with a type. */
14398   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
14399     {
14400       tree elt, elttype;
14401       unsigned i;
14402       tree orig_parm = parm;
14403
14404       /* Replace T with std::initializer_list<T> for deduction.  */
14405       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14406           && flag_deduce_init_list)
14407         parm = listify (parm);
14408
14409       if (!is_std_init_list (parm))
14410         /* We can only deduce from an initializer list argument if the
14411            parameter is std::initializer_list; otherwise this is a
14412            non-deduced context. */
14413         return 0;
14414
14415       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
14416
14417       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
14418         {
14419           int elt_strict = strict;
14420           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
14421             {
14422               tree type = TREE_TYPE (elt);
14423               /* It should only be possible to get here for a call.  */
14424               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
14425               elt_strict |= maybe_adjust_types_for_deduction
14426                 (DEDUCE_CALL, &elttype, &type, elt);
14427               elt = type;
14428             }
14429
14430           if (unify (tparms, targs, elttype, elt, elt_strict))
14431             return 1;
14432         }
14433
14434       /* If the std::initializer_list<T> deduction worked, replace the
14435          deduced A with std::initializer_list<A>.  */
14436       if (orig_parm != parm)
14437         {
14438           idx = TEMPLATE_TYPE_IDX (orig_parm);
14439           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14440           targ = listify (targ);
14441           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
14442         }
14443       return 0;
14444     }
14445
14446   /* Immediately reject some pairs that won't unify because of
14447      cv-qualification mismatches.  */
14448   if (TREE_CODE (arg) == TREE_CODE (parm)
14449       && TYPE_P (arg)
14450       /* It is the elements of the array which hold the cv quals of an array
14451          type, and the elements might be template type parms. We'll check
14452          when we recurse.  */
14453       && TREE_CODE (arg) != ARRAY_TYPE
14454       /* We check the cv-qualifiers when unifying with template type
14455          parameters below.  We want to allow ARG `const T' to unify with
14456          PARM `T' for example, when computing which of two templates
14457          is more specialized, for example.  */
14458       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
14459       && !check_cv_quals_for_unify (strict_in, arg, parm))
14460     return 1;
14461
14462   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
14463       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
14464     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
14465   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
14466   strict &= ~UNIFY_ALLOW_DERIVED;
14467   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14468   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
14469
14470   switch (TREE_CODE (parm))
14471     {
14472     case TYPENAME_TYPE:
14473     case SCOPE_REF:
14474     case UNBOUND_CLASS_TEMPLATE:
14475       /* In a type which contains a nested-name-specifier, template
14476          argument values cannot be deduced for template parameters used
14477          within the nested-name-specifier.  */
14478       return 0;
14479
14480     case TEMPLATE_TYPE_PARM:
14481     case TEMPLATE_TEMPLATE_PARM:
14482     case BOUND_TEMPLATE_TEMPLATE_PARM:
14483       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14484       if (tparm == error_mark_node)
14485         return 1;
14486
14487       if (TEMPLATE_TYPE_LEVEL (parm)
14488           != template_decl_level (tparm))
14489         /* The PARM is not one we're trying to unify.  Just check
14490            to see if it matches ARG.  */
14491         return (TREE_CODE (arg) == TREE_CODE (parm)
14492                 && same_type_p (parm, arg)) ? 0 : 1;
14493       idx = TEMPLATE_TYPE_IDX (parm);
14494       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14495       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
14496
14497       /* Check for mixed types and values.  */
14498       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14499            && TREE_CODE (tparm) != TYPE_DECL)
14500           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14501               && TREE_CODE (tparm) != TEMPLATE_DECL))
14502         return 1;
14503
14504       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14505         {
14506           /* ARG must be constructed from a template class or a template
14507              template parameter.  */
14508           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
14509               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
14510             return 1;
14511
14512           {
14513             tree parmvec = TYPE_TI_ARGS (parm);
14514             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
14515             tree parm_parms 
14516               = DECL_INNERMOST_TEMPLATE_PARMS
14517                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
14518             int i, len;
14519             int parm_variadic_p = 0;
14520
14521             /* The resolution to DR150 makes clear that default
14522                arguments for an N-argument may not be used to bind T
14523                to a template template parameter with fewer than N
14524                parameters.  It is not safe to permit the binding of
14525                default arguments as an extension, as that may change
14526                the meaning of a conforming program.  Consider:
14527
14528                   struct Dense { static const unsigned int dim = 1; };
14529
14530                   template <template <typename> class View,
14531                             typename Block>
14532                   void operator+(float, View<Block> const&);
14533
14534                   template <typename Block,
14535                             unsigned int Dim = Block::dim>
14536                   struct Lvalue_proxy { operator float() const; };
14537
14538                   void
14539                   test_1d (void) {
14540                     Lvalue_proxy<Dense> p;
14541                     float b;
14542                     b + p;
14543                   }
14544
14545               Here, if Lvalue_proxy is permitted to bind to View, then
14546               the global operator+ will be used; if they are not, the
14547               Lvalue_proxy will be converted to float.  */
14548             if (coerce_template_parms (parm_parms,
14549                                        argvec,
14550                                        TYPE_TI_TEMPLATE (parm),
14551                                        tf_none,
14552                                        /*require_all_args=*/true,
14553                                        /*use_default_args=*/false)
14554                 == error_mark_node)
14555               return 1;
14556
14557             /* Deduce arguments T, i from TT<T> or TT<i>.
14558                We check each element of PARMVEC and ARGVEC individually
14559                rather than the whole TREE_VEC since they can have
14560                different number of elements.  */
14561
14562             parmvec = expand_template_argument_pack (parmvec);
14563             argvec = expand_template_argument_pack (argvec);
14564
14565             len = TREE_VEC_LENGTH (parmvec);
14566
14567             /* Check if the parameters end in a pack, making them
14568                variadic.  */
14569             if (len > 0
14570                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
14571               parm_variadic_p = 1;
14572             
14573             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
14574               return 1;
14575
14576              for (i = 0; i < len - parm_variadic_p; ++i)
14577               {
14578                 if (unify (tparms, targs,
14579                            TREE_VEC_ELT (parmvec, i),
14580                            TREE_VEC_ELT (argvec, i),
14581                            UNIFY_ALLOW_NONE))
14582                   return 1;
14583               }
14584
14585             if (parm_variadic_p
14586                 && unify_pack_expansion (tparms, targs,
14587                                          parmvec, argvec,
14588                                          UNIFY_ALLOW_NONE,
14589                                          /*call_args_p=*/false,
14590                                          /*subr=*/false))
14591               return 1;
14592           }
14593           arg = TYPE_TI_TEMPLATE (arg);
14594
14595           /* Fall through to deduce template name.  */
14596         }
14597
14598       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14599           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14600         {
14601           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
14602
14603           /* Simple cases: Value already set, does match or doesn't.  */
14604           if (targ != NULL_TREE && template_args_equal (targ, arg))
14605             return 0;
14606           else if (targ)
14607             return 1;
14608         }
14609       else
14610         {
14611           /* If PARM is `const T' and ARG is only `int', we don't have
14612              a match unless we are allowing additional qualification.
14613              If ARG is `const int' and PARM is just `T' that's OK;
14614              that binds `const int' to `T'.  */
14615           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
14616                                          arg, parm))
14617             return 1;
14618
14619           /* Consider the case where ARG is `const volatile int' and
14620              PARM is `const T'.  Then, T should be `volatile int'.  */
14621           arg = cp_build_qualified_type_real
14622             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
14623           if (arg == error_mark_node)
14624             return 1;
14625
14626           /* Simple cases: Value already set, does match or doesn't.  */
14627           if (targ != NULL_TREE && same_type_p (targ, arg))
14628             return 0;
14629           else if (targ)
14630             return 1;
14631
14632           /* Make sure that ARG is not a variable-sized array.  (Note
14633              that were talking about variable-sized arrays (like
14634              `int[n]'), rather than arrays of unknown size (like
14635              `int[]').)  We'll get very confused by such a type since
14636              the bound of the array will not be computable in an
14637              instantiation.  Besides, such types are not allowed in
14638              ISO C++, so we can do as we please here.  */
14639           if (variably_modified_type_p (arg, NULL_TREE))
14640             return 1;
14641
14642           /* Strip typedefs as in convert_template_argument.  */
14643           arg = strip_typedefs (arg);
14644         }
14645
14646       /* If ARG is a parameter pack or an expansion, we cannot unify
14647          against it unless PARM is also a parameter pack.  */
14648       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14649           && !template_parameter_pack_p (parm))
14650         return 1;
14651
14652       /* If the argument deduction results is a METHOD_TYPE,
14653          then there is a problem.
14654          METHOD_TYPE doesn't map to any real C++ type the result of
14655          the deduction can not be of that type.  */
14656       if (TREE_CODE (arg) == METHOD_TYPE)
14657         return 1;
14658
14659       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14660       return 0;
14661
14662     case TEMPLATE_PARM_INDEX:
14663       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14664       if (tparm == error_mark_node)
14665         return 1;
14666
14667       if (TEMPLATE_PARM_LEVEL (parm)
14668           != template_decl_level (tparm))
14669         /* The PARM is not one we're trying to unify.  Just check
14670            to see if it matches ARG.  */
14671         return !(TREE_CODE (arg) == TREE_CODE (parm)
14672                  && cp_tree_equal (parm, arg));
14673
14674       idx = TEMPLATE_PARM_IDX (parm);
14675       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14676
14677       if (targ)
14678         return !cp_tree_equal (targ, arg);
14679
14680       /* [temp.deduct.type] If, in the declaration of a function template
14681          with a non-type template-parameter, the non-type
14682          template-parameter is used in an expression in the function
14683          parameter-list and, if the corresponding template-argument is
14684          deduced, the template-argument type shall match the type of the
14685          template-parameter exactly, except that a template-argument
14686          deduced from an array bound may be of any integral type.
14687          The non-type parameter might use already deduced type parameters.  */
14688       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
14689       if (!TREE_TYPE (arg))
14690         /* Template-parameter dependent expression.  Just accept it for now.
14691            It will later be processed in convert_template_argument.  */
14692         ;
14693       else if (same_type_p (TREE_TYPE (arg), tparm))
14694         /* OK */;
14695       else if ((strict & UNIFY_ALLOW_INTEGER)
14696                && (TREE_CODE (tparm) == INTEGER_TYPE
14697                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
14698         /* Convert the ARG to the type of PARM; the deduced non-type
14699            template argument must exactly match the types of the
14700            corresponding parameter.  */
14701         arg = fold (build_nop (tparm, arg));
14702       else if (uses_template_parms (tparm))
14703         /* We haven't deduced the type of this parameter yet.  Try again
14704            later.  */
14705         return 0;
14706       else
14707         return 1;
14708
14709       /* If ARG is a parameter pack or an expansion, we cannot unify
14710          against it unless PARM is also a parameter pack.  */
14711       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14712           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
14713         return 1;
14714
14715       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14716       return 0;
14717
14718     case PTRMEM_CST:
14719      {
14720         /* A pointer-to-member constant can be unified only with
14721          another constant.  */
14722       if (TREE_CODE (arg) != PTRMEM_CST)
14723         return 1;
14724
14725       /* Just unify the class member. It would be useless (and possibly
14726          wrong, depending on the strict flags) to unify also
14727          PTRMEM_CST_CLASS, because we want to be sure that both parm and
14728          arg refer to the same variable, even if through different
14729          classes. For instance:
14730
14731          struct A { int x; };
14732          struct B : A { };
14733
14734          Unification of &A::x and &B::x must succeed.  */
14735       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
14736                     PTRMEM_CST_MEMBER (arg), strict);
14737      }
14738
14739     case POINTER_TYPE:
14740       {
14741         if (TREE_CODE (arg) != POINTER_TYPE)
14742           return 1;
14743
14744         /* [temp.deduct.call]
14745
14746            A can be another pointer or pointer to member type that can
14747            be converted to the deduced A via a qualification
14748            conversion (_conv.qual_).
14749
14750            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
14751            This will allow for additional cv-qualification of the
14752            pointed-to types if appropriate.  */
14753
14754         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
14755           /* The derived-to-base conversion only persists through one
14756              level of pointers.  */
14757           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
14758
14759         return unify (tparms, targs, TREE_TYPE (parm),
14760                       TREE_TYPE (arg), strict);
14761       }
14762
14763     case REFERENCE_TYPE:
14764       if (TREE_CODE (arg) != REFERENCE_TYPE)
14765         return 1;
14766       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14767                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14768
14769     case ARRAY_TYPE:
14770       if (TREE_CODE (arg) != ARRAY_TYPE)
14771         return 1;
14772       if ((TYPE_DOMAIN (parm) == NULL_TREE)
14773           != (TYPE_DOMAIN (arg) == NULL_TREE))
14774         return 1;
14775       if (TYPE_DOMAIN (parm) != NULL_TREE)
14776         {
14777           tree parm_max;
14778           tree arg_max;
14779           bool parm_cst;
14780           bool arg_cst;
14781
14782           /* Our representation of array types uses "N - 1" as the
14783              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
14784              not an integer constant.  We cannot unify arbitrarily
14785              complex expressions, so we eliminate the MINUS_EXPRs
14786              here.  */
14787           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
14788           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
14789           if (!parm_cst)
14790             {
14791               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
14792               parm_max = TREE_OPERAND (parm_max, 0);
14793             }
14794           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
14795           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
14796           if (!arg_cst)
14797             {
14798               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
14799                  trying to unify the type of a variable with the type
14800                  of a template parameter.  For example:
14801
14802                    template <unsigned int N>
14803                    void f (char (&) [N]);
14804                    int g(); 
14805                    void h(int i) {
14806                      char a[g(i)];
14807                      f(a); 
14808                    }
14809
14810                 Here, the type of the ARG will be "int [g(i)]", and
14811                 may be a SAVE_EXPR, etc.  */
14812               if (TREE_CODE (arg_max) != MINUS_EXPR)
14813                 return 1;
14814               arg_max = TREE_OPERAND (arg_max, 0);
14815             }
14816
14817           /* If only one of the bounds used a MINUS_EXPR, compensate
14818              by adding one to the other bound.  */
14819           if (parm_cst && !arg_cst)
14820             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
14821                                     integer_type_node,
14822                                     parm_max,
14823                                     integer_one_node);
14824           else if (arg_cst && !parm_cst)
14825             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
14826                                    integer_type_node,
14827                                    arg_max,
14828                                    integer_one_node);
14829
14830           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
14831             return 1;
14832         }
14833       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14834                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14835
14836     case REAL_TYPE:
14837     case COMPLEX_TYPE:
14838     case VECTOR_TYPE:
14839     case INTEGER_TYPE:
14840     case BOOLEAN_TYPE:
14841     case ENUMERAL_TYPE:
14842     case VOID_TYPE:
14843       if (TREE_CODE (arg) != TREE_CODE (parm))
14844         return 1;
14845
14846       /* We have already checked cv-qualification at the top of the
14847          function.  */
14848       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
14849         return 1;
14850
14851       /* As far as unification is concerned, this wins.  Later checks
14852          will invalidate it if necessary.  */
14853       return 0;
14854
14855       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
14856       /* Type INTEGER_CST can come from ordinary constant template args.  */
14857     case INTEGER_CST:
14858       while (TREE_CODE (arg) == NOP_EXPR)
14859         arg = TREE_OPERAND (arg, 0);
14860
14861       if (TREE_CODE (arg) != INTEGER_CST)
14862         return 1;
14863       return !tree_int_cst_equal (parm, arg);
14864
14865     case TREE_VEC:
14866       {
14867         int i;
14868         if (TREE_CODE (arg) != TREE_VEC)
14869           return 1;
14870         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
14871           return 1;
14872         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
14873           if (unify (tparms, targs,
14874                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
14875                      UNIFY_ALLOW_NONE))
14876             return 1;
14877         return 0;
14878       }
14879
14880     case RECORD_TYPE:
14881     case UNION_TYPE:
14882       if (TREE_CODE (arg) != TREE_CODE (parm))
14883         return 1;
14884
14885       if (TYPE_PTRMEMFUNC_P (parm))
14886         {
14887           if (!TYPE_PTRMEMFUNC_P (arg))
14888             return 1;
14889
14890           return unify (tparms, targs,
14891                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
14892                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
14893                         strict);
14894         }
14895
14896       if (CLASSTYPE_TEMPLATE_INFO (parm))
14897         {
14898           tree t = NULL_TREE;
14899
14900           if (strict_in & UNIFY_ALLOW_DERIVED)
14901             {
14902               /* First, we try to unify the PARM and ARG directly.  */
14903               t = try_class_unification (tparms, targs,
14904                                          parm, arg);
14905
14906               if (!t)
14907                 {
14908                   /* Fallback to the special case allowed in
14909                      [temp.deduct.call]:
14910
14911                        If P is a class, and P has the form
14912                        template-id, then A can be a derived class of
14913                        the deduced A.  Likewise, if P is a pointer to
14914                        a class of the form template-id, A can be a
14915                        pointer to a derived class pointed to by the
14916                        deduced A.  */
14917                   t = get_template_base (tparms, targs, parm, arg);
14918
14919                   if (!t)
14920                     return 1;
14921                 }
14922             }
14923           else if (CLASSTYPE_TEMPLATE_INFO (arg)
14924                    && (CLASSTYPE_TI_TEMPLATE (parm)
14925                        == CLASSTYPE_TI_TEMPLATE (arg)))
14926             /* Perhaps PARM is something like S<U> and ARG is S<int>.
14927                Then, we should unify `int' and `U'.  */
14928             t = arg;
14929           else
14930             /* There's no chance of unification succeeding.  */
14931             return 1;
14932
14933           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
14934                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
14935         }
14936       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
14937         return 1;
14938       return 0;
14939
14940     case METHOD_TYPE:
14941     case FUNCTION_TYPE:
14942       {
14943         unsigned int nargs;
14944         tree *args;
14945         tree a;
14946         unsigned int i;
14947
14948         if (TREE_CODE (arg) != TREE_CODE (parm))
14949           return 1;
14950
14951         /* CV qualifications for methods can never be deduced, they must
14952            match exactly.  We need to check them explicitly here,
14953            because type_unification_real treats them as any other
14954            cv-qualified parameter.  */
14955         if (TREE_CODE (parm) == METHOD_TYPE
14956             && (!check_cv_quals_for_unify
14957                 (UNIFY_ALLOW_NONE,
14958                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
14959                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
14960           return 1;
14961
14962         if (unify (tparms, targs, TREE_TYPE (parm),
14963                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
14964           return 1;
14965
14966         nargs = list_length (TYPE_ARG_TYPES (arg));
14967         args = XALLOCAVEC (tree, nargs);
14968         for (a = TYPE_ARG_TYPES (arg), i = 0;
14969              a != NULL_TREE && a != void_list_node;
14970              a = TREE_CHAIN (a), ++i)
14971           args[i] = TREE_VALUE (a);
14972         nargs = i;
14973
14974         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
14975                                       args, nargs, 1, DEDUCE_EXACT,
14976                                       LOOKUP_NORMAL);
14977       }
14978
14979     case OFFSET_TYPE:
14980       /* Unify a pointer to member with a pointer to member function, which
14981          deduces the type of the member as a function type. */
14982       if (TYPE_PTRMEMFUNC_P (arg))
14983         {
14984           tree method_type;
14985           tree fntype;
14986           cp_cv_quals cv_quals;
14987
14988           /* Check top-level cv qualifiers */
14989           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
14990             return 1;
14991
14992           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14993                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
14994             return 1;
14995
14996           /* Determine the type of the function we are unifying against. */
14997           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
14998           fntype =
14999             build_function_type (TREE_TYPE (method_type),
15000                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
15001
15002           /* Extract the cv-qualifiers of the member function from the
15003              implicit object parameter and place them on the function
15004              type to be restored later. */
15005           cv_quals =
15006             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
15007           fntype = build_qualified_type (fntype, cv_quals);
15008           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
15009         }
15010
15011       if (TREE_CODE (arg) != OFFSET_TYPE)
15012         return 1;
15013       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15014                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
15015         return 1;
15016       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15017                     strict);
15018
15019     case CONST_DECL:
15020       if (DECL_TEMPLATE_PARM_P (parm))
15021         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
15022       if (arg != integral_constant_value (parm))
15023         return 1;
15024       return 0;
15025
15026     case FIELD_DECL:
15027     case TEMPLATE_DECL:
15028       /* Matched cases are handled by the ARG == PARM test above.  */
15029       return 1;
15030
15031     case TYPE_ARGUMENT_PACK:
15032     case NONTYPE_ARGUMENT_PACK:
15033       {
15034         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
15035         tree packed_args = ARGUMENT_PACK_ARGS (arg);
15036         int i, len = TREE_VEC_LENGTH (packed_parms);
15037         int argslen = TREE_VEC_LENGTH (packed_args);
15038         int parm_variadic_p = 0;
15039
15040         for (i = 0; i < len; ++i)
15041           {
15042             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
15043               {
15044                 if (i == len - 1)
15045                   /* We can unify against something with a trailing
15046                      parameter pack.  */
15047                   parm_variadic_p = 1;
15048                 else
15049                   /* Since there is something following the pack
15050                      expansion, we cannot unify this template argument
15051                      list.  */
15052                   return 0;
15053               }
15054           }
15055           
15056
15057         /* If we don't have enough arguments to satisfy the parameters
15058            (not counting the pack expression at the end), or we have
15059            too many arguments for a parameter list that doesn't end in
15060            a pack expression, we can't unify.  */
15061         if (argslen < (len - parm_variadic_p)
15062             || (argslen > len && !parm_variadic_p))
15063           return 1;
15064
15065         /* Unify all of the parameters that precede the (optional)
15066            pack expression.  */
15067         for (i = 0; i < len - parm_variadic_p; ++i)
15068           {
15069             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
15070                        TREE_VEC_ELT (packed_args, i), strict))
15071               return 1;
15072           }
15073
15074         if (parm_variadic_p)
15075           return unify_pack_expansion (tparms, targs, 
15076                                        packed_parms, packed_args,
15077                                        strict, /*call_args_p=*/false,
15078                                        /*subr=*/false);
15079         return 0;
15080       }
15081
15082       break;
15083
15084     case TYPEOF_TYPE:
15085     case DECLTYPE_TYPE:
15086       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
15087          nodes.  */
15088       return 0;
15089
15090     case ERROR_MARK:
15091       /* Unification fails if we hit an error node.  */
15092       return 1;
15093
15094     default:
15095       gcc_assert (EXPR_P (parm));
15096
15097       /* We must be looking at an expression.  This can happen with
15098          something like:
15099
15100            template <int I>
15101            void foo(S<I>, S<I + 2>);
15102
15103          This is a "nondeduced context":
15104
15105            [deduct.type]
15106
15107            The nondeduced contexts are:
15108
15109            --A type that is a template-id in which one or more of
15110              the template-arguments is an expression that references
15111              a template-parameter.
15112
15113          In these cases, we assume deduction succeeded, but don't
15114          actually infer any unifications.  */
15115
15116       if (!uses_template_parms (parm)
15117           && !template_args_equal (parm, arg))
15118         return 1;
15119       else
15120         return 0;
15121     }
15122 }
15123 \f
15124 /* Note that DECL can be defined in this translation unit, if
15125    required.  */
15126
15127 static void
15128 mark_definable (tree decl)
15129 {
15130   tree clone;
15131   DECL_NOT_REALLY_EXTERN (decl) = 1;
15132   FOR_EACH_CLONE (clone, decl)
15133     DECL_NOT_REALLY_EXTERN (clone) = 1;
15134 }
15135
15136 /* Called if RESULT is explicitly instantiated, or is a member of an
15137    explicitly instantiated class.  */
15138
15139 void
15140 mark_decl_instantiated (tree result, int extern_p)
15141 {
15142   SET_DECL_EXPLICIT_INSTANTIATION (result);
15143
15144   /* If this entity has already been written out, it's too late to
15145      make any modifications.  */
15146   if (TREE_ASM_WRITTEN (result))
15147     return;
15148
15149   if (TREE_CODE (result) != FUNCTION_DECL)
15150     /* The TREE_PUBLIC flag for function declarations will have been
15151        set correctly by tsubst.  */
15152     TREE_PUBLIC (result) = 1;
15153
15154   /* This might have been set by an earlier implicit instantiation.  */
15155   DECL_COMDAT (result) = 0;
15156
15157   if (extern_p)
15158     DECL_NOT_REALLY_EXTERN (result) = 0;
15159   else
15160     {
15161       mark_definable (result);
15162       /* Always make artificials weak.  */
15163       if (DECL_ARTIFICIAL (result) && flag_weak)
15164         comdat_linkage (result);
15165       /* For WIN32 we also want to put explicit instantiations in
15166          linkonce sections.  */
15167       else if (TREE_PUBLIC (result))
15168         maybe_make_one_only (result);
15169     }
15170
15171   /* If EXTERN_P, then this function will not be emitted -- unless
15172      followed by an explicit instantiation, at which point its linkage
15173      will be adjusted.  If !EXTERN_P, then this function will be
15174      emitted here.  In neither circumstance do we want
15175      import_export_decl to adjust the linkage.  */
15176   DECL_INTERFACE_KNOWN (result) = 1;
15177 }
15178
15179 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
15180    important template arguments.  If any are missing, we check whether
15181    they're important by using error_mark_node for substituting into any
15182    args that were used for partial ordering (the ones between ARGS and END)
15183    and seeing if it bubbles up.  */
15184
15185 static bool
15186 check_undeduced_parms (tree targs, tree args, tree end)
15187 {
15188   bool found = false;
15189   int i;
15190   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
15191     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
15192       {
15193         found = true;
15194         TREE_VEC_ELT (targs, i) = error_mark_node;
15195       }
15196   if (found)
15197     {
15198       for (; args != end; args = TREE_CHAIN (args))
15199         {
15200           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
15201           if (substed == error_mark_node)
15202             return true;
15203         }
15204     }
15205   return false;
15206 }
15207
15208 /* Given two function templates PAT1 and PAT2, return:
15209
15210    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
15211    -1 if PAT2 is more specialized than PAT1.
15212    0 if neither is more specialized.
15213
15214    LEN indicates the number of parameters we should consider
15215    (defaulted parameters should not be considered).
15216
15217    The 1998 std underspecified function template partial ordering, and
15218    DR214 addresses the issue.  We take pairs of arguments, one from
15219    each of the templates, and deduce them against each other.  One of
15220    the templates will be more specialized if all the *other*
15221    template's arguments deduce against its arguments and at least one
15222    of its arguments *does* *not* deduce against the other template's
15223    corresponding argument.  Deduction is done as for class templates.
15224    The arguments used in deduction have reference and top level cv
15225    qualifiers removed.  Iff both arguments were originally reference
15226    types *and* deduction succeeds in both directions, the template
15227    with the more cv-qualified argument wins for that pairing (if
15228    neither is more cv-qualified, they both are equal).  Unlike regular
15229    deduction, after all the arguments have been deduced in this way,
15230    we do *not* verify the deduced template argument values can be
15231    substituted into non-deduced contexts.
15232
15233    The logic can be a bit confusing here, because we look at deduce1 and
15234    targs1 to see if pat2 is at least as specialized, and vice versa; if we
15235    can find template arguments for pat1 to make arg1 look like arg2, that
15236    means that arg2 is at least as specialized as arg1.  */
15237
15238 int
15239 more_specialized_fn (tree pat1, tree pat2, int len)
15240 {
15241   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
15242   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
15243   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
15244   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
15245   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
15246   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
15247   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
15248   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
15249   tree origs1, origs2;
15250   bool lose1 = false;
15251   bool lose2 = false;
15252
15253   /* Remove the this parameter from non-static member functions.  If
15254      one is a non-static member function and the other is not a static
15255      member function, remove the first parameter from that function
15256      also.  This situation occurs for operator functions where we
15257      locate both a member function (with this pointer) and non-member
15258      operator (with explicit first operand).  */
15259   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
15260     {
15261       len--; /* LEN is the number of significant arguments for DECL1 */
15262       args1 = TREE_CHAIN (args1);
15263       if (!DECL_STATIC_FUNCTION_P (decl2))
15264         args2 = TREE_CHAIN (args2);
15265     }
15266   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
15267     {
15268       args2 = TREE_CHAIN (args2);
15269       if (!DECL_STATIC_FUNCTION_P (decl1))
15270         {
15271           len--;
15272           args1 = TREE_CHAIN (args1);
15273         }
15274     }
15275
15276   /* If only one is a conversion operator, they are unordered.  */
15277   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
15278     return 0;
15279
15280   /* Consider the return type for a conversion function */
15281   if (DECL_CONV_FN_P (decl1))
15282     {
15283       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
15284       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
15285       len++;
15286     }
15287
15288   processing_template_decl++;
15289
15290   origs1 = args1;
15291   origs2 = args2;
15292
15293   while (len--
15294          /* Stop when an ellipsis is seen.  */
15295          && args1 != NULL_TREE && args2 != NULL_TREE)
15296     {
15297       tree arg1 = TREE_VALUE (args1);
15298       tree arg2 = TREE_VALUE (args2);
15299       int deduce1, deduce2;
15300       int quals1 = -1;
15301       int quals2 = -1;
15302
15303       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15304           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15305         {
15306           /* When both arguments are pack expansions, we need only
15307              unify the patterns themselves.  */
15308           arg1 = PACK_EXPANSION_PATTERN (arg1);
15309           arg2 = PACK_EXPANSION_PATTERN (arg2);
15310
15311           /* This is the last comparison we need to do.  */
15312           len = 0;
15313         }
15314
15315       if (TREE_CODE (arg1) == REFERENCE_TYPE)
15316         {
15317           arg1 = TREE_TYPE (arg1);
15318           quals1 = cp_type_quals (arg1);
15319         }
15320
15321       if (TREE_CODE (arg2) == REFERENCE_TYPE)
15322         {
15323           arg2 = TREE_TYPE (arg2);
15324           quals2 = cp_type_quals (arg2);
15325         }
15326
15327       if ((quals1 < 0) != (quals2 < 0))
15328         {
15329           /* Only of the args is a reference, see if we should apply
15330              array/function pointer decay to it.  This is not part of
15331              DR214, but is, IMHO, consistent with the deduction rules
15332              for the function call itself, and with our earlier
15333              implementation of the underspecified partial ordering
15334              rules.  (nathan).  */
15335           if (quals1 >= 0)
15336             {
15337               switch (TREE_CODE (arg1))
15338                 {
15339                 case ARRAY_TYPE:
15340                   arg1 = TREE_TYPE (arg1);
15341                   /* FALLTHROUGH. */
15342                 case FUNCTION_TYPE:
15343                   arg1 = build_pointer_type (arg1);
15344                   break;
15345
15346                 default:
15347                   break;
15348                 }
15349             }
15350           else
15351             {
15352               switch (TREE_CODE (arg2))
15353                 {
15354                 case ARRAY_TYPE:
15355                   arg2 = TREE_TYPE (arg2);
15356                   /* FALLTHROUGH. */
15357                 case FUNCTION_TYPE:
15358                   arg2 = build_pointer_type (arg2);
15359                   break;
15360
15361                 default:
15362                   break;
15363                 }
15364             }
15365         }
15366
15367       arg1 = TYPE_MAIN_VARIANT (arg1);
15368       arg2 = TYPE_MAIN_VARIANT (arg2);
15369
15370       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
15371         {
15372           int i, len2 = list_length (args2);
15373           tree parmvec = make_tree_vec (1);
15374           tree argvec = make_tree_vec (len2);
15375           tree ta = args2;
15376
15377           /* Setup the parameter vector, which contains only ARG1.  */
15378           TREE_VEC_ELT (parmvec, 0) = arg1;
15379
15380           /* Setup the argument vector, which contains the remaining
15381              arguments.  */
15382           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
15383             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15384
15385           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
15386                                            argvec, UNIFY_ALLOW_NONE, 
15387                                            /*call_args_p=*/false, 
15388                                            /*subr=*/0);
15389
15390           /* We cannot deduce in the other direction, because ARG1 is
15391              a pack expansion but ARG2 is not.  */
15392           deduce2 = 0;
15393         }
15394       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15395         {
15396           int i, len1 = list_length (args1);
15397           tree parmvec = make_tree_vec (1);
15398           tree argvec = make_tree_vec (len1);
15399           tree ta = args1;
15400
15401           /* Setup the parameter vector, which contains only ARG1.  */
15402           TREE_VEC_ELT (parmvec, 0) = arg2;
15403
15404           /* Setup the argument vector, which contains the remaining
15405              arguments.  */
15406           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
15407             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15408
15409           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
15410                                            argvec, UNIFY_ALLOW_NONE, 
15411                                            /*call_args_p=*/false, 
15412                                            /*subr=*/0);
15413
15414           /* We cannot deduce in the other direction, because ARG2 is
15415              a pack expansion but ARG1 is not.*/
15416           deduce1 = 0;
15417         }
15418
15419       else
15420         {
15421           /* The normal case, where neither argument is a pack
15422              expansion.  */
15423           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
15424           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
15425         }
15426
15427       /* If we couldn't deduce arguments for tparms1 to make arg1 match
15428          arg2, then arg2 is not as specialized as arg1.  */
15429       if (!deduce1)
15430         lose2 = true;
15431       if (!deduce2)
15432         lose1 = true;
15433
15434       /* "If, for a given type, deduction succeeds in both directions
15435          (i.e., the types are identical after the transformations above)
15436          and if the type from the argument template is more cv-qualified
15437          than the type from the parameter template (as described above)
15438          that type is considered to be more specialized than the other. If
15439          neither type is more cv-qualified than the other then neither type
15440          is more specialized than the other."
15441
15442          We check same_type_p explicitly because deduction can also succeed
15443          in both directions when there is a nondeduced context.  */
15444       if (deduce1 && deduce2
15445           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0
15446           && same_type_p (arg1, arg2))
15447         {
15448           if ((quals1 & quals2) == quals2)
15449             lose2 = true;
15450           if ((quals1 & quals2) == quals1)
15451             lose1 = true;
15452         }
15453
15454       if (lose1 && lose2)
15455         /* We've failed to deduce something in either direction.
15456            These must be unordered.  */
15457         break;
15458
15459       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15460           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15461         /* We have already processed all of the arguments in our
15462            handing of the pack expansion type.  */
15463         len = 0;
15464
15465       args1 = TREE_CHAIN (args1);
15466       args2 = TREE_CHAIN (args2);
15467     }
15468
15469   /* "In most cases, all template parameters must have values in order for
15470      deduction to succeed, but for partial ordering purposes a template
15471      parameter may remain without a value provided it is not used in the
15472      types being used for partial ordering."
15473
15474      Thus, if we are missing any of the targs1 we need to substitute into
15475      origs1, then pat2 is not as specialized as pat1.  This can happen when
15476      there is a nondeduced context.  */
15477   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
15478     lose2 = true;
15479   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
15480     lose1 = true;
15481
15482   processing_template_decl--;
15483
15484   /* All things being equal, if the next argument is a pack expansion
15485      for one function but not for the other, prefer the
15486      non-variadic function.  FIXME this is bogus; see c++/41958.  */
15487   if (lose1 == lose2
15488       && args1 && TREE_VALUE (args1)
15489       && args2 && TREE_VALUE (args2))
15490     {
15491       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
15492       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
15493     }
15494
15495   if (lose1 == lose2)
15496     return 0;
15497   else if (!lose1)
15498     return 1;
15499   else
15500     return -1;
15501 }
15502
15503 /* Determine which of two partial specializations is more specialized.
15504
15505    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
15506    to the first partial specialization.  The TREE_VALUE is the
15507    innermost set of template parameters for the partial
15508    specialization.  PAT2 is similar, but for the second template.
15509
15510    Return 1 if the first partial specialization is more specialized;
15511    -1 if the second is more specialized; 0 if neither is more
15512    specialized.
15513
15514    See [temp.class.order] for information about determining which of
15515    two templates is more specialized.  */
15516
15517 static int
15518 more_specialized_class (tree pat1, tree pat2)
15519 {
15520   tree targs;
15521   tree tmpl1, tmpl2;
15522   int winner = 0;
15523   bool any_deductions = false;
15524
15525   tmpl1 = TREE_TYPE (pat1);
15526   tmpl2 = TREE_TYPE (pat2);
15527
15528   /* Just like what happens for functions, if we are ordering between
15529      different class template specializations, we may encounter dependent
15530      types in the arguments, and we need our dependency check functions
15531      to behave correctly.  */
15532   ++processing_template_decl;
15533   targs = get_class_bindings (TREE_VALUE (pat1),
15534                               CLASSTYPE_TI_ARGS (tmpl1),
15535                               CLASSTYPE_TI_ARGS (tmpl2));
15536   if (targs)
15537     {
15538       --winner;
15539       any_deductions = true;
15540     }
15541
15542   targs = get_class_bindings (TREE_VALUE (pat2),
15543                               CLASSTYPE_TI_ARGS (tmpl2),
15544                               CLASSTYPE_TI_ARGS (tmpl1));
15545   if (targs)
15546     {
15547       ++winner;
15548       any_deductions = true;
15549     }
15550   --processing_template_decl;
15551
15552   /* In the case of a tie where at least one of the class templates
15553      has a parameter pack at the end, the template with the most
15554      non-packed parameters wins.  */
15555   if (winner == 0
15556       && any_deductions
15557       && (template_args_variadic_p (TREE_PURPOSE (pat1))
15558           || template_args_variadic_p (TREE_PURPOSE (pat2))))
15559     {
15560       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
15561       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
15562       int len1 = TREE_VEC_LENGTH (args1);
15563       int len2 = TREE_VEC_LENGTH (args2);
15564
15565       /* We don't count the pack expansion at the end.  */
15566       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
15567         --len1;
15568       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
15569         --len2;
15570
15571       if (len1 > len2)
15572         return 1;
15573       else if (len1 < len2)
15574         return -1;
15575     }
15576
15577   return winner;
15578 }
15579
15580 /* Return the template arguments that will produce the function signature
15581    DECL from the function template FN, with the explicit template
15582    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
15583    also match.  Return NULL_TREE if no satisfactory arguments could be
15584    found.  */
15585
15586 static tree
15587 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
15588 {
15589   int ntparms = DECL_NTPARMS (fn);
15590   tree targs = make_tree_vec (ntparms);
15591   tree decl_type;
15592   tree decl_arg_types;
15593   tree *args;
15594   unsigned int nargs, ix;
15595   tree arg;
15596
15597   /* Substitute the explicit template arguments into the type of DECL.
15598      The call to fn_type_unification will handle substitution into the
15599      FN.  */
15600   decl_type = TREE_TYPE (decl);
15601   if (explicit_args && uses_template_parms (decl_type))
15602     {
15603       tree tmpl;
15604       tree converted_args;
15605
15606       if (DECL_TEMPLATE_INFO (decl))
15607         tmpl = DECL_TI_TEMPLATE (decl);
15608       else
15609         /* We can get here for some invalid specializations.  */
15610         return NULL_TREE;
15611
15612       converted_args
15613         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
15614                                  explicit_args, NULL_TREE,
15615                                  tf_none,
15616                                  /*require_all_args=*/false,
15617                                  /*use_default_args=*/false);
15618       if (converted_args == error_mark_node)
15619         return NULL_TREE;
15620
15621       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
15622       if (decl_type == error_mark_node)
15623         return NULL_TREE;
15624     }
15625
15626   /* Never do unification on the 'this' parameter.  */
15627   decl_arg_types = skip_artificial_parms_for (decl, 
15628                                               TYPE_ARG_TYPES (decl_type));
15629
15630   nargs = list_length (decl_arg_types);
15631   args = XALLOCAVEC (tree, nargs);
15632   for (arg = decl_arg_types, ix = 0;
15633        arg != NULL_TREE && arg != void_list_node;
15634        arg = TREE_CHAIN (arg), ++ix)
15635     args[ix] = TREE_VALUE (arg);
15636
15637   if (fn_type_unification (fn, explicit_args, targs,
15638                            args, ix,
15639                            (check_rettype || DECL_CONV_FN_P (fn)
15640                             ? TREE_TYPE (decl_type) : NULL_TREE),
15641                            DEDUCE_EXACT, LOOKUP_NORMAL))
15642     return NULL_TREE;
15643
15644   return targs;
15645 }
15646
15647 /* Return the innermost template arguments that, when applied to a
15648    template specialization whose innermost template parameters are
15649    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
15650    ARGS.
15651
15652    For example, suppose we have:
15653
15654      template <class T, class U> struct S {};
15655      template <class T> struct S<T*, int> {};
15656
15657    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
15658    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
15659    int}.  The resulting vector will be {double}, indicating that `T'
15660    is bound to `double'.  */
15661
15662 static tree
15663 get_class_bindings (tree tparms, tree spec_args, tree args)
15664 {
15665   int i, ntparms = TREE_VEC_LENGTH (tparms);
15666   tree deduced_args;
15667   tree innermost_deduced_args;
15668
15669   innermost_deduced_args = make_tree_vec (ntparms);
15670   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15671     {
15672       deduced_args = copy_node (args);
15673       SET_TMPL_ARGS_LEVEL (deduced_args,
15674                            TMPL_ARGS_DEPTH (deduced_args),
15675                            innermost_deduced_args);
15676     }
15677   else
15678     deduced_args = innermost_deduced_args;
15679
15680   if (unify (tparms, deduced_args,
15681              INNERMOST_TEMPLATE_ARGS (spec_args),
15682              INNERMOST_TEMPLATE_ARGS (args),
15683              UNIFY_ALLOW_NONE))
15684     return NULL_TREE;
15685
15686   for (i =  0; i < ntparms; ++i)
15687     if (! TREE_VEC_ELT (innermost_deduced_args, i))
15688       return NULL_TREE;
15689
15690   /* Verify that nondeduced template arguments agree with the type
15691      obtained from argument deduction.
15692
15693      For example:
15694
15695        struct A { typedef int X; };
15696        template <class T, class U> struct C {};
15697        template <class T> struct C<T, typename T::X> {};
15698
15699      Then with the instantiation `C<A, int>', we can deduce that
15700      `T' is `A' but unify () does not check whether `typename T::X'
15701      is `int'.  */
15702   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
15703   if (spec_args == error_mark_node
15704       /* We only need to check the innermost arguments; the other
15705          arguments will always agree.  */
15706       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
15707                               INNERMOST_TEMPLATE_ARGS (args)))
15708     return NULL_TREE;
15709
15710   /* Now that we have bindings for all of the template arguments,
15711      ensure that the arguments deduced for the template template
15712      parameters have compatible template parameter lists.  See the use
15713      of template_template_parm_bindings_ok_p in fn_type_unification
15714      for more information.  */
15715   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
15716     return NULL_TREE;
15717
15718   return deduced_args;
15719 }
15720
15721 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
15722    Return the TREE_LIST node with the most specialized template, if
15723    any.  If there is no most specialized template, the error_mark_node
15724    is returned.
15725
15726    Note that this function does not look at, or modify, the
15727    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
15728    returned is one of the elements of INSTANTIATIONS, callers may
15729    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
15730    and retrieve it from the value returned.  */
15731
15732 tree
15733 most_specialized_instantiation (tree templates)
15734 {
15735   tree fn, champ;
15736
15737   ++processing_template_decl;
15738
15739   champ = templates;
15740   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
15741     {
15742       int fate = 0;
15743
15744       if (get_bindings (TREE_VALUE (champ),
15745                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15746                         NULL_TREE, /*check_ret=*/false))
15747         fate--;
15748
15749       if (get_bindings (TREE_VALUE (fn),
15750                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15751                         NULL_TREE, /*check_ret=*/false))
15752         fate++;
15753
15754       if (fate == -1)
15755         champ = fn;
15756       else if (!fate)
15757         {
15758           /* Equally specialized, move to next function.  If there
15759              is no next function, nothing's most specialized.  */
15760           fn = TREE_CHAIN (fn);
15761           champ = fn;
15762           if (!fn)
15763             break;
15764         }
15765     }
15766
15767   if (champ)
15768     /* Now verify that champ is better than everything earlier in the
15769        instantiation list.  */
15770     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
15771       if (get_bindings (TREE_VALUE (champ),
15772                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15773                         NULL_TREE, /*check_ret=*/false)
15774           || !get_bindings (TREE_VALUE (fn),
15775                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15776                             NULL_TREE, /*check_ret=*/false))
15777         {
15778           champ = NULL_TREE;
15779           break;
15780         }
15781
15782   processing_template_decl--;
15783
15784   if (!champ)
15785     return error_mark_node;
15786
15787   return champ;
15788 }
15789
15790 /* If DECL is a specialization of some template, return the most
15791    general such template.  Otherwise, returns NULL_TREE.
15792
15793    For example, given:
15794
15795      template <class T> struct S { template <class U> void f(U); };
15796
15797    if TMPL is `template <class U> void S<int>::f(U)' this will return
15798    the full template.  This function will not trace past partial
15799    specializations, however.  For example, given in addition:
15800
15801      template <class T> struct S<T*> { template <class U> void f(U); };
15802
15803    if TMPL is `template <class U> void S<int*>::f(U)' this will return
15804    `template <class T> template <class U> S<T*>::f(U)'.  */
15805
15806 tree
15807 most_general_template (tree decl)
15808 {
15809   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
15810      an immediate specialization.  */
15811   if (TREE_CODE (decl) == FUNCTION_DECL)
15812     {
15813       if (DECL_TEMPLATE_INFO (decl)) {
15814         decl = DECL_TI_TEMPLATE (decl);
15815
15816         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
15817            template friend.  */
15818         if (TREE_CODE (decl) != TEMPLATE_DECL)
15819           return NULL_TREE;
15820       } else
15821         return NULL_TREE;
15822     }
15823
15824   /* Look for more and more general templates.  */
15825   while (DECL_TEMPLATE_INFO (decl))
15826     {
15827       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
15828          (See cp-tree.h for details.)  */
15829       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
15830         break;
15831
15832       if (CLASS_TYPE_P (TREE_TYPE (decl))
15833           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
15834         break;
15835
15836       /* Stop if we run into an explicitly specialized class template.  */
15837       if (!DECL_NAMESPACE_SCOPE_P (decl)
15838           && DECL_CONTEXT (decl)
15839           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
15840         break;
15841
15842       decl = DECL_TI_TEMPLATE (decl);
15843     }
15844
15845   return decl;
15846 }
15847
15848 /* Return the most specialized of the class template partial
15849    specializations of TMPL which can produce TYPE, a specialization of
15850    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
15851    a _TYPE node corresponding to the partial specialization, while the
15852    TREE_PURPOSE is the set of template arguments that must be
15853    substituted into the TREE_TYPE in order to generate TYPE.
15854
15855    If the choice of partial specialization is ambiguous, a diagnostic
15856    is issued, and the error_mark_node is returned.  If there are no
15857    partial specializations of TMPL matching TYPE, then NULL_TREE is
15858    returned.  */
15859
15860 static tree
15861 most_specialized_class (tree type, tree tmpl)
15862 {
15863   tree list = NULL_TREE;
15864   tree t;
15865   tree champ;
15866   int fate;
15867   bool ambiguous_p;
15868   tree args;
15869   tree outer_args = NULL_TREE;
15870
15871   tmpl = most_general_template (tmpl);
15872   args = CLASSTYPE_TI_ARGS (type);
15873
15874   /* For determining which partial specialization to use, only the
15875      innermost args are interesting.  */
15876   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15877     {
15878       outer_args = strip_innermost_template_args (args, 1);
15879       args = INNERMOST_TEMPLATE_ARGS (args);
15880     }
15881
15882   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
15883     {
15884       tree partial_spec_args;
15885       tree spec_args;
15886       tree parms = TREE_VALUE (t);
15887
15888       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
15889       if (outer_args)
15890         {
15891           int i;
15892
15893           ++processing_template_decl;
15894
15895           /* Discard the outer levels of args, and then substitute in the
15896              template args from the enclosing class.  */
15897           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
15898           partial_spec_args = tsubst_template_args
15899             (partial_spec_args, outer_args, tf_none, NULL_TREE);
15900
15901           /* PARMS already refers to just the innermost parms, but the
15902              template parms in partial_spec_args had their levels lowered
15903              by tsubst, so we need to do the same for the parm list.  We
15904              can't just tsubst the TREE_VEC itself, as tsubst wants to
15905              treat a TREE_VEC as an argument vector.  */
15906           parms = copy_node (parms);
15907           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
15908             TREE_VEC_ELT (parms, i) =
15909               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
15910
15911           --processing_template_decl;
15912         }
15913       spec_args = get_class_bindings (parms,
15914                                       partial_spec_args,
15915                                       args);
15916       if (spec_args)
15917         {
15918           if (outer_args)
15919             spec_args = add_to_template_args (outer_args, spec_args);
15920           list = tree_cons (spec_args, TREE_VALUE (t), list);
15921           TREE_TYPE (list) = TREE_TYPE (t);
15922         }
15923     }
15924
15925   if (! list)
15926     return NULL_TREE;
15927
15928   ambiguous_p = false;
15929   t = list;
15930   champ = t;
15931   t = TREE_CHAIN (t);
15932   for (; t; t = TREE_CHAIN (t))
15933     {
15934       fate = more_specialized_class (champ, t);
15935       if (fate == 1)
15936         ;
15937       else
15938         {
15939           if (fate == 0)
15940             {
15941               t = TREE_CHAIN (t);
15942               if (! t)
15943                 {
15944                   ambiguous_p = true;
15945                   break;
15946                 }
15947             }
15948           champ = t;
15949         }
15950     }
15951
15952   if (!ambiguous_p)
15953     for (t = list; t && t != champ; t = TREE_CHAIN (t))
15954       {
15955         fate = more_specialized_class (champ, t);
15956         if (fate != 1)
15957           {
15958             ambiguous_p = true;
15959             break;
15960           }
15961       }
15962
15963   if (ambiguous_p)
15964     {
15965       const char *str;
15966       char *spaces = NULL;
15967       error ("ambiguous class template instantiation for %q#T", type);
15968       str = TREE_CHAIN (list) ? _("candidates are:") : _("candidate is:");
15969       for (t = list; t; t = TREE_CHAIN (t))
15970         {
15971           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
15972           spaces = spaces ? spaces : get_spaces (str);
15973         }
15974       free (spaces);
15975       return error_mark_node;
15976     }
15977
15978   return champ;
15979 }
15980
15981 /* Explicitly instantiate DECL.  */
15982
15983 void
15984 do_decl_instantiation (tree decl, tree storage)
15985 {
15986   tree result = NULL_TREE;
15987   int extern_p = 0;
15988
15989   if (!decl || decl == error_mark_node)
15990     /* An error occurred, for which grokdeclarator has already issued
15991        an appropriate message.  */
15992     return;
15993   else if (! DECL_LANG_SPECIFIC (decl))
15994     {
15995       error ("explicit instantiation of non-template %q#D", decl);
15996       return;
15997     }
15998   else if (TREE_CODE (decl) == VAR_DECL)
15999     {
16000       /* There is an asymmetry here in the way VAR_DECLs and
16001          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
16002          the latter, the DECL we get back will be marked as a
16003          template instantiation, and the appropriate
16004          DECL_TEMPLATE_INFO will be set up.  This does not happen for
16005          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
16006          should handle VAR_DECLs as it currently handles
16007          FUNCTION_DECLs.  */
16008       if (!DECL_CLASS_SCOPE_P (decl))
16009         {
16010           error ("%qD is not a static data member of a class template", decl);
16011           return;
16012         }
16013       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
16014       if (!result || TREE_CODE (result) != VAR_DECL)
16015         {
16016           error ("no matching template for %qD found", decl);
16017           return;
16018         }
16019       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
16020         {
16021           error ("type %qT for explicit instantiation %qD does not match "
16022                  "declared type %qT", TREE_TYPE (result), decl,
16023                  TREE_TYPE (decl));
16024           return;
16025         }
16026     }
16027   else if (TREE_CODE (decl) != FUNCTION_DECL)
16028     {
16029       error ("explicit instantiation of %q#D", decl);
16030       return;
16031     }
16032   else
16033     result = decl;
16034
16035   /* Check for various error cases.  Note that if the explicit
16036      instantiation is valid the RESULT will currently be marked as an
16037      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
16038      until we get here.  */
16039
16040   if (DECL_TEMPLATE_SPECIALIZATION (result))
16041     {
16042       /* DR 259 [temp.spec].
16043
16044          Both an explicit instantiation and a declaration of an explicit
16045          specialization shall not appear in a program unless the explicit
16046          instantiation follows a declaration of the explicit specialization.
16047
16048          For a given set of template parameters, if an explicit
16049          instantiation of a template appears after a declaration of an
16050          explicit specialization for that template, the explicit
16051          instantiation has no effect.  */
16052       return;
16053     }
16054   else if (DECL_EXPLICIT_INSTANTIATION (result))
16055     {
16056       /* [temp.spec]
16057
16058          No program shall explicitly instantiate any template more
16059          than once.
16060
16061          We check DECL_NOT_REALLY_EXTERN so as not to complain when
16062          the first instantiation was `extern' and the second is not,
16063          and EXTERN_P for the opposite case.  */
16064       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
16065         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
16066       /* If an "extern" explicit instantiation follows an ordinary
16067          explicit instantiation, the template is instantiated.  */
16068       if (extern_p)
16069         return;
16070     }
16071   else if (!DECL_IMPLICIT_INSTANTIATION (result))
16072     {
16073       error ("no matching template for %qD found", result);
16074       return;
16075     }
16076   else if (!DECL_TEMPLATE_INFO (result))
16077     {
16078       permerror (input_location, "explicit instantiation of non-template %q#D", result);
16079       return;
16080     }
16081
16082   if (storage == NULL_TREE)
16083     ;
16084   else if (storage == ridpointers[(int) RID_EXTERN])
16085     {
16086       if (!in_system_header && (cxx_dialect == cxx98))
16087         pedwarn (input_location, OPT_pedantic, 
16088                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
16089                  "instantiations");
16090       extern_p = 1;
16091     }
16092   else
16093     error ("storage class %qD applied to template instantiation", storage);
16094
16095   check_explicit_instantiation_namespace (result);
16096   mark_decl_instantiated (result, extern_p);
16097   if (! extern_p)
16098     instantiate_decl (result, /*defer_ok=*/1,
16099                       /*expl_inst_class_mem_p=*/false);
16100 }
16101
16102 static void
16103 mark_class_instantiated (tree t, int extern_p)
16104 {
16105   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
16106   SET_CLASSTYPE_INTERFACE_KNOWN (t);
16107   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
16108   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
16109   if (! extern_p)
16110     {
16111       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
16112       rest_of_type_compilation (t, 1);
16113     }
16114 }
16115
16116 /* Called from do_type_instantiation through binding_table_foreach to
16117    do recursive instantiation for the type bound in ENTRY.  */
16118 static void
16119 bt_instantiate_type_proc (binding_entry entry, void *data)
16120 {
16121   tree storage = *(tree *) data;
16122
16123   if (MAYBE_CLASS_TYPE_P (entry->type)
16124       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
16125     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
16126 }
16127
16128 /* Called from do_type_instantiation to instantiate a member
16129    (a member function or a static member variable) of an
16130    explicitly instantiated class template.  */
16131 static void
16132 instantiate_class_member (tree decl, int extern_p)
16133 {
16134   mark_decl_instantiated (decl, extern_p);
16135   if (! extern_p)
16136     instantiate_decl (decl, /*defer_ok=*/1,
16137                       /*expl_inst_class_mem_p=*/true);
16138 }
16139
16140 /* Perform an explicit instantiation of template class T.  STORAGE, if
16141    non-null, is the RID for extern, inline or static.  COMPLAIN is
16142    nonzero if this is called from the parser, zero if called recursively,
16143    since the standard is unclear (as detailed below).  */
16144
16145 void
16146 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
16147 {
16148   int extern_p = 0;
16149   int nomem_p = 0;
16150   int static_p = 0;
16151   int previous_instantiation_extern_p = 0;
16152
16153   if (TREE_CODE (t) == TYPE_DECL)
16154     t = TREE_TYPE (t);
16155
16156   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
16157     {
16158       error ("explicit instantiation of non-template type %qT", t);
16159       return;
16160     }
16161
16162   complete_type (t);
16163
16164   if (!COMPLETE_TYPE_P (t))
16165     {
16166       if (complain & tf_error)
16167         error ("explicit instantiation of %q#T before definition of template",
16168                t);
16169       return;
16170     }
16171
16172   if (storage != NULL_TREE)
16173     {
16174       if (!in_system_header)
16175         {
16176           if (storage == ridpointers[(int) RID_EXTERN])
16177             {
16178               if (cxx_dialect == cxx98)
16179                 pedwarn (input_location, OPT_pedantic, 
16180                          "ISO C++ 1998 forbids the use of %<extern%> on "
16181                          "explicit instantiations");
16182             }
16183           else
16184             pedwarn (input_location, OPT_pedantic, 
16185                      "ISO C++ forbids the use of %qE"
16186                      " on explicit instantiations", storage);
16187         }
16188
16189       if (storage == ridpointers[(int) RID_INLINE])
16190         nomem_p = 1;
16191       else if (storage == ridpointers[(int) RID_EXTERN])
16192         extern_p = 1;
16193       else if (storage == ridpointers[(int) RID_STATIC])
16194         static_p = 1;
16195       else
16196         {
16197           error ("storage class %qD applied to template instantiation",
16198                  storage);
16199           extern_p = 0;
16200         }
16201     }
16202
16203   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
16204     {
16205       /* DR 259 [temp.spec].
16206
16207          Both an explicit instantiation and a declaration of an explicit
16208          specialization shall not appear in a program unless the explicit
16209          instantiation follows a declaration of the explicit specialization.
16210
16211          For a given set of template parameters, if an explicit
16212          instantiation of a template appears after a declaration of an
16213          explicit specialization for that template, the explicit
16214          instantiation has no effect.  */
16215       return;
16216     }
16217   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
16218     {
16219       /* [temp.spec]
16220
16221          No program shall explicitly instantiate any template more
16222          than once.
16223
16224          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
16225          instantiation was `extern'.  If EXTERN_P then the second is.
16226          These cases are OK.  */
16227       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
16228
16229       if (!previous_instantiation_extern_p && !extern_p
16230           && (complain & tf_error))
16231         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
16232
16233       /* If we've already instantiated the template, just return now.  */
16234       if (!CLASSTYPE_INTERFACE_ONLY (t))
16235         return;
16236     }
16237
16238   check_explicit_instantiation_namespace (TYPE_NAME (t));
16239   mark_class_instantiated (t, extern_p);
16240
16241   if (nomem_p)
16242     return;
16243
16244   {
16245     tree tmp;
16246
16247     /* In contrast to implicit instantiation, where only the
16248        declarations, and not the definitions, of members are
16249        instantiated, we have here:
16250
16251          [temp.explicit]
16252
16253          The explicit instantiation of a class template specialization
16254          implies the instantiation of all of its members not
16255          previously explicitly specialized in the translation unit
16256          containing the explicit instantiation.
16257
16258        Of course, we can't instantiate member template classes, since
16259        we don't have any arguments for them.  Note that the standard
16260        is unclear on whether the instantiation of the members are
16261        *explicit* instantiations or not.  However, the most natural
16262        interpretation is that it should be an explicit instantiation.  */
16263
16264     if (! static_p)
16265       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
16266         if (TREE_CODE (tmp) == FUNCTION_DECL
16267             && DECL_TEMPLATE_INSTANTIATION (tmp))
16268           instantiate_class_member (tmp, extern_p);
16269
16270     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
16271       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
16272         instantiate_class_member (tmp, extern_p);
16273
16274     if (CLASSTYPE_NESTED_UTDS (t))
16275       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
16276                              bt_instantiate_type_proc, &storage);
16277   }
16278 }
16279
16280 /* Given a function DECL, which is a specialization of TMPL, modify
16281    DECL to be a re-instantiation of TMPL with the same template
16282    arguments.  TMPL should be the template into which tsubst'ing
16283    should occur for DECL, not the most general template.
16284
16285    One reason for doing this is a scenario like this:
16286
16287      template <class T>
16288      void f(const T&, int i);
16289
16290      void g() { f(3, 7); }
16291
16292      template <class T>
16293      void f(const T& t, const int i) { }
16294
16295    Note that when the template is first instantiated, with
16296    instantiate_template, the resulting DECL will have no name for the
16297    first parameter, and the wrong type for the second.  So, when we go
16298    to instantiate the DECL, we regenerate it.  */
16299
16300 static void
16301 regenerate_decl_from_template (tree decl, tree tmpl)
16302 {
16303   /* The arguments used to instantiate DECL, from the most general
16304      template.  */
16305   tree args;
16306   tree code_pattern;
16307
16308   args = DECL_TI_ARGS (decl);
16309   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
16310
16311   /* Make sure that we can see identifiers, and compute access
16312      correctly.  */
16313   push_access_scope (decl);
16314
16315   if (TREE_CODE (decl) == FUNCTION_DECL)
16316     {
16317       tree decl_parm;
16318       tree pattern_parm;
16319       tree specs;
16320       int args_depth;
16321       int parms_depth;
16322
16323       args_depth = TMPL_ARGS_DEPTH (args);
16324       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
16325       if (args_depth > parms_depth)
16326         args = get_innermost_template_args (args, parms_depth);
16327
16328       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
16329                                               args, tf_error, NULL_TREE);
16330       if (specs)
16331         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
16332                                                     specs);
16333
16334       /* Merge parameter declarations.  */
16335       decl_parm = skip_artificial_parms_for (decl,
16336                                              DECL_ARGUMENTS (decl));
16337       pattern_parm
16338         = skip_artificial_parms_for (code_pattern,
16339                                      DECL_ARGUMENTS (code_pattern));
16340       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
16341         {
16342           tree parm_type;
16343           tree attributes;
16344           
16345           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16346             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
16347           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
16348                               NULL_TREE);
16349           parm_type = type_decays_to (parm_type);
16350           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16351             TREE_TYPE (decl_parm) = parm_type;
16352           attributes = DECL_ATTRIBUTES (pattern_parm);
16353           if (DECL_ATTRIBUTES (decl_parm) != attributes)
16354             {
16355               DECL_ATTRIBUTES (decl_parm) = attributes;
16356               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16357             }
16358           decl_parm = TREE_CHAIN (decl_parm);
16359           pattern_parm = TREE_CHAIN (pattern_parm);
16360         }
16361       /* Merge any parameters that match with the function parameter
16362          pack.  */
16363       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
16364         {
16365           int i, len;
16366           tree expanded_types;
16367           /* Expand the TYPE_PACK_EXPANSION that provides the types for
16368              the parameters in this function parameter pack.  */
16369           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
16370                                                  args, tf_error, NULL_TREE);
16371           len = TREE_VEC_LENGTH (expanded_types);
16372           for (i = 0; i < len; i++)
16373             {
16374               tree parm_type;
16375               tree attributes;
16376           
16377               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16378                 /* Rename the parameter to include the index.  */
16379                 DECL_NAME (decl_parm) = 
16380                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
16381               parm_type = TREE_VEC_ELT (expanded_types, i);
16382               parm_type = type_decays_to (parm_type);
16383               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16384                 TREE_TYPE (decl_parm) = parm_type;
16385               attributes = DECL_ATTRIBUTES (pattern_parm);
16386               if (DECL_ATTRIBUTES (decl_parm) != attributes)
16387                 {
16388                   DECL_ATTRIBUTES (decl_parm) = attributes;
16389                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16390                 }
16391               decl_parm = TREE_CHAIN (decl_parm);
16392             }
16393         }
16394       /* Merge additional specifiers from the CODE_PATTERN.  */
16395       if (DECL_DECLARED_INLINE_P (code_pattern)
16396           && !DECL_DECLARED_INLINE_P (decl))
16397         DECL_DECLARED_INLINE_P (decl) = 1;
16398     }
16399   else if (TREE_CODE (decl) == VAR_DECL)
16400     DECL_INITIAL (decl) =
16401       tsubst_expr (DECL_INITIAL (code_pattern), args,
16402                    tf_error, DECL_TI_TEMPLATE (decl),
16403                    /*integral_constant_expression_p=*/false);
16404   else
16405     gcc_unreachable ();
16406
16407   pop_access_scope (decl);
16408 }
16409
16410 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
16411    substituted to get DECL.  */
16412
16413 tree
16414 template_for_substitution (tree decl)
16415 {
16416   tree tmpl = DECL_TI_TEMPLATE (decl);
16417
16418   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
16419      for the instantiation.  This is not always the most general
16420      template.  Consider, for example:
16421
16422         template <class T>
16423         struct S { template <class U> void f();
16424                    template <> void f<int>(); };
16425
16426      and an instantiation of S<double>::f<int>.  We want TD to be the
16427      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
16428   while (/* An instantiation cannot have a definition, so we need a
16429             more general template.  */
16430          DECL_TEMPLATE_INSTANTIATION (tmpl)
16431            /* We must also deal with friend templates.  Given:
16432
16433                 template <class T> struct S {
16434                   template <class U> friend void f() {};
16435                 };
16436
16437               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
16438               so far as the language is concerned, but that's still
16439               where we get the pattern for the instantiation from.  On
16440               other hand, if the definition comes outside the class, say:
16441
16442                 template <class T> struct S {
16443                   template <class U> friend void f();
16444                 };
16445                 template <class U> friend void f() {}
16446
16447               we don't need to look any further.  That's what the check for
16448               DECL_INITIAL is for.  */
16449           || (TREE_CODE (decl) == FUNCTION_DECL
16450               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
16451               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
16452     {
16453       /* The present template, TD, should not be a definition.  If it
16454          were a definition, we should be using it!  Note that we
16455          cannot restructure the loop to just keep going until we find
16456          a template with a definition, since that might go too far if
16457          a specialization was declared, but not defined.  */
16458       gcc_assert (TREE_CODE (decl) != VAR_DECL
16459                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
16460
16461       /* Fetch the more general template.  */
16462       tmpl = DECL_TI_TEMPLATE (tmpl);
16463     }
16464
16465   return tmpl;
16466 }
16467
16468 /* Returns true if we need to instantiate this template instance even if we
16469    know we aren't going to emit it..  */
16470
16471 bool
16472 always_instantiate_p (tree decl)
16473 {
16474   /* We always instantiate inline functions so that we can inline them.  An
16475      explicit instantiation declaration prohibits implicit instantiation of
16476      non-inline functions.  With high levels of optimization, we would
16477      normally inline non-inline functions -- but we're not allowed to do
16478      that for "extern template" functions.  Therefore, we check
16479      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
16480   return ((TREE_CODE (decl) == FUNCTION_DECL
16481            && DECL_DECLARED_INLINE_P (decl))
16482           /* And we need to instantiate static data members so that
16483              their initializers are available in integral constant
16484              expressions.  */
16485           || (TREE_CODE (decl) == VAR_DECL
16486               && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl)));
16487 }
16488
16489 /* Produce the definition of D, a _DECL generated from a template.  If
16490    DEFER_OK is nonzero, then we don't have to actually do the
16491    instantiation now; we just have to do it sometime.  Normally it is
16492    an error if this is an explicit instantiation but D is undefined.
16493    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
16494    explicitly instantiated class template.  */
16495
16496 tree
16497 instantiate_decl (tree d, int defer_ok,
16498                   bool expl_inst_class_mem_p)
16499 {
16500   tree tmpl = DECL_TI_TEMPLATE (d);
16501   tree gen_args;
16502   tree args;
16503   tree td;
16504   tree code_pattern;
16505   tree spec;
16506   tree gen_tmpl;
16507   bool pattern_defined;
16508   int need_push;
16509   location_t saved_loc = input_location;
16510   bool external_p;
16511
16512   /* This function should only be used to instantiate templates for
16513      functions and static member variables.  */
16514   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
16515               || TREE_CODE (d) == VAR_DECL);
16516
16517   /* Variables are never deferred; if instantiation is required, they
16518      are instantiated right away.  That allows for better code in the
16519      case that an expression refers to the value of the variable --
16520      if the variable has a constant value the referring expression can
16521      take advantage of that fact.  */
16522   if (TREE_CODE (d) == VAR_DECL)
16523     defer_ok = 0;
16524
16525   /* Don't instantiate cloned functions.  Instead, instantiate the
16526      functions they cloned.  */
16527   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
16528     d = DECL_CLONED_FUNCTION (d);
16529
16530   if (DECL_TEMPLATE_INSTANTIATED (d)
16531       || DECL_TEMPLATE_SPECIALIZATION (d))
16532     /* D has already been instantiated or explicitly specialized, so
16533        there's nothing for us to do here.
16534
16535        It might seem reasonable to check whether or not D is an explicit
16536        instantiation, and, if so, stop here.  But when an explicit
16537        instantiation is deferred until the end of the compilation,
16538        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
16539        the instantiation.  */
16540     return d;
16541
16542   /* Check to see whether we know that this template will be
16543      instantiated in some other file, as with "extern template"
16544      extension.  */
16545   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
16546
16547   /* In general, we do not instantiate such templates.  */
16548   if (external_p && !always_instantiate_p (d))
16549     return d;
16550
16551   gen_tmpl = most_general_template (tmpl);
16552   gen_args = DECL_TI_ARGS (d);
16553
16554   if (tmpl != gen_tmpl)
16555     /* We should already have the extra args.  */
16556     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
16557                 == TMPL_ARGS_DEPTH (gen_args));
16558   /* And what's in the hash table should match D.  */
16559   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
16560               || spec == NULL_TREE);
16561
16562   /* This needs to happen before any tsubsting.  */
16563   if (! push_tinst_level (d))
16564     return d;
16565
16566   timevar_push (TV_PARSE);
16567
16568   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
16569      for the instantiation.  */
16570   td = template_for_substitution (d);
16571   code_pattern = DECL_TEMPLATE_RESULT (td);
16572
16573   /* We should never be trying to instantiate a member of a class
16574      template or partial specialization.  */
16575   gcc_assert (d != code_pattern);
16576
16577   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
16578       || DECL_TEMPLATE_SPECIALIZATION (td))
16579     /* In the case of a friend template whose definition is provided
16580        outside the class, we may have too many arguments.  Drop the
16581        ones we don't need.  The same is true for specializations.  */
16582     args = get_innermost_template_args
16583       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
16584   else
16585     args = gen_args;
16586
16587   if (TREE_CODE (d) == FUNCTION_DECL)
16588     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
16589   else
16590     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
16591
16592   /* We may be in the middle of deferred access check.  Disable it now.  */
16593   push_deferring_access_checks (dk_no_deferred);
16594
16595   /* Unless an explicit instantiation directive has already determined
16596      the linkage of D, remember that a definition is available for
16597      this entity.  */
16598   if (pattern_defined
16599       && !DECL_INTERFACE_KNOWN (d)
16600       && !DECL_NOT_REALLY_EXTERN (d))
16601     mark_definable (d);
16602
16603   input_location = DECL_SOURCE_LOCATION (d);
16604
16605   /* If D is a member of an explicitly instantiated class template,
16606      and no definition is available, treat it like an implicit
16607      instantiation.  */
16608   if (!pattern_defined && expl_inst_class_mem_p
16609       && DECL_EXPLICIT_INSTANTIATION (d))
16610     {
16611       DECL_NOT_REALLY_EXTERN (d) = 0;
16612       DECL_INTERFACE_KNOWN (d) = 0;
16613       SET_DECL_IMPLICIT_INSTANTIATION (d);
16614     }
16615
16616   /* Recheck the substitutions to obtain any warning messages
16617      about ignoring cv qualifiers.  Don't do this for artificial decls,
16618      as it breaks the context-sensitive substitution for lambda op(). */
16619   if (!defer_ok && !DECL_ARTIFICIAL (d))
16620     {
16621       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
16622       tree type = TREE_TYPE (gen);
16623
16624       /* Make sure that we can see identifiers, and compute access
16625          correctly.  D is already the target FUNCTION_DECL with the
16626          right context.  */
16627       push_access_scope (d);
16628
16629       if (TREE_CODE (gen) == FUNCTION_DECL)
16630         {
16631           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
16632           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
16633                                           d);
16634           /* Don't simply tsubst the function type, as that will give
16635              duplicate warnings about poor parameter qualifications.
16636              The function arguments are the same as the decl_arguments
16637              without the top level cv qualifiers.  */
16638           type = TREE_TYPE (type);
16639         }
16640       tsubst (type, gen_args, tf_warning_or_error, d);
16641
16642       pop_access_scope (d);
16643     }
16644
16645   /* Defer all other templates, unless we have been explicitly
16646      forbidden from doing so.  */
16647   if (/* If there is no definition, we cannot instantiate the
16648          template.  */
16649       ! pattern_defined
16650       /* If it's OK to postpone instantiation, do so.  */
16651       || defer_ok
16652       /* If this is a static data member that will be defined
16653          elsewhere, we don't want to instantiate the entire data
16654          member, but we do want to instantiate the initializer so that
16655          we can substitute that elsewhere.  */
16656       || (external_p && TREE_CODE (d) == VAR_DECL))
16657     {
16658       /* The definition of the static data member is now required so
16659          we must substitute the initializer.  */
16660       if (TREE_CODE (d) == VAR_DECL
16661           && !DECL_INITIAL (d)
16662           && DECL_INITIAL (code_pattern))
16663         {
16664           tree ns;
16665           tree init;
16666
16667           ns = decl_namespace_context (d);
16668           push_nested_namespace (ns);
16669           push_nested_class (DECL_CONTEXT (d));
16670           init = tsubst_expr (DECL_INITIAL (code_pattern),
16671                               args,
16672                               tf_warning_or_error, NULL_TREE,
16673                               /*integral_constant_expression_p=*/false);
16674           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
16675                           /*asmspec_tree=*/NULL_TREE,
16676                           LOOKUP_ONLYCONVERTING);
16677           pop_nested_class ();
16678           pop_nested_namespace (ns);
16679         }
16680
16681       /* We restore the source position here because it's used by
16682          add_pending_template.  */
16683       input_location = saved_loc;
16684
16685       if (at_eof && !pattern_defined
16686           && DECL_EXPLICIT_INSTANTIATION (d)
16687           && DECL_NOT_REALLY_EXTERN (d))
16688         /* [temp.explicit]
16689
16690            The definition of a non-exported function template, a
16691            non-exported member function template, or a non-exported
16692            member function or static data member of a class template
16693            shall be present in every translation unit in which it is
16694            explicitly instantiated.  */
16695         permerror (input_location,  "explicit instantiation of %qD "
16696                    "but no definition available", d);
16697
16698       /* ??? Historically, we have instantiated inline functions, even
16699          when marked as "extern template".  */
16700       if (!(external_p && TREE_CODE (d) == VAR_DECL))
16701         add_pending_template (d);
16702       goto out;
16703     }
16704   /* Tell the repository that D is available in this translation unit
16705      -- and see if it is supposed to be instantiated here.  */
16706   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
16707     {
16708       /* In a PCH file, despite the fact that the repository hasn't
16709          requested instantiation in the PCH it is still possible that
16710          an instantiation will be required in a file that includes the
16711          PCH.  */
16712       if (pch_file)
16713         add_pending_template (d);
16714       /* Instantiate inline functions so that the inliner can do its
16715          job, even though we'll not be emitting a copy of this
16716          function.  */
16717       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
16718         goto out;
16719     }
16720
16721   need_push = !cfun || !global_bindings_p ();
16722   if (need_push)
16723     push_to_top_level ();
16724
16725   /* Mark D as instantiated so that recursive calls to
16726      instantiate_decl do not try to instantiate it again.  */
16727   DECL_TEMPLATE_INSTANTIATED (d) = 1;
16728
16729   /* Regenerate the declaration in case the template has been modified
16730      by a subsequent redeclaration.  */
16731   regenerate_decl_from_template (d, td);
16732
16733   /* We already set the file and line above.  Reset them now in case
16734      they changed as a result of calling regenerate_decl_from_template.  */
16735   input_location = DECL_SOURCE_LOCATION (d);
16736
16737   if (TREE_CODE (d) == VAR_DECL)
16738     {
16739       tree init;
16740
16741       /* Clear out DECL_RTL; whatever was there before may not be right
16742          since we've reset the type of the declaration.  */
16743       SET_DECL_RTL (d, NULL_RTX);
16744       DECL_IN_AGGR_P (d) = 0;
16745
16746       /* The initializer is placed in DECL_INITIAL by
16747          regenerate_decl_from_template.  Pull it out so that
16748          cp_finish_decl can process it.  */
16749       init = DECL_INITIAL (d);
16750       DECL_INITIAL (d) = NULL_TREE;
16751       DECL_INITIALIZED_P (d) = 0;
16752
16753       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
16754          initializer.  That function will defer actual emission until
16755          we have a chance to determine linkage.  */
16756       DECL_EXTERNAL (d) = 0;
16757
16758       /* Enter the scope of D so that access-checking works correctly.  */
16759       push_nested_class (DECL_CONTEXT (d));
16760       cp_finish_decl (d, init, false, NULL_TREE, 0);
16761       pop_nested_class ();
16762     }
16763   else if (TREE_CODE (d) == FUNCTION_DECL)
16764     {
16765       htab_t saved_local_specializations;
16766       tree subst_decl;
16767       tree tmpl_parm;
16768       tree spec_parm;
16769
16770       /* Save away the current list, in case we are instantiating one
16771          template from within the body of another.  */
16772       saved_local_specializations = local_specializations;
16773
16774       /* Set up the list of local specializations.  */
16775       local_specializations = htab_create (37,
16776                                            hash_local_specialization,
16777                                            eq_local_specializations,
16778                                            NULL);
16779
16780       /* Set up context.  */
16781       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
16782
16783       /* Create substitution entries for the parameters.  */
16784       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
16785       tmpl_parm = DECL_ARGUMENTS (subst_decl);
16786       spec_parm = DECL_ARGUMENTS (d);
16787       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
16788         {
16789           register_local_specialization (spec_parm, tmpl_parm);
16790           spec_parm = skip_artificial_parms_for (d, spec_parm);
16791           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
16792         }
16793       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16794         {
16795           register_local_specialization (spec_parm, tmpl_parm);
16796           tmpl_parm = TREE_CHAIN (tmpl_parm);
16797           spec_parm = TREE_CHAIN (spec_parm);
16798         }
16799       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16800         {
16801           /* Register the (value) argument pack as a specialization of
16802              TMPL_PARM, then move on.  */
16803           tree argpack = make_fnparm_pack (spec_parm);
16804           register_local_specialization (argpack, tmpl_parm);
16805           tmpl_parm = TREE_CHAIN (tmpl_parm);
16806           spec_parm = NULL_TREE;
16807         }
16808       gcc_assert (!spec_parm);
16809
16810       /* Substitute into the body of the function.  */
16811       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
16812                    tf_warning_or_error, tmpl,
16813                    /*integral_constant_expression_p=*/false);
16814
16815       /* Set the current input_location to the end of the function
16816          so that finish_function knows where we are.  */
16817       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
16818
16819       /* We don't need the local specializations any more.  */
16820       htab_delete (local_specializations);
16821       local_specializations = saved_local_specializations;
16822
16823       /* Finish the function.  */
16824       d = finish_function (0);
16825       expand_or_defer_fn (d);
16826     }
16827
16828   /* We're not deferring instantiation any more.  */
16829   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
16830
16831   if (need_push)
16832     pop_from_top_level ();
16833
16834 out:
16835   input_location = saved_loc;
16836   pop_deferring_access_checks ();
16837   pop_tinst_level ();
16838
16839   timevar_pop (TV_PARSE);
16840
16841   return d;
16842 }
16843
16844 /* Run through the list of templates that we wish we could
16845    instantiate, and instantiate any we can.  RETRIES is the
16846    number of times we retry pending template instantiation.  */
16847
16848 void
16849 instantiate_pending_templates (int retries)
16850 {
16851   int reconsider;
16852   location_t saved_loc = input_location;
16853
16854   /* Instantiating templates may trigger vtable generation.  This in turn
16855      may require further template instantiations.  We place a limit here
16856      to avoid infinite loop.  */
16857   if (pending_templates && retries >= max_tinst_depth)
16858     {
16859       tree decl = pending_templates->tinst->decl;
16860
16861       error ("template instantiation depth exceeds maximum of %d"
16862              " instantiating %q+D, possibly from virtual table generation"
16863              " (use -ftemplate-depth= to increase the maximum)",
16864              max_tinst_depth, decl);
16865       if (TREE_CODE (decl) == FUNCTION_DECL)
16866         /* Pretend that we defined it.  */
16867         DECL_INITIAL (decl) = error_mark_node;
16868       return;
16869     }
16870
16871   do
16872     {
16873       struct pending_template **t = &pending_templates;
16874       struct pending_template *last = NULL;
16875       reconsider = 0;
16876       while (*t)
16877         {
16878           tree instantiation = reopen_tinst_level ((*t)->tinst);
16879           bool complete = false;
16880
16881           if (TYPE_P (instantiation))
16882             {
16883               tree fn;
16884
16885               if (!COMPLETE_TYPE_P (instantiation))
16886                 {
16887                   instantiate_class_template (instantiation);
16888                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
16889                     for (fn = TYPE_METHODS (instantiation);
16890                          fn;
16891                          fn = TREE_CHAIN (fn))
16892                       if (! DECL_ARTIFICIAL (fn))
16893                         instantiate_decl (fn,
16894                                           /*defer_ok=*/0,
16895                                           /*expl_inst_class_mem_p=*/false);
16896                   if (COMPLETE_TYPE_P (instantiation))
16897                     reconsider = 1;
16898                 }
16899
16900               complete = COMPLETE_TYPE_P (instantiation);
16901             }
16902           else
16903             {
16904               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
16905                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
16906                 {
16907                   instantiation
16908                     = instantiate_decl (instantiation,
16909                                         /*defer_ok=*/0,
16910                                         /*expl_inst_class_mem_p=*/false);
16911                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
16912                     reconsider = 1;
16913                 }
16914
16915               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
16916                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
16917             }
16918
16919           if (complete)
16920             /* If INSTANTIATION has been instantiated, then we don't
16921                need to consider it again in the future.  */
16922             *t = (*t)->next;
16923           else
16924             {
16925               last = *t;
16926               t = &(*t)->next;
16927             }
16928           tinst_depth = 0;
16929           current_tinst_level = NULL;
16930         }
16931       last_pending_template = last;
16932     }
16933   while (reconsider);
16934
16935   input_location = saved_loc;
16936 }
16937
16938 /* Substitute ARGVEC into T, which is a list of initializers for
16939    either base class or a non-static data member.  The TREE_PURPOSEs
16940    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
16941    instantiate_decl.  */
16942
16943 static tree
16944 tsubst_initializer_list (tree t, tree argvec)
16945 {
16946   tree inits = NULL_TREE;
16947
16948   for (; t; t = TREE_CHAIN (t))
16949     {
16950       tree decl;
16951       tree init;
16952       tree expanded_bases = NULL_TREE;
16953       tree expanded_arguments = NULL_TREE;
16954       int i, len = 1;
16955
16956       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
16957         {
16958           tree expr;
16959           tree arg;
16960
16961           /* Expand the base class expansion type into separate base
16962              classes.  */
16963           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
16964                                                  tf_warning_or_error,
16965                                                  NULL_TREE);
16966           if (expanded_bases == error_mark_node)
16967             continue;
16968           
16969           /* We'll be building separate TREE_LISTs of arguments for
16970              each base.  */
16971           len = TREE_VEC_LENGTH (expanded_bases);
16972           expanded_arguments = make_tree_vec (len);
16973           for (i = 0; i < len; i++)
16974             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
16975
16976           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
16977              expand each argument in the TREE_VALUE of t.  */
16978           expr = make_node (EXPR_PACK_EXPANSION);
16979           PACK_EXPANSION_PARAMETER_PACKS (expr) =
16980             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
16981
16982           if (TREE_VALUE (t) == void_type_node)
16983             /* VOID_TYPE_NODE is used to indicate
16984                value-initialization.  */
16985             {
16986               for (i = 0; i < len; i++)
16987                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
16988             }
16989           else
16990             {
16991               /* Substitute parameter packs into each argument in the
16992                  TREE_LIST.  */
16993               in_base_initializer = 1;
16994               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
16995                 {
16996                   tree expanded_exprs;
16997
16998                   /* Expand the argument.  */
16999                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
17000                   expanded_exprs 
17001                     = tsubst_pack_expansion (expr, argvec,
17002                                              tf_warning_or_error,
17003                                              NULL_TREE);
17004                   if (expanded_exprs == error_mark_node)
17005                     continue;
17006
17007                   /* Prepend each of the expanded expressions to the
17008                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
17009                   for (i = 0; i < len; i++)
17010                     {
17011                       TREE_VEC_ELT (expanded_arguments, i) = 
17012                         tree_cons (NULL_TREE, 
17013                                    TREE_VEC_ELT (expanded_exprs, i),
17014                                    TREE_VEC_ELT (expanded_arguments, i));
17015                     }
17016                 }
17017               in_base_initializer = 0;
17018
17019               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
17020                  since we built them backwards.  */
17021               for (i = 0; i < len; i++)
17022                 {
17023                   TREE_VEC_ELT (expanded_arguments, i) = 
17024                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
17025                 }
17026             }
17027         }
17028
17029       for (i = 0; i < len; ++i)
17030         {
17031           if (expanded_bases)
17032             {
17033               decl = TREE_VEC_ELT (expanded_bases, i);
17034               decl = expand_member_init (decl);
17035               init = TREE_VEC_ELT (expanded_arguments, i);
17036             }
17037           else
17038             {
17039               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
17040                                   tf_warning_or_error, NULL_TREE);
17041
17042               decl = expand_member_init (decl);
17043               if (decl && !DECL_P (decl))
17044                 in_base_initializer = 1;
17045
17046               init = tsubst_expr (TREE_VALUE (t), argvec, 
17047                                   tf_warning_or_error, NULL_TREE,
17048                                   /*integral_constant_expression_p=*/false);
17049               in_base_initializer = 0;
17050             }
17051
17052           if (decl)
17053             {
17054               init = build_tree_list (decl, init);
17055               TREE_CHAIN (init) = inits;
17056               inits = init;
17057             }
17058         }
17059     }
17060   return inits;
17061 }
17062
17063 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
17064
17065 static void
17066 set_current_access_from_decl (tree decl)
17067 {
17068   if (TREE_PRIVATE (decl))
17069     current_access_specifier = access_private_node;
17070   else if (TREE_PROTECTED (decl))
17071     current_access_specifier = access_protected_node;
17072   else
17073     current_access_specifier = access_public_node;
17074 }
17075
17076 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
17077    is the instantiation (which should have been created with
17078    start_enum) and ARGS are the template arguments to use.  */
17079
17080 static void
17081 tsubst_enum (tree tag, tree newtag, tree args)
17082 {
17083   tree e;
17084
17085   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
17086     {
17087       tree value;
17088       tree decl;
17089
17090       decl = TREE_VALUE (e);
17091       /* Note that in a template enum, the TREE_VALUE is the
17092          CONST_DECL, not the corresponding INTEGER_CST.  */
17093       value = tsubst_expr (DECL_INITIAL (decl),
17094                            args, tf_warning_or_error, NULL_TREE,
17095                            /*integral_constant_expression_p=*/true);
17096
17097       /* Give this enumeration constant the correct access.  */
17098       set_current_access_from_decl (decl);
17099
17100       /* Actually build the enumerator itself.  */
17101       build_enumerator (DECL_NAME (decl), value, newtag);
17102     }
17103
17104   finish_enum (newtag);
17105   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
17106     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
17107 }
17108
17109 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
17110    its type -- but without substituting the innermost set of template
17111    arguments.  So, innermost set of template parameters will appear in
17112    the type.  */
17113
17114 tree
17115 get_mostly_instantiated_function_type (tree decl)
17116 {
17117   tree fn_type;
17118   tree tmpl;
17119   tree targs;
17120   tree tparms;
17121   int parm_depth;
17122
17123   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
17124   targs = DECL_TI_ARGS (decl);
17125   tparms = DECL_TEMPLATE_PARMS (tmpl);
17126   parm_depth = TMPL_PARMS_DEPTH (tparms);
17127
17128   /* There should be as many levels of arguments as there are levels
17129      of parameters.  */
17130   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
17131
17132   fn_type = TREE_TYPE (tmpl);
17133
17134   if (parm_depth == 1)
17135     /* No substitution is necessary.  */
17136     ;
17137   else
17138     {
17139       int i, save_access_control;
17140       tree partial_args;
17141
17142       /* Replace the innermost level of the TARGS with NULL_TREEs to
17143          let tsubst know not to substitute for those parameters.  */
17144       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
17145       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
17146         SET_TMPL_ARGS_LEVEL (partial_args, i,
17147                              TMPL_ARGS_LEVEL (targs, i));
17148       SET_TMPL_ARGS_LEVEL (partial_args,
17149                            TMPL_ARGS_DEPTH (targs),
17150                            make_tree_vec (DECL_NTPARMS (tmpl)));
17151
17152       /* Disable access control as this function is used only during
17153          name-mangling.  */
17154       save_access_control = flag_access_control;
17155       flag_access_control = 0;
17156
17157       ++processing_template_decl;
17158       /* Now, do the (partial) substitution to figure out the
17159          appropriate function type.  */
17160       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
17161       --processing_template_decl;
17162
17163       /* Substitute into the template parameters to obtain the real
17164          innermost set of parameters.  This step is important if the
17165          innermost set of template parameters contains value
17166          parameters whose types depend on outer template parameters.  */
17167       TREE_VEC_LENGTH (partial_args)--;
17168       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
17169
17170       flag_access_control = save_access_control;
17171     }
17172
17173   return fn_type;
17174 }
17175
17176 /* Return truthvalue if we're processing a template different from
17177    the last one involved in diagnostics.  */
17178 int
17179 problematic_instantiation_changed (void)
17180 {
17181   return last_template_error_tick != tinst_level_tick;
17182 }
17183
17184 /* Remember current template involved in diagnostics.  */
17185 void
17186 record_last_problematic_instantiation (void)
17187 {
17188   last_template_error_tick = tinst_level_tick;
17189 }
17190
17191 struct tinst_level *
17192 current_instantiation (void)
17193 {
17194   return current_tinst_level;
17195 }
17196
17197 /* [temp.param] Check that template non-type parm TYPE is of an allowable
17198    type. Return zero for ok, nonzero for disallowed. Issue error and
17199    warning messages under control of COMPLAIN.  */
17200
17201 static int
17202 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
17203 {
17204   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
17205     return 0;
17206   else if (POINTER_TYPE_P (type))
17207     return 0;
17208   else if (TYPE_PTR_TO_MEMBER_P (type))
17209     return 0;
17210   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
17211     return 0;
17212   else if (TREE_CODE (type) == TYPENAME_TYPE)
17213     return 0;
17214
17215   if (complain & tf_error)
17216     error ("%q#T is not a valid type for a template constant parameter", type);
17217   return 1;
17218 }
17219
17220 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
17221    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
17222
17223 static bool
17224 dependent_type_p_r (tree type)
17225 {
17226   tree scope;
17227
17228   /* [temp.dep.type]
17229
17230      A type is dependent if it is:
17231
17232      -- a template parameter. Template template parameters are types
17233         for us (since TYPE_P holds true for them) so we handle
17234         them here.  */
17235   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17236       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
17237     return true;
17238   /* -- a qualified-id with a nested-name-specifier which contains a
17239         class-name that names a dependent type or whose unqualified-id
17240         names a dependent type.  */
17241   if (TREE_CODE (type) == TYPENAME_TYPE)
17242     return true;
17243   /* -- a cv-qualified type where the cv-unqualified type is
17244         dependent.  */
17245   type = TYPE_MAIN_VARIANT (type);
17246   /* -- a compound type constructed from any dependent type.  */
17247   if (TYPE_PTR_TO_MEMBER_P (type))
17248     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
17249             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
17250                                            (type)));
17251   else if (TREE_CODE (type) == POINTER_TYPE
17252            || TREE_CODE (type) == REFERENCE_TYPE)
17253     return dependent_type_p (TREE_TYPE (type));
17254   else if (TREE_CODE (type) == FUNCTION_TYPE
17255            || TREE_CODE (type) == METHOD_TYPE)
17256     {
17257       tree arg_type;
17258
17259       if (dependent_type_p (TREE_TYPE (type)))
17260         return true;
17261       for (arg_type = TYPE_ARG_TYPES (type);
17262            arg_type;
17263            arg_type = TREE_CHAIN (arg_type))
17264         if (dependent_type_p (TREE_VALUE (arg_type)))
17265           return true;
17266       return false;
17267     }
17268   /* -- an array type constructed from any dependent type or whose
17269         size is specified by a constant expression that is
17270         value-dependent.  */
17271   if (TREE_CODE (type) == ARRAY_TYPE)
17272     {
17273       if (TYPE_DOMAIN (type)
17274           && dependent_type_p (TYPE_DOMAIN (type)))
17275         return true;
17276       return dependent_type_p (TREE_TYPE (type));
17277     }
17278   else if (TREE_CODE (type) == INTEGER_TYPE
17279            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
17280     {
17281       /* If this is the TYPE_DOMAIN of an array type, consider it
17282          dependent.  We already checked for value-dependence in
17283          compute_array_index_type.  */
17284       return type_dependent_expression_p (TYPE_MAX_VALUE (type));
17285     }
17286
17287   /* -- a template-id in which either the template name is a template
17288      parameter ...  */
17289   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
17290     return true;
17291   /* ... or any of the template arguments is a dependent type or
17292         an expression that is type-dependent or value-dependent.  */
17293   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
17294            && (any_dependent_template_arguments_p
17295                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
17296     return true;
17297
17298   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
17299      argument of the `typeof' expression is not type-dependent, then
17300      it should already been have resolved.  */
17301   if (TREE_CODE (type) == TYPEOF_TYPE
17302       || TREE_CODE (type) == DECLTYPE_TYPE)
17303     return true;
17304
17305   /* A template argument pack is dependent if any of its packed
17306      arguments are.  */
17307   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
17308     {
17309       tree args = ARGUMENT_PACK_ARGS (type);
17310       int i, len = TREE_VEC_LENGTH (args);
17311       for (i = 0; i < len; ++i)
17312         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17313           return true;
17314     }
17315
17316   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
17317      be template parameters.  */
17318   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
17319     return true;
17320
17321   /* The standard does not specifically mention types that are local
17322      to template functions or local classes, but they should be
17323      considered dependent too.  For example:
17324
17325        template <int I> void f() {
17326          enum E { a = I };
17327          S<sizeof (E)> s;
17328        }
17329
17330      The size of `E' cannot be known until the value of `I' has been
17331      determined.  Therefore, `E' must be considered dependent.  */
17332   scope = TYPE_CONTEXT (type);
17333   if (scope && TYPE_P (scope))
17334     return dependent_type_p (scope);
17335   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
17336     return type_dependent_expression_p (scope);
17337
17338   /* Other types are non-dependent.  */
17339   return false;
17340 }
17341
17342 /* Returns TRUE if TYPE is dependent, in the sense of
17343    [temp.dep.type].  */
17344
17345 bool
17346 dependent_type_p (tree type)
17347 {
17348   /* If there are no template parameters in scope, then there can't be
17349      any dependent types.  */
17350   if (!processing_template_decl)
17351     {
17352       /* If we are not processing a template, then nobody should be
17353          providing us with a dependent type.  */
17354       gcc_assert (type);
17355       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
17356       return false;
17357     }
17358
17359   /* If the type is NULL, we have not computed a type for the entity
17360      in question; in that case, the type is dependent.  */
17361   if (!type)
17362     return true;
17363
17364   /* Erroneous types can be considered non-dependent.  */
17365   if (type == error_mark_node)
17366     return false;
17367
17368   /* If we have not already computed the appropriate value for TYPE,
17369      do so now.  */
17370   if (!TYPE_DEPENDENT_P_VALID (type))
17371     {
17372       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
17373       TYPE_DEPENDENT_P_VALID (type) = 1;
17374     }
17375
17376   return TYPE_DEPENDENT_P (type);
17377 }
17378
17379 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
17380    lookup.  In other words, a dependent type that is not the current
17381    instantiation.  */
17382
17383 bool
17384 dependent_scope_p (tree scope)
17385 {
17386   return (scope && TYPE_P (scope) && dependent_type_p (scope)
17387           && !currently_open_class (scope));
17388 }
17389
17390 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
17391
17392 static bool
17393 dependent_scope_ref_p (tree expression, bool criterion (tree))
17394 {
17395   tree scope;
17396   tree name;
17397
17398   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
17399
17400   if (!TYPE_P (TREE_OPERAND (expression, 0)))
17401     return true;
17402
17403   scope = TREE_OPERAND (expression, 0);
17404   name = TREE_OPERAND (expression, 1);
17405
17406   /* [temp.dep.expr]
17407
17408      An id-expression is type-dependent if it contains a
17409      nested-name-specifier that contains a class-name that names a
17410      dependent type.  */
17411   /* The suggested resolution to Core Issue 224 implies that if the
17412      qualifying type is the current class, then we must peek
17413      inside it.  */
17414   if (DECL_P (name)
17415       && currently_open_class (scope)
17416       && !criterion (name))
17417     return false;
17418   if (dependent_type_p (scope))
17419     return true;
17420
17421   return false;
17422 }
17423
17424 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
17425    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
17426    expression.  */
17427
17428 bool
17429 value_dependent_expression_p (tree expression)
17430 {
17431   if (!processing_template_decl)
17432     return false;
17433
17434   /* A name declared with a dependent type.  */
17435   if (DECL_P (expression) && type_dependent_expression_p (expression))
17436     return true;
17437
17438   switch (TREE_CODE (expression))
17439     {
17440     case IDENTIFIER_NODE:
17441       /* A name that has not been looked up -- must be dependent.  */
17442       return true;
17443
17444     case TEMPLATE_PARM_INDEX:
17445       /* A non-type template parm.  */
17446       return true;
17447
17448     case CONST_DECL:
17449       /* A non-type template parm.  */
17450       if (DECL_TEMPLATE_PARM_P (expression))
17451         return true;
17452       return value_dependent_expression_p (DECL_INITIAL (expression));
17453
17454     case VAR_DECL:
17455        /* A constant with integral or enumeration type and is initialized
17456           with an expression that is value-dependent.  */
17457       if (DECL_INITIAL (expression)
17458           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
17459           && value_dependent_expression_p (DECL_INITIAL (expression)))
17460         return true;
17461       return false;
17462
17463     case DYNAMIC_CAST_EXPR:
17464     case STATIC_CAST_EXPR:
17465     case CONST_CAST_EXPR:
17466     case REINTERPRET_CAST_EXPR:
17467     case CAST_EXPR:
17468       /* These expressions are value-dependent if the type to which
17469          the cast occurs is dependent or the expression being casted
17470          is value-dependent.  */
17471       {
17472         tree type = TREE_TYPE (expression);
17473
17474         if (dependent_type_p (type))
17475           return true;
17476
17477         /* A functional cast has a list of operands.  */
17478         expression = TREE_OPERAND (expression, 0);
17479         if (!expression)
17480           {
17481             /* If there are no operands, it must be an expression such
17482                as "int()". This should not happen for aggregate types
17483                because it would form non-constant expressions.  */
17484             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
17485
17486             return false;
17487           }
17488
17489         if (TREE_CODE (expression) == TREE_LIST)
17490           return any_value_dependent_elements_p (expression);
17491
17492         return value_dependent_expression_p (expression);
17493       }
17494
17495     case SIZEOF_EXPR:
17496     case ALIGNOF_EXPR:
17497       /* A `sizeof' expression is value-dependent if the operand is
17498          type-dependent or is a pack expansion.  */
17499       expression = TREE_OPERAND (expression, 0);
17500       if (PACK_EXPANSION_P (expression))
17501         return true;
17502       else if (TYPE_P (expression))
17503         return dependent_type_p (expression);
17504       return type_dependent_expression_p (expression);
17505
17506     case SCOPE_REF:
17507       return dependent_scope_ref_p (expression, value_dependent_expression_p);
17508
17509     case COMPONENT_REF:
17510       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
17511               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
17512
17513     case CALL_EXPR:
17514       /* A CALL_EXPR may appear in a constant expression if it is a
17515          call to a builtin function, e.g., __builtin_constant_p.  All
17516          such calls are value-dependent.  */
17517       return true;
17518
17519     case NONTYPE_ARGUMENT_PACK:
17520       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
17521          is value-dependent.  */
17522       {
17523         tree values = ARGUMENT_PACK_ARGS (expression);
17524         int i, len = TREE_VEC_LENGTH (values);
17525         
17526         for (i = 0; i < len; ++i)
17527           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
17528             return true;
17529         
17530         return false;
17531       }
17532
17533     case TRAIT_EXPR:
17534       {
17535         tree type2 = TRAIT_EXPR_TYPE2 (expression);
17536         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
17537                 || (type2 ? dependent_type_p (type2) : false));
17538       }
17539
17540     case MODOP_EXPR:
17541       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
17542               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
17543
17544     default:
17545       /* A constant expression is value-dependent if any subexpression is
17546          value-dependent.  */
17547       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
17548         {
17549         case tcc_reference:
17550         case tcc_unary:
17551           return (value_dependent_expression_p
17552                   (TREE_OPERAND (expression, 0)));
17553
17554         case tcc_comparison:
17555         case tcc_binary:
17556           return ((value_dependent_expression_p
17557                    (TREE_OPERAND (expression, 0)))
17558                   || (value_dependent_expression_p
17559                       (TREE_OPERAND (expression, 1))));
17560
17561         case tcc_expression:
17562         case tcc_vl_exp:
17563           {
17564             int i;
17565             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
17566               /* In some cases, some of the operands may be missing.
17567                  (For example, in the case of PREDECREMENT_EXPR, the
17568                  amount to increment by may be missing.)  That doesn't
17569                  make the expression dependent.  */
17570               if (TREE_OPERAND (expression, i)
17571                   && (value_dependent_expression_p
17572                       (TREE_OPERAND (expression, i))))
17573                 return true;
17574             return false;
17575           }
17576
17577         default:
17578           break;
17579         }
17580     }
17581
17582   /* The expression is not value-dependent.  */
17583   return false;
17584 }
17585
17586 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
17587    [temp.dep.expr].  */
17588
17589 bool
17590 type_dependent_expression_p (tree expression)
17591 {
17592   if (!processing_template_decl)
17593     return false;
17594
17595   if (expression == error_mark_node)
17596     return false;
17597
17598   /* An unresolved name is always dependent.  */
17599   if (TREE_CODE (expression) == IDENTIFIER_NODE
17600       || TREE_CODE (expression) == USING_DECL)
17601     return true;
17602
17603   /* Some expression forms are never type-dependent.  */
17604   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
17605       || TREE_CODE (expression) == SIZEOF_EXPR
17606       || TREE_CODE (expression) == ALIGNOF_EXPR
17607       || TREE_CODE (expression) == TRAIT_EXPR
17608       || TREE_CODE (expression) == TYPEID_EXPR
17609       || TREE_CODE (expression) == DELETE_EXPR
17610       || TREE_CODE (expression) == VEC_DELETE_EXPR
17611       || TREE_CODE (expression) == THROW_EXPR)
17612     return false;
17613
17614   /* The types of these expressions depends only on the type to which
17615      the cast occurs.  */
17616   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
17617       || TREE_CODE (expression) == STATIC_CAST_EXPR
17618       || TREE_CODE (expression) == CONST_CAST_EXPR
17619       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
17620       || TREE_CODE (expression) == CAST_EXPR)
17621     return dependent_type_p (TREE_TYPE (expression));
17622
17623   /* The types of these expressions depends only on the type created
17624      by the expression.  */
17625   if (TREE_CODE (expression) == NEW_EXPR
17626       || TREE_CODE (expression) == VEC_NEW_EXPR)
17627     {
17628       /* For NEW_EXPR tree nodes created inside a template, either
17629          the object type itself or a TREE_LIST may appear as the
17630          operand 1.  */
17631       tree type = TREE_OPERAND (expression, 1);
17632       if (TREE_CODE (type) == TREE_LIST)
17633         /* This is an array type.  We need to check array dimensions
17634            as well.  */
17635         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
17636                || value_dependent_expression_p
17637                     (TREE_OPERAND (TREE_VALUE (type), 1));
17638       else
17639         return dependent_type_p (type);
17640     }
17641
17642   if (TREE_CODE (expression) == SCOPE_REF
17643       && dependent_scope_ref_p (expression,
17644                                 type_dependent_expression_p))
17645     return true;
17646
17647   if (TREE_CODE (expression) == FUNCTION_DECL
17648       && DECL_LANG_SPECIFIC (expression)
17649       && DECL_TEMPLATE_INFO (expression)
17650       && (any_dependent_template_arguments_p
17651           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
17652     return true;
17653
17654   if (TREE_CODE (expression) == TEMPLATE_DECL
17655       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
17656     return false;
17657
17658   if (TREE_CODE (expression) == STMT_EXPR)
17659     expression = stmt_expr_value_expr (expression);
17660
17661   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
17662     {
17663       tree elt;
17664       unsigned i;
17665
17666       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
17667         {
17668           if (type_dependent_expression_p (elt))
17669             return true;
17670         }
17671       return false;
17672     }
17673
17674   if (TREE_TYPE (expression) == unknown_type_node)
17675     {
17676       if (TREE_CODE (expression) == ADDR_EXPR)
17677         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
17678       if (TREE_CODE (expression) == COMPONENT_REF
17679           || TREE_CODE (expression) == OFFSET_REF)
17680         {
17681           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
17682             return true;
17683           expression = TREE_OPERAND (expression, 1);
17684           if (TREE_CODE (expression) == IDENTIFIER_NODE)
17685             return false;
17686         }
17687       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
17688       if (TREE_CODE (expression) == SCOPE_REF)
17689         return false;
17690
17691       if (TREE_CODE (expression) == BASELINK)
17692         expression = BASELINK_FUNCTIONS (expression);
17693
17694       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
17695         {
17696           if (any_dependent_template_arguments_p
17697               (TREE_OPERAND (expression, 1)))
17698             return true;
17699           expression = TREE_OPERAND (expression, 0);
17700         }
17701       gcc_assert (TREE_CODE (expression) == OVERLOAD
17702                   || TREE_CODE (expression) == FUNCTION_DECL);
17703
17704       while (expression)
17705         {
17706           if (type_dependent_expression_p (OVL_CURRENT (expression)))
17707             return true;
17708           expression = OVL_NEXT (expression);
17709         }
17710       return false;
17711     }
17712
17713   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
17714
17715   return (dependent_type_p (TREE_TYPE (expression)));
17716 }
17717
17718 /* Like type_dependent_expression_p, but it also works while not processing
17719    a template definition, i.e. during substitution or mangling.  */
17720
17721 bool
17722 type_dependent_expression_p_push (tree expr)
17723 {
17724   bool b;
17725   ++processing_template_decl;
17726   b = type_dependent_expression_p (expr);
17727   --processing_template_decl;
17728   return b;
17729 }
17730
17731 /* Returns TRUE if ARGS contains a type-dependent expression.  */
17732
17733 bool
17734 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
17735 {
17736   unsigned int i;
17737   tree arg;
17738
17739   for (i = 0; VEC_iterate (tree, args, i, arg); ++i)
17740     {
17741       if (type_dependent_expression_p (arg))
17742         return true;
17743     }
17744   return false;
17745 }
17746
17747 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
17748    expressions) contains any value-dependent expressions.  */
17749
17750 bool
17751 any_value_dependent_elements_p (const_tree list)
17752 {
17753   for (; list; list = TREE_CHAIN (list))
17754     if (value_dependent_expression_p (TREE_VALUE (list)))
17755       return true;
17756
17757   return false;
17758 }
17759
17760 /* Returns TRUE if the ARG (a template argument) is dependent.  */
17761
17762 bool
17763 dependent_template_arg_p (tree arg)
17764 {
17765   if (!processing_template_decl)
17766     return false;
17767
17768   if (TREE_CODE (arg) == TEMPLATE_DECL
17769       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17770     return dependent_template_p (arg);
17771   else if (ARGUMENT_PACK_P (arg))
17772     {
17773       tree args = ARGUMENT_PACK_ARGS (arg);
17774       int i, len = TREE_VEC_LENGTH (args);
17775       for (i = 0; i < len; ++i)
17776         {
17777           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17778             return true;
17779         }
17780
17781       return false;
17782     }
17783   else if (TYPE_P (arg))
17784     return dependent_type_p (arg);
17785   else
17786     return (type_dependent_expression_p (arg)
17787             || value_dependent_expression_p (arg));
17788 }
17789
17790 /* Returns true if ARGS (a collection of template arguments) contains
17791    any types that require structural equality testing.  */
17792
17793 bool
17794 any_template_arguments_need_structural_equality_p (tree args)
17795 {
17796   int i;
17797   int j;
17798
17799   if (!args)
17800     return false;
17801   if (args == error_mark_node)
17802     return true;
17803
17804   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17805     {
17806       tree level = TMPL_ARGS_LEVEL (args, i + 1);
17807       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17808         {
17809           tree arg = TREE_VEC_ELT (level, j);
17810           tree packed_args = NULL_TREE;
17811           int k, len = 1;
17812
17813           if (ARGUMENT_PACK_P (arg))
17814             {
17815               /* Look inside the argument pack.  */
17816               packed_args = ARGUMENT_PACK_ARGS (arg);
17817               len = TREE_VEC_LENGTH (packed_args);
17818             }
17819
17820           for (k = 0; k < len; ++k)
17821             {
17822               if (packed_args)
17823                 arg = TREE_VEC_ELT (packed_args, k);
17824
17825               if (error_operand_p (arg))
17826                 return true;
17827               else if (TREE_CODE (arg) == TEMPLATE_DECL
17828                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17829                 continue;
17830               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
17831                 return true;
17832               else if (!TYPE_P (arg) && TREE_TYPE (arg)
17833                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
17834                 return true;
17835             }
17836         }
17837     }
17838
17839   return false;
17840 }
17841
17842 /* Returns true if ARGS (a collection of template arguments) contains
17843    any dependent arguments.  */
17844
17845 bool
17846 any_dependent_template_arguments_p (const_tree args)
17847 {
17848   int i;
17849   int j;
17850
17851   if (!args)
17852     return false;
17853   if (args == error_mark_node)
17854     return true;
17855
17856   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17857     {
17858       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
17859       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17860         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
17861           return true;
17862     }
17863
17864   return false;
17865 }
17866
17867 /* Returns TRUE if the template TMPL is dependent.  */
17868
17869 bool
17870 dependent_template_p (tree tmpl)
17871 {
17872   if (TREE_CODE (tmpl) == OVERLOAD)
17873     {
17874       while (tmpl)
17875         {
17876           if (dependent_template_p (OVL_FUNCTION (tmpl)))
17877             return true;
17878           tmpl = OVL_CHAIN (tmpl);
17879         }
17880       return false;
17881     }
17882
17883   /* Template template parameters are dependent.  */
17884   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
17885       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
17886     return true;
17887   /* So are names that have not been looked up.  */
17888   if (TREE_CODE (tmpl) == SCOPE_REF
17889       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
17890     return true;
17891   /* So are member templates of dependent classes.  */
17892   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
17893     return dependent_type_p (DECL_CONTEXT (tmpl));
17894   return false;
17895 }
17896
17897 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
17898
17899 bool
17900 dependent_template_id_p (tree tmpl, tree args)
17901 {
17902   return (dependent_template_p (tmpl)
17903           || any_dependent_template_arguments_p (args));
17904 }
17905
17906 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
17907    is dependent.  */
17908
17909 bool
17910 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
17911 {
17912   int i;
17913
17914   if (!processing_template_decl)
17915     return false;
17916
17917   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
17918     {
17919       tree decl = TREE_VEC_ELT (declv, i);
17920       tree init = TREE_VEC_ELT (initv, i);
17921       tree cond = TREE_VEC_ELT (condv, i);
17922       tree incr = TREE_VEC_ELT (incrv, i);
17923
17924       if (type_dependent_expression_p (decl))
17925         return true;
17926
17927       if (init && type_dependent_expression_p (init))
17928         return true;
17929
17930       if (type_dependent_expression_p (cond))
17931         return true;
17932
17933       if (COMPARISON_CLASS_P (cond)
17934           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
17935               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
17936         return true;
17937
17938       if (TREE_CODE (incr) == MODOP_EXPR)
17939         {
17940           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
17941               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
17942             return true;
17943         }
17944       else if (type_dependent_expression_p (incr))
17945         return true;
17946       else if (TREE_CODE (incr) == MODIFY_EXPR)
17947         {
17948           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
17949             return true;
17950           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
17951             {
17952               tree t = TREE_OPERAND (incr, 1);
17953               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
17954                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
17955                 return true;
17956             }
17957         }
17958     }
17959
17960   return false;
17961 }
17962
17963 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
17964    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
17965    no such TYPE can be found.  Note that this function peers inside
17966    uninstantiated templates and therefore should be used only in
17967    extremely limited situations.  ONLY_CURRENT_P restricts this
17968    peering to the currently open classes hierarchy (which is required
17969    when comparing types).  */
17970
17971 tree
17972 resolve_typename_type (tree type, bool only_current_p)
17973 {
17974   tree scope;
17975   tree name;
17976   tree decl;
17977   int quals;
17978   tree pushed_scope;
17979   tree result;
17980
17981   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
17982
17983   scope = TYPE_CONTEXT (type);
17984   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
17985      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
17986      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
17987      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
17988      identifier  of the TYPENAME_TYPE anymore.
17989      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
17990      TYPENAME_TYPE instead, we avoid messing up with a possible
17991      typedef variant case.  */
17992   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
17993
17994   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
17995      it first before we can figure out what NAME refers to.  */
17996   if (TREE_CODE (scope) == TYPENAME_TYPE)
17997     scope = resolve_typename_type (scope, only_current_p);
17998   /* If we don't know what SCOPE refers to, then we cannot resolve the
17999      TYPENAME_TYPE.  */
18000   if (TREE_CODE (scope) == TYPENAME_TYPE)
18001     return type;
18002   /* If the SCOPE is a template type parameter, we have no way of
18003      resolving the name.  */
18004   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
18005     return type;
18006   /* If the SCOPE is not the current instantiation, there's no reason
18007      to look inside it.  */
18008   if (only_current_p && !currently_open_class (scope))
18009     return type;
18010   /* If this is a typedef, we don't want to look inside (c++/11987).  */
18011   if (typedef_variant_p (type))
18012     return type;
18013   /* If SCOPE isn't the template itself, it will not have a valid
18014      TYPE_FIELDS list.  */
18015   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
18016     /* scope is either the template itself or a compatible instantiation
18017        like X<T>, so look up the name in the original template.  */
18018     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
18019   else
18020     /* scope is a partial instantiation, so we can't do the lookup or we
18021        will lose the template arguments.  */
18022     return type;
18023   /* Enter the SCOPE so that name lookup will be resolved as if we
18024      were in the class definition.  In particular, SCOPE will no
18025      longer be considered a dependent type.  */
18026   pushed_scope = push_scope (scope);
18027   /* Look up the declaration.  */
18028   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
18029
18030   result = NULL_TREE;
18031   
18032   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
18033      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
18034   if (!decl)
18035     /*nop*/;
18036   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
18037            && TREE_CODE (decl) == TYPE_DECL)
18038     {
18039       result = TREE_TYPE (decl);
18040       if (result == error_mark_node)
18041         result = NULL_TREE;
18042     }
18043   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
18044            && DECL_CLASS_TEMPLATE_P (decl))
18045     {
18046       tree tmpl;
18047       tree args;
18048       /* Obtain the template and the arguments.  */
18049       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
18050       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
18051       /* Instantiate the template.  */
18052       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
18053                                       /*entering_scope=*/0,
18054                                       tf_error | tf_user);
18055       if (result == error_mark_node)
18056         result = NULL_TREE;
18057     }
18058   
18059   /* Leave the SCOPE.  */
18060   if (pushed_scope)
18061     pop_scope (pushed_scope);
18062
18063   /* If we failed to resolve it, return the original typename.  */
18064   if (!result)
18065     return type;
18066   
18067   /* If lookup found a typename type, resolve that too.  */
18068   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
18069     {
18070       /* Ill-formed programs can cause infinite recursion here, so we
18071          must catch that.  */
18072       TYPENAME_IS_RESOLVING_P (type) = 1;
18073       result = resolve_typename_type (result, only_current_p);
18074       TYPENAME_IS_RESOLVING_P (type) = 0;
18075     }
18076   
18077   /* Qualify the resulting type.  */
18078   quals = cp_type_quals (type);
18079   if (quals)
18080     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
18081
18082   return result;
18083 }
18084
18085 /* EXPR is an expression which is not type-dependent.  Return a proxy
18086    for EXPR that can be used to compute the types of larger
18087    expressions containing EXPR.  */
18088
18089 tree
18090 build_non_dependent_expr (tree expr)
18091 {
18092   tree inner_expr;
18093
18094   /* Preserve null pointer constants so that the type of things like
18095      "p == 0" where "p" is a pointer can be determined.  */
18096   if (null_ptr_cst_p (expr))
18097     return expr;
18098   /* Preserve OVERLOADs; the functions must be available to resolve
18099      types.  */
18100   inner_expr = expr;
18101   if (TREE_CODE (inner_expr) == STMT_EXPR)
18102     inner_expr = stmt_expr_value_expr (inner_expr);
18103   if (TREE_CODE (inner_expr) == ADDR_EXPR)
18104     inner_expr = TREE_OPERAND (inner_expr, 0);
18105   if (TREE_CODE (inner_expr) == COMPONENT_REF)
18106     inner_expr = TREE_OPERAND (inner_expr, 1);
18107   if (is_overloaded_fn (inner_expr)
18108       || TREE_CODE (inner_expr) == OFFSET_REF)
18109     return expr;
18110   /* There is no need to return a proxy for a variable.  */
18111   if (TREE_CODE (expr) == VAR_DECL)
18112     return expr;
18113   /* Preserve string constants; conversions from string constants to
18114      "char *" are allowed, even though normally a "const char *"
18115      cannot be used to initialize a "char *".  */
18116   if (TREE_CODE (expr) == STRING_CST)
18117     return expr;
18118   /* Preserve arithmetic constants, as an optimization -- there is no
18119      reason to create a new node.  */
18120   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
18121     return expr;
18122   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
18123      There is at least one place where we want to know that a
18124      particular expression is a throw-expression: when checking a ?:
18125      expression, there are special rules if the second or third
18126      argument is a throw-expression.  */
18127   if (TREE_CODE (expr) == THROW_EXPR)
18128     return expr;
18129
18130   if (TREE_CODE (expr) == COND_EXPR)
18131     return build3 (COND_EXPR,
18132                    TREE_TYPE (expr),
18133                    TREE_OPERAND (expr, 0),
18134                    (TREE_OPERAND (expr, 1)
18135                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
18136                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
18137                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
18138   if (TREE_CODE (expr) == COMPOUND_EXPR
18139       && !COMPOUND_EXPR_OVERLOADED (expr))
18140     return build2 (COMPOUND_EXPR,
18141                    TREE_TYPE (expr),
18142                    TREE_OPERAND (expr, 0),
18143                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
18144
18145   /* If the type is unknown, it can't really be non-dependent */
18146   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
18147
18148   /* Otherwise, build a NON_DEPENDENT_EXPR.
18149
18150      REFERENCE_TYPEs are not stripped for expressions in templates
18151      because doing so would play havoc with mangling.  Consider, for
18152      example:
18153
18154        template <typename T> void f<T& g>() { g(); }
18155
18156      In the body of "f", the expression for "g" will have
18157      REFERENCE_TYPE, even though the standard says that it should
18158      not.  The reason is that we must preserve the syntactic form of
18159      the expression so that mangling (say) "f<g>" inside the body of
18160      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
18161      stripped here.  */
18162   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
18163 }
18164
18165 /* ARGS is a vector of expressions as arguments to a function call.
18166    Replace the arguments with equivalent non-dependent expressions.
18167    This modifies ARGS in place.  */
18168
18169 void
18170 make_args_non_dependent (VEC(tree,gc) *args)
18171 {
18172   unsigned int ix;
18173   tree arg;
18174
18175   for (ix = 0; VEC_iterate (tree, args, ix, arg); ++ix)
18176     {
18177       tree newarg = build_non_dependent_expr (arg);
18178       if (newarg != arg)
18179         VEC_replace (tree, args, ix, newarg);
18180     }
18181 }
18182
18183 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
18184    with a level one deeper than the actual template parms.  */
18185
18186 tree
18187 make_auto (void)
18188 {
18189   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
18190   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
18191                                TYPE_DECL, get_identifier ("auto"), au);
18192   TYPE_STUB_DECL (au) = TYPE_NAME (au);
18193   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
18194     (0, processing_template_decl + 1, processing_template_decl + 1,
18195      TYPE_NAME (au), NULL_TREE);
18196   TYPE_CANONICAL (au) = canonical_type_parameter (au);
18197   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
18198   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
18199
18200   return au;
18201 }
18202
18203 /* Given type ARG, return std::initializer_list<ARG>.  */
18204
18205 static tree
18206 listify (tree arg)
18207 {
18208   tree std_init_list = namespace_binding
18209     (get_identifier ("initializer_list"), std_node);
18210   tree argvec;
18211   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
18212     {    
18213       error ("deducing from brace-enclosed initializer list requires "
18214              "#include <initializer_list>");
18215       return error_mark_node;
18216     }
18217   argvec = make_tree_vec (1);
18218   TREE_VEC_ELT (argvec, 0) = arg;
18219   return lookup_template_class (std_init_list, argvec, NULL_TREE,
18220                                 NULL_TREE, 0, tf_warning_or_error);
18221 }
18222
18223 /* Replace auto in TYPE with std::initializer_list<auto>.  */
18224
18225 static tree
18226 listify_autos (tree type, tree auto_node)
18227 {
18228   tree init_auto = listify (auto_node);
18229   tree argvec = make_tree_vec (1);
18230   TREE_VEC_ELT (argvec, 0) = init_auto;
18231   if (processing_template_decl)
18232     argvec = add_to_template_args (current_template_args (), argvec);
18233   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18234 }
18235
18236 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
18237    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
18238
18239 tree
18240 do_auto_deduction (tree type, tree init, tree auto_node)
18241 {
18242   tree parms, tparms, targs;
18243   tree args[1];
18244   int val;
18245
18246   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
18247      with either a new invented type template parameter U or, if the
18248      initializer is a braced-init-list (8.5.4), with
18249      std::initializer_list<U>.  */
18250   if (BRACE_ENCLOSED_INITIALIZER_P (init))
18251     type = listify_autos (type, auto_node);
18252
18253   parms = build_tree_list (NULL_TREE, type);
18254   args[0] = init;
18255   tparms = make_tree_vec (1);
18256   targs = make_tree_vec (1);
18257   TREE_VEC_ELT (tparms, 0)
18258     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
18259   val = type_unification_real (tparms, targs, parms, args, 1, 0,
18260                                DEDUCE_CALL, LOOKUP_NORMAL);
18261   if (val > 0)
18262     {
18263       error ("unable to deduce %qT from %qE", type, init);
18264       return error_mark_node;
18265     }
18266
18267   /* If the list of declarators contains more than one declarator, the type
18268      of each declared variable is determined as described above. If the
18269      type deduced for the template parameter U is not the same in each
18270      deduction, the program is ill-formed.  */
18271   if (TREE_TYPE (auto_node)
18272       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
18273     {
18274       error ("inconsistent deduction for %qT: %qT and then %qT",
18275              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
18276       return error_mark_node;
18277     }
18278   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
18279
18280   if (processing_template_decl)
18281     targs = add_to_template_args (current_template_args (), targs);
18282   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
18283 }
18284
18285 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
18286    result.  */
18287
18288 tree
18289 splice_late_return_type (tree type, tree late_return_type)
18290 {
18291   tree argvec;
18292
18293   if (late_return_type == NULL_TREE)
18294     return type;
18295   argvec = make_tree_vec (1);
18296   TREE_VEC_ELT (argvec, 0) = late_return_type;
18297   if (processing_template_decl)
18298     argvec = add_to_template_args (current_template_args (), argvec);
18299   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18300 }
18301
18302 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
18303
18304 bool
18305 is_auto (const_tree type)
18306 {
18307   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18308       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
18309     return true;
18310   else
18311     return false;
18312 }
18313
18314 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
18315    appear as a type-specifier for the declaration in question, we don't
18316    have to look through the whole type.  */
18317
18318 tree
18319 type_uses_auto (tree type)
18320 {
18321   enum tree_code code;
18322   if (is_auto (type))
18323     return type;
18324
18325   code = TREE_CODE (type);
18326
18327   if (code == POINTER_TYPE || code == REFERENCE_TYPE
18328       || code == OFFSET_TYPE || code == FUNCTION_TYPE
18329       || code == METHOD_TYPE || code == ARRAY_TYPE)
18330     return type_uses_auto (TREE_TYPE (type));
18331
18332   if (TYPE_PTRMEMFUNC_P (type))
18333     return type_uses_auto (TREE_TYPE (TREE_TYPE
18334                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
18335
18336   return NULL_TREE;
18337 }
18338
18339 /* For a given template T, return the vector of typedefs referenced
18340    in T for which access check is needed at T instantiation time.
18341    T is either  a FUNCTION_DECL or a RECORD_TYPE.
18342    Those typedefs were added to T by the function
18343    append_type_to_template_for_access_check.  */
18344
18345 VEC(qualified_typedef_usage_t,gc)*
18346 get_types_needing_access_check (tree t)
18347 {
18348   tree ti;
18349   VEC(qualified_typedef_usage_t,gc) *result = NULL;
18350
18351   if (!t || t == error_mark_node)
18352     return NULL;
18353
18354   if (!(ti = get_template_info (t)))
18355     return NULL;
18356
18357   if (CLASS_TYPE_P (t)
18358       || TREE_CODE (t) == FUNCTION_DECL)
18359     {
18360       if (!TI_TEMPLATE (ti))
18361         return NULL;
18362
18363       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
18364     }
18365
18366   return result;
18367 }
18368
18369 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
18370    tied to T. That list of typedefs will be access checked at
18371    T instantiation time.
18372    T is either a FUNCTION_DECL or a RECORD_TYPE.
18373    TYPE_DECL is a TYPE_DECL node representing a typedef.
18374    SCOPE is the scope through which TYPE_DECL is accessed.
18375    LOCATION is the location of the usage point of TYPE_DECL.
18376
18377    This function is a subroutine of
18378    append_type_to_template_for_access_check.  */
18379
18380 static void
18381 append_type_to_template_for_access_check_1 (tree t,
18382                                             tree type_decl,
18383                                             tree scope,
18384                                             location_t location)
18385 {
18386   qualified_typedef_usage_t typedef_usage;
18387   tree ti;
18388
18389   if (!t || t == error_mark_node)
18390     return;
18391
18392   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
18393                || CLASS_TYPE_P (t))
18394               && type_decl
18395               && TREE_CODE (type_decl) == TYPE_DECL
18396               && scope);
18397
18398   if (!(ti = get_template_info (t)))
18399     return;
18400
18401   gcc_assert (TI_TEMPLATE (ti));
18402
18403   typedef_usage.typedef_decl = type_decl;
18404   typedef_usage.context = scope;
18405   typedef_usage.locus = location;
18406
18407   VEC_safe_push (qualified_typedef_usage_t, gc,
18408                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
18409                  &typedef_usage);
18410 }
18411
18412 /* Append TYPE_DECL to the template TEMPL.
18413    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
18414    At TEMPL instanciation time, TYPE_DECL will be checked to see
18415    if it can be accessed through SCOPE.
18416    LOCATION is the location of the usage point of TYPE_DECL.
18417
18418    e.g. consider the following code snippet:
18419
18420      class C
18421      {
18422        typedef int myint;
18423      };
18424
18425      template<class U> struct S
18426      {
18427        C::myint mi; // <-- usage point of the typedef C::myint
18428      };
18429
18430      S<char> s;
18431
18432    At S<char> instantiation time, we need to check the access of C::myint
18433    In other words, we need to check the access of the myint typedef through
18434    the C scope. For that purpose, this function will add the myint typedef
18435    and the scope C through which its being accessed to a list of typedefs
18436    tied to the template S. That list will be walked at template instantiation
18437    time and access check performed on each typedefs it contains.
18438    Note that this particular code snippet should yield an error because
18439    myint is private to C.  */
18440
18441 void
18442 append_type_to_template_for_access_check (tree templ,
18443                                           tree type_decl,
18444                                           tree scope,
18445                                           location_t location)
18446 {
18447   qualified_typedef_usage_t *iter;
18448   int i;
18449
18450   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
18451
18452   /* Make sure we don't append the type to the template twice.  */
18453   for (i = 0;
18454        VEC_iterate (qualified_typedef_usage_t,
18455                     get_types_needing_access_check (templ),
18456                     i, iter);
18457        ++i)
18458     if (iter->typedef_decl == type_decl && scope == iter->context)
18459       return;
18460
18461   append_type_to_template_for_access_check_1 (templ, type_decl,
18462                                               scope, location);
18463 }
18464
18465 /* Set up the hash tables for template instantiations.  */
18466
18467 void
18468 init_template_processing (void)
18469 {
18470   decl_specializations = htab_create_ggc (37,
18471                                           hash_specialization,
18472                                           eq_specializations,
18473                                           ggc_free);
18474   type_specializations = htab_create_ggc (37,
18475                                           hash_specialization,
18476                                           eq_specializations,
18477                                           ggc_free);
18478 }
18479
18480 #include "gt-cp-pt.h"